Imported Upstream version 0.5
[pysam.git] / setup.py
1 #!/usr/bin/python
2 '''
3
4 pysam
5 *****
6
7 '''
8
9 import os, sys, glob, shutil, hashlib, re, fnmatch
10 import platform
11
12 name = "pysam"
13
14 # collect pysam version
15 sys.path.insert( 0, "pysam")
16 import version
17
18 version = version.__version__
19
20 samtools_exclude = ( "bamtk.c", "razip.c", "bgzip.c", 
21                      "bam_reheader.c", 
22                      "main.c", "calDepth.c", "bam2bed.c",
23                      "wgsim.c", "md5fa.c", "maq2sam.c",)
24 samtools_dest = os.path.abspath( "samtools" )
25 tabix_exclude = ( "main.c", )
26 tabix_dest = os.path.abspath( "tabix" )
27
28 def locate(pattern, root=os.curdir):
29     '''Locate all files matching supplied filename pattern in and below
30     supplied root directory.'''
31     for path, dirs, files in os.walk(os.path.abspath(root)):
32        for filename in fnmatch.filter(files, pattern):
33           yield os.path.join(path, filename)
34
35 def _update_pysam_files(cf, destdir):
36   for filename in cf:
37      if not filename: continue
38      dest = filename + ".pysam.c"
39      with open( filename ) as infile:
40         with open( dest, "w" ) as outfile:
41            outfile.write( '#include "pysam.h"\n\n' )
42            outfile.write( re.sub( "stderr", "pysamerr", "".join(infile.readlines()) ) )
43   with open( os.path.join( destdir, "pysam.h" ), "w" )as outfile:
44      outfile.write ("""#ifndef PYSAM_H
45 #define PYSAM_H
46 #include "stdio.h"
47 extern FILE * pysamerr;
48 #endif
49 """)
50
51 # copy samtools source
52 if len(sys.argv) >= 2 and sys.argv[1] == "import":
53    if len(sys.argv) < 3: raise ValueError("missing PATH to samtools source directory")
54    if len(sys.argv) < 4: raise ValueError("missing PATH to tabix source directory")
55
56    for destdir, srcdir, exclude in zip( 
57       (samtools_dest, tabix_dest), 
58       sys.argv[2:4],
59       (samtools_exclude, tabix_exclude)):
60
61       srcdir = os.path.abspath( srcdir )
62       if not os.path.exists( srcdir ): raise IOError( "samtools src dir `%s` does not exist." % srcdir )
63
64       cfiles = locate( "*.c", srcdir )
65       hfiles = locate( "*.h", srcdir )
66       ncopied = 0
67       
68       def _compareAndCopy( src, srcdir, destdir, exclude ):
69
70          d, f = os.path.split(src)
71          if f in exclude: return None
72          common_prefix = os.path.commonprefix( (d, srcdir ) )
73          subdir = re.sub( common_prefix, "", d )[1:]
74          targetdir = os.path.join( destdir, subdir )
75          if not os.path.exists( targetdir ):
76             os.makedirs( targetdir )
77          old_file = os.path.join( targetdir, f )
78          if os.path.exists( old_file ):
79             md5_old = hashlib.md5("".join(open(old_file,"r").readlines())).digest()
80             md5_new = hashlib.md5("".join(open(src,"r").readlines())).digest()
81             if md5_old != md5_new:
82                raise ValueError( "incompatible files for %s and %s" % (old_file, src ))
83
84          shutil.copy( src, targetdir )
85          return old_file
86
87       for src_file in hfiles:
88          _compareAndCopy( src_file, srcdir,destdir, exclude )
89          ncopied += 1
90
91       cf = []
92       for src_file in cfiles:
93          cf.append( _compareAndCopy( src_file, srcdir, destdir, exclude ) )
94          ncopied += 1
95          
96       print "installed latest source code from %s: %i files copied" % (srcdir, ncopied)
97       # redirect stderr to pysamerr and replace bam.h with a stub.
98       print "applying stderr redirection"
99      
100       _update_pysam_files(cf, destdir)
101       
102
103    sys.exit(0)
104
105 if len(sys.argv) >= 2 and sys.argv[1] == "refresh":
106     print "refreshing latest source code from .c to .pysam.c"
107 # redirect stderr to pysamerr and replace bam.h with a stub.
108     print "applying stderr redirection"
109     for destdir in ('samtools', 'tabix'):
110         pysamcfiles = locate( "*.pysam.c", destdir )
111         for f in pysamcfiles: os.remove(f)
112         cfiles = locate( "*.c", destdir )
113         _update_pysam_files(cfiles, destdir)
114
115     sys.exit(0)
116
117
118
119 from ez_setup import use_setuptools
120 use_setuptools()
121
122 from setuptools import Extension, setup
123
124 ## note that for automatic cythoning, 
125 ## both pyrex and cython need to be installed.
126 ## see http://mail.python.org/pipermail/distutils-sig/2007-September/008204.html
127
128 try:
129     from Cython.Distutils import build_ext
130 except:
131     from setuptools.command.build_ext import build_ext
132
133 classifiers = """
134 Development Status :: 2 - Alpha
135 Operating System :: MacOS :: MacOS X
136 Operating System :: Microsoft :: Windows :: Windows NT/2000
137 Operating System :: OS Independent
138 Operating System :: POSIX
139 Operating System :: POSIX :: Linux
140 Operating System :: Unix
141 Programming Language :: Python
142 Topic :: Scientific/Engineering
143 Topic :: Scientific/Engineering :: Bioinformatics
144 """
145
146 if platform.system()=='Windows':
147     include_os = ['win32']
148     os_c_files = ['win32/getopt.c']
149 else:
150     include_os = []
151     os_c_files = []
152
153 samtools = Extension(
154     "csamtools",                   # name of extension
155     [ "pysam/csamtools.pyx" ]  +\
156         [ "pysam/%s" % x for x in (
157                 "pysam_util.c", )] +\
158         glob.glob( os.path.join( "samtools", "*.pysam.c" )) +\
159         os_c_files + \
160         glob.glob( os.path.join( "samtools", "*", "*.pysam.c" ) ),
161     library_dirs=[],
162     include_dirs=[ "samtools", "pysam" ] + include_os,
163     libraries=[ "z", ],
164     language="c",
165     define_macros = [('_FILE_OFFSET_BITS','64'),
166                      ('_USE_KNETFILE','')], 
167     )
168
169 tabix = Extension(
170     "ctabix",                   # name of extension
171     [ "pysam/ctabix.pyx", ]  +\
172        [ "pysam/%s" % x for x in ( "tabix_util.c", )] +\
173         os_c_files + \
174        glob.glob( os.path.join( "tabix", "*.pysam.c" ) ),
175     library_dirs=[],
176     include_dirs=[ "tabix", "pysam" ] + include_os,
177     libraries=[ "z", ],
178     language="c",
179     )
180
181 tabproxies = Extension(
182     "TabProxies",                   # name of extension
183     [ "pysam/TabProxies.pyx", ] + os_c_files,
184     library_dirs=[],
185     include_dirs= include_os,
186     libraries=[ "z", ],
187     language="c",
188     )
189
190 cvcf = Extension(
191     "cvcf",                   # name of extension
192     [ "pysam/cvcf.pyx", ] + os_c_files,
193     library_dirs=[],
194     include_dirs= ["tabix",] + include_os,
195     libraries=[ "z", ],
196     language="c",
197     )
198
199 metadata = {
200     'name': name,
201     'version': version,
202     'description': "pysam", 
203     'long_description': __doc__,
204     'author': "Andreas Heger",
205     'author_email': "andreas.heger@gmail.com",
206     'license': "MIT",
207     'platforms': "ALL",
208     'url': "http://code.google.com/p/pysam/",
209     'py_modules': [
210       "pysam/__init__", 
211       "pysam/Pileup", 
212       "pysam/namedtuple",
213       "pysam/version" ],
214     'requires' : ['cython (>=0.12)'],
215     'ext_modules': [samtools, tabix, tabproxies, cvcf ],
216     'cmdclass' : {'build_ext': build_ext},
217     'install_requires' : ['cython>=0.12.1',], 
218     # do not pack in order to permit linking to csamtools.so
219     'zip_safe' :False,
220     }
221
222 if __name__=='__main__':
223    dist = setup(**metadata)