-
Notifications
You must be signed in to change notification settings - Fork 0
/
SConstruct
1859 lines (1569 loc) · 65.9 KB
/
SConstruct
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
#
# SConstruct for FDNT/, generates the _fdnt python library (among other
# objects and executables)
#
# Heavily copied from Mike Jarvis' SConstruct/SConscript files from GalSim.
#
import os
import sys
import SCons
import platform
import distutils.sysconfig
from sys import stdout,stderr
print 'SCons is version',SCons.__version__,'using python version',platform.python_version()
print "Python is from", distutils.sysconfig.get_python_inc()
# Require SCons version >= 1.1
# (This is the earliest version I could find to test on. Probably works with 1.0.)
EnsureSConsVersion(1, 1)
# Subdirectories containing SConscript files. We always process these, but
# there are some other optional ones
subdirs=['src', 'pysrc', 'fdnt',]
# Configurations will be saved here so command line options don't
# have to be sent more than once
config_file = 'fdnt_scons.conf'
# Default directory for installation.
# This is the only UNIX specific things I am aware
# of in the script. On the other hand, these are not required for the
# script to work since prefix can be set on the command line and the
# extra paths are not needed, but I wish I knew how to get the default
# prefix for the system so I didn't have to set this.
# MJ: Is there a python function that might return this in a more platform-independent way?
default_prefix = '/usr/local'
default_python = '/usr/bin/env python'
default_cxx = 'c++'
# first check for a saved conf file
opts = Variables(config_file)
# Now set up options for the command line
opts.Add('CXX','Name of c++ compiler', default_cxx)
opts.Add('FLAGS','Compiler flags to send to use instead of the automatic ones','')
opts.Add('EXTRA_FLAGS','Extra compiler flags to use in addition to automatic ones','')
opts.Add('LINKFLAGS','Additional flags to use when linking','')
opts.Add(BoolVariable('DEBUG','Turn on debugging statements',True))
opts.Add(BoolVariable('EXTRA_DEBUG','Turn on extra debugging info',False))
opts.Add(BoolVariable('WARN','Add warning compiler flags, like -Wall', False))
opts.Add('PYTHON','Name of python executable','')
opts.Add(BoolVariable('WITH_UPS','Install ups/ directory for use with EUPS', False))
opts.Add(PathVariable('PREFIX','prefix for installation',
'', PathVariable.PathAccept))
opts.Add(PathVariable('PYPREFIX','location of your site-packages directory',
'', PathVariable.PathAccept))
opts.Add(PathVariable('FINAL_PREFIX',
'final installation prefix if different from PREFIX',
'', PathVariable.PathAccept))
opts.Add('TMV_DIR','Explicitly give the tmv prefix','')
opts.Add('TMV_LINK','File that contains the linking instructions for TMV','')
opts.Add('FFTW_DIR','Explicitly give the fftw3 prefix','')
opts.Add('BOOST_DIR','Explicitly give the boost prefix','')
opts.Add('CCFITS_DIR','Explicitly give the CCfits prefix','')
opts.Add(PathVariable('EXTRA_INCLUDE_PATH',
'Extra paths for header files (separated by : if more than 1)',
'', PathVariable.PathAccept))
opts.Add(PathVariable('EXTRA_LIB_PATH',
'Extra paths for linking (separated by : if more than 1)',
'', PathVariable.PathAccept))
opts.Add(PathVariable('EXTRA_PATH',
'Extra paths for executables (separated by : if more than 1)',
'', PathVariable.PathAccept))
opts.Add(BoolVariable('IMPORT_PATHS',
'Import PATH, C_INCLUDE_PATH and LIBRARY_PATH/LD_LIBRARY_PATH environment variables',
False))
opts.Add(BoolVariable('IMPORT_ENV',
'Import full environment from calling shell',True))
opts.Add('EXTRA_LIBS','Libraries to send to the linker','')
opts.Add(BoolVariable('IMPORT_PREFIX',
'Use PREFIX/include and PREFIX/lib in search paths', True))
opts.Add('NOSETESTS','Name of nosetests executable','')
opts.Add(BoolVariable('CACHE_LIB','Cache the results of the library checks',True))
opts.Add(BoolVariable('WITH_PROF',
'Use the compiler flag -pg to include profiling info for gprof', False))
opts.Add(BoolVariable('MEM_TEST','Test for memory leaks', False))
opts.Add(BoolVariable('TMV_DEBUG','Turn on extra debugging statements within TMV library',False))
# None of the code uses openmp yet. Probably make this default True if we start using it.
opts.Add(BoolVariable('WITH_OPENMP','Look for openmp and use if found.', False))
opts.Add(BoolVariable('USE_UNKNOWN_VARS',
'Allow other parameters besides the ones listed here.',False))
# This helps us determine of openmp is available
openmp_mingcc_vers = 4.1
openmp_minicpc_vers = 9.1 # 9.0 is supposed to work, but has bugs
openmp_minpgcc_vers = 6.0
openmp_mincc_vers = 5.0 # I don't actually know what this should be.
def RunInstall(env, targets, subdir):
install_dir = os.path.join(env['INSTALL_PREFIX'], subdir)
env.Alias(target='install',
source=env.Install(dir=install_dir, source=targets))
def RunUninstall(env, targets, subdir):
# There is no env.Uninstall method, we must build our own
install_dir = os.path.join(env['INSTALL_PREFIX'], subdir)
deltarget = Delete("$TARGET")
# delete from $prefix/bin/
files = []
for t in targets:
ifile = os.path.join(install_dir, os.path.basename(str(t)))
files.append(ifile)
for f in files:
env.Alias('uninstall', env.Command(f, None, deltarget))
def ClearCache():
"""
Clear the SCons cache files
"""
if os.path.exists(".sconsign.dblite"):
os.remove(".sconsign.dblite")
import shutil
if os.path.exists(".sconf_temp"):
shutil.rmtree(".sconf_temp")
def ErrorExit(*args, **kwargs):
"""
Whenever we get an error in the initial setup checking for the various
libraries, compiler, etc., we don't want to cache the result.
On the other hand, if we delete the .scon* files now, then they aren't
available to diagnose any problems.
So we write a file called gs.error that
a) includes some relevant information to diagnose the problem.
b) indicates that we should clear the cache the next time we run scons.
"""
import shutil
out = open("gs.error","wb")
# Start with the error message to output both to the screen and to the end of gs.error:
print
for s in args:
print s
out.write(s + '\n')
out.write('\n')
# Write out the current options:
out.write('Using the following options:\n')
for opt in opts.options:
out.write(' %s = %s\n'%(opt.key,env[opt.key]))
out.write('\n')
# Write out the current environment:
out.write('The system environment is:\n')
for key in os.environ.keys():
out.write(' %s = %s\n'%(key,os.environ[key]))
out.write('\n')
out.write('The SCons environment is:\n')
for key in env.Dictionary().keys():
out.write(' %s = %s\n'%(key,env[key]))
out.write('\n')
# Next put the full config.log in there.
out.write('The full config.log file is:\n')
out.write('==================\n')
shutil.copyfileobj(open("config.log","rb"),out)
out.write('==================\n\n')
# It is sometimes helpful to see the output of the scons executables.
# SCons just uses >, not >&, so we'll repeat those runs here and get both.
try:
import subprocess
cmd = ("ls -d .sconf_temp/conftest* | grep -v '\.out' | grep -v '\.cpp' "+
"| grep -v '\.o' | grep -v '\_mod'")
p = subprocess.Popen([cmd],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
conftest_list = p.stdout.readlines()
for conftest in conftest_list:
conftest = conftest.strip()
if os.access(conftest, os.X_OK):
cmd = conftest
else:
cmd = env['PYTHON'] + " < " + conftest
p = subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
shell=True)
conftest_out = p.stdout.readlines()
out.write('Output of the command %s is:\n'%cmd)
out.write(''.join(conftest_out) + '\n')
except:
out.write("Error trying to get output of conftest executables.\n")
out.write(sys.exc_info()[0])
print
print 'Please fix the above error(s) and rerun scons.'
print 'Note: you may want to look through the file INSTALL.md for advice.'
#print 'Also, if you are having trouble, please check the INSTALL FAQ at '
#print ' https://github.com/GalSim-developers/GalSim/wiki/Installation%20FAQ'
print
Exit(1)
def BasicCCFlags(env):
"""
"""
compiler = env['CXXTYPE']
version = env['CXXVERSION_NUMERICAL']
# First parse the EXTRA_LIBS option if present
if env['EXTRA_LIBS'] == '':
env.Replace(LIBS=[])
else:
libs = env['EXTRA_LIBS'].split(' ')
env.Replace(LIBS=libs)
if compiler == 'g++' and version >= 4.4:
# Workaround for a bug in the g++ v4.4 exception handling
# I don't think 4.5 or 4.6 actually need it, but keep >= for now
# just to be safe.
env.AppendUnique(LIBS='pthread')
if env['FLAGS'] == '':
if compiler == 'g++':
env.Replace(CCFLAGS=['-O2'])
env.Append(CCFLAGS=['-fno-strict-aliasing'])
# Unfortunately this next flag requires strict-aliasing, but allowing that
# opens up a Pandora's box of bugs and warnings, so I don't want to do that.
#env.Append(CCFLAGS=['-ftree-vectorize'])
if env['WITH_PROF']:
env.Append(CCFLAGS=['-pg'])
env.Append(LINKFLAGS=['-pg'])
if env['WARN']:
env.Append(CCFLAGS=['-Wall','-Werror'])
if env['EXTRA_DEBUG']:
env.Append(CCFLAGS=['-g3'])
elif compiler == 'clang++':
env.Replace(CCFLAGS=['-O2'])
if env['WITH_PROF']:
env.Append(CCFLAGS=['-pg'])
env.Append(LINKFLAGS=['-pg'])
if env['WARN']:
env.Append(CCFLAGS=['-Wall','-Werror'])
if env['EXTRA_DEBUG']:
env.Append(CCFLAGS=['-g3'])
elif compiler == 'icpc':
env.Replace(CCFLAGS=['-O2','-msse2'])
if version >= 10:
env.Append(CCFLAGS=['-vec-report0'])
if env['WITH_PROF']:
env.Append(CCFLAGS=['-pg'])
env.Append(LINKFLAGS=['-pg'])
if env['WARN']:
env.Append(CCFLAGS=['-Wall','-Werror','-wd279,383,810,981'])
if version >= 9:
env.Append(CCFLAGS=['-wd1572'])
if version >= 11:
env.Append(CCFLAGS=['-wd2259'])
if env['EXTRA_DEBUG']:
env.Append(CCFLAGS=['-g'])
elif compiler == 'pgCC':
env.Replace(CCFLAGS=['-O2','-fast','-Mcache_align'])
if env['WITH_PROF']:
env.Append(CCFLAGS=['-pg'])
env.Append(LINKFLAGS=['-pg'])
if env['EXTRA_DEBUG']:
env.Append(CCFLAGS=['-g'])
elif compiler == 'CC':
env.Replace(CCFLAGS=['-O2','-fast','-instances=semiexplicit'])
if env['WARN']:
env.Append(CCFLAGS=['+w'])
if env['EXTRA_DEBUG']:
env.Append(CCFLAGS=['-g'])
elif compiler == 'cl':
env.Replace(CCFLAGS=['/EHsc','/nologo','/O2','/Oi'])
if env['WARN']:
env.Append(CCFLAGS=['/W2','/WX'])
else:
print '\nWARNING: Unknown compiler. You should set FLAGS directly.\n'
env.Replace(CCFLAGS=[])
else :
# If flags are specified as an option use them:
cxx_flags = env['FLAGS'].split(' ')
env.Replace(CCFLAGS=cxx_flags)
for flag in cxx_flags:
if flag.startswith('-Wl') or flag.startswith('-m'):
# Then this also needs to be in LINKFLAGS
env.AppendUnique(LINKFLAGS=flag)
extra_flags = env['EXTRA_FLAGS'].split(' ')
env.AppendUnique(CCFLAGS=extra_flags)
for flag in extra_flags:
if flag.startswith('-Wl') or flag.startswith('-m'):
# Then this also needs to be in LINKFLAGS
env.AppendUnique(LINKFLAGS=flag)
def AddOpenMPFlag(env):
"""
Make sure you do this after you have determined the version of
the compiler.
g++ uses -fopemnp
clang++ doesn't have OpenMP support yet
icpc uses -openmp
pgCC uses -mp
CC uses -xopenmp
Other compilers?
"""
compiler = env['CXXTYPE']
version = env['CXXVERSION_NUMERICAL']
if compiler == 'g++':
if version < openmp_mingcc_vers:
print 'No OpenMP support for g++ versions before ',openmp_mingcc_vers
env['WITH_OPENMP'] = False
return
flag = ['-fopenmp']
ldflag = ['-fopenmp']
xlib = ['pthread']
# Note: gcc_eh is required on MacOs, but not linux
# Update: Starting with g++4.6, gcc_eh seems to break exception
# throwing, and so I'm only going to use that for version <= 4.5.
# Also, I learned how to check if the platform is darwin (aka MacOs)
if (version <= 4.5) and (sys.platform.find('darwin') != -1):
xlib += ['gcc_eh']
env.Append(CCFLAGS=['-fopenmp'])
elif compiler == 'clang++':
print 'No OpenMP support for clang++'
env['WITH_OPENMP'] = False
return
elif compiler == 'icpc':
if version < openmp_minicpc_vers:
print 'No OpenMP support for icpc versions before ',openmp_minicpc_vers
env['WITH_OPENMP'] = False
return
flag = ['-openmp']
ldflag = ['-openmp']
xlib = ['pthread']
env.Append(CCFLAGS=['-openmp'])
elif compiler == 'pgCC':
if version < openmp_minpgcc_vers:
print 'No OpenMP support for pgCC versions before ',openmp_minpgcc_vers
env['WITH_OPENMP'] = False
return
flag = ['-mp','--exceptions']
ldflag = ['-mp']
xlib = ['pthread']
elif compiler == 'cl':
#flag = ['/openmp']
#ldflag = ['/openmp']
#xlib = []
# The Express edition, which is the one I have, doesn't come with
# the file omp.h, which we need. So I am unable to test TMV's
# OpenMP with cl.
# I believe the Professional edition has full OpenMP support,
# so if you have that, the above lines might work for you.
# Just uncomment those, and commend the below three lines.
print 'No OpenMP support for cl'
env['WITH_OPENMP'] = False
return
else:
print '\nWARNING: No OpenMP support for compiler ',compiler,'\n'
env['WITH_OPENMP'] = False
return
#print 'Adding openmp support:',flag
print 'Using OpenMP'
env.AppendUnique(LINKFLAGS=ldflag)
env.AppendUnique(LIBS=xlib)
def which(program):
"""
Mimic functionality of unix which command
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
if sys.platform == "win32" and not program.endswith(".exe"):
program += ".exe"
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def GetCompilerVersion(env):
"""Determine the version of the compiler
"""
if env['CXX'] is None:
env['CXX'] = default_cxx
compiler = which(env['CXX'])
if compiler is None:
ErrorExit('Specified compiler not found in path: %s' % env['CXX'])
print 'Using compiler:',compiler
compiler_real = os.path.realpath(compiler)
compiler_base = os.path.basename(compiler)
# Get the compiler type without suffix or path.
# e.g. /sw/bin/g++-4 -> g++
if 'icpc' in compiler_base :
compilertype = 'icpc'
versionflag = '--version'
linenum=0
elif 'pgCC' in compiler_base :
compilertype = 'pgCC'
versionflag = '--version'
linenum=1
# pgCC puts the version number on the second line of output.
elif 'clang++' in compiler_base :
compilertype = 'clang++'
versionflag = '--version'
linenum=0
elif 'g++' in compiler_base :
compilertype = 'g++'
versionflag = '--version'
linenum=0
elif 'CC' in compiler_base :
compilertype = 'CC'
versionflag = '-V'
linenum=0
elif 'cl' in compiler_base :
compilertype = 'cl'
versionflag = ''
linenum=0
elif 'c++' in compiler_base :
compilertype = 'c++'
versionflag = '--version'
linenum=0
else :
compilertype = 'unknown'
version = 0
vnum = 0
if compilertype != 'unknown':
cmd = compiler + ' ' + versionflag + ' 2>&1'
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
lines = p.stdout.readlines()
# Check if g++ is a symlink for something else:
if compilertype is 'g++':
if 'clang' in lines[0]:
print 'Detected clang++ masquerading as g++'
compilertype = 'clang++'
# When it is masquerading, the line with the version is the second line.
linenum=1
# Check if c++ is a symlink for something else:
if compilertype is 'c++':
if 'clang' in lines[0]:
print 'Detected clang++ masquerading as c++'
compilertype = 'clang++'
elif 'g++' in lines[0] or 'gcc' in lines[0]:
print 'Detected g++ masquerading as c++'
compilertype = 'g++'
else:
print 'Cannot determine what kind of compiler c++ really is'
compilertype = 'unknown'
# Any others I should look for?
# redo this check in case was c++ -> unknown
if compilertype != 'unknown':
line = lines[linenum]
import re
match = re.search(r'[0-9]+(\.[0-9]+)+', line)
if match:
version = match.group(0)
# Get the version up to the first decimal
# e.g. for 4.3.1 we only keep 4.3
vnum = version[0:version.find('.')+2]
else:
version = 0
vnum = 0
print 'compiler version:',version
env['CXXTYPE'] = compilertype
env['CXXVERSION'] = version
env['CXXVERSION_NUMERICAL'] = float(vnum)
def GetNosetestsVersion(env):
"""Determine the version of nosetests
"""
import subprocess
cmd = env['NOSETESTS'] + ' --version 2>&1'
p = subprocess.Popen([cmd],stdout=subprocess.PIPE,shell=True)
line = p.stdout.readlines()[0]
version = line.split()[2]
print 'nosetests version:',version
env['NOSETESTSVERSION'] = version
def ExpandPath(path):
p=os.path.expanduser(path)
p=os.path.expandvars(p)
return p
def AddPath(pathlist, newpath, prepend=False):
"""
Add path(s) to a list of paths. Check the path exists and that it is
not already in the list
"""
if type(newpath) == list:
for l in newpath:
AddPath(pathlist, l)
else:
# to deal with ~ and ${var} expansions
p = ExpandPath(newpath)
p = os.path.abspath(p)
if os.path.exists(p):
if p not in pathlist:
if prepend:
pathlist.insert(0, p)
else:
pathlist.append(p)
def AddDepPaths(bin_paths,cpp_paths,lib_paths):
"""
Look for paths associated with the dependencies. E.g. if TMV_DIR is set
either on the command line or in the environment, add $TMV_DIR/include etc.
to the paths. Will add them to the back of the paths. Also, we don't have
to worry about dups because AddPath checks for that.
"""
types = ['BOOST', 'TMV', 'FFTW', 'CCFITS']
for t in types:
dirtag = t+'_DIR'
tdir = FindPathInEnv(env, dirtag)
if tdir is None:
if env[dirtag] != '':
print 'WARNING: could not find specified %s = %s'%(dirtag,env[dirtag])
continue
AddPath(bin_paths, os.path.join(tdir, 'bin'))
AddPath(lib_paths, os.path.join(tdir, 'lib'))
AddPath(cpp_paths, os.path.join(tdir, 'include'))
def AddExtraPaths(env):
"""
Add some include and library paths.
Also merge in $PATH, $C_INCLUDE_PATH and $LIBRARY_PATH/$LD_LIBRARY_PATH
environment variables if requested.
The set itself is created in order of appearance here, but then this
whole set is prepended. The order within this list is:
local lib and include paths
paths in FFTW_DIR, TMV_DIR, etc.
paths in EXTRA_*PATH parameters
paths in PREFIX directory
paths from the user's environment
Only paths that actually exists are kept.
"""
# local includes and lib paths
# The # symbol means to interpret these from the top-level scons
# directory even when we are in a sub-directory (src,test,etc.)
bin_paths = []
cpp_paths = ['#include']
lib_paths = ['#lib']
# Add directories specified explicitly for our dependencies on the command
# line or as an environment variable.
AddDepPaths(bin_paths,cpp_paths,lib_paths)
# Paths specified in EXTRA_*
bin_paths += env['EXTRA_PATH'].split(':')
lib_paths += env['EXTRA_LIB_PATH'].split(':')
cpp_paths += env['EXTRA_INCLUDE_PATH'].split(':')
# PREFIX directory
# If none given, then don't add them to the -L and -I directories.
# But still use the default /usr/local for installation
if env['PREFIX'] == '':
env['INSTALL_PREFIX'] = default_prefix
env['FINAL_PREFIX'] = default_prefix
else:
if os.path.isfile(env['PREFIX']) and os.path.samefile('.',env['PREFIX']):
ErrorExit(
'Using the source directory as the PREFIX value is not allowed.',
'You should install FDNT to some other directory. The typical',
'choice is to use your home directory, which on most machines can',
'be specified using PREFIX=~')
env['INSTALL_PREFIX'] = env['PREFIX']
# FINAL_PREFIX is designed for installations like that done by fink where it installs
# everything into a temporary directory, and then once it finished successfully, it
# copies the resulting files to a final location.
if env['FINAL_PREFIX'] == '':
env['FINAL_PREFIX'] = env['PREFIX']
if env['IMPORT_PREFIX']:
AddPath(bin_paths, os.path.join(env['PREFIX'], 'bin'))
AddPath(lib_paths, os.path.join(env['PREFIX'], 'lib'))
AddPath(cpp_paths, os.path.join(env['PREFIX'], 'include'))
# Paths found in environment paths
if env['IMPORT_PATHS'] and os.environ.has_key('PATH'):
paths=os.environ['PATH']
paths=paths.split(os.pathsep)
AddPath(bin_paths, paths)
if env['IMPORT_PATHS'] and os.environ.has_key('C_INCLUDE_PATH'):
paths=os.environ['C_INCLUDE_PATH']
paths=paths.split(os.pathsep)
AddPath(cpp_paths, paths)
if env['IMPORT_PATHS'] and os.environ.has_key('LIBRARY_PATH'):
paths=os.environ['LIBRARY_PATH']
paths=paths.split(os.pathsep)
AddPath(lib_paths, paths)
if env['IMPORT_PATHS'] and os.environ.has_key('LD_LIBRARY_PATH'):
paths=os.environ['LD_LIBRARY_PATH']
paths=paths.split(os.pathsep)
AddPath(lib_paths, paths)
if env['IMPORT_PATHS'] and os.environ.has_key('DYLD_LIBRARY_PATH'):
paths=os.environ['DYLD_LIBRARY_PATH']
paths=paths.split(os.pathsep)
AddPath(lib_paths, paths)
env.PrependENVPath('PATH', bin_paths)
env.Prepend(LIBPATH= lib_paths)
env.Prepend(CPPPATH= cpp_paths)
def ReadFileList(fname):
"""
This reads a list of whitespace separated values from the input file fname
and stores it as a list. We will make this part of the environment so
other SConscripts can use it
"""
try:
files=open(fname).read().split()
except:
print 'Could not open file:',fname
sys.exit(45)
files = [f.strip() for f in files]
return files
def TryRunResult(config,text,name):
# Check if a particular program (given as text) is compilable, runs, and returns the
# right value.
config.sconf.pspawn = config.sconf.env['PSPAWN']
save_spawn = config.sconf.env['SPAWN']
config.sconf.env['SPAWN'] = config.sconf.pspawn_wrapper
# First use the normal TryRun command
ok, out = config.TryRun(text,'.cpp')
config.sconf.env['SPAWN'] = save_spawn
# We have an arbitrary requirement that the executable output the answer 23.
# So if we didn't get this answer, then something must have gone wrong.
if out.strip() != '23':
ok = False
return ok
def CheckLibsSimple(config,try_libs,source_file,prepend=True):
init_libs = []
if 'LIBS' in config.env._dict.keys():
init_libs = config.env['LIBS']
if prepend:
config.env.PrependUnique(LIBS=try_libs)
else:
config.env.AppendUnique(LIBS=try_libs)
result = TryRunResult(config,source_file,'.cpp')
# If that didn't work, go back to the original LIBS
if not result :
config.env.Replace(LIBS=init_libs)
return result
def AddRPATH(env, rpath, prepend=False):
"""
Add rpath to the scons environment.
This is really a workaround for SCons bug. The normal command should just be:
config.env.AppendUnique(RPATH=rpath)
But this doesn't always work correctly, since RPATH sometimes clashes with LINKFLAGS.
So if LINKFLAGS is already set, we need this workaround.
See: http://scons.tigris.org/issues/show_bug.cgi?id=1644
(Fixed in version 2.1.)
"""
if prepend:
env.PrependUnique(RPATH=rpath)
else:
env.AppendUnique(RPATH=rpath)
major , minor , junk = SCons.__version__.split('.',2)
if int(major) < 2 or (int(major) == 2 and int(minor) == 0):
env.Append( LINKFLAGS = ["$__RPATH"] )
def CheckLibsFull(config,try_libs,source_file,prepend=True):
init_libs = []
if 'LIBS' in config.env._dict.keys():
init_libs = config.env['LIBS']
if prepend:
config.env.PrependUnique(LIBS=try_libs)
else:
config.env.AppendUnique(LIBS=try_libs)
result = TryRunResult(config,source_file,'.cpp')
if result: return result
init_rpath = []
init_link = []
if 'RPATH' in config.env._dict.keys():
init_rpath = config.env['RPATH']
if 'LINKFLAGS' in config.env._dict.keys():
init_link = config.env['LINKFLAGS']
# Sometimes we need to add a directory to RPATH, so try each one.
if not result and 'LIBPATH' in config.env._dict.keys():
for rpath in config.env['LIBPATH']:
AddRPATH(config.env,rpath,prepend)
result = TryRunResult(config,source_file,'.cpp')
if result:
break
else:
config.env.Replace(RPATH=init_rpath)
config.env.Replace(LINKFLAGS=init_link)
# If that doesn't work, also try adding all of them, just in case we need more than one.
if not result :
AddRPATH(config.env,config.env['LIBPATH'],prepend)
result = TryRunResult(config,source_file,'.cpp')
if not result:
config.env.Replace(RPATH=init_rpath)
config.env.Replace(LINKFLAGS=init_link)
# Next try the LIBRARY_PATH to see if any of these help.
if not result and 'LIBRARY_PATH' in os.environ.keys():
library_path=os.environ['LIBRARY_PATH']
library_path=library_path.split(os.pathsep)
for rpath in library_path:
AddRPATH(config.env,rpath,prepend)
result = TryRunResult(config,source_file,'.cpp')
if result:
break
else:
config.env.Replace(RPATH=init_rpath)
config.env.Replace(LINKFLAGS=init_link)
# If that doesn't work, also try adding all of them, just in case we need more than one.
if not result :
AddRPATH(config.env,library_path,prepend)
result = TryRunResult(config,source_file,'.cpp')
if not result:
config.env.Replace(RPATH=init_rpath)
config.env.Replace(LINKFLAGS=init_link)
# If nothing worked, go back to the original LIBS
if not result :
config.env.Replace(LIBS=init_libs)
return result
def CheckFFTW(config):
fftw_source_file = """
#include "fftw3.h"
#include <iostream>
int main()
{
double* ar = (double*) fftw_malloc(sizeof(double)*64);
fftw_complex* ac = (fftw_complex*) fftw_malloc(sizeof(double)*2*64);
fftw_plan plan = fftw_plan_dft_r2c_2d(8,8,ar,ac,FFTW_MEASURE);
fftw_destroy_plan(plan);
fftw_free(ar);
fftw_free(ac);
std::cout<<"23"<<std::endl;
return 0;
}
"""
config.Message('Checking for correct FFTW linkage... ')
if not config.TryCompile(fftw_source_file,'.cpp'):
ErrorExit(
'Error: fftw file failed to compile.',
'Check that the correct location is specified for FFTW_DIR')
result = (
CheckLibsFull(config,[''],fftw_source_file) or
CheckLibsFull(config,['fftw3'],fftw_source_file) )
if not result:
ErrorExit(
'Error: fftw file failed to link correctly',
'Check that the correct location is specified for FFTW_DIR')
config.Result(1)
return 1
def CheckBoost(config):
# At the C++ level, we only need boost header files, so no need to check libraries.
# Use boost/shared_ptr.hpp as a representative choice.
boost_source_file = """
#define BOOST_NO_CXX11_SMART_PTR
#include "boost/shared_ptr.hpp"
"""
config.Message('Checking for boost header files... ')
if not config.TryCompile(boost_source_file, ".cpp"):
ErrorExit(
'Boost not found',
'You should specify the location of Boost as BOOST_DIR=...')
config.Result(1)
boost_version_file = """
#include <iostream>
#define BOOST_NO_CXX11_SMART_PTR
#include "boost/version.hpp"
int main() { std::cout<<BOOST_VERSION<<std::endl; return 0; }
"""
ok, boost_version = config.TryRun(boost_version_file,'.cpp')
boost_version = int(boost_version.strip())
print 'Boost version is %d.%d.%d' % (
boost_version / 100000, boost_version / 100 % 1000, boost_version % 100)
return 1
def CheckTMV(config):
tmv_source_file = """
#include "TMV_Sym.h"
#include <iostream>
int main()
{
tmv::SymMatrix<double> S(10,4.);
//tmv::Matrix<double> S(10,10,4.);
tmv::Matrix<double> m(10,3,2.);
S += 50.;
tmv::Matrix<double> m2 = m / S;
std::cout<<"23"<<std::endl;
return 0;
}
"""
print 'Checking for correct TMV linkage... (this may take a little while)'
config.Message('Checking for correct TMV linkage... ')
result = config.TryCompile(tmv_source_file,'.cpp')
if not result:
ErrorExit(
'Error: TMV file failed to compile.',
'Check that the correct location is specified for TMV_DIR')
result = (
CheckLibsSimple(config,[''],tmv_source_file) or
CheckLibsSimple(config,['tmv_symband','tmv'],tmv_source_file) or
CheckLibsSimple(config,['tmv_symband','tmv','irc','imf'],tmv_source_file) or
CheckLibsFull(config,['tmv_symband','tmv'],tmv_source_file) or
CheckLibsFull(config,['tmv_symband','tmv','irc','imf'],tmv_source_file) )
if not result:
ErrorExit(
'Error: TMV file failed to link correctly',
'Check that the correct location is specified for TMV_DIR')
config.Result(1)
return 1
def CheckCCfits(config):
ccfits_source_file = """
#include "CCfits/CCfits"
#include <iostream>
int main()
{
CCfits::FITS* f=0;
try {
f = new CCfits::FITS("not_a_real_file.fits", CCfits::Read);
} catch (CCfits::FITS::CantOpen& e) {
// This is what should happen.
std::cout<<"23"<<std::endl;
}
delete f;
return 0;
}
"""
config.Message('Checking for correct CCfits linkage... ')
if not config.TryCompile(ccfits_source_file,'.cpp'):
ErrorExit(
'Error: CCfits file failed to compile.',
'Check that the correct location is specified for CCFITS_DIR')
result = (
CheckLibsFull(config,[''],ccfits_source_file) or
CheckLibsFull(config,['CCfits'],ccfits_source_file) )
if not result:
ErrorExit(
'Error: CCfits file failed to link correctly',
'Check that the correct location is specified for CCFITS_DIR')
config.Result(1)
return 1
def TryScript(config,text,executable):
# Check if a particular script (given as text) is runnable with the
# executable (given as executable).
#
# I couldn't find a way to do this using the existing SCons functions, so this
# is basically taken from parts of the code for TryBuild and TryRun.
# First make the file name using the same counter as TryBuild uses:
from SCons.SConf import _ac_build_counter
f = "conftest_" + str(SCons.SConf._ac_build_counter)
SCons.SConf._ac_build_counter = SCons.SConf._ac_build_counter + 1
config.sconf.pspawn = config.sconf.env['PSPAWN']
save_spawn = config.sconf.env['SPAWN']
config.sconf.env['SPAWN'] = config.sconf.pspawn_wrapper
# Build a file containg the given text
textFile = config.sconf.confdir.File(f)
sourcetext = config.env.Value(text)
textFileNode = config.env.SConfSourceBuilder(target=textFile, source=sourcetext)
config.sconf.BuildNodes(textFileNode)
source = textFileNode
# Run the given executable with the source file we just built
output = config.sconf.confdir.File(f + '.out')
node = config.env.Command(output, source, executable + " < $SOURCE > $TARGET")
ok = config.sconf.BuildNodes(node)
config.sconf.env['SPAWN'] = save_spawn
if ok:
# For successful execution, also return the output contents
outputStr = output.get_contents()
return 1, outputStr.strip()
else:
return 0, ""
def TryModule(config,text,name,pyscript=""):
# Check if a particular program (given as text) is compilable as a python module.
config.sconf.pspawn = config.sconf.env['PSPAWN']
save_spawn = config.sconf.env['SPAWN']
config.sconf.env['SPAWN'] = config.sconf.pspawn_wrapper
# First try to build the code as a SharedObject:
ok = config.TryBuild(config.env.SharedObject,text,'.cpp')
if not ok: return 0
# Get the object file as the lastTarget:
obj = config.sconf.lastTarget
# Try to build the LoadableModule
dir = os.path.splitext(os.path.basename(obj.path))[0] + '_mod'
output = config.sconf.confdir.File(os.path.join(dir,name + '.so'))
dir = os.path.dirname(output.path)
mod = config.env.LoadableModule(output, obj)
ok = config.sconf.BuildNodes(mod)
if not ok: return 0
# Finally try to import and run the module in python:
if pyscript == "":
pyscript = "import sys\nsys.path.append('%s')\nimport %s\nprint %s.run()"%(dir,name,name)
else: