source: trunk/fsource/SConstruct @ 606

Last change on this file since 606 was 370, checked in by toby, 14 years ago

Edits to build on 64-bit linux (RH Enterprise 5)

File size: 12.6 KB
Line 
1# this is a build script that is intended to be run from scons (it will not work in python)
2# it compiles the Fortran files needed to be used as Python packages for GSAS-II
3#
4# if the default options need to be overridden for this to work on your system, please let me
5# know the details of what OS, compiler and python you are using as well as the command-line
6# options you need.
7import platform
8import sys
9import os
10import glob
11import subprocess
12#==========================================================================================
13def is_exe(fpath):
14    return os.path.exists(fpath) and os.access(fpath, os.X_OK)
15def which_path(program):
16    "emulates Unix which: finds a program in path, but returns the path"
17    import os, sys
18    if sys.platform == "win32" and os.path.splitext(program)[1].lower() != '.exe':
19        program = program + '.exe'
20    fpath, fname = os.path.split(program)
21    if fpath:
22        if is_exe(program):
23            return fpath
24    else:
25        for path in os.environ["PATH"].split(os.pathsep):
26            exe_file = os.path.join(path, program)
27            if is_exe(exe_file):
28                return path
29    return ""
30#==========================================================================================
31# misc initializations
32# need command-line options for fortran command and fortran options
33F2PYflags = '' # compiler options for f2py command
34# find a default f2py relative to the scons location. Should be in the same place as f2py
35F2PYpath = ''
36for program in ['f2py','../f2py']:
37    if sys.platform == "win32" and os.path.splitext(program)[1].lower() != '.exe':
38        program = program + '.exe'
39    spath = os.path.split(sys.executable)[0]
40    print spath
41    f2pyprogram = os.path.normpath(os.path.join(spath,program))
42    if is_exe(f2pyprogram):
43        F2PYpath = os.path.split(f2pyprogram)[0]
44        break
45else:
46    print 'Note: Using f2py from path (hope that works!)'
47    F2PYpath = which_path('f2py')       # default path to f2py
48
49GFORTpath = which_path('gfortran')   # path to compiler
50FCompiler='gfortran'
51G77path = which_path('g77')     # path to compiler
52FORTpath = ""
53FORTflags = ""
54liblist = []
55LDFLAGS = ''
56#==========================================================================================
57# configure platform dependent options here:
58if sys.platform == "win32":
59    F2PYsuffix = '.pyd'
60    if G77path != "":
61      FCompiler='g77'
62    elif GFORTpath != "":
63      FCompiler='gfortran'
64    else:
65      print 'No Fortran compiler in path'
66      sys.exit()
67elif sys.platform == "darwin":
68    LDFLAGS = '-undefined dynamic_lookup -bundle -static-libgfortran -static-libgcc'
69    F2PYsuffix = '.so'
70elif sys.platform == "linux2":
71    #LDFLAGS = '-Wall -shared -static-libgfortran -static-libgcc' # does not work with gfortran 4.4.4 20100726 (Red Hat 4.4.4-13)
72    F2PYsuffix = '.so'
73else:
74    print "Sorry, parameters for platform "+sys.platform+" are not yet defined"
75    sys.exit()
76#==========================================================================================
77# help
78if 'help' in COMMAND_LINE_TARGETS:
79    print """
80----------------------------------------------
81Building Fortran routines for use with GSAS-II
82----------------------------------------------
83
84To build the compiled modules files needed to run GSAS-II, invoke this script:
85    scons [options]
86where the following options are defined (all are optional):
87
88-Q      -- produces less output from scons
89
90-n      -- causes scons to show but not execute the commands it will perform
91
92-c      -- clean: causes scons to delete previously created files (don't use
93   with install)
94
95help    -- causes this message to be displayed (no compiling is done)
96
97install -- causes the module files to be placed in an installation directory
98   (../bin<X>NNv.v) rather than ../bin (<X> is mac, win or linux; NN is 64-
99   or blank; v.v is the python version (2.6 or 2.7,...). Normally used only
100   by Brian or Bob for distribution of compiled software.
101
102The following options override defaults set in the scons script:
103
104FCompiler=<name>  -- define the name of the fortran compiler, typically g77
105   or gfortran; default is to use g77 on Windows and gfortran elsewhere. If
106   you use something other than these, you must also specify F2PYflags.
107
108FORTpath=<path>    -- define a path to the fortran program; default is to use
109   first gfortran (g77 for Windows) found in path
110
111FORTflags='string' -- string of options to be used for Fortran
112   during library build step
113
114F2PYpath=<path>    -- define a path to the f2py program; default is to use
115   first f2py found in path
116
117F2PYflags='string' -- defines optional flags to be supplied to f2py:
118   Typically these option define which fortran compiler to use.
119
120F2PYsuffix='.xxx'  -- extension for output module files (default: win: '.pyd',
121   mac/linux: '.so')
122
123LDFLAGS='string'   -- string of options to be used for f2py during link step
124
125Note that at present, this has been tested with 32-bit python on windows and
126Mac & 64 bit on linux. Python 3.x is not supported in GSAS-II yet.
127
128examples:
129    scons -Q
130       (builds into ../bin for current platform using default options)
131    scons -Q install
132       (builds into ../bin<platform> for module distribution)
133    scons -Q install F2PYpath=/Library/Frameworks/Python.framework/Versions/6.2/bin/
134       (builds with a non-default [e.g. older] version of python)
135    """
136    #sys.exit()
137#==========================================================================================
138# override from command-line options
139for var in ['F2PYflags','F2PYpath','F2PYsuffix','FCompiler','FORTpath','FORTflags','LDFLAGS']:
140    if ARGUMENTS.get(var, None) is not None:
141        print 'Setting',var,'to',ARGUMENTS.get(var),'based on command line'
142        exec(var + "= ARGUMENTS.get('" + var +"')")
143#==========================================================================================
144# get the python version number from the python image in the f2py directory
145# first check if we have a working path to f2py:
146f2pyprogram = os.path.normpath(os.path.join(F2PYpath,'f2py'))
147if sys.platform == "win32" and os.path.splitext(f2pyprogram)[1].lower() != '.exe':
148    f2pyprogram = f2pyprogram + '.exe'
149if not is_exe(f2pyprogram):
150    print '''
151ERROR: The f2py program was not found. If this program is installed
152but not in your path, you should specify the path on the command line:
153   scons -Q F2PYpath=/Library/Frameworks/Python.framework/Versions/6.2/bin/
154   scons -Q F2PYpath=D:/Python27/Scripts
155'''
156    sys.exit()
157# find the python location associated with the f2py in use. Note
158#   that on Windows it may be in the parent of the f2py location.
159# then run it to get info about the verision and the number of bits
160pythonpath = ''
161for program in ['python','../python']:
162    if sys.platform == "win32" and os.path.splitext(program)[1].lower() != '.exe':
163        program = program + '.exe'
164    pythonprogram = os.path.normpath(os.path.join(F2PYpath,program))
165    if is_exe(pythonprogram):
166        pythonpath = os.path.split(program)[0]
167        break
168else:
169    print 'python not found'
170    sys.exit()
171p = subprocess.Popen(pythonprogram, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
172p.stdin.write("import sys,platform;print str(sys.version_info[0]);print str(sys.version_info[1]);print platform.architecture()[0];sys.exit()")
173p.stdin.close()
174p.wait()
175versions = p.stdout.readlines()
176version = str(int(versions[0])) + '.' + str(int(versions[1]))
177PlatformBits = versions[2][:-1]
178#
179
180# Install location
181InstallLoc = '../bin'
182if len(COMMAND_LINE_TARGETS) == 0:
183    Default(InstallLoc)
184elif 'install' in COMMAND_LINE_TARGETS:
185    if PlatformBits == '64bit':
186        bits = '64-'
187    else:
188        bits = ''
189    if sys.platform == "win32":
190        prefix = 'binwin'
191    elif sys.platform == "darwin":
192        prefix = 'binmac'
193    elif sys.platform == "linux2":
194        prefix = 'binlinux'
195    InstallLoc = '../' + prefix + bits + version
196    Alias('install',InstallLoc)
197#==========================================================================================
198# use the compiler choice to set compiler options, but don't change anything
199# specified on the command line
200if FCompiler == 'gfortran':
201    if FORTpath == "": FORTpath = GFORTpath
202    if F2PYflags == "": F2PYflags = '--fcompiler=gnu95 --f77exec=gfortran --f77flags="-fno-range-check"'
203#    if sys.platform == "linux2":
204#        if FORTflags == "": FORTflags = ' -w -O2 -fPIC'
205    if sys.platform == "linux2" and PlatformBits == '64bit':
206        if FORTflags == "": FORTflags = ' -w -O2 -fPIC -m64'
207    elif sys.platform == "linux2":
208        if FORTflags == "": FORTflags = ' -w -O2 -fPIC -m32'
209elif FCompiler == 'g77':
210    if FORTpath == "": FORTpath = G77path
211    if sys.platform == "win32":
212        if F2PYflags == "": F2PYflags = '--compiler=mingw32 --fcompiler=gnu'
213        if FORTflags == "": FORTflags = ' -w -O2 -fno-automatic -finit-local-zero -malign-double -mwindows'
214    else:
215        if F2PYflags == "": F2PYflags = '--fcompiler=gnu --f77exec=g77 --f77flags="-fno-range-check"'
216
217else:
218    if FORTpath == "": print 'Likely error, FORTpath is not specified'
219    if F2PYflags == "":
220        print 'Error: specify a F2PYflags value'
221        sys.exit()
222#==========================================================================================
223# Setup build Environment
224env = Environment()
225# Define a builder to run f2py
226def generate_f2py(source, target, env, for_signature):
227    module = os.path.splitext(str(source[0]))[0]
228    if len(liblist) > 0:
229        for lib in liblist:
230            module = module + ' ' + str(lib)
231    return os.path.join(F2PYpath,'f2py')  + ' -c $SOURCE -m ' + module + ' ' + F2PYflags
232f2py = Builder(generator = generate_f2py)
233env.Append(BUILDERS = {'f2py' : f2py},)
234# create a builder for the fortran compiler for library compilation so we can control how it is done
235def generate_obj(source, target, env, for_signature):
236    dir = os.path.split(str(source[0]))[0]
237    obj = os.path.splitext(str(source[0]))[0]+'.o'
238    return os.path.join(FORTpath,FCompiler)  + ' -c $SOURCE ' + FORTflags + ' -I' + dir + ' -o' + obj
239fort = Builder(generator = generate_obj, suffix = '.o',
240               src_suffix = '.for')
241# create a library builder so we can control how it is done on windows
242def generate_lib(source, target, env, for_signature):
243    srclst = ""
244    for s in source:
245      srclst += str(s) + " "
246    return os.path.join(FORTpath,'ar.exe')  + ' -rs $TARGET ' + srclst
247lib = Builder(generator = generate_lib, suffix = '.a',
248               src_suffix = '.o')
249env.Append(BUILDERS = {'fort' : fort, 'lib' : lib},)
250
251#==========================================================================================
252# Setup build Environment
253#    add compiler, f2py & python to path
254if FORTpath != "":  env.PrependENVPath('PATH', FORTpath)
255if F2PYpath != "":  env.PrependENVPath('PATH', F2PYpath)
256if pythonpath != "" and pythonpath != F2PYpath: env.PrependENVPath('PATH', pythonpath)
257#   add other needed environment variables
258var = 'LDFLAGS'
259if eval(var) != "": env['ENV'][var] = eval(var)
260
261#==========================================================================================
262# finally ready to build something!
263# locate libraries to be built (subdirectories named *subs)
264for sub in glob.glob('*subs'):
265    filelist = []
266    for file in glob.glob(os.path.join(sub,'*.for')):
267        #target = os.path.splitext(file)[0]+'.o'
268        target = env.fort(file) # connect .o files to .for files
269        #print 'Compile: ',file, target
270        filelist.append(target)
271    #lib = Library(sub, Glob(os.path.join(sub,'*.for'))) # register library to be created
272    if sys.platform == "win32":
273         lib = env.lib(sub, filelist)
274    else:
275       lib = Library(sub, filelist) # register library to be created
276    liblist.append(lib[0].name)
277    filename = str(lib[0])
278    #Install(InstallLoc,filename)
279# find modules that need to be built
280modlist = []
281for src in glob.glob('*.for'):
282    target = os.path.splitext(src)[0] + F2PYsuffix
283    out = env.f2py(target,src)
284    Depends(target, liblist) # make sure libraries are rebuilt if old
285    modlist.append(out[0].name)
286    env.Install(InstallLoc, out[0].name)
287    #break # bail out early for testing
288#==========================================================================================
289# all done with setup, show the user the options and let scons do the work
290print 80*'='
291for var in ['FCompiler','FORTpath','FORTflags','F2PYflags','F2PYpath','F2PYsuffix','LDFLAGS']:
292    print 'Variable',var,'is',eval(var)
293print 'Using python at', pythonprogram
294print 'Python/f2py version =',version,PlatformBits
295print 'Install directory is',InstallLoc
296print 'Will build object libraries:',
297for lib in liblist: print " " + lib,
298print ""
299print 'f2py will build these modules:',
300for mod in modlist: print " " + mod,
301print ""
302print 80*'='
303#print env.Dump()
304if 'help' in COMMAND_LINE_TARGETS: sys.exit()
Note: See TracBrowser for help on using the repository browser.