forked from pyrocko/pyrocko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
733 lines (590 loc) · 22.3 KB
/
setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
from __future__ import absolute_import, division, print_function
import sys
import os
import time
import shutil
import tempfile
from os.path import join as pjoin
from distutils.sysconfig import get_python_inc
from setuptools import setup, Extension, Command
from setuptools.command.build_py import build_py
from setuptools.command.build_ext import build_ext
from setuptools.command.install import install
packname = 'pyrocko'
version = '2018.01.29'
op = os.path
try:
import numpy
except ImportError:
class numpy():
def __init__(self):
pass
@classmethod
def get_include(self):
return ''
class NotInAGitRepos(Exception):
pass
def git_infos():
'''Query git about sha1 of last commit and check if there are local \
modifications.'''
from subprocess import Popen, PIPE
import re
def q(c):
return Popen(c, stdout=PIPE).communicate()[0]
if not op.exists('.git'):
raise NotInAGitRepos()
sha1 = q(['git', 'log', '--pretty=oneline', '-n1']).split()[0]
sha1 = re.sub(br'[^0-9a-f]', '', sha1)
sha1 = str(sha1.decode('ascii'))
sstatus = q(['git', 'status'])
local_modifications = bool(re.search(br'^#\s+modified:', sstatus,
flags=re.M))
return sha1, local_modifications
def bash_completions_dir():
from subprocess import Popen, PIPE
def q(c):
return Popen(c, stdout=PIPE).communicate()[0]
try:
d = q(['pkg-config', 'bash-completion', '--variable=completionsdir'])
return d.strip().decode('utf-8')
except Exception:
return None
def make_info_module(packname, version):
'''Put version and revision information into file src/info.py.'''
sha1, local_modifications = None, None
combi = '%s-%s' % (packname, version)
try:
sha1, local_modifications = git_infos()
combi += '-%s' % sha1
if local_modifications:
combi += '-modified'
except (OSError, NotInAGitRepos):
pass
datestr = time.strftime('%Y-%m-%d_%H:%M:%S')
combi += '-%s' % datestr
s = '''# This module is automatically created from setup.py
git_sha1 = %s
local_modifications = %s
version = %s
long_version = %s # noqa
installed_date = %s
''' % tuple([repr(x) for x in (
sha1, local_modifications, version, combi, datestr)])
try:
f = open(pjoin('src', 'info.py'), 'w')
f.write(s)
f.close()
except Exception:
pass
def make_prerequisites():
from subprocess import check_call
try:
check_call(['sh', 'prerequisites/prerequisites.sh'])
except Exception:
sys.exit('error: failed to build the included prerequisites with '
'"sh prerequisites/prerequisites.sh"')
def get_readme_paths():
paths = []
for (path, dirnames, filenames) in os.walk(
op.join(op.dirname(__file__), 'src')):
paths.extend(
[op.join(path.split('/', 1)[1], fn) for fn in filenames if
fn == 'README.md'])
return paths
def get_build_include(lib_name):
return op.join(op.dirname(op.abspath(__file__)), lib_name)
def find_pyrocko_installs():
found = []
seen = set()
orig_sys_path = sys.path
for p in sys.path:
ap = op.abspath(p)
if ap == op.abspath('.'):
continue
if ap in seen:
continue
seen.add(ap)
sys.path = [p]
try:
import pyrocko
dpath = op.dirname(op.abspath(pyrocko.__file__))
x = (pyrocko.installed_date, p, dpath,
pyrocko.long_version)
found.append(x)
del sys.modules['pyrocko']
del sys.modules['pyrocko.info']
except ImportError:
pass
sys.path = orig_sys_path
return found
def print_installs(found, file):
print(
'\nsys.path configuration is: \n %s\n' % '\n '.join(sys.path),
file=file)
dates = sorted([xx[0] for xx in found])
i = 1
for (installed_date, p, installed_path, long_version) in found:
oldnew = ''
if len(dates) >= 2:
if installed_date == dates[0]:
oldnew = ' (oldest)'
if installed_date == dates[-1]:
oldnew = ' (newest)'
print('''Pyrocko installation #%i:
date installed: %s%s
version: %s
path: %s
''' % (i, installed_date, oldnew, long_version, installed_path), file=file)
i += 1
def check_multiple_install():
found = find_pyrocko_installs()
e = sys.stderr
dates = sorted([xx[0] for xx in found])
if len(found) > 1:
print_installs(found, e)
if len(found) > 1:
print(
'''Installation #1 is used with default sys.path configuration.
WARNING: Multiple installations of Pyrocko are present on this system.''',
file=e)
if found[0][0] != dates[-1]:
print('WARNING: Not using newest installed version.', file=e)
def check_pyrocko_install_compat():
found = find_pyrocko_installs()
if len(found) == 0:
return
expected_submodules = ['gui', 'dataset', 'client',
'streaming', 'io', 'model']
installed_date, p, install_path, long_version = found[0]
installed_submodules = [d for d in os.listdir(install_path)
if op.isdir(op.join(install_path, d))]
if not all([ed in installed_submodules for ed in expected_submodules]):
print_installs(found, sys.stdout)
print('''\n
###############################################################################
WARNING: Found an old, incompatible, Pyrocko installation!
Please purge the old installation and the 'build' directory before installing
this new version:
sudo rm -rf '%s' build
###############################################################################
''' % install_path)
sys.exit(1)
class CheckInstalls(Command):
description = '''check for multiple installations of Pyrocko'''
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
check_multiple_install()
class Uninstall(Command):
description = 'delete installations of Pyrocko known to the invoked ' \
'Python interpreter'''
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
found = find_pyrocko_installs()
print_installs(found, sys.stdout)
if found:
print('''
Use the following commands to remove the Pyrocko installation(s) known to the
currently running Python interpreter:
sudo rm -rf build''')
for _, _, install_path, _ in found:
print(' sudo rm -rf "%s"' % install_path)
print()
else:
print('''
No Pyrocko installations found with the currently running Python interpreter.
''')
class CustomInstallCommand(install):
def run(self):
check_pyrocko_install_compat()
install.run(self)
check_multiple_install()
bd_dir = bash_completions_dir()
if bd_dir:
try:
shutil.copy('extras/pyrocko', bd_dir)
print('Installing pyrocko bash_completion to "%s"' % bd_dir)
except Exception:
print(
'Could not install pyrocko bash_completion to "%s" '
'(continuing without)'
% bd_dir)
class InstallPrerequisits(Command):
description = '''install prerequisites with system package manager'''
user_options = [
('force-yes', None, 'Do not ask for confirmation to install')]
def initialize_options(self):
self.force_yes = False
def finalize_options(self):
pass
def run(self):
from subprocess import Popen, PIPE, STDOUT
import platform
distribution = platform.linux_distribution()[0].lower().rstrip()
if distribution == 'ubuntu':
distribution = 'debian'
if distribution.startswith('centos'):
distribution = 'centos'
fn = 'prerequisites/prerequisites_%s_python%i.sh' % (
distribution, sys.version_info.major)
if not self.force_yes:
try:
input = raw_input
except NameError:
pass
confirm = input('Execute: %s \n\
proceed? [y/n]' % open(fn, 'r').read())
if not confirm.lower() == 'y':
sys.exit(0)
p = Popen(['sh', fn], stdin=PIPE, stdout=PIPE, stderr=STDOUT,
shell=False)
while p.poll() is None:
print(p.stdout.readline().decode('ascii').rstrip())
print(p.stdout.read().decode('ascii'))
class CustomBuildPyCommand(build_py):
def make_compat_modules(self):
mapping = [
('pyrocko', 'css', ['pyrocko.io.css']),
('pyrocko', 'datacube', ['pyrocko.io.datacube']),
('pyrocko.fdsn', '__init__', []),
('pyrocko.fdsn', 'enhanced_sacpz', ['pyrocko.io.enhanced_sacpz']),
('pyrocko.fdsn', 'station', ['pyrocko.io.stationxml']),
('pyrocko', 'gcf', ['pyrocko.io.gcf']),
('pyrocko', 'gse1', ['pyrocko.io.gse1']),
('pyrocko', 'gse2_io_wrap', ['pyrocko.io.gse2']),
('pyrocko', 'ims', ['pyrocko.io.ims']),
('pyrocko', 'io_common', ['pyrocko.io.io_common']),
('pyrocko', 'kan', ['pyrocko.io.kan']),
('pyrocko', 'mseed', ['pyrocko.io.mseed']),
('pyrocko', 'rdseed', ['pyrocko.io.rdseed']),
('pyrocko.fdsn', 'resp', ['pyrocko.io.resp']),
('pyrocko', 'sacio', ['pyrocko.io.sac']),
('pyrocko', 'segy', ['pyrocko.io.segy']),
('pyrocko', 'seisan_response', ['pyrocko.io.seisan_response']),
('pyrocko', 'seisan_waveform', ['pyrocko.io.seisan_waveform']),
('pyrocko', 'suds', ['pyrocko.io.suds']),
('pyrocko', 'yaff', ['pyrocko.io.yaff']),
('pyrocko', 'eventdata', ['pyrocko.io.eventdata']),
('pyrocko.fdsn', 'ws', ['pyrocko.client.fdsn']),
('pyrocko', 'catalog', ['pyrocko.client.catalog']),
('pyrocko', 'iris_ws', ['pyrocko.client.iris']),
('pyrocko', 'crust2x2', ['pyrocko.dataset.crust2x2']),
('pyrocko', 'crustdb', ['pyrocko.dataset.crustdb']),
('pyrocko', 'geonames', ['pyrocko.dataset.geonames']),
('pyrocko', 'tectonics', ['pyrocko.dataset.tectonics']),
('pyrocko', 'topo', ['pyrocko.dataset.topo']),
('pyrocko', 'automap', ['pyrocko.plot.automap']),
('pyrocko', 'beachball', ['pyrocko.plot.beachball']),
('pyrocko', 'cake_plot', ['pyrocko.plot.cake_plot']),
('pyrocko', 'gmtpy', ['pyrocko.plot.gmtpy']),
('pyrocko', 'hudson', ['pyrocko.plot.hudson']),
('pyrocko', 'response_plot', ['pyrocko.plot.response']),
('pyrocko', 'snuffling', ['pyrocko.gui.snuffling']),
('pyrocko', 'pile_viewer', ['pyrocko.gui.pile_viewer']),
('pyrocko', 'marker', ['pyrocko.gui.marker']),
('pyrocko', 'snuffler', ['pyrocko.gui.snuffler']),
('pyrocko', 'gui_util', ['pyrocko.gui.util']),
]
for (package, compat_module, import_modules) in mapping:
module_code = '''
import sys
import pyrocko
if pyrocko.grumpy:
sys.stderr.write('using renamed pyrocko module: %s.%s\\n')
sys.stderr.write(' -> should now use: %s\\n\\n')
''' % (package, compat_module, ', '.join(import_modules)) + ''.join(
['from %s import *\n' % module for module in import_modules])
outfile = self.get_module_outfile(
self.build_lib, package.split('.'), compat_module)
dir = os.path.dirname(outfile)
self.mkpath(dir)
with open(outfile, 'w') as f:
f.write(module_code)
def run(self):
make_info_module(packname, version)
self.make_compat_modules()
build_py.run(self)
class CustomBuildExtCommand(build_ext):
def run(self):
make_prerequisites()
build_ext.run(self)
class CustomBuildAppCommand(build_ext):
def run(self):
self.make_app()
def make_app(self):
import glob
import os
import shutil
from setuptools import setup
APP = ['apps/snuffler']
DATA_FILES = []
OPTIONS = {
'argv_emulation': True,
'iconfile': 'src/data/snuffler.icns',
'packages': 'pyrocko',
'excludes': [
'PyQt4.QtDesigner',
'PyQt4.QtScript',
'PyQt4.QtScriptTools',
'PyQt4.QtTest',
'PyQt4.QtCLucene',
'PyQt4.QtDeclarative',
'PyQt4.QtHelp',
'PyQt4.QtSql',
'PyQt4.QtTest',
'PyQt4.QtXml',
'PyQt4.QtXmlPatterns',
'PyQt4.QtMultimedia',
'PyQt4.phonon',
'matplotlib.tests',
'matplotlib.testing'],
'plist': 'src/data/Info.plist'}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
# Manually delete files which refuse to be ignored using 'excludes':
want_delete = glob.glob(
'dist/snuffler.app/Contents/Frameworks/libvtk*')
map(os.remove, want_delete)
want_delete_dir = glob.glob(
'dist/Snuffler.app/Contents/Resources/lib/python2.7/'
'matplotlib/test*')
map(shutil.rmtree, want_delete_dir)
def _check_for_openmp():
"""Check whether the default compiler supports OpenMP.
This routine is adapted from pynbody // yt.
Thanks to Nathan Goldbaum and Andrew Pontzen.
"""
import distutils.sysconfig
import subprocess
tmpdir = tempfile.mkdtemp(prefix='pyrocko')
compiler = os.environ.get(
'CC', distutils.sysconfig.get_config_var('CC')).split()[0]
# Attempt to compile a test script.
# See http://openmp.org/wp/openmp-compilers/
tmpfile = pjoin(tmpdir, 'check_openmp.c')
with open(tmpfile, 'w') as f:
f.write('''
#include <omp.h>
#include <stdio.h>
int main() {
#pragma omp parallel
printf("Hello from thread %d", omp_get_thread_num());
}
''')
try:
with open(os.devnull, 'w') as fnull:
exit_code = subprocess.call([compiler, '-fopenmp', '-o%s'
% pjoin(tmpdir, 'check_openmp'),
tmpfile],
stdout=fnull, stderr=fnull)
except OSError:
exit_code = 1
finally:
shutil.rmtree(tmpdir)
if exit_code == 0:
print('Continuing your build using OpenMP...')
return True
import multiprocessing
import platform
if multiprocessing.cpu_count() > 1:
print('''WARNING
OpenMP support is not available in your default C compiler, even though
your machine has more than one core available.
Some routines in pyrocko are parallelized using OpenMP and these will
only run on one core with your current configuration.
''')
if platform.uname()[0] == 'Darwin':
print('''Since you are running on Mac OS, it's likely that the problem here
is Apple's Clang, which does not support OpenMP at all. The easiest
way to get around this is to download the latest version of gcc from
here: http://hpc.sourceforge.net. After downloading, just point the
CC environment variable to the real gcc and OpenMP support should
get enabled automatically. Something like this -
sudo tar -xzf /path/to/download.tar.gz /
export CC='/usr/local/bin/gcc'
python setup.py clean
python setup.py build
''')
print('Continuing your build without OpenMP...')
return False
if _check_for_openmp():
omp_arg = ['-fopenmp']
omp_lib = ['-lgomp']
else:
omp_arg = []
omp_lib = []
subpacknames = [
'pyrocko.gf',
'pyrocko.fomosto',
'pyrocko.fomosto.report',
'pyrocko.client',
'pyrocko.apps',
'pyrocko.io',
'pyrocko.model',
'pyrocko.plot',
'pyrocko.gui',
'pyrocko.gui.snufflings',
'pyrocko.gui.snufflings.map',
'pyrocko.dataset',
'pyrocko.dataset.topo',
'pyrocko.streaming',
'pyrocko.scenario',
'pyrocko.scenario.targets',
'pyrocko.scenario.sources',
'pyrocko.obspy_compat',
]
setup(
cmdclass={
'install': CustomInstallCommand,
'build_py': CustomBuildPyCommand,
# 'py2app': CustomBuildAppCommand,
'build_ext': CustomBuildExtCommand,
'check_multiple_install': CheckInstalls,
'install_prerequisites': InstallPrerequisits,
'uninstall': Uninstall,
},
name=packname,
version=version,
description='A versatile seismology toolkit for Python.',
author='The Pyrocko Developers',
author_email='[email protected]',
url='http://pyrocko.org',
license='GPLv3',
classifiers=[
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: C',
'Programming Language :: Python :: Implementation :: CPython',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Physics',
'Topic :: Scientific/Engineering :: Visualization',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Application Frameworks',
],
keywords=[
'seismology, waveform analysis, earthquake modelling, geophysics,'
' geophysical inversion'],
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, <4',
install_requires=[],
extras_require={
'gui_scripts': ['PyQt4'],
},
packages=[packname] + subpacknames,
package_dir={'pyrocko': 'src'},
ext_package=packname,
ext_modules=[
Extension(
'util_ext',
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'ext', 'util_ext.c')]),
Extension(
'signal_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'ext', 'signal_ext.c')]),
Extension(
'mseed_ext',
include_dirs=[get_python_inc(), numpy.get_include(),
get_build_include('libmseed/')],
library_dirs=[get_build_include('libmseed/')],
libraries=['mseed'],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'io', 'ext', 'mseed_ext.c')]),
Extension(
'evalresp_ext',
include_dirs=[get_python_inc(), numpy.get_include(),
get_build_include('evalresp-3.3.0/include/')],
library_dirs=[get_build_include('evalresp-3.3.0/lib/')],
libraries=['evresp'],
extra_compile_args=[
'-Wextra',
'-I%s' % get_build_include('evalresp-3.3.0/include')],
sources=[pjoin('src', 'ext', 'evalresp_ext.c')]),
Extension(
'ims_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'io', 'ext', 'ims_ext.c')]),
Extension(
'datacube_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'io', 'ext', 'datacube_ext.c')]),
Extension(
'autopick_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'ext', 'autopick_ext.c')]),
Extension(
'gf.store_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-D_FILE_OFFSET_BITS=64', '-Wextra'] + omp_arg,
extra_link_args=[] + omp_lib,
sources=[pjoin('src', 'gf', 'ext', 'store_ext.c')]),
Extension(
'parstack_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'] + omp_arg,
extra_link_args=[] + omp_lib,
sources=[pjoin('src', 'ext', 'parstack_ext.c')]),
Extension(
'ahfullgreen_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'ext', 'ahfullgreen_ext.c')]),
Extension(
'orthodrome_ext',
include_dirs=[get_python_inc(), numpy.get_include()],
extra_compile_args=['-Wextra'],
sources=[pjoin('src', 'ext', 'orthodrome_ext.c')]),
Extension(
"avl",
sources=[pjoin('src', 'ext', 'pyavl-1.12', 'avl.c'),
pjoin('src', 'ext', 'pyavl-1.12', 'avlmodule.c')],
define_macros=[('HAVE_AVL_VERIFY', None),
('AVL_FOR_PYTHON', None)],
include_dirs=[get_python_inc()],
extra_compile_args=['-Wno-parentheses', '-Wno-uninitialized'],
extra_link_args=[] if sys.platform != 'sunos5' else ['-Wl,-x']),
],
scripts=[
'src/apps/gmtpy-epstopdf',
],
entry_points={
'console_scripts':
['fomosto = pyrocko.apps.fomosto:main',
'cake = pyrocko.apps.cake:main',
'automap = pyrocko.apps.automap:main',
'hamster = pyrocko.apps.hamster:main',
'jackseis = pyrocko.apps.jackseis:main',
'colosseo = pyrocko.apps.colosseo:main'],
'gui_scripts':
['snuffler = pyrocko.apps.snuffler:main']
},
package_data={
packname: ['data/*.png',
'data/*.html',
'data/earthmodels/*.nd',
'data/colortables/*.cpt',
'data/tectonics/*.txt',
'data/fomosto_report/gfreport.*',
'gui/snufflings/map/*ml',
'gui/snufflings/map/*.js',
] + get_readme_paths()}
)