source: sasview/setup.py @ dbc1f73

Last change on this file since dbc1f73 was 46119c2, checked in by wojciech, 5 years ago

cleaning up setup

  • Property mode set to 100755
File size: 14.9 KB
Line 
1# -*- coding: utf-8 -*-
2#!/usr/bin/env python
3
4"""
5    Setup for SasView
6    TODO: Add checks to see that all the dependencies are on the system
7"""
8from __future__ import print_function
9
10import os
11import subprocess
12import shutil
13import sys
14
15import numpy as np
16
17from setuptools import Extension, setup
18from setuptools import Command
19from setuptools.command.build_ext import build_ext
20
21try:
22    import tinycc.distutils
23except ImportError:
24    pass
25
26# Convert "test" argument to "pytest" so 'python setup.py test' works
27sys.argv = [("pytest" if s == "test" else s) for s in sys.argv]
28
29# Manage version number ######################################
30with open(os.path.join("src", "sas", "sasview", "__init__.py")) as fid:
31    for line in fid:
32        if line.startswith('__version__'):
33            VERSION = line.split('"')[1]
34            break
35    else:
36        raise ValueError("Could not find version in src/sas/sasview/__init__.py")
37##############################################################
38
39package_dir = {}
40package_data = {}
41packages = []
42ext_modules = []
43
44# Remove all files that should be updated by this setup
45# We do this here because application updates these files from .sasview
46# except when there is no such file
47# Todo : make this list generic
48# plugin_model_list = ['polynominal5.py', 'sph_bessel_jn.py',
49#                      'sum_Ap1_1_Ap2.py', 'sum_p1_p2.py',
50#                      'testmodel_2.py', 'testmodel.py',
51#                      'polynominal5.pyc', 'sph_bessel_jn.pyc',
52#                      'sum_Ap1_1_Ap2.pyc', 'sum_p1_p2.pyc',
53#                      'testmodel_2.pyc', 'testmodel.pyc', 'plugins.log']
54
55CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
56SASVIEW_BUILD = os.path.join(CURRENT_SCRIPT_DIR, "build")
57
58
59# Optionally clean before build.
60dont_clean = 'update' in sys.argv
61if dont_clean:
62    sys.argv.remove('update')
63elif os.path.exists(SASVIEW_BUILD):
64    print("Removing existing build directory", SASVIEW_BUILD, "for a clean build")
65    shutil.rmtree(SASVIEW_BUILD)
66
67# 'sys.maxsize' and 64bit: Not supported for python2.5
68is_64bits = sys.maxsize > 2**32
69
70enable_openmp = False
71if sys.platform == 'darwin':
72    if not is_64bits:
73        # Disable OpenMP
74        enable_openmp = False
75    else:
76        # Newer versions of Darwin don't support openmp
77        try:
78            darwin_ver = int(os.uname()[2].split('.')[0])
79            if darwin_ver >= 12:
80                enable_openmp = False
81        except:
82            print("PROBLEM determining Darwin version")
83
84# Options to enable OpenMP
85copt = {'msvc': ['/openmp'],
86        'mingw32': ['-fopenmp'],
87        'unix': ['-fopenmp']}
88lopt = {'msvc': ['/MANIFEST'],
89        'mingw32': ['-fopenmp'],
90        'unix': ['-lgomp']}
91
92# Platform-specific link options
93platform_lopt = {'msvc': ['/MANIFEST']}
94platform_copt = {}
95
96# Set copts to get compile working on OS X >= 10.9 using clang
97if sys.platform == 'darwin':
98    try:
99        darwin_ver = int(os.uname()[2].split('.')[0])
100        if darwin_ver >= 13 and darwin_ver < 14:
101            platform_copt = {
102                'unix': ['-Wno-error=unused-command-line-argument-hard-error-in-future']}
103    except:
104        print("PROBLEM determining Darwin version")
105
106
107class DisableOpenMPCommand(Command):
108    description = "The version of MinGW that comes with Anaconda does not come with OpenMP :( "\
109                  "This commands means we can turn off compiling with OpenMP for this or any "\
110                  "other reason."
111    user_options = []
112
113    def initialize_options(self):
114        self.cwd = None
115
116    def finalize_options(self):
117        self.cwd = os.getcwd()
118        global enable_openmp
119        enable_openmp = False
120
121    def run(self):
122        pass
123
124
125class build_ext_subclass(build_ext):
126    def build_extensions(self):
127        # Get 64-bitness
128        c = self.compiler.compiler_type
129        print("Compiling with %s (64bit=%s)" % (c, str(is_64bits)))
130        #print("=== compiler attributes ===")
131        #print("\n".join("%s: %s"%(k, v) for k, v in sorted(self.compiler.__dict__.items())))
132        #print("=== build_ext attributes ===")
133        #print("\n".join("%s: %s"%(k, v) for k, v in self.__dict__.items()))
134        #sys.exit(1)
135
136        # OpenMP build options
137        if enable_openmp:
138            if c in copt:
139                for e in self.extensions:
140                    e.extra_compile_args = copt[c]
141            if c in lopt:
142                for e in self.extensions:
143                    e.extra_link_args = lopt[c]
144
145        # Platform-specific build options
146        if c in platform_lopt:
147            for e in self.extensions:
148                e.extra_link_args = platform_lopt[c]
149
150        if c in platform_copt:
151            for e in self.extensions:
152                e.extra_compile_args = platform_copt[c]
153
154        build_ext.build_extensions(self)
155
156
157class BuildSphinxCommand(Command):
158    description = "Build Sphinx documentation."
159    user_options = []
160
161    def initialize_options(self):
162        self.cwd = None
163
164    def finalize_options(self):
165        self.cwd = os.getcwd()
166
167    def run(self):
168        ''' First builds the sasmodels documentation if the directory
169        is present. Then builds the sasview docs.
170        '''
171        ### AJJ - Add code for building sasmodels docs here:
172        # check for doc path
173        SASMODELS_DOCPATH = os.path.abspath(os.path.join(os.getcwd(), '..', 'sasmodels', 'doc'))
174        print("========= check for sasmodels at", SASMODELS_DOCPATH, "============")
175        if os.path.exists(SASMODELS_DOCPATH):
176            if os.path.isdir(SASMODELS_DOCPATH):
177                # if available, build sasmodels docs
178                print("============= Building sasmodels model documentation ===============")
179                smdocbuild = subprocess.call(["make", "-C", SASMODELS_DOCPATH, "html"])
180        else:
181            # if not available warning message
182            print("== !!WARNING!! sasmodels directory not found. Cannot build model docs. ==")
183
184        #Now build sasview (+sasmodels) docs
185        sys.path.append("docs/sphinx-docs")
186        import build_sphinx
187        build_sphinx.rebuild()
188
189
190# sas module
191package_dir["sas"] = os.path.join("src", "sas")
192packages.append("sas")
193
194# sas module
195package_dir["sas.sasgui"] = os.path.join("src", "sas", "sasgui")
196packages.append("sas.sasgui")
197
198# sas module
199package_dir["sas.sascalc"] = os.path.join("src", "sas", "sascalc")
200packages.append("sas.sascalc")
201
202# sas.sascalc.invariant
203package_dir["sas.sascalc.invariant"] = os.path.join(
204    "src", "sas", "sascalc", "invariant")
205packages.extend(["sas.sascalc.invariant"])
206
207# sas.sasgui.guiframe
208guiframe_path = os.path.join("src", "sas", "sasgui", "guiframe")
209package_dir["sas.sasgui.guiframe"] = guiframe_path
210package_dir["sas.sasgui.guiframe.local_perspectives"] = os.path.join(
211    os.path.join(guiframe_path, "local_perspectives"))
212package_data["sas.sasgui.guiframe"] = ['images/*', 'media/*']
213packages.extend(
214    ["sas.sasgui.guiframe", "sas.sasgui.guiframe.local_perspectives"])
215# build local plugin
216for d in os.listdir(os.path.join(guiframe_path, "local_perspectives")):
217    if d not in ['.svn', '__init__.py', '__init__.pyc']:
218        package_name = "sas.sasgui.guiframe.local_perspectives." + d
219        packages.append(package_name)
220        package_dir[package_name] = os.path.join(
221            guiframe_path, "local_perspectives", d)
222
223# sas.sascalc.dataloader
224package_dir["sas.sascalc.dataloader"] = os.path.join(
225    "src", "sas", "sascalc", "dataloader")
226package_data["sas.sascalc.dataloader.readers"] = ['schema/*.xsd']
227packages.extend(["sas.sascalc.dataloader", "sas.sascalc.dataloader.readers",
228                 "sas.sascalc.dataloader.readers.schema"])
229
230
231# sas.sascalc.calculator
232gen_dir = os.path.join("src", "sas", "sascalc", "calculator", "c_extensions")
233package_dir["sas.sascalc.calculator"] = os.path.join(
234    "src", "sas", "sascalc", "calculator")
235packages.append("sas.sascalc.calculator")
236ext_modules.append(Extension("sas.sascalc.calculator._sld2i",
237                             sources=[
238                                 os.path.join(gen_dir, "sld2i_module.c"),
239                                 os.path.join(gen_dir, "sld2i.c"),
240                                 os.path.join(gen_dir, "libfunc.c"),
241                                 os.path.join(gen_dir, "librefl.c"),
242                             ],
243                             include_dirs=[gen_dir],
244                             ))
245
246# sas.sascalc.pr
247srcdir = os.path.join("src", "sas", "sascalc", "pr", "c_extensions")
248package_dir["sas.sascalc.pr"] = os.path.join("src", "sas", "sascalc", "pr")
249packages.append("sas.sascalc.pr")
250ext_modules.append(Extension("sas.sascalc.pr._pr_inversion",
251                             sources=[os.path.join(srcdir, "Cinvertor.c"),
252                                      os.path.join(srcdir, "invertor.c"),
253                                      ],
254                             include_dirs=[],
255                             ))
256
257
258# sas.sascalc.file_converter
259mydir = os.path.join("src", "sas", "sascalc", "file_converter", "c_ext")
260package_dir["sas.sascalc.file_converter"] = os.path.join(
261    "src", "sas", "sascalc", "file_converter")
262packages.append("sas.sascalc.file_converter")
263ext_modules.append(Extension("sas.sascalc.file_converter._bsl_loader",
264                             sources=[os.path.join(mydir, "bsl_loader.c")],
265                             include_dirs=[np.get_include()],
266                             ))
267
268# sas.sascalc.corfunc
269package_dir["sas.sascalc.corfunc"] = os.path.join(
270    "src", "sas", "sascalc", "corfunc")
271
272packages.extend(["sas.sascalc.corfunc"])
273
274# sas.sascalc.fit
275package_dir["sas.sascalc.fit"] = os.path.join("src", "sas", "sascalc", "fit")
276packages.append("sas.sascalc.fit")
277
278# Perspectives
279package_dir["sas.sasgui.perspectives"] = os.path.join(
280    "src", "sas", "sasgui", "perspectives")
281package_dir["sas.sasgui.perspectives.pr"] = os.path.join(
282    "src", "sas", "sasgui", "perspectives", "pr")
283packages.extend(["sas.sasgui.perspectives", "sas.sasgui.perspectives.pr"])
284package_data["sas.sasgui.perspectives.pr"] = ['media/*']
285
286package_dir["sas.sasgui.perspectives.invariant"] = os.path.join(
287    "src", "sas", "sasgui", "perspectives", "invariant")
288packages.extend(["sas.sasgui.perspectives.invariant"])
289package_data['sas.sasgui.perspectives.invariant'] = [
290    os.path.join("media", '*')]
291
292package_dir["sas.sasgui.perspectives.fitting"] = os.path.join(
293    "src", "sas", "sasgui", "perspectives", "fitting")
294package_dir["sas.sasgui.perspectives.fitting.plugin_models"] = os.path.join(
295    "src", "sas", "sasgui", "perspectives", "fitting", "plugin_models")
296packages.extend(["sas.sasgui.perspectives.fitting",
297                 "sas.sasgui.perspectives.fitting.plugin_models"])
298package_data['sas.sasgui.perspectives.fitting'] = [
299    'media/*', 'plugin_models/*']
300
301packages.extend(["sas.sasgui.perspectives",
302                 "sas.sasgui.perspectives.calculator"])
303package_data['sas.sasgui.perspectives.calculator'] = ['images/*', 'media/*']
304
305package_dir["sas.sasgui.perspectives.corfunc"] = os.path.join(
306    "src", "sas", "sasgui", "perspectives", "corfunc")
307packages.extend(["sas.sasgui.perspectives.corfunc"])
308package_data['sas.sasgui.perspectives.corfunc'] = ['media/*']
309
310package_dir["sas.sasgui.perspectives.file_converter"] = os.path.join(
311    "src", "sas", "sasgui", "perspectives", "file_converter")
312packages.extend(["sas.sasgui.perspectives.file_converter"])
313package_data['sas.sasgui.perspectives.file_converter'] = ['media/*']
314
315# Data util
316package_dir["sas.sascalc.data_util"] = os.path.join(
317    "src", "sas", "sascalc", "data_util")
318packages.append("sas.sascalc.data_util")
319
320# Plottools
321package_dir["sas.sasgui.plottools"] = os.path.join(
322    "src", "sas", "sasgui", "plottools")
323packages.append("sas.sasgui.plottools")
324
325# # Last of the sas.models
326# package_dir["sas.models"] = os.path.join("src", "sas", "models")
327# packages.append("sas.models")
328
329EXTENSIONS = [".c", ".cpp"]
330
331
332def append_file(file_list, dir_path):
333    """
334    Add sources file to sources
335    """
336    for f in os.listdir(dir_path):
337        if os.path.isfile(os.path.join(dir_path, f)):
338            _, ext = os.path.splitext(f)
339            if ext.lower() in EXTENSIONS:
340                file_list.append(os.path.join(dir_path, f))
341        elif os.path.isdir(os.path.join(dir_path, f)) and \
342                not f.startswith("."):
343            sub_dir = os.path.join(dir_path, f)
344            for new_f in os.listdir(sub_dir):
345                if os.path.isfile(os.path.join(sub_dir, new_f)):
346                    _, ext = os.path.splitext(new_f)
347                    if ext.lower() in EXTENSIONS:
348                        file_list.append(os.path.join(sub_dir, new_f))
349
350
351# Comment out the following to avoid rebuilding all the models
352file_sources = []
353append_file(file_sources, gen_dir)
354
355# Wojtek's hacky way to add doc files while bundling egg
356# def add_doc_files(directory):
357#    paths = []
358#    for (path, directories, filenames) in os.walk(directory):
359#        for filename in filenames:
360#            paths.append(os.path.join(path, filename))
361#    return paths
362
363#doc_files = add_doc_files('doc')
364
365# SasView
366package_data['sas'] = ['logging.ini']
367package_data['sas.sasview'] = ['images/*',
368                               'media/*',
369                               'test/*.txt',
370                               'test/1d_data/*',
371                               'test/2d_data/*',
372                               'test/convertible_files/*',
373                               'test/coordinate_data/*',
374                               'test/image_data/*',
375                               'test/media/*',
376                               'test/other_files/*',
377                               'test/save_states/*',
378                               'test/sesans_data/*',
379                               'test/upcoming_formats/*',
380                               ]
381packages.append("sas.sasview")
382
383required = [
384    'bumps>=0.7.5.9', 'periodictable>=1.5.0', 'pyparsing>=2.0.0',
385
386    # 'lxml>=2.2.2',
387    'lxml', 'h5py',
388
389    # The following dependecies won't install automatically, so assume them
390    # The numbers should be bumped up for matplotlib and wxPython as well.
391    # 'numpy>=1.4.1', 'scipy>=0.7.2', 'matplotlib>=0.99.1.1',
392    # 'wxPython>=2.8.11', 'pil',
393]
394
395if os.name == 'nt':
396    required.extend(['html5lib', 'reportlab'])
397else:
398    # 'pil' is now called 'pillow'
399    required.extend(['pillow'])
400
401# Set up SasView
402setup(
403    name="sasview",
404    version=VERSION,
405    description="SasView application",
406    author="SasView Team",
407    author_email="developers@sasview.org",
408    url="http://sasview.org",
409    license="PSF",
410    keywords="small-angle x-ray and neutron scattering analysis",
411    download_url="https://github.com/SasView/sasview.git",
412    package_dir=package_dir,
413    packages=packages,
414    package_data=package_data,
415    ext_modules=ext_modules,
416    install_requires=required,
417    zip_safe=False,
418    entry_points={
419        'console_scripts': [
420            "sasview = sas.sasview.sasview:run_gui",
421        ]
422    },
423    cmdclass={'build_ext': build_ext_subclass,
424              'docs': BuildSphinxCommand,
425              'disable_openmp': DisableOpenMPCommand},
426    setup_requires=['pytest-runner'] if 'pytest' in sys.argv else [],
427    tests_require=['pytest'],
428)
Note: See TracBrowser for help on using the repository browser.