/[escript]/trunk/SConstruct
ViewVC logotype

Diff of /trunk/SConstruct

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 965 by gross, Tue Feb 13 05:38:45 2007 UTC revision 3961 by jfenwick, Tue Sep 11 07:21:41 2012 UTC
# Line 1  Line 1 
1  #         Copyright 2006 by ACcESS MNRF  ########################################################
2  #  #
3  #              http://www.access.edu.au  # Copyright (c) 2003-2012 by University of Queensland
4  #       Primary Business: Queensland, Australia  # Earth Systems Science Computational Center (ESSCC)
5  #  Licensed under the Open Software License version 3.0  # http://www.uq.edu.au/esscc
 #     http://www.opensource.org/licenses/osl-3.0.php  
6  #  #
7    # Primary Business: Queensland, Australia
8    # Licensed under the Open Software License version 3.0
9    # http://www.opensource.org/licenses/osl-3.0.php
10  #  #
11  #  ########################################################
   
 # top-level Scons configuration file for all esys13 modules  
 # Begin initialisation Section  
 # all of this section just intialises default environments and helper  
 # scripts. You shouldn't need to modify this section.  
 EnsureSConsVersion(0,96,91)  
 EnsurePythonVersion(2,3)  
   
 # import tools:  
 import glob  
 import sys, os  
 import socket  
 # Add our extensions  
 if sys.path.count('scons')==0: sys.path.append('scons')  
 import scons_extensions  
   
 # check if UMFPACK is installed on the system:  
 if os.path.isdir('/opt/UMFPACK/Include') and os.path.isdir('/opt/UMFPACK/Lib'):  
    umf_path_default='/opt/UMFPACK/Include'  
    umf_lib_path_default='/opt/UMFPACK/Lib'  
    umf_libs_default=['umfpack']  
 else:  
    umf_path_default=None  
    umf_lib_path_default=None  
    umf_libs_default=None  
   
 if os.path.isdir('/opt/AMD/Include') and os.path.isdir('/opt/AMD/Lib'):  
    amd_path_default='/opt/AMD/Include'  
    amd_lib_path_default='/opt/AMD/Lib'  
    amd_libs_default=['amd']  
 else:  
    amd_path_default=None  
    amd_lib_path_default=None  
    amd_libs_default=None  
   
 if os.path.isdir('/opt/UFconfig'):  
    ufc_path_default='/opt/UFconfig'  
 else:  
    ufc_path_default=None  
   
 # Default options and options help text  
 # These are defaults and can be overridden using command line arguments or an options file.  
 # if the options_file or ARGUMENTS do not exist then the ones listed as default here are used  
 # DO NOT CHANGE THEM HERE  
 if ARGUMENTS.get('options_file',0):  
    options_file = ARGUMENTS.get('options_file',0)  
 else:  
    from string import ascii_letters,digits  
    hostname=""  
    for s in socket.gethostname().split('.')[0]:  
       if s in ascii_letters+digits:  
          hostname+=s  
       else:  
          hostname+="_"  
    options_file = "scons/"+hostname+"_options.py"  
   
 opts = Options(options_file, ARGUMENTS)  
 opts.AddOptions(  
 # Where to install esys stuff  
   ('incinstall', 'where the esys headers will be installed', Dir('#.').abspath+'/include'),  
   ('libinstall', 'where the esys libraries will be installed', Dir('#.').abspath+'/lib'),  
   ('pyinstall', 'where the esys python modules will be installed', Dir('#.').abspath),  
   ('src_zipfile', 'the source zip file will be installed.', Dir('#.').abspath+"/release/escript_src.zip"),  
   ('test_zipfile', 'the test zip file will be installed.', Dir('#.').abspath+"/release/escript_tests.zip"),  
   ('src_tarfile', 'the source tar file will be installed.', Dir('#.').abspath+"/release/escript_src.tar.gz"),  
   ('test_tarfile', 'the test tar file will be installed.', Dir('#.').abspath+"/release/escript_tests.tar.gz"),  
   ('examples_tarfile', 'the examples tar file will be installed.', Dir('#.').abspath+"/release/doc/escript_examples.tar.gz"),  
   ('examples_zipfile', 'the examples zip file will be installed.', Dir('#.').abspath+"/release/doc/escript_examples.zip"),  
   ('guide_pdf', 'name of the user guide in pdf format', Dir('#.').abspath+"/release/doc/user/guide.pdf"),  
   ('api_epydoc', 'name of the epydoc api docs directory',Dir('#.').abspath+"/release/doc/epydoc"),  
   ('guide_html', 'name of the directory for user guide in html format', Dir('#.').abspath+"/release/doc/user/html"),  
 # Compilation options  
   BoolOption('dodebug', 'Do you want a debug build?', 'no'),  
   ('options_file', "Optional file containing preferred options. Ignored if it doesn't exist (default: scons/hostname_options.py)", options_file),  
   ('cc_defines','C/C++ defines to use', None),  
   ('cc_flags','C compiler flags to use (Release build)', '-O3 -std=c99 -ffast-math -fpic -Wno-unknown-pragmas'),  
   ('cc_flags_debug', 'C compiler flags to use (Debug build)', '-g -O0 -ffast-math -std=c99 -fpic -Wno-unknown-pragmas'),  
   ('cxx_flags', 'C++ compiler flags to use (Release build)', '--no-warn -ansi'),  
   ('cxx_flags_debug', 'C++ compiler flags to use (Debug build)', '--no-warn -ansi -DDOASSERT -DDOPROF'),  
   ('cc_flags_MPI','C compiler flags to use (Release MPI build)', '-O3 -ftz -IPF_ftlacc- -IPF_fma -fno-alias -fno-alias -c99 -w1 -fpic -wd161'),  
   ('cc_flags_debug_MPI', 'C compiler flags to use (Debug MPI build)', '-g -O0 -c99 -w1 -fpic -wd161'),  
   ('cxx_flags_MPI', 'C++ compiler flags to use (Release MPI build)', '-ansi -wd1563 -wd161'),  
   ('cxx_flags_debug_MPI', 'C++ compiler flags to use (Debug MPI build)', '-ansi -DDOASSERT -DDOPROF -wd1563 -wd161'),  
   ('ar_flags', 'Static library archiver flags to use', None),  
   ('sys_libs', 'System libraries to link with', None),  
   ('tar_flags','flags for zip files','-c -z'),  
 # MKL  
   PathOption('mkl_path', 'Path to MKL includes', None),  
   PathOption('mkl_lib_path', 'Path to MKL libs', None),  
   ('mkl_libs', 'MKL libraries to link with', None),  
 # SCSL  
   PathOption('scsl_path', 'Path to SCSL includes', None),  
   PathOption('scsl_lib_path', 'Path to SCSL libs', None),  
   ('scsl_libs', 'SCSL libraries to link with', None),  
   ('scsl_libs_MPI', 'SCSL libraries to link with for MPI build', None),  
 # UMFPACK  
   PathOption('ufc_path', 'Path to UFconfig includes', ufc_path_default),  
   PathOption('umf_path', 'Path to UMFPACK includes', umf_path_default),  
   PathOption('umf_lib_path', 'Path to UMFPACK libs', umf_lib_path_default),  
   ('umf_libs', 'UMFPACK libraries to link with', umf_libs_default),  
 # AMD (used by UMFPACK)  
   PathOption('amd_path', 'Path to AMD includes', amd_path_default),  
   PathOption('amd_lib_path', 'Path to AMD libs', amd_lib_path_default),  
   ('amd_libs', 'AMD libraries to link with', amd_libs_default),  
 # BLAS  
   PathOption('blas_path', 'Path to BLAS includes', None),  
   PathOption('blas_lib_path', 'Path to BLAS libs', None),  
   ('blas_libs', 'BLAS libraries to link with', None),  
 # netCDF  
   PathOption('netCDF_path', 'Path to netCDF includes', '/usr/local/include'),  
   PathOption('netCDF_lib_path', 'Path to netCDF libs', '/usr/local/lib'),  
   ('netCDF_libs_cxx', 'netCDF C++ libraries to link with', [ 'netcdf_c++', 'netcdf'] ),  
 # Python  
 # locations of include files for python  
   PathOption('python_path', 'Path to Python includes', '/usr/include/python%s.%s'%(sys.version_info[0],sys.version_info[1])),  
   PathOption('python_lib_path', 'Path to Python libs', '/usr/lib'),  
   ('python_lib', 'Python libraries to link with', ["python%s.%s"%(sys.version_info[0],sys.version_info[1]),]),  
 # Boost  
   PathOption('boost_path', 'Path to Boost includes', '/usr/include'),  
   PathOption('boost_lib_path', 'Path to Boost libs', '/usr/lib'),  
   ('boost_lib', 'Boost libraries to link with', ['boost_python',]),  
 # Doc building  
 #  PathOption('doxygen_path', 'Path to Doxygen executable', None),  
 #  PathOption('epydoc_path', 'Path to Epydoc executable', None),  
 # PAPI  
   PathOption('papi_path', 'Path to PAPI includes', None),  
   PathOption('papi_lib_path', 'Path to PAPI libs', None),  
   ('papi_libs', 'PAPI libraries to link with', None),  
 # MPI  
   BoolOption('useMPI', 'Compile parallel version using MPI', 'no'),  
 )  
12    
13  # Initialise Scons Build Environment  EnsureSConsVersion(0,98,1)
14  # check for user environment variables we are interested in  EnsurePythonVersion(2,5)
 try:  
    python_path = os.environ['PYTHONPATH']  
 except KeyError:  
    python_path = ''  
 try:  
    path = os.environ['PATH']  
 except KeyError:  
    path = ''  
 try:  
    ld_library_path = os.environ['LD_LIBRARY_PATH']  
 except KeyError:  
    ld_library_path = ''  
15    
16  # Note: On the Altix the intel compilers are not automatically  import sys, os, platform, re
17  # detected by scons intelc.py script. The Altix has a different directory  from distutils import sysconfig
18  # path and in some locations the "modules" facility is used to support  from site_init import *
19  # multiple compiler versions. This forces the need to import the users PATH  import subprocess
20  # environment which isn't the "scons way"  from subprocess import PIPE, Popen
21  # This doesn't impact linux and windows which will use the default compiler (g++ or msvc, or the intel compiler if it is installed on both platforms)  
22  # FIXME: Perhaps a modification to intelc.py will allow better support for ia64 on altix  # Version number to check for in options file. Increment when new features are
23    # added or existing options changed.
24  if os.name != "nt" and os.uname()[4]=='ia64':  REQUIRED_OPTS_VERSION=201
25     env = Environment(ENV = {'PATH':path}, tools = ['default', 'intelc'], options = opts)  
26     env['ENV']['PATH'] = path  # MS Windows support, many thanks to PH
27     env['ENV']['LD_LIBRARY_PATH'] = ld_library_path  IS_WINDOWS = (os.name == 'nt')
28     env['ENV']['PYTHONPATH'] = python_path  
29     if env['CXX'] == 'icpc':  ########################## Determine options file ############################
30        env['LINK'] = env['CXX'] # version >=9 of intel c++ compiler requires use of icpc to link in C++ runtimes (icc does not). FIXME: this behaviour could be directly incorporated into scons intelc.py  # 1. command line
31  elif os.name == "nt":  # 2. scons/<hostname>_options.py
32     env = Environment(tools = ['default', 'intelc'], options = opts)  # 3. name as part of a cluster
33     env['ENV']['PYTHONPATH'] = python_path  options_file=ARGUMENTS.get('options_file', None)
34  else:  if not options_file:
35     env = Environment(tools = ['default'], options = opts)      ext_dir = os.path.join(os.getcwd(), 'scons')
36     env['ENV']['PATH'] = path      hostname = platform.node().split('.')[0]
37     env['ENV']['LD_LIBRARY_PATH'] = ld_library_path      for name in hostname, effectiveName(hostname):
38     env['ENV']['PYTHONPATH'] = python_path          mangledhostname = re.sub('[^0-9a-zA-Z]', '_', hostname)
39            options_file = os.path.join(ext_dir, mangledhostname+'_options.py')
40            if os.path.isfile(options_file): break
41    
42    if not os.path.isfile(options_file):
43        print("\nWARNING:\nOptions file %s" % options_file)
44        print("not found! Default options will be used which is most likely suboptimal.")
45        print("It is recommended that you copy one of the TEMPLATE files in the scons/")
46        print("subdirectory and customize it to your needs.\n")
47        options_file = None
48    
49    ############################### Build options ################################
50    
51    default_prefix='/usr'
52    mpi_flavours=('no', 'none', 'MPT', 'MPICH', 'MPICH2', 'OPENMPI', 'INTELMPI')
53    lapack_flavours=('none', 'clapack', 'mkl')
54    
55    vars = Variables(options_file, ARGUMENTS)
56    vars.AddVariables(
57      PathVariable('options_file', 'Path to options file', options_file, PathVariable.PathIsFile),
58      PathVariable('prefix', 'Installation prefix', Dir('#.').abspath, PathVariable.PathIsDirCreate),
59      PathVariable('build_dir', 'Top-level build directory', Dir('#/build').abspath, PathVariable.PathIsDirCreate),
60      BoolVariable('verbose', 'Output full compile/link lines', False),
61    # Compiler/Linker options
62      ('cc', 'Path to C compiler', 'default'),
63      ('cxx', 'Path to C++ compiler', 'default'),
64      ('cc_flags', 'Base C/C++ compiler flags', 'default'),
65      ('cc_optim', 'Additional C/C++ flags for a non-debug build', 'default'),
66      ('cc_debug', 'Additional C/C++ flags for a debug build', 'default'),
67      ('cc_extra', 'Extra C compiler flags', ''),
68      ('cxx_extra', 'Extra C++ compiler flags', ''),
69      ('ld_extra', 'Extra linker flags', ''),
70      BoolVariable('werror','Treat compiler warnings as errors', True),
71      BoolVariable('debug', 'Compile with debug flags', False),
72      BoolVariable('openmp', 'Compile parallel version using OpenMP', False),
73      ('omp_flags', 'OpenMP compiler flags', 'default'),
74      ('omp_ldflags', 'OpenMP linker flags', 'default'),
75    # Mandatory libraries
76      ('boost_prefix', 'Prefix/Paths of boost installation', default_prefix),
77      ('boost_libs', 'Boost libraries to link with', ['boost_python-mt']),
78    # Mandatory for tests
79      ('cppunit_prefix', 'Prefix/Paths of CppUnit installation', default_prefix),
80      ('cppunit_libs', 'CppUnit libraries to link with', ['cppunit']),
81    # Optional libraries and options
82      EnumVariable('mpi', 'Compile parallel version using MPI flavour', 'none', allowed_values=mpi_flavours),
83      ('mpi_prefix', 'Prefix/Paths of MPI installation', default_prefix),
84      ('mpi_libs', 'MPI shared libraries to link with', ['mpi']),
85      BoolVariable('netcdf', 'Enable netCDF file support', False),
86      ('netcdf_prefix', 'Prefix/Paths of netCDF installation', default_prefix),
87      ('netcdf_libs', 'netCDF libraries to link with', ['netcdf_c++', 'netcdf']),
88      BoolVariable('parmetis', 'Enable ParMETIS (requires MPI)', False),
89      ('parmetis_prefix', 'Prefix/Paths of ParMETIS installation', default_prefix),
90      ('parmetis_libs', 'ParMETIS libraries to link with', ['parmetis', 'metis']),
91      BoolVariable('papi', 'Enable PAPI', False),
92      ('papi_prefix', 'Prefix/Paths to PAPI installation', default_prefix),
93      ('papi_libs', 'PAPI libraries to link with', ['papi']),
94      BoolVariable('papi_instrument_solver', 'Use PAPI to instrument each iteration of the solver', False),
95      BoolVariable('mkl', 'Enable the Math Kernel Library', False),
96      ('mkl_prefix', 'Prefix/Paths to MKL installation', default_prefix),
97      ('mkl_libs', 'MKL libraries to link with', ['mkl_solver','mkl_em64t','guide','pthread']),
98      BoolVariable('umfpack', 'Enable UMFPACK', False),
99      ('umfpack_prefix', 'Prefix/Paths to UMFPACK installation', default_prefix),
100      ('umfpack_libs', 'UMFPACK libraries to link with', ['umfpack']),
101      BoolVariable('boomeramg', 'Enable BoomerAMG', False),
102      ('boomeramg_prefix', 'Prefix/Paths to BoomerAMG installation', default_prefix),
103      ('boomeramg_libs', 'BoomerAMG libraries to link with', ['boomeramg']),
104      EnumVariable('lapack', 'Set LAPACK flavour', 'none', allowed_values=lapack_flavours),
105      ('lapack_prefix', 'Prefix/Paths to LAPACK installation', default_prefix),
106      ('lapack_libs', 'LAPACK libraries to link with', []),
107      BoolVariable('silo', 'Enable the Silo file format in weipa', False),
108      ('silo_prefix', 'Prefix/Paths to Silo installation', default_prefix),
109      ('silo_libs', 'Silo libraries to link with', ['siloh5', 'hdf5']),
110      BoolVariable('visit', 'Enable the VisIt simulation interface', False),
111      ('visit_prefix', 'Prefix/Paths to VisIt installation', default_prefix),
112      ('visit_libs', 'VisIt libraries to link with', ['simV2']),
113      BoolVariable('vsl_random', 'Use VSL from intel for random data', False),
114    # Advanced settings
115      #dudley_assemble_flags = -funroll-loops      to actually do something
116      ('dudley_assemble_flags', 'compiler flags for some dudley optimisations', ''),
117      # To enable passing function pointers through python
118      BoolVariable('iknowwhatimdoing', 'Allow non-standard C', False),
119      # An option for specifying the compiler tools (see windows branch)
120      ('tools_names', 'Compiler tools to use', ['default']),
121      ('env_export', 'Environment variables to be passed to tools',[]),
122      EnumVariable('forcelazy', 'For testing use only - set the default value for autolazy', 'leave_alone', allowed_values=('leave_alone', 'on', 'off')),
123      EnumVariable('forcecollres', 'For testing use only - set the default value for force resolving collective ops', 'leave_alone', allowed_values=('leave_alone', 'on', 'off')),
124      # finer control over library building, intel aggressive global optimisation
125      # works with dynamic libraries on windows.
126      ('build_shared', 'Build dynamic libraries only', False),
127      ('sys_libs', 'Extra libraries to link with', []),
128      ('escript_opts_version', 'Version of options file (do not specify on command line)'),
129      ('SVN_VERSION', 'Do not use from options file', -2),
130      ('pythoncmd', 'which python to compile with','python'),
131      ('usepython3', 'Is this a python3 build? (experimental)', False),
132      ('pythonlibname', 'Name of the python library to link. (This is found automatically for python2.X.)', ''),
133      ('pythonlibpath', 'Path to the python library. (You should not need to set this unless your python has moved)',''),
134      ('pythonincpath','Path to python include files. (You should not need to set this unless your python has moved',''),
135      BoolVariable('BADPYTHONMACROS','Extra \#include to get around a python bug.', True),
136    )
137    
138  # Setup help for options  ##################### Create environment and help text #######################
 Help(opts.GenerateHelpText(env))  
139    
140  # Add some customer builders  # Intel's compiler uses regular expressions improperly and emits a warning
141  py_builder = Builder(action = scons_extensions.build_py, suffix = '.pyc', src_suffix = '.py', single_source=True)  # about failing to find the compilers. This warning can be safely ignored.
 env.Append(BUILDERS = {'PyCompile' : py_builder});  
142    
143  if env['PLATFORM'] == "win32":  # PATH is needed so the compiler, linker and tools are found if they are not
144     runUnitTest_builder = Builder(action = scons_extensions.runUnitTest, suffix = '.passed', src_suffix='.exe', single_source=True)  # in default locations.
145    env = Environment(tools = ['default'], options = vars,
146                      ENV = {'PATH': os.environ['PATH']})
147    if env['tools_names'] != 'default':
148        env = Environment(tools = ['default'] + env['tools_names'], options = vars,
149                          ENV = {'PATH' : os.environ['PATH']})
150    
151    if options_file:
152        opts_valid=False
153        if 'escript_opts_version' in env.Dictionary() and \
154            int(env['escript_opts_version']) >= REQUIRED_OPTS_VERSION:
155                opts_valid=True
156        if opts_valid:
157            print("Using options in %s." % options_file)
158        else:
159            print("\nOptions file %s" % options_file)
160            print("is outdated! Please update the file by examining one of the TEMPLATE")
161            print("files in the scons/ subdirectory and setting escript_opts_version to %d.\n"%REQUIRED_OPTS_VERSION)
162            Exit(1)
163    
164    # Generate help text (scons -h)
165    Help(vars.GenerateHelpText(env))
166    
167    # Check for superfluous options
168    if len(vars.UnknownVariables())>0:
169        for k in vars.UnknownVariables():
170            print("Unknown option '%s'" % k)
171        Exit(1)
172    
173    #################### Make sure install directories exist #####################
174    
175    env['BUILD_DIR']=env['build_dir']
176    prefix=Dir(env['prefix']).abspath
177    env['incinstall'] = os.path.join(prefix, 'include')
178    env['bininstall'] = os.path.join(prefix, 'bin')
179    env['libinstall'] = os.path.join(prefix, 'lib')
180    env['pyinstall']  = os.path.join(prefix, 'esys')
181    if not os.path.isdir(env['bininstall']):
182        os.makedirs(env['bininstall'])
183    if not os.path.isdir(env['libinstall']):
184        os.makedirs(env['libinstall'])
185    if not os.path.isdir(env['pyinstall']):
186        os.makedirs(env['pyinstall'])
187    
188    env.Append(CPPPATH = [env['incinstall']])
189    env.Append(LIBPATH = [env['libinstall']])
190    
191    ################# Fill in compiler options if not set above ##################
192    
193    if env['cc'] != 'default': env['CC']=env['cc']
194    if env['cxx'] != 'default': env['CXX']=env['cxx']
195    
196    # version >=9 of intel C++ compiler requires use of icpc to link in C++
197    # runtimes (icc does not)
198    if not IS_WINDOWS and os.uname()[4]=='ia64' and env['CXX']=='icpc':
199        env['LINK'] = env['CXX']
200    
201    # default compiler/linker options
202    cc_flags = ''
203    cc_optim = ''
204    cc_debug = ''
205    omp_flags = ''
206    omp_ldflags = ''
207    fatalwarning = '' # switch to turn warnings into errors
208    sysheaderopt = '' # how to indicate that a header is a system header
209    
210    # env['CC'] might be a full path
211    cc_name=os.path.basename(env['CC'])
212    
213    if cc_name == 'icc':
214        # Intel compiler
215        cc_flags    = "-std=c99 -fPIC -wd161 -w1 -vec-report0 -DBLOCKTIMER -DCORE_ID1"
216        cc_optim    = "-O3 -ftz -IPF_ftlacc- -IPF_fma -fno-alias -ip"
217        cc_debug    = "-g -O0 -DDOASSERT -DDOPROF -DBOUNDS_CHECK"
218        omp_flags   = "-openmp -openmp_report0"
219        omp_ldflags = "-openmp -openmp_report0 -lpthread"
220        fatalwarning = "-Werror"
221    elif cc_name[:3] == 'gcc':
222        # GNU C on any system
223        cc_flags     = "-pedantic -Wall -fPIC -ffast-math -Wno-unknown-pragmas -DBLOCKTIMER  -Wno-sign-compare -Wno-system-headers -Wno-long-long -Wno-strict-aliasing -finline-functions"
224        cc_optim     = "-O3"
225        cc_debug     = "-g -O0 -DDOASSERT -DDOPROF -DBOUNDS_CHECK"
226        omp_flags    = "-fopenmp"
227        omp_ldflags  = "-fopenmp"
228        fatalwarning = "-Werror"
229        sysheaderopt = "-isystem"
230    elif cc_name == 'cl':
231        # Microsoft Visual C on Windows
232        cc_flags     = "/EHsc /MD /GR /wd4068 /D_USE_MATH_DEFINES /DDLL_NETCDF"
233        cc_optim     = "/O2 /Op /W3"
234        cc_debug     = "/Od /RTCcsu /ZI /DBOUNDS_CHECK"
235        fatalwarning = "/WX"
236    elif cc_name == 'icl':
237        # Intel C on Windows
238        cc_flags     = '/EHsc /GR /MD'
239        cc_optim     = '/fast /Oi /W3 /Qssp /Qinline-factor- /Qinline-min-size=0 /Qunroll'
240        cc_debug     = '/Od /RTCcsu /Zi /Y- /debug:all /Qtrapuv'
241        omp_flags    = '/Qvec-report0 /Qopenmp /Qopenmp-report0 /Qparallel'
242        omp_ldflags  = '/Qvec-report0 /Qopenmp /Qopenmp-report0 /Qparallel'
243    
244    # set defaults if not otherwise specified
245    if env['cc_flags']    == 'default': env['cc_flags'] = cc_flags
246    if env['cc_optim']    == 'default': env['cc_optim'] = cc_optim
247    if env['cc_debug']    == 'default': env['cc_debug'] = cc_debug
248    if env['omp_flags']   == 'default': env['omp_flags'] = omp_flags
249    if env['omp_ldflags'] == 'default': env['omp_ldflags'] = omp_ldflags
250    if env['cc_extra']  != '': env.Append(CFLAGS = env['cc_extra'])
251    if env['cxx_extra'] != '': env.Append(CXXFLAGS = env['cxx_extra'])
252    if env['ld_extra']  != '': env.Append(LINKFLAGS = env['ld_extra'])
253    
254    if env['BADPYTHONMACROS']: env.Append(CXXFLAGS = ' -DBADPYTHONMACROS')
255    
256    if env['usepython3']:
257        env.Append(CPPDEFINES=['ESPYTHON3'])
258    
259    # set up the autolazy values
260    if env['forcelazy'] == 'on':
261        env.Append(CPPDEFINES=['FAUTOLAZYON'])
262    elif env['forcelazy'] == 'off':
263        env.Append(CPPDEFINES=['FAUTOLAZYOFF'])
264    
265    # set up the collective resolve values
266    if env['forcecollres'] == 'on':
267        env.Append(CPPDEFINES=['FRESCOLLECTON'])
268    elif env['forcecollres'] == 'off':
269        env.Append(CPPDEFINES=['FRESCOLLECTOFF'])
270    
271    # allow non-standard C if requested
272    if env['iknowwhatimdoing']:
273        env.Append(CPPDEFINES=['IKNOWWHATIMDOING'])
274    
275    # Disable OpenMP if no flags provided
276    if env['openmp'] and env['omp_flags'] == '':
277       print("OpenMP requested but no flags provided - disabling OpenMP!")
278       env['openmp'] = False
279    
280    if env['openmp']:
281        env.Append(CCFLAGS = env['omp_flags'])
282        if env['omp_ldflags'] != '': env.Append(LINKFLAGS = env['omp_ldflags'])
283    else:
284        env['omp_flags']=''
285        env['omp_ldflags']=''
286    
287    # add debug/non-debug compiler flags
288    if env['debug']:
289        env.Append(CCFLAGS = env['cc_debug'])
290    else:
291        env.Append(CCFLAGS = env['cc_optim'])
292    
293    # always add cc_flags
294    env.Append(CCFLAGS = env['cc_flags'])
295    
296    # add system libraries
297    env.AppendUnique(LIBS = env['sys_libs'])
298    
299    
300    global_revision=ARGUMENTS.get('SVN_VERSION', None)
301    if global_revision:
302        global_revision = re.sub(':.*', '', global_revision)
303        global_revision = re.sub('[^0-9]', '', global_revision)
304        if global_revision == '': global_revision='-2'
305  else:  else:
306     runUnitTest_builder = Builder(action = scons_extensions.runUnitTest, suffix = '.passed', single_source=True)    # Get the global Subversion revision number for the getVersion() method
307  env.Append(BUILDERS = {'RunUnitTest' : runUnitTest_builder});    try:
308        global_revision = os.popen('svnversion -n .').read()
309  runPyUnitTest_builder = Builder(action = scons_extensions.runPyUnitTest, suffix = '.passed', src_suffic='.py', single_source=True)      global_revision = re.sub(':.*', '', global_revision)
310  env.Append(BUILDERS = {'RunPyUnitTest' : runPyUnitTest_builder});      global_revision = re.sub('[^0-9]', '', global_revision)
311        if global_revision == '': global_revision='-2'
312  # Convert the options which are held in environment variable into python variables for ease of handling and configure compilation options    except:
313  try:      global_revision = '-1'
314     incinstall = env['incinstall']  env['svn_revision']=global_revision
315     env.Append(CPPPATH = [incinstall,])  env.Append(CPPDEFINES=['SVN_VERSION='+global_revision])
316  except KeyError:  
317     incinstall = None  if IS_WINDOWS:
318  try:      if not env['build_shared']:
319     libinstall = env['libinstall']          env.Append(CPPDEFINES = ['ESYSUTILS_STATIC_LIB'])
320     env.Append(LIBPATH = [libinstall,])          env.Append(CPPDEFINES = ['PASO_STATIC_LIB'])
321     env.PrependENVPath('LD_LIBRARY_PATH', libinstall)  
322     if env['PLATFORM'] == "win32":  ###################### Copy required environment vars ########################
323        env.PrependENVPath('PATH', libinstall)  
324        env.PrependENVPath('PATH', env['boost_lib_path'])  # Windows doesn't use LD_LIBRARY_PATH but PATH instead
325  except KeyError:  if IS_WINDOWS:
326     libinstall = None      LD_LIBRARY_PATH_KEY='PATH'
327  try:      env['ENV']['LD_LIBRARY_PATH']=''
328     pyinstall = env['pyinstall']+'/esys' # all targets will install into pyinstall/esys but PYTHONPATH points at straight pyinstall so you go import esys.escript etc  else:
329     env.PrependENVPath('PYTHONPATH', env['pyinstall'])      LD_LIBRARY_PATH_KEY='LD_LIBRARY_PATH'
 except KeyError:  
    pyinstall = None  
 try:  
    dodebug = env['dodebug']  
 except KeyError:  
    dodebug = None  
 try:  
    useMPI = env['useMPI']  
 except KeyError:  
    useMPI = None  
 try:  
    cc_defines = env['cc_defines']  
    env.Append(CPPDEFINES = cc_defines)  
 except KeyError:  
    pass  
330    
331  if 'shake71' == socket.gethostname().split('.')[0]:  # the following env variables are exported for the unit tests
   if useMPI:  
     env['CC'] = 'mpicc'  
     env['CXX'] = 'mpiCC'  
332    
333  if dodebug:  for key in 'OMP_NUM_THREADS', 'ESCRIPT_NUM_PROCS', 'ESCRIPT_NUM_NODES':
   if useMPI:  
334      try:      try:
335        flags = env['cc_flags_debug_MPI']          env['ENV'][key] = os.environ[key]
       env.Append(CCFLAGS = flags)  
336      except KeyError:      except KeyError:
337        pass          env['ENV'][key] = 1
338    else:  
339    env_export=env['env_export']
340    env_export.extend(['ESCRIPT_NUM_THREADS','ESCRIPT_HOSTFILE','DISPLAY','XAUTHORITY','PATH','HOME','TMPDIR','TEMP','TMP'])
341    
342    for key in set(env_export):
343      try:      try:
344        flags = env['cc_flags_debug']          env['ENV'][key] = os.environ[key]
       env.Append(CCFLAGS = flags)  
345      except KeyError:      except KeyError:
       pass  
 else:  
   if useMPI:  
    try:  
      flags = env['cc_flags_MPI']  
      env.Append(CCFLAGS = flags)  
    except KeyError:  
       pass  
   else:  
    try:  
       flags = env['cc_flags']  
       env.Append(CCFLAGS = flags)  
    except KeyError:  
       pass  
 if dodebug:  
    if useMPI:  
      try:  
         flags = env['cxx_flags_debug_MPI']  
         env.Append(CXXFLAGS = flags)  
      except KeyError:  
         pass  
    else:  
      try:  
         flags = env['cxx_flags_debug']  
         env.Append(CXXFLAGS = flags)  
      except KeyError:  
346          pass          pass
 else:  
    if useMPI:  
      try:  
         flags = env['cxx_flags_MPI']  
         env.Append(CXXFLAGS = flags)  
      except KeyError:  
         pass  
    else:  
      try:  
         flags = env['cxx_flags']  
         env.Append(CXXFLAGS = flags)  
      except KeyError:  
         pass  
 try:  
    flags = env['ar_flags']  
    env.Append(ARFLAGS = flags)  
 except KeyError:  
    ar_flags = None  
 try:  
    sys_libs = env['sys_libs']  
 except KeyError:  
    sys_libs = ''  
347    
348  try:  try:
349     tar_flags = env['tar_flags']      env.PrependENVPath(LD_LIBRARY_PATH_KEY, os.environ[LD_LIBRARY_PATH_KEY])
    env.Replace(TARFLAGS = tar_flags)  
350  except KeyError:  except KeyError:
351     pass      pass
   
 try:  
    includes = env['mkl_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
   
 try:  
    lib_path = env['mkl_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
   
 if useMPI:  
    mkl_libs = ''  
 else:  
    try:  
       mkl_libs = env['mkl_libs']  
    except KeyError:  
       mkl_libs = ''  
   
 try:  
    includes = env['scsl_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
   
 try:  
    lib_path = env['scsl_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
   
 if useMPI:  
   try:  
     scsl_libs = env['scsl_libs_MPI']  
   except KeyError:  
     scsl_libs = ''  
 else:  
   try:  
     scsl_libs = env['scsl_libs']  
   except KeyError:  
     scsl_libs = ''  
   
 try:  
    includes = env['umf_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
   
 try:  
    lib_path = env['umf_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
   
 if useMPI:  
     umf_libs = ''  
 else:  
    try:  
       umf_libs = env['umf_libs']  
    except KeyError:  
       umf_libs = ''  
352    
353  try:  # these shouldn't be needed
354     includes = env['ufc_path']  #for key in 'C_INCLUDE_PATH','CPLUS_INCLUDE_PATH','LIBRARY_PATH':
355     env.Append(CPPPATH = [includes,])  #    try:
356  except KeyError:  #        env['ENV'][key] = os.environ[key]
357     pass  #    except KeyError:
358    #        pass
359    
360  try:  try:
361     includes = env['amd_path']      env['ENV']['PYTHONPATH'] = os.environ['PYTHONPATH']
    env.Append(CPPPATH = [includes,])  
362  except KeyError:  except KeyError:
363     pass      pass
364    
365  try:  ######################## Add some custom builders ############################
    lib_path = env['amd_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
366    
367  if useMPI:  if env['pythoncmd']=='python':
368      amd_libs = ''      py_builder = Builder(action = build_py, suffix = '.pyc', src_suffix = '.py', single_source=True)
369  else:  else:
370     try:      py_builder = Builder(action = env['pythoncmd']+" scripts/py_comp.py $SOURCE $TARGET", suffix = '.pyc', src_suffix = '.py', single_source=True)
371        amd_libs = env['amd_libs']  env.Append(BUILDERS = {'PyCompile' : py_builder});
    except KeyError:  
       amd_libs = ''  
   
 try:  
    includes = env['blas_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
   
 try:  
    lib_path = env['blas_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
   
 try:  
    blas_libs = env['blas_libs']  
 except KeyError:  
    blas_libs = ''  
   
 try:  
    includes = env['netCDF_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
372    
373  try:  runUnitTest_builder = Builder(action = runUnitTest, suffix = '.passed', src_suffix=env['PROGSUFFIX'], single_source=True)
374     lib_path = env['netCDF_lib_path']  env.Append(BUILDERS = {'RunUnitTest' : runUnitTest_builder});
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
375    
376  try:  runPyUnitTest_builder = Builder(action = runPyUnitTest, suffix = '.passed', src_suffic='.py', single_source=True)
377     netCDF_libs_cxx = env['netCDF_libs_cxx']  env.Append(BUILDERS = {'RunPyUnitTest' : runPyUnitTest_builder});
 except KeyError:  
    netCDF_lib_cxx = [ ]  
378    
379  try:  epstopdfbuilder = Builder(action = eps2pdf, suffix='.pdf', src_suffix='.eps', single_source=True)
380     includes = env['boost_path']  env.Append(BUILDERS = {'EpsToPDF' : epstopdfbuilder});
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
 try:  
    lib_path = env['boost_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
 try:  
    boost_lib = env['boost_lib']  
 except KeyError:  
    boost_lib = None  
 try:  
    includes = env['python_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
 try:  
    lib_path = env['python_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
 try:  
    python_lib = env['python_lib']  
 except KeyError:  
    python_lib = None  
 try:  
    doxygen_path = env['doxygen_path']  
 except KeyError:  
    doxygen_path = None  
 try:  
    epydoc_path = env['epydoc_path']  
 except KeyError:  
    epydoc_path = None  
 try:  
    includes = env['papi_path']  
    env.Append(CPPPATH = [includes,])  
 except KeyError:  
    pass  
 try:  
    lib_path = env['papi_lib_path']  
    env.Append(LIBPATH = [lib_path,])  
 except KeyError:  
    pass  
 try:  
    papi_libs = env['papi_libs']  
 except KeyError:  
    papi_libs = None  
381    
382    ############################ Dependency checks ###############################
383    
384  try:  # Create a Configure() environment to check for compilers and python
385     src_zipfile = env.File(env['src_zipfile'])  conf = Configure(env.Clone())
 except KeyError:  
    src_zipfile = None  
 try:  
    test_zipfile = env.File(env['test_zipfile'])  
 except KeyError:  
    test_zipfile = None  
 try:  
    examples_zipfile = env.File(env['examples_zipfile'])  
 except KeyError:  
    examples_zipfile = None  
386    
387  try:  ######## Test that the compilers work
388     src_tarfile = env.File(env['src_tarfile'])  
389  except KeyError:  if 'CheckCC' in dir(conf): # exists since scons 1.1.0
390     src_tarfile = None      if not conf.CheckCC():
391  try:          print("Cannot run C compiler '%s' (check config.log)" % (env['CC']))
392     test_tarfile = env.File(env['test_tarfile'])          Exit(1)
393  except KeyError:      if not conf.CheckCXX():
394     test_tarfile = None          print("Cannot run C++ compiler '%s' (check config.log)" % (env['CXX']))
395  try:          Exit(1)
396     examples_tarfile = env.File(env['examples_tarfile'])  else:
397  except KeyError:      if not conf.CheckFunc('printf', language='c'):
398     examples_tarfile = None          print("Cannot run C compiler '%s' (check config.log)" % (env['CC']))
399            Exit(1)
400        if not conf.CheckFunc('printf', language='c++'):
401            print("Cannot run C++ compiler '%s' (check config.log)" % (env['CXX']))
402            Exit(1)
403    
404    if conf.CheckFunc('gethostname'):
405        conf.env.Append(CPPDEFINES = ['HAVE_GETHOSTNAME'])
406    
407    ######## Python headers & library (required)
408    
409    #First we check to see if the config file has specified
410    ##Where to find the filae. Ideally, this should be automatic
411    #But we need to deal with the case where python is not in its INSTALL
412    #Directory
413    # Use the python scons is running
414    if env['pythoncmd']=='python':
415        python_inc_path=sysconfig.get_python_inc()
416        if IS_WINDOWS:
417            python_lib_path=os.path.join(sysconfig.get_config_var('prefix'), 'libs')
418        elif env['PLATFORM']=='darwin':
419            python_lib_path=sysconfig.get_config_var('LIBPL')
420        else:
421            python_lib_path=sysconfig.get_config_var('LIBDIR')
422    
423        #python_libs=[sysconfig.get_config_var('LDLIBRARY')] # only on linux
424        if IS_WINDOWS:
425            python_libs=['python%s%s'%(sys.version_info[0], sys.version_info[1])]
426        else:
427            python_libs=['python'+sysconfig.get_python_version()]
428    
429    #if we want to use a python other than the one scons is running
430    else:
431        initstring='from __future__ import print_function;from distutils import sysconfig;'
432        if env['pythonlibname']!='':
433            python_libs=env['pythonlibname']
434        else:   # work it out by calling python    
435            if IS_WINDOWS:
436                cmd='print("python%s%s"%(sys.version_info[0], sys.version_info[1]))'
437            else:
438                cmd='print("python"+sysconfig.get_python_version())'
439            p=Popen([env['pythoncmd'], '-c', initstring+cmd], stdout=PIPE)
440            python_libs=p.stdout.readline()
441            if env['usepython3']:       # This is to convert unicode str into py2 string
442                python_libs=python_libs.encode() # If scons runs on py3 then this must be rethought
443            p.wait()
444            python_libs=python_libs.strip()
445    
446      
447        # Now we know whether we are using python3 or not
448        p=Popen([env['pythoncmd'], '-c',  initstring+'print(sysconfig.get_python_inc())'], stdout=PIPE)
449        python_inc_path=p.stdout.readline()
450        if env['usepython3']:
451             python_inc_path=python_inc_path.encode()
452        p.wait()  
453        python_inc_path=python_inc_path.strip()
454        if IS_WINDOWS:
455            cmd="os.path.join(sysconfig.get_config_var('prefix'), 'libs')"
456        elif env['PLATFORM']=='darwin':
457            cmd="sysconfig.get_config_var(\"LIBPL\")"
458        else:
459            cmd="sysconfig.get_config_var(\"LIBDIR\")"
460    
461        p=Popen([env['pythoncmd'], '-c', initstring+'print('+cmd+')'], stdout=PIPE)
462        python_lib_path=p.stdout.readline()
463        if env['usepython3']:
464            python_lib_path=python_lib_path.decode()
465        p.wait()
466        python_lib_path=python_lib_path.strip()
467    
468    #Check for an override from the config file.
469    #Ideally, this should be automatic
470    #But we need to deal with the case where python is not in its INSTALL
471    #Directory
472    if env['pythonlibpath']!='':
473        python_lib_path=env['pythonlibpath']
474    
475    if env['pythonincpath']!='':
476        python_inc_path=env['pythonincpath']
477    
478    
479    if sysheaderopt == '':
480        conf.env.AppendUnique(CPPPATH = [python_inc_path])
481    else:
482        conf.env.Append(CCFLAGS = [sysheaderopt, python_inc_path])
483    
484    conf.env.AppendUnique(LIBPATH = [python_lib_path])
485    conf.env.AppendUnique(LIBS = python_libs)
486    # The wrapper script needs to find the libs
487    conf.env.PrependENVPath(LD_LIBRARY_PATH_KEY, python_lib_path)
488    
489    if not conf.CheckCHeader('Python.h'):
490        print("Cannot find python include files (tried 'Python.h' in directory %s)" % (python_inc_path))
491        Exit(1)
492    if not conf.CheckFunc('Py_Exit'):
493        print("Cannot find python library method Py_Main (tried %s in directory %s)" % (python_libs, python_lib_path))
494        Exit(1)
495    
496    ## reuse conf to check for numpy header (optional)
497    if env['usepython3']:
498        # FIXME: This is until we can work out how to make the checks in python 3
499        conf.env['numpy_h']=False
500    else:
501        if conf.CheckCXXHeader(['Python.h','numpy/ndarrayobject.h']):
502            conf.env.Append(CPPDEFINES = ['HAVE_NUMPY_H'])
503            conf.env['numpy_h']=True
504        else:
505            conf.env['numpy_h']=False
506    
507    # Commit changes to environment
508    env = conf.Finish()
509    
510    ######## boost (required)
511    
512    boost_inc_path,boost_lib_path=findLibWithHeader(env, env['boost_libs'], 'boost/python.hpp', env['boost_prefix'], lang='c++')
513    if sysheaderopt == '':
514        env.AppendUnique(CPPPATH = [boost_inc_path])
515    else:
516        # This is required because we can't -isystem /usr/include since it breaks
517        # std includes
518        if os.path.normpath(boost_inc_path) == '/usr/include':
519            conf.env.Append(CCFLAGS=[sysheaderopt, os.path.join(boost_inc_path,'boost')])
520        else:
521            env.Append(CCFLAGS=[sysheaderopt, boost_inc_path])
522    
523    env.AppendUnique(LIBPATH = [boost_lib_path])
524    env.AppendUnique(LIBS = env['boost_libs'])
525    env.PrependENVPath(LD_LIBRARY_PATH_KEY, boost_lib_path)
526    
527  try:  ######## numpy (required)
    guide_pdf = env.File(env['guide_pdf'])  
 except KeyError:  
    guide_pdf = None  
528    
529  try:  if env['pythoncmd']=='python':
530     guide_html_index = env.File('index.htm',env['guide_html'])      try:
531  except KeyError:        from numpy import identity
532     guide_html_index = None      except ImportError:
533          print("Cannot import numpy, you need to set your PYTHONPATH and probably %s"%LD_LIBRARY_PATH_KEY)
534          Exit(1)
535    else:
536        p=subprocess.call([env['pythoncmd'],'-c','import numpy'])
537        if p!=0:
538          print("Cannot import numpy, you need to set your PYTHONPATH and probably %s"%LD_LIBRARY_PATH_KEY)
539          Exit(1)
540    
541    ######## CppUnit (required for tests)
542    
543    try:
544        cppunit_inc_path,cppunit_lib_path=findLibWithHeader(env, env['cppunit_libs'], 'cppunit/TestFixture.h', env['cppunit_prefix'], lang='c++')
545        env.AppendUnique(CPPPATH = [cppunit_inc_path])
546        env.AppendUnique(LIBPATH = [cppunit_lib_path])
547        env.PrependENVPath(LD_LIBRARY_PATH_KEY, cppunit_lib_path)
548        env['cppunit']=True
549    except:
550        env['cppunit']=False
551    
552    ######## netCDF (optional)
553    
554    netcdf_inc_path=''
555    netcdf_lib_path=''
556    if env['netcdf']:
557        netcdf_inc_path,netcdf_lib_path=findLibWithHeader(env, env['netcdf_libs'], 'netcdf.h', env['netcdf_prefix'], lang='c++')
558        env.AppendUnique(CPPPATH = [netcdf_inc_path])
559        env.AppendUnique(LIBPATH = [netcdf_lib_path])
560        env.AppendUnique(LIBS = env['netcdf_libs'])
561        env.PrependENVPath(LD_LIBRARY_PATH_KEY, netcdf_lib_path)
562        env.Append(CPPDEFINES = ['USE_NETCDF'])
563    
564    ######## PAPI (optional)
565    
566    papi_inc_path=''
567    papi_lib_path=''
568    if env['papi']:
569        papi_inc_path,papi_lib_path=findLibWithHeader(env, env['papi_libs'], 'papi.h', env['papi_prefix'], lang='c')
570        env.AppendUnique(CPPPATH = [papi_inc_path])
571        env.AppendUnique(LIBPATH = [papi_lib_path])
572        env.AppendUnique(LIBS = env['papi_libs'])
573        env.PrependENVPath(LD_LIBRARY_PATH_KEY, papi_lib_path)
574        env.Append(CPPDEFINES = ['BLOCKPAPI'])
575    
576    ######## MKL (optional)
577    
578    mkl_inc_path=''
579    mkl_lib_path=''
580    if env['mkl']:
581        mkl_inc_path,mkl_lib_path=findLibWithHeader(env, env['mkl_libs'], 'mkl_solver.h', env['mkl_prefix'], lang='c')
582        env.AppendUnique(CPPPATH = [mkl_inc_path])
583        env.AppendUnique(LIBPATH = [mkl_lib_path])
584        env.AppendUnique(LIBS = env['mkl_libs'])
585        env.PrependENVPath(LD_LIBRARY_PATH_KEY, mkl_lib_path)
586        env.Append(CPPDEFINES = ['MKL'])
587    
588    ######## UMFPACK (optional)
589    
590    umfpack_inc_path=''
591    umfpack_lib_path=''
592    if env['umfpack']:
593        umfpack_inc_path,umfpack_lib_path=findLibWithHeader(env, env['umfpack_libs'], 'umfpack.h', env['umfpack_prefix'], lang='c')
594        env.AppendUnique(CPPPATH = [umfpack_inc_path])
595        env.AppendUnique(LIBPATH = [umfpack_lib_path])
596        env.AppendUnique(LIBS = env['umfpack_libs'])
597        env.PrependENVPath(LD_LIBRARY_PATH_KEY, umfpack_lib_path)
598        env.Append(CPPDEFINES = ['UMFPACK'])
599    
600    ######## LAPACK (optional)
601    
602    if env['lapack']=='mkl' and not env['mkl']:
603        print("mkl_lapack requires MKL!")
604        Exit(1)
605    
606    env['uselapack'] = env['lapack']!='none'
607    lapack_inc_path=''
608    lapack_lib_path=''
609    if env['uselapack']:
610        header='clapack.h'
611        if env['lapack']=='mkl':
612            env.AppendUnique(CPPDEFINES = ['MKL_LAPACK'])
613            header='mkl_lapack.h'
614        lapack_inc_path,lapack_lib_path=findLibWithHeader(env, env['lapack_libs'], header, env['lapack_prefix'], lang='c')
615        env.AppendUnique(CPPPATH = [lapack_inc_path])
616        env.AppendUnique(LIBPATH = [lapack_lib_path])
617        env.AppendUnique(LIBS = env['lapack_libs'])
618        env.Append(CPPDEFINES = ['USE_LAPACK'])
619    
620    ######## Silo (optional)
621    
622    silo_inc_path=''
623    silo_lib_path=''
624    if env['silo']:
625        silo_inc_path,silo_lib_path=findLibWithHeader(env, env['silo_libs'], 'silo.h', env['silo_prefix'], lang='c')
626        env.AppendUnique(CPPPATH = [silo_inc_path])
627        env.AppendUnique(LIBPATH = [silo_lib_path])
628        # Note that we do not add the libs since they are only needed for the
629        # weipa library and tools.
630        #env.AppendUnique(LIBS = [env['silo_libs']])
631    
632    ######## VSL random numbers (optional)
633    if env['vsl_random']:
634        env.Append(CPPDEFINES = ['MKLRANDOM'])
635    
636    ######## VisIt (optional)
637    
638    visit_inc_path=''
639    visit_lib_path=''
640    if env['visit']:
641        visit_inc_path,visit_lib_path=findLibWithHeader(env, env['visit_libs'], 'VisItControlInterface_V2.h', env['visit_prefix'], lang='c')
642        env.AppendUnique(CPPPATH = [visit_inc_path])
643        env.AppendUnique(LIBPATH = [visit_lib_path])
644    
645    ######## MPI (optional)
646    
647    if env['mpi']=='no':
648        env['mpi']='none'
649    
650    env['usempi'] = env['mpi']!='none'
651    mpi_inc_path=''
652    mpi_lib_path=''
653    if env['usempi']:
654        mpi_inc_path,mpi_lib_path=findLibWithHeader(env, env['mpi_libs'], 'mpi.h', env['mpi_prefix'], lang='c')
655        env.AppendUnique(CPPPATH = [mpi_inc_path])
656        env.AppendUnique(LIBPATH = [mpi_lib_path])
657        env.AppendUnique(LIBS = env['mpi_libs'])
658        env.PrependENVPath(LD_LIBRARY_PATH_KEY, mpi_lib_path)
659        env.Append(CPPDEFINES = ['ESYS_MPI', 'MPI_NO_CPPBIND', 'MPICH_IGNORE_CXX_SEEK'])
660        # NetCDF 4.1 defines MPI_Comm et al. if MPI_INCLUDED is not defined!
661        # On the other hand MPT and OpenMPI don't define the latter so we have to
662        # do that here
663        if env['netcdf'] and env['mpi'] in ['MPT','OPENMPI']:
664            env.Append(CPPDEFINES = ['MPI_INCLUDED'])
665    
666    ######## BOOMERAMG (optional)
667    
668    if env['mpi'] == 'none': env['boomeramg'] = False
669    
670    boomeramg_inc_path=''
671    boomeramg_lib_path=''
672    if env['boomeramg']:
673        boomeramg_inc_path,boomeramg_lib_path=findLibWithHeader(env, env['boomeramg_libs'], 'HYPRE.h', env['boomeramg_prefix'], lang='c')
674        env.AppendUnique(CPPPATH = [boomeramg_inc_path])
675        env.AppendUnique(LIBPATH = [boomeramg_lib_path])
676        env.AppendUnique(LIBS = env['boomeramg_libs'])
677        env.PrependENVPath(LD_LIBRARY_PATH_KEY, boomeramg_lib_path)
678        env.Append(CPPDEFINES = ['BOOMERAMG'])
679    
680    ######## ParMETIS (optional)
681    
682    if not env['usempi']: env['parmetis'] = False
683    
684    parmetis_inc_path=''
685    parmetis_lib_path=''
686    if env['parmetis']:
687        parmetis_inc_path,parmetis_lib_path=findLibWithHeader(env, env['parmetis_libs'], 'parmetis.h', env['parmetis_prefix'], lang='c')
688        env.AppendUnique(CPPPATH = [parmetis_inc_path])
689        env.AppendUnique(LIBPATH = [parmetis_lib_path])
690        env.AppendUnique(LIBS = env['parmetis_libs'])
691        env.PrependENVPath(LD_LIBRARY_PATH_KEY, parmetis_lib_path)
692        env.Append(CPPDEFINES = ['USE_PARMETIS'])
693    
694    ######## gmsh (optional, for tests)
695    
696    try:
697        import subprocess
698        p=subprocess.Popen(['gmsh', '-info'], stderr=subprocess.PIPE)
699        _,e=p.communicate()
700        if e.split().count("MPI"):
701            env['gmsh']='m'
702        else:
703            env['gmsh']='s'
704    except OSError:
705        env['gmsh']=False
706    
707    ######## PDFLaTeX (for documentation)
708    if 'PDF' in dir(env) and '.tex' in env.PDF.builder.src_suffixes(env):
709        env['pdflatex']=True
710    else:
711        env['pdflatex']=False
712    
713    ######################## Summarize our environment ###########################
714    
715    # keep some of our install paths first in the list for the unit tests
716    env.PrependENVPath(LD_LIBRARY_PATH_KEY, env['libinstall'])
717    env.PrependENVPath('PYTHONPATH', prefix)
718    env['ENV']['ESCRIPT_ROOT'] = prefix
719    
720    if not env['verbose']:
721        env['CCCOMSTR'] = "Compiling $TARGET"
722        env['CXXCOMSTR'] = "Compiling $TARGET"
723        env['SHCCCOMSTR'] = "Compiling $TARGET"
724        env['SHCXXCOMSTR'] = "Compiling $TARGET"
725        env['ARCOMSTR'] = "Linking $TARGET"
726        env['LINKCOMSTR'] = "Linking $TARGET"
727        env['SHLINKCOMSTR'] = "Linking $TARGET"
728        env['PDFLATEXCOMSTR'] = "Building $TARGET from LaTeX input $SOURCES"
729        env['BIBTEXCOMSTR'] = "Generating bibliography $TARGET"
730        env['MAKEINDEXCOMSTR'] = "Generating index $TARGET"
731        env['PDFLATEXCOMSTR'] = "Building $TARGET from LaTeX input $SOURCES"
732        #Progress(['Checking -\r', 'Checking \\\r', 'Checking |\r', 'Checking /\r'], interval=17)
733    
734    print("")
735    print("*** Config Summary (see config.log and lib/buildvars for details) ***")
736    print("Escript/Finley revision %s"%global_revision)
737    print("  Install prefix:  %s"%env['prefix'])
738    print("          Python:  %s"%sysconfig.PREFIX)
739    print("           boost:  %s"%env['boost_prefix'])
740    print("           numpy:  YES")
741    if env['usempi']:
742        print("             MPI:  YES (flavour: %s)"%env['mpi'])
743    else:
744        print("             MPI:  DISABLED")
745    if env['uselapack']:
746        print("          LAPACK:  YES (flavour: %s)"%env['lapack'])
747    else:
748        print("          LAPACK:  DISABLED")
749    d_list=[]
750    e_list=[]
751    for i in 'debug','openmp','netcdf','parmetis','papi','mkl','umfpack','boomeramg','silo','visit','vsl_random':
752        if env[i]: e_list.append(i)
753        else: d_list.append(i)
754    for i in e_list:
755        print("%16s:  YES"%i)
756    for i in d_list:
757        print("%16s:  DISABLED"%i)
758    if env['cppunit']:
759        print("         CppUnit:  FOUND")
760    else:
761        print("         CppUnit:  NOT FOUND")
762    if env['gmsh']=='m':
763        print("            gmsh:  FOUND, MPI-ENABLED")
764    elif env['gmsh']=='s':
765        print("            gmsh:  FOUND")
766    else:
767        print("            gmsh:  NOT FOUND")
768    if env['numpy_h']:
769        print("   numpy headers:  FOUND")
770    else:
771        print("   numpy headers:  NOT FOUND")
772    print("   vsl_random:  %s"%env['vsl_random'])
773        
774    if ((fatalwarning != '') and (env['werror'])):
775        print("  Treating warnings as errors")
776    else:
777        print("  NOT treating warnings as errors")
778    print("")
779    
780    ####################### Configure the subdirectories #########################
781    
782    from grouptest import *
783    
784    TestGroups=[]
785    
786    # keep an environment without warnings-as-errors
787    dodgy_env=env.Clone()
788    
789    # now add warnings-as-errors flags. This needs to be done after configuration
790    # because the scons test files have warnings in them
791    if ((fatalwarning != '') and (env['werror'])):
792        env.Append(CCFLAGS = fatalwarning)
793    
794    Export(
795      ['env',
796       'dodgy_env',
797       'IS_WINDOWS',
798       'TestGroups'
799      ]
800    )
801    
802  try:  env.SConscript(dirs = ['tools/escriptconvert'], variant_dir='$BUILD_DIR/$PLATFORM/tools/escriptconvert', duplicate=0)
803     api_epydoc = env.Dir(env['api_epydoc'])  env.SConscript(dirs = ['paso/src'], variant_dir='$BUILD_DIR/$PLATFORM/paso', duplicate=0)
804  except KeyError:  env.SConscript(dirs = ['weipa/src'], variant_dir='$BUILD_DIR/$PLATFORM/weipa', duplicate=0)
805     api_epydoc = None  env.SConscript(dirs = ['escript/src'], variant_dir='$BUILD_DIR/$PLATFORM/escript', duplicate=0)
806    env.SConscript(dirs = ['esysUtils/src'], variant_dir='$BUILD_DIR/$PLATFORM/esysUtils', duplicate=0)
807    env.SConscript(dirs = ['pasowrap/src'], variant_dir='$BUILD_DIR/$PLATFORM/pasowrap', duplicate=0)
808    env.SConscript(dirs = ['dudley/src'], variant_dir='$BUILD_DIR/$PLATFORM/dudley', duplicate=0)
809    env.SConscript(dirs = ['finley/src'], variant_dir='$BUILD_DIR/$PLATFORM/finley', duplicate=0)
810    env.SConscript(dirs = ['ripley/src'], variant_dir='$BUILD_DIR/$PLATFORM/ripley', duplicate=0)
811    env.SConscript(dirs = ['downunder/py_src'], variant_dir='$BUILD_DIR/$PLATFORM/downunder', duplicate=0)
812    env.SConscript(dirs = ['modellib/py_src'], variant_dir='$BUILD_DIR/$PLATFORM/modellib', duplicate=0)
813    env.SConscript(dirs = ['pycad/py_src'], variant_dir='$BUILD_DIR/$PLATFORM/pycad', duplicate=0)
814    env.SConscript(dirs = ['pythonMPI/src'], variant_dir='$BUILD_DIR/$PLATFORM/pythonMPI', duplicate=0)
815    env.SConscript(dirs = ['doc'], variant_dir='$BUILD_DIR/$PLATFORM/doc', duplicate=0)
816    env.SConscript(dirs = ['paso/profiling'], variant_dir='$BUILD_DIR/$PLATFORM/paso/profiling', duplicate=0)
817    
818    
819    ######################## Populate the buildvars file #########################
820    
821    # remove obsolete file
822    if not env['usempi']:
823        Execute(Delete(os.path.join(env['libinstall'], 'pythonMPI')))
824        Execute(Delete(os.path.join(env['libinstall'], 'pythonMPIredirect')))
825    
826    # Try to extract the boost version from version.hpp
827    boosthpp=open(os.path.join(boost_inc_path, 'boost', 'version.hpp'))
828    boostversion='unknown'
829    try:
830        for line in boosthpp:
831            ver=re.match(r'#define BOOST_VERSION (\d+)',line)
832            if ver:
833                boostversion=ver.group(1)
834    except StopIteration:
835        pass
836    boosthpp.close()
837    
838    
839    buildvars=open(os.path.join(env['libinstall'], 'buildvars'), 'w')
840    buildvars.write("svn_revision="+str(global_revision)+"\n")
841    buildvars.write("prefix="+prefix+"\n")
842    buildvars.write("cc="+env['CC']+"\n")
843    buildvars.write("cxx="+env['CXX']+"\n")
844    if env['pythoncmd']=='python':
845        buildvars.write("python="+sys.executable+"\n")
846        buildvars.write("python_version="+str(sys.version_info[0])+"."+str(sys.version_info[1])+"."+str(sys.version_info[2])+"\n")
847    else:
848        buildvars.write("python="+env['pythoncmd']+"\n")
849        p=Popen([env['pythoncmd'], '-c', 'from __future__ import print_function;import sys;print(str(sys.version_info[0])+"."+str(sys.version_info[1])+"."+str(sys.version_info[2]))'], stdout=PIPE)
850        verstring=p.stdout.readline().strip()
851        p.wait()
852        buildvars.write("python_version="+verstring+"\n")
853    buildvars.write("boost_inc_path="+boost_inc_path+"\n")
854    buildvars.write("boost_lib_path="+boost_lib_path+"\n")
855    buildvars.write("boost_version="+boostversion+"\n")
856    buildvars.write("debug=%d\n"%int(env['debug']))
857    buildvars.write("openmp=%d\n"%int(env['openmp']))
858    buildvars.write("mpi=%s\n"%env['mpi'])
859    buildvars.write("mpi_inc_path=%s\n"%mpi_inc_path)
860    buildvars.write("mpi_lib_path=%s\n"%mpi_lib_path)
861    buildvars.write("lapack=%s\n"%env['lapack'])
862    buildvars.write("vsl_random=%d\n"%int(env['vsl_random']))
863    for i in 'netcdf','parmetis','papi','mkl','umfpack','boomeramg','silo','visit':
864        buildvars.write("%s=%d\n"%(i, int(env[i])))
865        if env[i]:
866            buildvars.write("%s_inc_path=%s\n"%(i, eval(i+'_inc_path')))
867            buildvars.write("%s_lib_path=%s\n"%(i, eval(i+'_lib_path')))
868    buildvars.close()
869    
870    ################### Targets to build and install libraries ###################
871    
872    target_init = env.Command(os.path.join(env['pyinstall'],'__init__.py'), None, Touch('$TARGET'))
873    env.Alias('target_init', [target_init])
874    # delete buildvars upon cleanup
875    env.Clean('target_init', os.path.join(env['libinstall'], 'buildvars'))
876    
877    # The headers have to be installed prior to build in order to satisfy
878    # #include <paso/Common.h>
879    env.Alias('build_esysUtils', ['install_esysUtils_headers', 'build_esysUtils_lib'])
880    env.Alias('install_esysUtils', ['build_esysUtils', 'install_esysUtils_lib'])
881    
882    env.Alias('build_paso', ['install_paso_headers', 'build_paso_lib'])
883    env.Alias('install_paso', ['build_paso', 'install_paso_lib'])
884    
885    env.Alias('build_escript', ['install_escript_headers', 'build_escript_lib', 'build_escriptcpp_lib'])
886    env.Alias('install_escript', ['build_escript', 'install_escript_lib', 'install_escriptcpp_lib', 'install_escript_py'])
887    
888    env.Alias('build_pasowrap', ['install_pasowrap_headers', 'build_pasowrap_lib', 'build_pasowrapcpp_lib'])
889    env.Alias('install_pasowrap', ['build_pasowrap', 'install_pasowrap_lib', 'install_pasowrapcpp_lib', 'install_pasowrap_py'])
890    
891    env.Alias('build_dudley', ['install_dudley_headers', 'build_dudley_lib', 'build_dudleycpp_lib'])
892    env.Alias('install_dudley', ['build_dudley', 'install_dudley_lib', 'install_dudleycpp_lib', 'install_dudley_py'])
893    
894    env.Alias('build_finley', ['install_finley_headers', 'build_finley_lib', 'build_finleycpp_lib'])
895    env.Alias('install_finley', ['build_finley', 'install_finley_lib', 'install_finleycpp_lib', 'install_finley_py'])
896    
897    env.Alias('build_ripley', ['install_ripley_headers', 'build_ripley_lib', 'build_ripleycpp_lib'])
898    env.Alias('install_ripley', ['build_ripley', 'install_ripley_lib', 'install_ripleycpp_lib', 'install_ripley_py'])
899    
900    env.Alias('build_weipa', ['install_weipa_headers', 'build_weipa_lib', 'build_weipacpp_lib'])
901    env.Alias('install_weipa', ['build_weipa', 'install_weipa_lib', 'install_weipacpp_lib', 'install_weipa_py'])
902    
903    env.Alias('build_escriptreader', ['install_weipa_headers', 'build_escriptreader_lib'])
904    env.Alias('install_escriptreader', ['build_escriptreader', 'install_escriptreader_lib'])
905    
906    # Now gather all the above into some easy targets: build_all and install_all
907    build_all_list = []
908    build_all_list += ['build_esysUtils']
909    build_all_list += ['build_paso']
910    build_all_list += ['build_escript']
911    build_all_list += ['build_pasowrap']
912    build_all_list += ['build_dudley']
913    build_all_list += ['build_finley']
914    build_all_list += ['build_ripley']
915    build_all_list += ['build_weipa']
916    if not IS_WINDOWS: build_all_list += ['build_escriptreader']
917    if env['usempi']:   build_all_list += ['build_pythonMPI']
918    build_all_list += ['build_escriptconvert']
919    env.Alias('build_all', build_all_list)
920    
921    install_all_list = []
922    install_all_list += ['target_init']
923    install_all_list += ['install_esysUtils']
924    install_all_list += ['install_paso']
925    install_all_list += ['install_escript']
926    install_all_list += ['install_pasowrap']
927    install_all_list += ['install_dudley']
928    install_all_list += ['install_finley']
929    install_all_list += ['install_ripley']
930    install_all_list += ['install_weipa']
931    if not IS_WINDOWS: install_all_list += ['install_escriptreader']
932    install_all_list += ['install_downunder_py']
933    install_all_list += ['install_modellib_py']
934    install_all_list += ['install_pycad_py']
935    if env['usempi']:   install_all_list += ['install_pythonMPI']
936    install_all_list += ['install_escriptconvert']
937    env.Alias('install_all', install_all_list)
938    
939    # Default target is install
940    env.Default('install_all')
941    
942    ################## Targets to build and run the test suite ###################
943    
944    if not env['cppunit']:
945        test_msg = env.Command('.dummy.', None, '@echo "Cannot run C/C++ unit tests, CppUnit not found!";exit 1')
946        env.Alias('run_tests', test_msg)
947    env.Alias('run_tests', ['install_all'])
948    env.Alias('all_tests', ['install_all', 'run_tests', 'py_tests'])
949    env.Alias('build_full',['install_all','build_tests','build_py_tests'])
950    env.Alias('build_PasoTests','$BUILD_DIR/$PLATFORM/paso/profiling/PasoTests')
951    
952    ##################### Targets to build the documentation #####################
953    
954    env.Alias('api_epydoc','install_all')
955    env.Alias('docs', ['examples_tarfile', 'examples_zipfile', 'api_epydoc', 'api_doxygen', 'user_pdf', 'install_pdf', 'cookbook_pdf'])
956    env.Alias('release_prep', ['docs', 'install_all'])
957    
958  # Zipgets  if not IS_WINDOWS:
959        try:
960            utest=open('utest.sh','w')
961            utest.write(GroupTest.makeHeader(env['PLATFORM'], prefix))
962            for tests in TestGroups:
963                utest.write(tests.makeString())
964            utest.close()
965            Execute(Chmod('utest.sh', 0o755))
966            print("Generated utest.sh.")
967        except IOError:
968            print("Error attempting to write unittests file.")
969            Exit(1)
970    
971        # delete utest.sh upon cleanup
972        env.Clean('target_init', 'utest.sh')
973    
974        # Make sure that the escript wrapper is in place
975        if not os.path.isfile(os.path.join(env['bininstall'], 'run-escript')):
976            print("Copying escript wrapper.")
977            Execute(Copy(os.path.join(env['bininstall'],'run-escript'), 'bin/run-escript'))
978    
 env.Default(libinstall)  
 env.Default(incinstall)  
 env.Default(pyinstall)  
 env.Alias('release_src',[ src_zipfile, src_tarfile ])  
 env.Alias('release_tests',[ test_zipfile, test_tarfile])  
 env.Alias('release_examples',[ examples_zipfile, examples_tarfile])  
 env.Alias('api_epydoc',api_epydoc)  
 env.Alias('guide_pdf', guide_pdf)  
 env.Alias('docs',[ 'release_examples', 'guide_pdf', guide_html_index, api_epydoc])  
 env.Alias('release', ['release_src', 'release_tests', 'docs'])  
 env.Alias('build_tests')    # target to build all C++ tests  
 env.Alias('build_py_tests') # target to build all python tests  
 env.Alias('build_all_tests', [ 'build_tests', 'build_py_tests' ] ) # target to build all python tests  
 env.Alias('run_tests', 'build_tests')   # target to run all C++ test  
 env.Alias('py_tests', 'build_py_tests') # taget to run all released python tests  
 env.Alias('all_tests', ['run_tests', 'py_tests']) # target to run all C++ and released python tests  
   
 # Python install - esys __init__.py  
 init_target = env.Command(pyinstall+'/__init__.py', None, Touch('$TARGET'))  
 env.Alias(init_target)  
   
 # Allow sconscripts to see the env  
 Export(["env", "incinstall", "libinstall", "pyinstall", "dodebug", "mkl_libs", "scsl_libs", "umf_libs", "amd_libs", "blas_libs", "netCDF_libs_cxx",  
     "boost_lib", "python_lib", "doxygen_path", "epydoc_path", "papi_libs",  
         "sys_libs", "test_zipfile", "src_zipfile", "test_tarfile", "src_tarfile", "examples_tarfile", "examples_zipfile",  
         "guide_pdf", "guide_html_index", "api_epydoc", "useMPI"])  
   
 # End initialisation section  
 # Begin configuration section  
 # adds this file and the scons option directore to the source tar  
 release_srcfiles=[env.File('SConstruct'),]+[ env.File(x) for x in glob.glob('scons/*.py') ]  
 release_testfiles=[env.File('README_TESTS'),]  
 env.Zip(src_zipfile, release_srcfiles)  
 env.Zip(test_zipfile, release_testfiles)  
 env.Tar(src_tarfile, release_srcfiles)  
 env.Tar(test_tarfile, release_testfiles)  
   
 # Insert new components to be build here  
 # FIXME: might be nice to replace this verbosity with a list of targets and some  
 # FIXME: nifty python to create the lengthy but very similar env.Sconscript lines  
 # Third Party libraries  
 env.SConscript(dirs = ['tools/CppUnitTest/src'], build_dir='build/$PLATFORM/tools/CppUnitTest', duplicate=0)  
 # C/C++ Libraries  
 env.SConscript(dirs = ['paso/src'], build_dir='build/$PLATFORM/paso', duplicate=0)  
 # bruce is removed for now as it doesn't really do anything  
 # env.SConscript(dirs = ['bruce/src'], build_dir='build/$PLATFORM/bruce', duplicate=0)  
 env.SConscript(dirs = ['escript/src'], build_dir='build/$PLATFORM/escript', duplicate=0)  
 env.SConscript(dirs = ['esysUtils/src'], build_dir='build/$PLATFORM/esysUtils', duplicate=0)  
 env.SConscript(dirs = ['finley/src'], build_dir='build/$PLATFORM/finley', duplicate=0)  
 env.SConscript(dirs = ['modellib/py_src'], build_dir='build/$PLATFORM/modellib', duplicate=0)  
 env.SConscript(dirs = ['doc'], build_dir='build/$PLATFORM/doc', duplicate=0)  
 env.SConscript(dirs = ['pyvisi/py_src'], build_dir='build/$PLATFORM/pyvisi', duplicate=0)  
 env.SConscript(dirs = ['pycad/py_src'], build_dir='build/$PLATFORM/pycad', duplicate=0)  
   
 # added by Ben Cumming  
 env.SConscript(dirs = ['pythonMPI/src'], build_dir='build/$PLATFORM/pythonMPI', duplicate=0)  
 #env.SConscript(dirs = ['../test'], build_dir='../test/build', duplicate=0)  

Legend:
Removed from v.965  
changed lines
  Added in v.3961

  ViewVC Help
Powered by ViewVC 1.1.26