setup.py 9.65 KB
Newer Older
1
2
3
"""
setup.py: Used for building python wrappers for Simbios' OpenMM library.
"""
4
5
6
7
8
import ast
import re
import os
import sys
import platform
9
import numpy
10
from distutils.core import setup
peastman's avatar
peastman committed
11
from Cython.Build import cythonize
12

13
14
15
MAJOR_VERSION_NUM='@OPENMM_MAJOR_VERSION@'
MINOR_VERSION_NUM='@OPENMM_MINOR_VERSION@'
BUILD_INFO='@OPENMM_BUILD_VERSION@'
16
17
IS_RELEASED = False

Robert McGibbon's avatar
merge  
Robert McGibbon committed
18
__author__ = "Peter Eastman"
19
__version__ = "%s.%s" % (MAJOR_VERSION_NUM, MINOR_VERSION_NUM)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

def reportError(message):
    sys.stdout.write("ERROR: ")
    sys.stdout.write(message)
    sys.stdout.write("\nExiting\n")
    sys.exit(1)

def removeRecursive(dir):
    for file in os.listdir(dir):
        path = os.path.join(dir, file)
        if os.path.isdir(path):
            removeRecursive(path)
        else:
            os.remove(path)
    os.rmdir(dir)

def removePackage(mod, verbose):
        try:
            pathList = mod.__path__
        except AttributeError:
            return
        if len(pathList) > 1:
           raise Exception("more than one item in simtk.__path__")
        simtkInstallPath = pathList[0]
        if os.path.exists(simtkInstallPath):
            if verbose:
                sys.stdout.write('REMOVING "%s"\n' % simtkInstallPath)
            removeRecursive(simtkInstallPath)

def uninstall(verbose=True):
    save_path=sys.path[:]
    sys.path=[]
    for item in save_path:
        if item!='.' and item!=os.getcwd():
            sys.path.append(item)
    try:
56
        import simtk.openmm as openmm
57
58
59
60
61
62
63
64
65
66
67
68
        removePackage(openmm, verbose)
    except ImportError:
        pass

    try:
        import simtk.unit as unit
        removePackage(unit, verbose)
    except ImportError:
        pass
    sys.path=save_path


69
def writeVersionPy(filename="simtk/openmm/version.py", major_version_num=MAJOR_VERSION_NUM,
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
                     minor_version_num=MINOR_VERSION_NUM, build_info=BUILD_INFO):
    """Write a version.py file into the python source directory before installation.
    If a version.py file already exists, we assume that it contains only the git_revision
    information, since from within this python session in the python staging directory, we're
    not in the version controlled directory hierarchy.

    When cmake is copying files into the PYTHON_STAGING_DIRECTORY, it will write the
    git revision to version.py. We read that, and then overwrite it.
    """

    cnt = """
# THIS FILE IS GENERATED FROM OPENMM SETUP.PY
short_version = '%(version)s'
version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
Robert T. McGibbon's avatar
Robert T. McGibbon committed
87
openmm_library_path = r'%(path)s'
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

if not release:
    version = full_version
"""

    if os.path.exists(filename):
        # git_revision is written to the file by cmake
        with open(filename) as f:
            text = f.read()
            match = re.search(r"git_revision\s+=\s+(.*)", text, re.MULTILINE)
        try:
            git_revision = ast.literal_eval(match.group(1))
        except:
            # except anything, including no re match or
            # literal_eval failing
            git_revision = 'Unknown'
    else:
        git_revision = 'Unknown'

    version = full_version = '%s.%s.%s' % (major_version_num, minor_version_num, build_info)
    if not IS_RELEASED:
        full_version += '.dev-' + git_revision[:7]

    a = open(filename, 'w')
    try:
        a.write(cnt % {'version': version,
                       'full_version' : full_version,
                       'git_revision' : git_revision,
116
117
                       'isrelease': str(IS_RELEASED),
                       'path': os.getenv('OPENMM_LIB_PATH')})
118
119
120
121
    finally:
        a.close()


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM,
                           minor_version_num=MINOR_VERSION_NUM,
                           build_info=BUILD_INFO):
    from distutils.core import Extension
    setupKeywords = {}
    setupKeywords["name"]              = "OpenMM"
    setupKeywords["version"]           = "%s.%s.%s" % (major_version_num,
                                                       minor_version_num,
                                                       build_info)
    setupKeywords["author"]            = "Randall J. Radmer"
    setupKeywords["author_email"]      = "radmer@stanford.edu"
    setupKeywords["license"]           = \
    "Python Software Foundation License (BSD-like)"
    setupKeywords["url"]               = "https://simtk.org/home/openmm"
    setupKeywords["download_url"]      = "https://simtk.org/home/openmm"
    setupKeywords["packages"]          = ["simtk",
                                          "simtk.unit",
139
140
                                          "simtk.openmm",
                                          "simtk.openmm.app",
Jason Swails's avatar
Jason Swails committed
141
                                          "simtk.openmm.app.internal",
142
                                          "simtk.openmm.app.internal.charmm",
peastman's avatar
Bug fix  
peastman committed
143
                                          "simtk.openmm.app.internal.pdbx",
144
145
                                          "simtk.openmm.app.internal.pdbx.reader",
                                          "simtk.openmm.app.internal.pdbx.writer"]
146
147
148
    setupKeywords["data_files"]        = []
    setupKeywords["package_data"]      = {"simtk" : [],
                                          "simtk.unit" : [],
149
                                          "simtk.openmm" : [],
150
                                          "simtk.openmm.app" : ['data/*.xml', 'data/*.pdb', 'data/amber14/*.xml', 'data/charmm36/*.xml'],
151
                                          "simtk.openmm.app.internal" : []}
152
153
154
155
    setupKeywords["platforms"]         = ["Linux", "Mac OS X", "Windows"]
    setupKeywords["description"]       = \
    "Python wrapper for OpenMM (a C++ MD package)"
    setupKeywords["long_description"]  = \
Robert McGibbon's avatar
Robert McGibbon committed
156
157
158
159
160
    """OpenMM is a toolkit for molecular simulation. It can be used either as a
    stand-alone application for running simulations, or as a library you call
    from your own code. It provides a combination of extreme flexibility
    (through custom forces and integrators), openness, and high performance
    (especially on recent GPUs) that make it truly unique among simulation codes.
161
162
163
164
165
166
167
    """

    define_macros = [('MAJOR_VERSION', major_version_num),
                     ('MINOR_VERSION', minor_version_num)]

    libraries=['OpenMM',
               'OpenMMAmoeba',
168
               'OpenMMRPMD',
169
               'OpenMMDrude',
170
171
172
173
174
175
176
177
178
              ]
    if 'OPENMM_USE_DEBUG_LIBS' in os.environ:
        if platform.system() == "Windows":
            raise Exception("use of OpenMM debug libs not supported on Win OS")
        else:
            sys.stdout.write("WARNING: using debug libs:\n")
            for ii in range(len(libraries)):
                libraries[ii]="%s_d" % libraries[ii]
                sys.stdout.write("%s\n" % libraries[ii])
Robert McGibbon's avatar
Robert McGibbon committed
179

180
181
182
183
184
185
186
    openmm_include_path = os.getenv('OPENMM_INCLUDE_PATH')
    if not openmm_include_path:
        reportError("Set OPENMM_INCLUDE_PATH to point to the include directory for OpenMM")
    openmm_lib_path = os.getenv('OPENMM_LIB_PATH')
    if not openmm_lib_path:
        reportError("Set OPENMM_LIB_PATH to point to the lib directory for OpenMM")

Andy Simmonett's avatar
Andy Simmonett committed
187
    extra_compile_args=['-std=c++11']
188
189
190
191
192
193
194
195
    extra_link_args=[]
    if platform.system() == "Windows":
        define_macros.append( ('WIN32', None) )
        define_macros.append( ('_WINDOWS', None) )
        define_macros.append( (' _MSC_VER', None) )
        extra_compile_args.append('/EHsc')
    else:
        if platform.system() == 'Darwin':
Andy Simmonett's avatar
Andy Simmonett committed
196
            extra_compile_args += ['-std=c++11 -stdlib=libc++', '-mmacosx-version-min=10.7']
Robert McGibbon's avatar
Robert McGibbon committed
197
            extra_link_args += ['-stdlib=libc++', '-mmacosx-version-min=10.7', '-Wl', '-rpath', openmm_lib_path]
198
199
200
201
202
203
204
            # Hard-code CC and CXX to clang, since gcc/g++ will *not* work with
            # Anaconda, despite the fact that distutils will try to use them.
            # System Python, homebrew, and MacPorts on Macs will always use
            # clang, so this hack should always work and fix issues with users
            # that have GCC installed from MacPorts or homebrew *and* Anaconda
            os.environ['CC'] = 'clang'
            os.environ['CXX'] = 'clang++'
205
206
207

    library_dirs=[openmm_lib_path]
    include_dirs=openmm_include_path.split(';')
208
    include_dirs.append(numpy.get_include())
209

peastman's avatar
peastman committed
210
211
212
213
214
215
216
217
218
219
220
    extensionArgs = {"name": "simtk.openmm._openmm",
                    "sources": ["src/swig_doxygen/OpenMMSwig.cxx"],
                    "include_dirs": include_dirs,
                    "define_macros": define_macros,
                    "library_dirs": library_dirs,
                    "libraries": libraries,
                    "extra_compile_args": extra_compile_args,
                    "extra_link_args": extra_link_args}
    if platform.system() != "Windows":
        extensionArgs["runtime_library_dirs"] = library_dirs
    setupKeywords["ext_modules"] = [Extension(**extensionArgs)]
peastman's avatar
peastman committed
221
    setupKeywords["ext_modules"] += cythonize('simtk/openmm/app/internal/*.pyx', language='c++')
222
223
224
225

    outputString = ''
    firstTab     = 40
    secondTab    = 60
Peter Eastman's avatar
Peter Eastman committed
226
    for key in sorted(iter(setupKeywords)):
227
228
         value         = setupKeywords[key]
         outputString += key.rjust(firstTab) + str( value ).rjust(secondTab) + "\n"
Robert McGibbon's avatar
Robert McGibbon committed
229

Peter Eastman's avatar
Peter Eastman committed
230
    sys.stdout.write("%s" % outputString)
231
232

    return setupKeywords
Robert McGibbon's avatar
Robert McGibbon committed
233

234
235

def main():
236
237
    if sys.version_info < (2, 7):
        reportError("OpenMM requires Python 2.7 or better.")
238
239
240
241
    if platform.system() == 'Darwin':
        macVersion = [int(x) for x in platform.mac_ver()[0].split('.')]
        if tuple(macVersion) < (10, 5):
            reportError("OpenMM requires Mac OS X Leopard (10.5) or better.")
242
243
244
245
    try:
        uninstall()
    except:
        pass
246
    setupKeywords=buildKeywordDictionary()
247
    writeVersionPy()
248
249
250
251
252
253
    setup(**setupKeywords)

if __name__ == '__main__':
    main()