forked from GalSim-developers/GalSim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
1455 lines (1277 loc) · 57 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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2012-2023 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
import sys,os,glob,re
import platform
import ctypes
import ctypes.util
import types
import subprocess
import re
import tempfile
import urllib.request as urllib2
import tarfile
import shutil
try:
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from setuptools.command.build_clib import build_clib
from setuptools.command.install import install
from setuptools.command.install_scripts import install_scripts
from setuptools.command.easy_install import easy_install
from setuptools.command.test import test
import setuptools
print("Using setuptools version",setuptools.__version__)
except ImportError:
print()
print("****")
print(" Installation requires setuptools version >= 38.")
print(" Please upgrade or install with pip install -U setuptools")
print("****")
print()
raise
# Turn this on for more verbose debugging output about compile attempts.
debug = False
print('Python version = ',sys.version)
py_version = "%d.%d"%sys.version_info[0:2] # we check things based on the major.minor version.
scripts = ['galsim', 'galsim_download_cosmos']
scripts = [ os.path.join('bin',f) for f in scripts ]
def all_files_from(dir, ext=''):
files = []
for root, dirnames, filenames in os.walk(dir):
for filename in filenames:
if filename.endswith(ext) and not filename.startswith('.'):
files.append(os.path.join(root, filename))
return files
py_sources = all_files_from('pysrc', '.cpp')
cpp_sources = all_files_from('src', '.cpp')
test_sources = all_files_from('tests', '.cpp')
headers = all_files_from('include')
inst = all_files_from('src', '.inst')
shared_data = all_files_from('share')
copt = {
'gcc' : ['-O2','-std=c++11','-fvisibility=hidden','-fopenmp'],
'gcc w/ GPU' : ['-O2','-std=c++11','-fvisibility=hidden','-fopenmp','-foffload=nvptx-none','-DGALSIM_USE_GPU'],
'icc' : ['-O2','-vec-report0','-std=c++11','-openmp'],
'clang' : ['-O2','-std=c++11',
'-Wno-shorten-64-to-32','-fvisibility=hidden','-stdlib=libc++'],
'clang w/ OpenMP' : ['-O2','-std=c++11','-fopenmp',
'-Wno-shorten-64-to-32','-fvisibility=hidden','-stdlib=libc++'],
'clang w/ Intel OpenMP' : ['-O2','-std=c++11','-Xpreprocessor','-fopenmp',
'-Wno-shorten-64-to-32','-fvisibility=hidden','-stdlib=libc++'],
'clang w/ manual OpenMP' : ['-O2','-std=c++11','-Xpreprocessor','-fopenmp',
'-Wno-shorten-64-to-32','-fvisibility=hidden','-stdlib=libc++'],
'clang w/ GPU' : ['-O2','-msse2','-std=c++11','-fopenmp','-fopenmp-targets=nvptx64-nvidia-cuda',
'-Wno-openmp-mapping','-Wno-unknown-cuda-version',
'-Wno-shorten-64-to-32','-fvisibility=hidden', '-DGALSIM_USE_GPU'],
'nvc++' : ['-O2','-std=c++11','-mp=gpu','-DGALSIM_USE_GPU'],
'unknown' : [],
}
lopt = {
'gcc' : ['-fopenmp'],
'gcc w/ GPU' : ['-fopenmp','-foffload=nvptx-none', '-foffload=-lm'],
'icc' : ['-openmp'],
'clang' : ['-stdlib=libc++'],
'clang w/ OpenMP' : ['-stdlib=libc++','-fopenmp'],
'clang w/ Intel OpenMP' : ['-stdlib=libc++','-liomp5'],
'clang w/ manual OpenMP' : ['-stdlib=libc++','-lomp'],
'clang w/ GPU' : ['-fopenmp','-fopenmp-targets=nvptx64-nvidia-cuda',
'-Wno-openmp-mapping','-Wno-unknown-cuda-version'],
'nvc++' : ['-mp=gpu'],
'unknown' : [],
}
# If we build with debug, undefine NDEBUG flag
# Note: setuptools stopped allowing --debug, so if we need this, we'll need to find another
# mechanism.
undef_macros = []
if "--debug" in sys.argv:
undef_macros+=['NDEBUG']
for name in copt.keys():
if name != 'unknown':
copt[name].append('-g')
copt[name].append('-DMEM_TEST')
else:
# Including mmgr.cpp in the library leads to problems if the other files don't
# include mmgr.h. So remove it.
cpp_sources.remove('src/mmgr.cpp')
# Verbose is the default for setuptools logging, but if it's on the command line, we take it
# to mean that we should also be verbose.
if "--debug" in sys.argv or "--verbose" in sys.argv:
debug = True
local_tmp = 'tmp'
def get_compiler_type(compiler, check_unknown=True, output=False):
"""Try to figure out which kind of compiler this really is.
In particular, try to distinguish between clang and gcc, either of which may
be called cc or gcc.
"""
if debug: output=True
cc = compiler.compiler_so[0]
if cc == 'ccache':
cc = compiler.compiler_so[1]
cmd = [cc,'--version']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = p.stdout.readlines()
if output:
print('compiler version information: ')
for line in lines:
print(line.decode().strip())
# Python3 needs this decode bit.
# Python2.7 doesn't need it, but it works fine.
line = lines[0].decode(encoding='UTF-8')
if line.startswith('Configured'):
line = lines[1].decode(encoding='UTF-8')
# nvc++ version info starts with a blank line
if line.strip() == "":
line = lines[1].decode(encoding='UTF-8')
if 'clang' in line:
# clang 3.7 is the first with openmp support. But Apple lies about the version
# number of clang, so the most reliable thing to do is to just try the compilation
# with the openmp flag and see if it works.
if output:
print('Compiler is Clang. Checking if it is a version that supports OpenMP.')
if supports_gpu(compiler, 'clang w/ GPU'):
if output:
print("Yay! This version of clang supports GPU!")
return 'clang w/ GPU'
elif try_openmp(compiler, 'clang w/ OpenMP'):
if output:
print("Yay! This version of clang supports OpenMP!")
return 'clang w/ OpenMP'
elif try_openmp(compiler, 'clang w/ Intel OpenMP'):
if output:
print("Yay! This version of clang supports OpenMP!")
return 'clang w/ Intel OpenMP'
elif try_openmp(compiler, 'clang w/ manual OpenMP'):
if output:
print("Yay! This version of clang supports OpenMP!")
return 'clang w/ manual OpenMP'
else:
if output:
print("\nSorry. This version of clang doesn't seem to support OpenMP.\n")
print("If you think it should, you can use `python setup.py build --debug`")
print("to get more information about the commands that failed.")
print("You might need to add something to your C_INCLUDE_PATH or LIBRARY_PATH")
print("(and probabaly LD_LIBRARY_PATH) to get it to work.\n")
return 'clang'
elif 'gcc' in line or 'GCC' in line:
if supports_gpu(compiler, 'gcc w/ GPU'):
if output:
print("Yay! This version of gcc supports GPU!")
return 'gcc w/ GPU'
return 'gcc'
elif 'nvc++' in line or 'nvcc' in line or 'NVIDIA' in line:
return 'nvc++'
elif 'clang' in cc:
return 'clang'
elif 'gcc' in cc or 'g++' in cc:
return 'gcc'
elif 'icc' in cc or 'icpc' in cc:
return 'icc'
elif check_unknown:
# OK, the main thing we need to know is what openmp flag we need for this compiler,
# so let's just try the various options and see what works. Don't try icc, since
# the -openmp flag there gets treated as '-o penmp' by gcc and clang, which is bad.
# Plus, icc should be detected correctly by the above procedure anyway.
if output:
print('Unknown compiler.')
for cc_type in ['gcc', 'clang w/ OpenMP', 'clang w/ manual OpenMP', 'clang w/ Intel OpenMP',
'clang']:
if output:
print('Check if the compiler works like ',cc_type)
if try_openmp(compiler, cc_type):
return cc_type
# I guess none of them worked. Now we really do have to bail.
if output:
print("None of these compile options worked. Not adding any optimization flags.")
return 'unknown'
else:
return 'unknown'
# Check whether this build of Clang supports offloading to GPU via OpenMP
def supports_gpu(compiler, cc_type):
cpp_code = """
#include <iostream>
#define N 500
int main() {
double arrA[N], arrB[N], arrC[N];
for (int i = 0; i < N; i++) {
arrA[i] = (double)i;
arrB[i] = 1.0;
}
#ifdef _OPENMP
#pragma omp target teams distribute parallel for
#endif
for (int i = 0; i < N; i++) {
arrC[i] = arrA[i] * arrB[i];
}
double sum = 0.0;
for (int i = 0; i < N; i++) {
sum += arrC[i];
}
std::cout << "Sum=" << sum << std::endl;
return 0;
}
"""
extra_cflags = copt[cc_type]
extra_lflags = lopt[cc_type]
return try_compile(cpp_code, compiler, extra_cflags, extra_lflags)
# Check for the fftw3 library in some likely places
def find_fftw_lib(output=False):
import distutils.sysconfig
if debug: output = True
try_libdirs = []
# Start with the explicit FFTW_DIR, if present.
if 'FFTW_DIR' in os.environ:
try_libdirs.append(os.environ['FFTW_DIR'])
try_libdirs.append(os.path.join(os.environ['FFTW_DIR'],'lib'))
# Add the python system library directory.
try_libdirs.append(distutils.sysconfig.get_config_var('LIBDIR'))
# If using Anaconda, add their lib dir in case fftw is installed there.
# (With envs, this might be different than the sysconfig LIBDIR.)
if 'CONDA_PREFIX' in os.environ:
try_libdirs.append(os.path.join(os.environ['CONDA_PREFIX'],'lib'))
# Try some standard locations where things get installed
try_libdirs.extend(['/usr/local/lib', '/usr/lib'])
if sys.platform == "darwin":
try_libdirs.extend(['/sw/lib', '/opt/local/lib'])
# Check the directories in LD_LIBRARY_PATH. This doesn't work on OSX >= 10.11
for path in ['LIBRARY_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']:
if path in os.environ:
for dir in os.environ[path].split(':'):
try_libdirs.append(dir)
# The user's home directory is often a good place to check.
try_libdirs.append(os.path.join(os.path.expanduser("~"),"lib"))
# If the above don't work, the fftw3 module may have the right directory.
try:
import fftw3
try_libdirs.append(fftw3.lib.libdir)
except ImportError:
pass
if sys.platform == "darwin":
lib_ext = '.dylib'
else:
lib_ext = '.so'
name = 'libfftw3' + lib_ext
if output: print("Looking for ",name)
tried_dirs = set() # Keep track, so we don't try the same thing twice.
for dir in try_libdirs:
if dir == '': continue # This messes things up if it's in there.
if dir in tried_dirs: continue
else: tried_dirs.add(dir)
if not os.path.isdir(dir): continue
libpath = os.path.join(dir, name)
if not os.path.isfile(libpath): continue
if output: print(" ", dir, end='')
try:
lib = ctypes.cdll.LoadLibrary(libpath)
if output: print(" (yes)")
return libpath
except OSError as e:
if output: print(" (no)")
# Some places use lib64 rather than/in addition to lib. Try that as well.
if dir.endswith('lib') and os.path.isdir(dir + '64'):
dir += '64'
try:
libpath = os.path.join(dir, name)
if not os.path.isfile(libpath): continue
lib = ctypes.cdll.LoadLibrary(libpath)
if output: print(" ", dir, " (yes)")
return libpath
except OSError:
pass
# If we didn't find it anywhere, but the user has set FFTW_DIR, trust it.
if 'FFTW_DIR' in os.environ:
libpath = os.path.join(os.environ['FFTW_DIR'], name)
print("WARNING:")
print("Could not find an installed fftw3 library named %s"%(name))
print("Trusting the provided FFTW_DIR=%s for the library location."%(libpath))
print("If this is incorrect, you may have errors later when linking.")
return libpath
# Last ditch attempt. Use ctypes.util.find_library, which sometimes manages to find it
# when the above attempts fail.
try:
libpath = ctypes.util.find_library('fftw3')
if libpath == None:
raise OSError
if os.path.split(libpath)[0] == '':
# If the above doesn't return a real path, try this instead.
libpath = ctypes.util._findLib_gcc('fftw3')
if libpath == None:
raise OSError
libpath = os.path.realpath(libpath)
lib = ctypes.cdll.LoadLibrary(libpath)
except Exception as e:
print("Could not find fftw3 library. Make sure it is installed either in a standard ")
print("location such as /usr/local/lib, or the installation directory is either in ")
print("your LIBRARY_PATH or FFTW_DIR environment variable.")
raise
else:
dir, name = os.path.split(libpath)
if output:
if dir == '': dir = '[none]'
print(" ", dir, " (yes)")
return libpath
# Check for Eigen in some likely places
def find_eigen_dir(output=False):
if debug: output = True
import distutils.sysconfig
try_dirs = []
# Start with a user-specified directory.
if 'EIGEN_DIR' in os.environ:
try_dirs.append(os.environ['EIGEN_DIR'])
try_dirs.append(os.path.join(os.environ['EIGEN_DIR'], 'include'))
# Add the python system include directory.
try_dirs.append(distutils.sysconfig.get_config_var('INCLUDEDIR'))
# If using Anaconda, add their lib dir in case fftw is installed there.
# (With envs, this might be different than the sysconfig LIBDIR.)
if 'CONDA_PREFIX' in os.environ:
try_dirs.append(os.path.join(os.environ['CONDA_PREFIX'],'lib'))
# Some standard install locations:
try_dirs.extend(['/usr/local/include', '/usr/include'])
if sys.platform == "darwin":
try_dirs.extend(['/sw/include', '/opt/local/include'])
# Also if there is a C_INCLUDE_PATH, check those dirs.
for path in ['C_INCLUDE_PATH']:
if path in os.environ:
for dir in os.environ[path].split(':'):
try_dirs.append(dir)
# Finally, (last resort) check our own download of eigen.
if os.path.isdir('downloaded_eigen'):
try_dirs.extend(glob.glob(os.path.join('downloaded_eigen','*')))
if output: print("Looking for Eigen:")
for dir in try_dirs:
if dir is None: continue
if not os.path.isdir(dir): continue
if output: print(" ", dir, end='')
if os.path.isfile(os.path.join(dir, 'Eigen/Core')):
if output: print(" (yes)")
return dir
if os.path.isfile(os.path.join(dir, 'eigen3', 'Eigen/Core')):
dir = os.path.join(dir, 'eigen3')
if output:
# Only print this if the eigen3 addition was key to finding it.
print("\n ", dir, " (yes)")
return dir
if output: print(" (no)")
if output:
print("Could not find Eigen in any of the standard locations.")
print("Will now try to download it from gitlab.com. This requires an internet")
print("connection, so it will fail if you are currently offline.")
print("If Eigen is installed in a non-standard location, and you want to use that")
print("instead, you should make sure the right directory is either in your")
print("C_INCLUDE_PATH or specified in an EIGEN_DIR environment variable.")
try:
dir = 'downloaded_eigen'
if os.path.isdir(dir):
# If this exists, it was tried above and failed. Something must be wrong with it.
print("Previous attempt to download eigen found. Deleting and trying again.")
shutil.rmtree(dir)
os.mkdir(dir)
url = 'https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.bz2'
if output:
print("Downloading eigen from ",url)
# Unfortunately, gitlab doesn't allow direct downloads. We need to spoof the request
# so it thinks we're a web browser.
# cf. https://stackoverflow.com/questions/42863240/how-to-get-round-the-http-error-403-forbidden-with-urllib-request-using-python
page=urllib2.Request(url,headers={'User-Agent': 'Mozilla/5.0'})
data=urllib2.urlopen(page).read()
fname = 'eigen.tar.bz2'
with open(fname, 'wb') as f:
f.write(data)
if output:
print("Downloaded %s. Unpacking tarball."%fname)
with tarfile.open(fname) as tar:
def is_within_directory(directory, target):
abs_directory = os.path.abspath(directory)
abs_target = os.path.abspath(target)
prefix = os.path.commonprefix([abs_directory, abs_target])
return prefix == abs_directory
def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
# Avoid security vulnerability in tar.extractall function.
# This bit of code was added by the Advanced Research Center at Trellix in PR #1188.
# For more information about the security vulnerability, see
# https://github.com/advisories/GHSA-gw9q-c7gh-j9vm
for member in tar.getmembers():
member_path = os.path.join(path, member.name)
if not is_within_directory(path, member_path):
raise Exception("Attempted Path Traversal in Tar File")
tar.extractall(path, members, numeric_owner=numeric_owner)
safe_extract(tar, dir)
os.remove(fname)
# This actually extracts into a subdirectory with a name eigen-eigen-5a0156e40feb/
# I'm not sure if that name is reliable, so use glob to get it.
dir = glob.glob(os.path.join(dir,'*'))[0]
if os.path.isfile(os.path.join(dir, 'Eigen/Core')):
return dir
elif output:
print("Downloaded eigen, but it didn't have the expected Eigen/Core file.")
except Exception as e:
if output:
print("Error encountered while downloading Eigen from the internet")
print(e)
raise OSError("Could not find Eigen")
def try_compile(cpp_code, compiler, cflags=[], lflags=[], prepend=None, check_warning=False):
"""Check if compiling some code with the given compiler and flags works properly.
"""
# Put the temporary files in a local tmp directory, so that they stick around after failures.
if not os.path.exists(local_tmp): os.makedirs(local_tmp)
# We delete these manually if successful. Otherwise, we leave them in the tmp directory
# so the user can troubleshoot the problem if they were expecting it to work.
with tempfile.NamedTemporaryFile(delete=False, suffix='.cpp', dir=local_tmp) as cpp_file:
cpp_file.write(cpp_code.encode())
cpp_name = cpp_file.name
# Just get a named temporary file to write to:
with tempfile.NamedTemporaryFile(delete=False, suffix='.o', dir=local_tmp) as o_file:
o_name = o_file.name
# Another named temporary file for the executable
with tempfile.NamedTemporaryFile(delete=False, suffix='.exe', dir=local_tmp) as exe_file:
exe_name = exe_file.name
# Try compiling with the given flags
cc = [compiler.compiler_so[0]]
if prepend:
cc = [prepend] + cc
cmd = cc + compiler.compiler_so[1:] + cflags + ['-c',cpp_name,'-o',o_name]
if debug:
print('cmd = ',' '.join(cmd))
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = p.stdout.readlines()
p.communicate()
if debug and p.returncode != 0:
print('Trying compile command:')
print(' '.join(cmd))
print('Output was:')
print(' ',b' '.join(lines).decode())
returncode = p.returncode
if check_warning:
output = b' '.join(lines).decode()
if 'warning' in output:
returncode = 1
except OSError as e:
if debug:
print('Trying compile command:')
print(cmd)
print('Caught error: ',repr(e))
returncode = 1
if returncode != 0:
# Don't delete files in case helpful for troubleshooting.
return False
# Link
cc = compiler.linker_so[0]
cmd = [cc] + compiler.linker_so[1:] + lflags + [o_name,'-o',exe_name]
if debug:
print('cmd = ',' '.join(cmd))
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = p.stdout.readlines()
p.communicate()
if debug and p.returncode != 0:
print('Trying link command:')
print(' '.join(cmd))
print('Output was:')
#print(' ',b' '.join(lines).decode())
print(' ',b' '.join(lines))
returncode = p.returncode
except OSError as e:
if debug:
print('Trying link command:')
print(' '.join(cmd))
print('Caught error: ',repr(e))
returncode = 1
if returncode:
# The linker needs to be a c++ linker, which isn't 'cc'. However, I couldn't figure
# out how to get setup.py to tell me the actual command to use for linking. All the
# executables available from build_ext.compiler.executables are 'cc', not 'c++'.
# I think this must be related to the bugs about not handling c++ correctly.
# http://bugs.python.org/issue9031
# http://bugs.python.org/issue1222585
# So just switch it manually and see if that works.
if 'clang' in cc:
cpp = cc.replace('clang', 'clang++')
elif 'icc' in cc:
cpp = cc.replace('icc', 'icpc')
elif 'gcc' in cc:
cpp = cc.replace('gcc', 'g++')
elif ' cc' in cc:
cpp = cc.replace(' cc', ' c++')
elif cc == 'cc':
cpp = 'c++'
else:
comp_type = get_compiler_type(compiler)
if comp_type == 'gcc':
cpp = 'g++'
elif comp_type == 'clang':
cpp = 'clang++'
elif comp_type == 'icc':
cpp = 'g++'
else:
cpp = 'c++'
# Finally, if GALSIM_CXX is in the environment, let that take precedence.
# (I don't know if it's safe to use a user's CXX always, so make sure the user really
# meant to direct GalSim to use some other compiler by requiring the GALSIM prefix.)
cpp = os.environ.get('GALSIM_CXX', cpp)
cmd = [cpp] + compiler.linker_so[1:] + lflags + [o_name,'-o',exe_name]
if debug:
print('cmd = ',' '.join(cmd))
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = p.stdout.readlines()
p.communicate()
if debug and p.returncode != 0:
print('Trying link command:')
print(' '.join(cmd))
print('Output was:')
#print(' ',b' '.join(lines).decode())
print(' ',b' '.join(lines))
returncode = p.returncode
except OSError as e:
if debug:
print('Trying to link using command:')
print(' '.join(cmd))
print('Caught error: ',repr(e))
returncode = 1
# Remove the temp files
if returncode != 0:
# Don't delete files in case helpful for troubleshooting.
return False
else:
os.remove(cpp_name)
os.remove(o_name)
if os.path.exists(exe_name):
os.remove(exe_name)
return True
def try_openmp(compiler, cc_type):
"""
If cc --version is not helpful, the last resort is to try each compiler type and see
if it works.
"""
cpp_code = """
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include "omp.h"
#endif
int get_max_threads() {
#ifdef _OPENMP
return omp_get_max_threads();
#else
return 1;
#endif
}
int main() {
int n = 500;
std::vector<double> x(n,0.);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) x[i] = 2*i+1;
double sum = 0.;
for (int i=0; i<n; ++i) sum += x[i];
// Sum should be n^2 = 250000
std::cout<<get_max_threads()<<" "<<sum<<std::endl;
return 0;
}
"""
extra_cflags = copt[cc_type]
extra_lflags = lopt[cc_type]
success = try_compile(cpp_code, compiler, extra_cflags, extra_lflags)
if not success:
# In case libc++ doesn't work, try letting the system use the default stdlib
try:
extra_cflags.remove('-stdlib=libc++')
extra_lflags.remove('-stdlib=libc++')
except (AttributeError, ValueError):
pass
else:
success = try_compile(cpp_code, compiler, extra_cflags, extra_lflags)
return success
def try_cpp(compiler, cflags=[], lflags=[], prepend=None):
"""Check if compiling a simple bit of c++ code with the given compiler works properly.
"""
from textwrap import dedent
cpp_code = dedent("""
#include <iostream>
#include <vector>
int main() {
int n = 500;
std::vector<double> x(n,0.);
for (int i=0; i<n; ++i) x[i] = 2*i+1;
double sum=0.;
for (int i=0; i<n; ++i) sum += x[i];
return sum;
}
""")
return try_compile(cpp_code, compiler, cflags, lflags, prepend=prepend)
def try_cpp11(compiler, cflags=[], lflags=[], check_warning=False):
"""Check if compiling c++11 code with the given compiler works properly.
"""
from textwrap import dedent
cpp_code = dedent("""
#include <iostream>
#include <forward_list>
#include <cmath>
int main(void) {
std::cout << std::tgamma(1.3) << std::endl;
return 0;
}
""")
return try_compile(cpp_code, compiler, cflags, lflags, check_warning=check_warning)
def cpu_count():
"""Get the number of cpus
"""
try:
import psutil
return psutil.cpu_count()
except ImportError:
pass
if hasattr(os, 'sysconf'):
if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf('SC_NPROCESSORS_ONLN')
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else: # OSX:
p = subprocess.Popen(['sysctl -n hw.ncpu'],stdout=subprocess.PIPE,shell=True)
return int(p.stdout.read().strip())
# Windows:
if 'NUMBER_OF_PROCESSORS' in os.environ:
ncpus = int(os.environ['NUMBER_OF_PROCESSORS'])
if ncpus > 0:
return ncpus
return 1 # Default
def parallel_compile(self, sources, output_dir=None, macros=None,
include_dirs=None, debug=0, extra_preargs=None,
extra_postargs=None, depends=None):
"""New compile function that we monkey patch into the existing compiler instance.
"""
import multiprocessing.pool
# Copied from the regular compile function
macros, objects, extra_postargs, pp_opts, build = \
self._setup_compile(output_dir, macros, include_dirs, sources,
depends, extra_postargs)
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
def _single_compile(obj):
try:
src, ext = build[obj]
except KeyError:
return
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
# Set by fix_compiler
global glob_use_njobs
if glob_use_njobs == 1:
# This is equivalent to regular compile function
for obj in objects:
_single_compile(obj)
else:
# Use ThreadPool, rather than Pool, since the objects are picklable.
pool = multiprocessing.pool.ThreadPool(glob_use_njobs)
pool.map(_single_compile, objects)
pool.close()
pool.join()
# Return *all* object filenames, not just the ones we just built.
return objects
def fix_compiler(compiler, njobs):
# Remove any -Wstrict-prototypes in the compiler flags (since invalid for C++)
try:
compiler.compiler_so.remove("-Wstrict-prototypes")
except (AttributeError, ValueError):
pass
# nvc++ doesn't support -Wno-unused-result
try:
compiler.compiler_so.remove("-Wno-unused-result")
except (AttributeError, ValueError):
pass
# Figure out what compiler it will use
comp_type = get_compiler_type(compiler, output=True)
cc = compiler.compiler_so[0]
already_have_ccache = False
if cc == 'ccache':
already_have_ccache = True
cc = compiler.compiler_so[1]
if cc == comp_type:
print('Using compiler %s'%(cc))
else:
print('Using compiler %s, which is %s'%(cc,comp_type))
# Make sure the compiler works with a simple c++ code
if not try_cpp(compiler):
# One failure mode is that sometimes there is a -B /path/to/compiler_compat
# which can cause problems. If we get here, try removing that.
success = False
if '-B' in compiler.linker_so:
for i in range(len(compiler.linker_so)):
if (compiler.linker_so[i] == '-B' and
'compiler_compat' in compiler.linker_so[i+1]):
print('Removing potentially problematic -B compiler_compat flags')
del compiler.linker_so[i:i+2]
success = try_cpp(compiler)
break
if not success:
print("There seems to be something wrong with the compiler or cflags")
print(str(compiler.compiler_so))
raise OSError("Compiler does not work for compiling C++ code")
# Check if we can use ccache to speed up repeated compilation.
if not already_have_ccache and try_cpp(compiler, prepend='ccache'):
print('Using ccache')
compiler.set_executable('compiler_so', ['ccache'] + compiler.compiler_so)
if njobs > 1:
# Global variable for tracking the number of jobs to use.
# We can't pass this to parallel compile, since the signature is fixed.
# So if using parallel compile, set this value to use within parallel compile.
global glob_use_njobs
glob_use_njobs = njobs
compiler.compile = types.MethodType(parallel_compile, compiler)
extra_cflags = copt[comp_type]
extra_lflags = lopt[comp_type]
success = try_cpp11(compiler, extra_cflags, extra_lflags)
if not success:
# In case libc++ doesn't work, try letting the system use the default stdlib
try:
extra_cflags.remove('-stdlib=libc++')
extra_lflags.remove('-stdlib=libc++')
except (AttributeError, ValueError):
pass
else:
success = try_cpp11(compiler, extra_cflags, extra_lflags)
if not success:
print('The compiler %s with flags %s did not successfully compile C++11 code'%
(cc, ' '.join(extra_cflags)))
raise OSError("Compiler is not C++-11 compatible")
# Also see if adding -msse2 works (and doesn't give a warning)
if '-msse2' not in extra_cflags:
extra_cflags.append('-msse2')
if try_cpp11(compiler, extra_cflags, extra_lflags, check_warning=True):
print('Using cflag -msse2')
else:
print('warning with -msse2.')
extra_cflags.remove('-msse2')
# If doing develop installation, it's important for the build directory to be before any
# other directories. Particularly ones that might have another version of GalSim installed.
# Otherwise the wrong library can be linked, which leads to errors.
# So, make sure that the -Lbuild/... directive happens first among any -L directives in
# the link flags.
linker_so = compiler.linker_so
# Find the first -L flag among the current flags (if any)
for i, flag in enumerate(linker_so):
if flag.startswith('-L'):
print('Found link: ',i,flag)
break
else:
i = len(linker_so)
# Insert -Llib for any libs that are in build directory, to make sure they are first.
linker_so[i:i] = ['-L' + l for l in compiler.library_dirs if l.startswith('build')]
# Copy this list back to the compiler object
compiler.set_executable('linker_so', linker_so)
# Return the extra cflags, since those will be added to the build step in a different place.
print('Using extra flags ',extra_cflags)
return extra_cflags, extra_lflags
def add_dirs(builder, output=False):
if debug: output = True
# We need to do most of this both for build_clib and build_ext, so separate it out here.
# First some basic ones we always need.
builder.include_dirs.append('include')
builder.include_dirs.append('include/galsim')
import numpy
builder.include_dirs.append(numpy.get_include())
# Look for fftw3.
fftw_lib = find_fftw_lib(output=output)
fftw_libpath, fftw_libname = os.path.split(fftw_lib)
if hasattr(builder, 'library_dirs'):
if fftw_libpath != '':
builder.library_dirs.append(fftw_libpath)
fftw_include = os.path.join(os.path.split(fftw_libpath)[0], 'include')
if os.path.isfile(os.path.join(fftw_include, 'fftw3.h')):
print('Include directory for fftw3 is ',fftw_include)
# Usually, the fftw3.h file is in an associated include dir, but not always.
builder.include_dirs.append(fftw_include)
else:
# If not, we have our own copy of fftw3.h here.
print('Using local copy of fftw3.h')
builder.include_dirs.append('include/fftw3')
# Look for Eigen/Core
eigen_dir = find_eigen_dir(output=output)
builder.include_dirs.append(eigen_dir)
# Finally, add pybind11's include dir
import pybind11
print('PyBind11 is version ',pybind11.__version__)
print('Looking for pybind11 header files: ')
locations = [pybind11.get_include(user=True),
pybind11.get_include(user=False),
'/usr/include',
'/usr/local/include',
None]
for try_dir in locations:
if try_dir is None:
# Last time through, raise an error.
print("Could not find pybind11 header files.")
print("They should have been in one of the following locations:")
for l in locations:
if l is not None:
print(" ", l)
raise OSError("Could not find PyBind11")
print(' ',try_dir,end='')
if os.path.isfile(os.path.join(try_dir, 'pybind11/pybind11.h')):
print(' (yes)')
builder.include_dirs.append(try_dir)
break
else:
print(' (no)')
def parse_njobs(njobs, task=None, command=None, maxn=4):
"""Helper function to parse njobs, which may be None (use ncpu) or an int.
Returns an int value for njobs
"""
if njobs is None:
njobs = cpu_count()
if maxn != None and njobs > maxn:
# Usually 4 is plenty. Testing with too many jobs tends to lead to
# memory and timeout errors. The user can bump this up if they want.
njobs = maxn
if task is not None:
if njobs == 1:
print('Using a single process for %s.'%task)
else:
print('Using %d cpus for %s'%(njobs,task))
print('To override, you may do python setup.py %s -jN'%command)
else:
njobs = int(njobs)
if task is not None:
if njobs == 1:
print('Using a single process for %s.'%task)
else:
print('Using %d cpus for %s'%(njobs,task))
return njobs
do_output = True # Keep track of whether we used output=True in add_dirs yet.
# It seems that different installation methods do things in different order,
# but we only want to output on the first pass through add_dirs.
# (Unless debug = True, then also output in the second pass.)
# Make a subclass of build_ext so we can add to the -I list.
class my_build_clib(build_clib):
user_options = build_ext.user_options + [('njobs=', 'j', "Number of jobs to use for compiling")]
def initialize_options(self):
build_clib.initialize_options(self)
self.njobs = None
def finalize_options(self):
global do_output
build_clib.finalize_options(self)
if self.njobs is None and 'glob_njobs' in globals():
global glob_njobs
self.njobs = glob_njobs
add_dirs(self, output=do_output)
do_output = False
# Add any extra things based on the compiler being used..
def build_libraries(self, libraries):
build_ext = self.distribution.get_command_obj('build_ext')
njobs = parse_njobs(self.njobs, 'compiling', 'install')
cflags, lflags = fix_compiler(self.compiler, njobs)
# Add the appropriate extra flags for that compiler.
for (lib_name, build_info) in libraries:
build_info['cflags'] = build_info.get('cflags',[]) + cflags
build_info['lflags'] = build_info.get('lflags',[]) + lflags
self.do_build_libraries(libraries)
def do_build_libraries(self, libraries):
# This version just calls the setuptools build_libraries function.
# We'll change this for build_shared_clib below.
build_clib.build_libraries(self, libraries)
class my_build_shared_clib(my_build_clib):
def do_build_libraries(self, libraries):
from distutils.errors import DistutilsSetupError
from distutils import log
from setuptools.dep_util import newer_pairwise_group