source: trunk/fsource/SConstruct @ 317

Last change on this file since 317 was 317, checked in by toby, 10 years ago

more work

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