File: setup.py

package info (click to toggle)
pyhst2 2020c-7
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm, sid
  • size: 13,540 kB
  • sloc: ansic: 11,807; python: 9,708; cpp: 6,786; makefile: 152; sh: 31
file content (880 lines) | stat: -rw-r--r-- 29,435 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
#!/usr/bin env python
# -*- coding: utf-8 -*-

#/*##########################################################################
# Copyright (C) 2001-2013 European Synchrotron Radiation Facility
#
#              PyHST2
#  European Synchrotron Radiation Facility, Grenoble,France
#
# PyHST2 is  developed at
# the ESRF by the Scientific Software  staff.
# Principal author for PyHST2: Alessandro Mirone.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# PyHST2 is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# PyHST2; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307, USA.
#
# PyHST2 follows the dual licensing model of Trolltech's Qt and Riverbank's PyQt
# and cannot be used as a free plugin for a non-free program.
#
# Please contact the ESRF industrial unit (industry@esrf.fr) if this license
# is a problem for you.
#############################################################################*/


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


"""
Installation script:

python setup.py build

"""

__author__ = "Jerome Kieffer"
__contact__ = "Jerome.Kieffer@ESRF.eu"
__license__ = "GPLv2+"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__date__ = "28/03/2013"
__satus__ = "development"
import sys, os
import math
import glob
from distutils.core import Extension, setup
# from distutils.command.build_ext import build_ext
from numpy.distutils.misc_util import get_numpy_include_dirs
from os.path import join as pjoin
import string
import stat

if 0:
    from optparse import OptionParser
    parser = OptionParser()
    parser.disable_interspersed_args()
    parser.add_option("--nocuda", action="store_false", dest="DOCUDA", default=True)
    parser.add_option("--onlycuda", action="store_true", dest="ONLYCUDA", default=False)
    (options, args) = parser.parse_args(sys.argv)
    print( args)
    DOCUDA=options.DOCUDA
    ONLYCUDA=options.ONLYCUDA
    if ONLYCUDA==1:
        DOCUDA=1

### DEFAULT
DOCUDA=1
ONLYCUDA=0
DO_LINK=0

### CHANGE HERE
DOCUDA   = 1
ONLYCUDA = 0
DO_LINK  = 0

global version
global aumento_versione
aumento_versione="a"

# Debian-specific version to match PEP-440 with setuptools v66.0.0
pep440_version = "2020.3.20230128" # 3 for c, today's date

global version

if DO_LINK==0:
    version = [eval(l.split("=")[1]) for l in open(os.path.join(os.path.dirname(
        os.path.abspath(__file__)), "PyHST", "__init__.py"))
               if l.strip().startswith("version")][0]
else:
    version = "2020c"
    

def do_link():
    global aumento_versione
    global version
    # aumento_versione=""


    version = "2020c"

    packages = []


    package_dir = {'PyHST2_'+version: 'PyHST', 'PyHST2_'+version+'.test': 'PyHST/test', 'PyHST2_'+version+'.third_party': 'PyHST/third_party' }

    script_files = glob.glob('scripts_link/pyhst2')+glob.glob('scripts_link/pyhst2_info')


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """

    distrib = setup(name="pyhst2_links",
                    license="GPL",
                    # Debian-specific version to fit PEP-440
                    version=pep440_version,
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.eu/projects/pyhst",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    scripts=script_files,
                    )


def do_link_unstable():
    global aumento_versione
    global version
   #  aumento_versione=""

    version = "2020b"

    packages = []


    package_dir = {'PyHST2_'+version: 'PyHST'}

    script_files = glob.glob('scripts_link/pyhst2_unstable')+glob.glob('scripts_link/pyhst2_unstable_info')


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """

    distrib = setup(name="pyhst2unstable_links",
                    license="GPL",
                    # Debian-specific version to fit PEP-440
                    version=pep440_version,
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.eu/projects/pyhst",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    scripts=script_files,
                    )



def do_pyhst():
    global version
    try:
        import numpy
    except ImportError:
        text = "You must have numpy installed.\n"
        text += "See http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103\n"
        raise ImportError( text)


    jn = os.sep.join

    mpi_dirs = ["/usr/include/openmpi/"]
    mpilibs_dirs = []

    # mpi_dirs = ["/home/test/packages/include"]
    # mpilibs_dirs = ["/home/test/packages/lib"]

    if 1:
        hdf5_dirs = ["/usr/include/hdf5/serial/"]
        hdf5_lib  = "hdf5_serial"
    else:
        hdf5_dirs = []
        hdf5_lib  = "hdf5"

    ###########################
    ## hdf5 desactivation ( during installation incompatibilities with different versions on the cluster)
    # hdf5_lib = "c"


    
    cmdclass = {}
    ext_modules = []
    internal_clibraries = []


    if not ONLYCUDA:
        packages = ['PyHST2_'+version, 'PyHST2_'+version+'.test', 'PyHST2_'+version+'.third_party']
    else:
        packages = []

    package_dir = {'PyHST2_'+version: 'PyHST'}
    if sys.platform == "win32":
        raise RuntimeError("non sense ")
    else:
        define_macros = []
        if not ONLYCUDA:
            script_files = glob.glob('scripts/*')
        else:
            script_files = []



    def find_in_path(name, path):
        "Find a file in a search path"
        #adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
        for dirn in path.split(os.pathsep):
            binpath = pjoin(dirn, name)
            if os.path.exists(binpath):
                return os.path.abspath(binpath)
        return None

    def locate_cuda():
        """Locate the CUDA environment on the system

        Returns a dict with keys 'home', 'nvcc', 'include', and 'lib'
        and values giving the absolute path to each directory.

        Starts by looking for the CUDAHOME env variable. If not found, everything
        is based on finding 'nvcc' in the PATH.
        """

        # first check if the CUDAHOME env variable is in use
        if 'CUDAHOME' in os.environ:
            home = os.environ['CUDAHOME']
            nvcc = pjoin(home, 'bin', 'nvcc')
        else:
            # otherwise, search the PATH for NVCC
            nvcc = find_in_path('nvcc', os.environ['PATH'])
            if nvcc is None:
                raise EnvironmentError('The nvcc binary could not be '
                    'located in your $PATH. Either add it to your path, or set $CUDAHOME')
            home = os.path.dirname(os.path.dirname(nvcc))

        cudaconfig = {'home':home, 'nvcc':nvcc,
                      'include': pjoin(home, 'include')}
        for key, val in cudaconfig.items():
            if not os.path.exists(val):
                raise EnvironmentError('The CUDA %s path could not be located in %s' % (key, val))
        return cudaconfig


    def customize_compiler_for_nvcc(self):
        """inject deep into distutils to customize how the dispatch
        to gcc/nvcc works.

        If you subclass UnixCCompiler, it's not trivial to get your subclass
        injected in, and still have the right customizations (i.e.
        distutils.sysconfig.customize_compiler) run on it. So instead of going
        the OO route, I have this. Note, it's kindof like a wierd functional
        subclassing going on."""

        # tell the compiler it can processes .cu
        self.src_extensions.append('.cu')

        # save references to the default compiler_so and _comple methods
        default_compiler_so = self.compiler_so
        super_comp = self._compile

        # now redefine the _compile method. This gets executed for each
        # object but distutils doesn't have the ability to change compilers
        # based on source extension: we add it.
        def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
            if os.path.splitext(src)[1] == '.cu':
                # use the cuda for .cu files
                self.set_executable('compiler_so', CUDA['nvcc'])
                # use only a subset of the extra_postargs, which are 1-1 translated
                # from the extra_compile_args in the Extension class

                
                postargs = extra_postargs['nvcc']

                if "USECLANG4NVCC" in os.environ and os.environ ["USECLANG4NVCC"]=="YES":
                    postargs = postargs + [" -ccbin clang-3.8"]
            else:
                print(" EXTRA ", extra_postargs)
                self.set_executable('compiler_so', "mpicc")
                postargs = extra_postargs['gcc']
                # postargs = extra_postargs['gcc']

            super_comp(obj, src, ext, cc_args, postargs, pp_opts)
            # reset the default compiler_so, which we might have changed for cuda
            self.compiler_so = default_compiler_so

        # inject our redefined _compile method into the class
        self._compile = _compile



    try:
        from Cython.Distutils import build_ext, Extension
        CYTHON = True
    except ImportError:
        CYTHON = False

    if CYTHON:
        cython_c_ext = ".pyx"
    else:
        cython_c_ext = ".cpp"
        from distutils.command.build_ext import build_ext, Extension


    # We subclass the build_ext class in order to handle compiler flags
    # for openmp and opencl etc in a cross platform way
    translator = {
            # Compiler
                # name, compileflag, linkflag
            'msvc' : {
                'openmp' : ('/openmp', ' '),
                'debug'  : ('/Zi', ' '),
                'OpenCL' : 'OpenCL',
                },
            'mingw32':{
                'openmp' : ('-fopenmp', '-fopenmp'),
                'debug'  : ('-g', '-g'),
                'stdc++' : 'stdc++',
                'OpenCL' : 'OpenCL'
                },
            'default':{
                'openmp' : ('-fopenmp', '-fopenmp'),
                'debug'  : ('-g', '-g'),
                'stdc++' : 'stdc++',
                'OpenCL' : 'OpenCL'
                }
            }

    cmdclass = {}

    class build_ext_tds2el(build_ext):
        def build_extensions(self):

            customize_compiler_for_nvcc(self.compiler)


            # print( self.compiler.compiler_type)

            if self.compiler.compiler_type in translator:
                trans = translator[self.compiler.compiler_type]
            else:
                trans = translator['default']


            for e in self.extensions:
                e.extra_compile_args = [ trans[a][0] if a in trans else a
                                        for a in e.extra_compile_args]
                e.extra_link_args = [ trans[a][1] if a in trans else a
                                     for a in e.extra_link_args]

                if    e.libraries !=[ "fftw3f"] and e.libraries !=[ "mpi"]:
                    e.libraries = filter(None, [ trans[a] if a in trans else None
                                                 for a in e.libraries])

                # If you are confused look here:
                # print( e, e.libraries)
                # print( e.extra_compile_args)
                # print( e.extra_link_args)
            build_ext.build_extensions(self)

    # cmdclass['build_ext'] = build_ext_tds2el


    # run the customize_compiler
    class custom_build_ext(build_ext):
        """
        Cuda aware builder with nvcc compiler support
        """
        def build_extensions(self):
            customize_compiler_for_nvcc(self.compiler)
            build_ext.build_extensions(self)

    cmdclass['build_ext'] = custom_build_ext

    CUDA={'include':[""]}
    if  DOCUDA:
        CUDA={'include':[]}
        CUDA .update(locate_cuda())

        CUDA["arch"] = [   "-gencode", "arch=compute_50,code=compute_50" ,
                           "-gencode", "arch=compute_60,code=compute_60" ,
                           "-gencode", "arch=compute_70,code=compute_70" ,
                           "-gencode", "arch=compute_80,code=compute_80" ,
                       ]

        # print( CUDA)

        CUDA["Xptxas"] = [" ", " -Xptxas=-v"]

    def build_Cspace():
        """
        Define how to build the main Cspace C extension

        @return: module
        """
        global version
        if sys.platform == "win32" :
            raise RuntimeError("non-sense ")
    #    else:
    #        sdk_libs = ['gcc', 'm']

        c_sorgenti_tmp = ["CCspace.c", "cpyutils.c", "Cspace.c"  , "edftools.c" , "cpu_main.c", "pyhst_nnfbp.c" ]#, "PyHST/Cspace/h5tools.c" ]
        c_sorgenti = [jn(['PyHST', 'Cspace', tok]) for tok in c_sorgenti_tmp]

        depends_tmp = [ "CCspace.h", "cpyutils.h", "edftools.h"]
        depends = [jn(['PyHST', 'Cspace', tok]) for tok in depends_tmp]
        depends = []


        module = Extension(name='PyHST2_'+version+'.Cspace',
                           sources=c_sorgenti ,
                           depends=depends,
                           library_dirs= mpilibs_dirs,
                           libraries=["fftw3f_threads", "fftw3f",hdf5_lib, "mpi"],
                           extra_link_args=['-fopenmp'] ,
                           extra_compile_args={'gcc': ["-fPIC",'-fopenmp',"-g" ,"-std=c99","-Wall"]},
                           define_macros=define_macros,
                           include_dirs=[ CUDA['include'], numpy.get_include()] + mpi_dirs + hdf5_dirs )
        return module



    def build_gputomo():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version

        sources = ["src/wt.cu", "src/common.cu", "src/utils.cu", "src/separable.cu", "src/nonseparable.cu", "src/haar.cu", "src/filters.cpp"]
        sources = [jn(['PyHST', 'Cspace', 'pdwt', tok]) for tok in sources]
        sources.extend(["PyHST/Cspace/gputomo.cu", "PyHST/Cspace/cudamedianfilter.cu","PyHST/Cspace/chambollepock.cu", "PyHST/Cspace/wavelets.cu", "PyHST/Cspace/sinofilters.cu"])

        module = Extension('PyHST2_'+version+'/libgputomo',
                    sources=sources,
                    libraries=['cudart', "cublas", "cuda", "cufft", hdf5_lib],
                    # this syntax is specific to this build system
                    # we're only going to use certain compiler args with nvcc and not with gcc
                    # the implementation of this trick is in customize_compiler() below
                    extra_compile_args={'gcc': ["-std=c99", "-g","-fPIC", "-O3","-Wall"],
                                        'nvcc': CUDA["arch"] + [ "--compiler-options",  "-fPIC", "-O3", "-g","-D_FORCE_INLINES" ]},
                    include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace'] + hdf5_dirs)
        return module

    def build_gpuunsharp():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version

        sources = ["PyHST/Cspace/unsharp3D.c" , "PyHST/Cspace/cudaunsharp.cu","PyHST/Cspace/cpyutils.c" ]


        module = Extension(name='PyHST2_'+version+'.unsharp3D',
                           sources=sources ,
                           depends=[],
                           libraries=['cudart','QtGui','QtCore','cudart','tiff'],
                           
                           extra_compile_args={'gcc': ["-std=c99","-g","-fPIC", "-O3","-Wall"],
                                               'nvcc': CUDA["arch"] + [ "--compiler-options",  "-fPIC", "-O3", "-g","-D_FORCE_INLINES" ]},
                           include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace',"/usr/include/qt4"] )


        return module


    def build_projection():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version
        module = Extension('PyHST2_'+version+'/libprojection',
                               sources=["PyHST/Cspace/c_hst_project_1over.cu"],
                               libraries=['cudart', "cuda", "cufft"],
                               extra_compile_args={'gcc': ["-fPIC", "-O3"],
                                                   'nvcc': CUDA["arch"] + ["--compiler-options", "-fPIC,-O3" ,"-D_FORCE_INLINES"]},
                               include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace']+ hdf5_dirs)
        return module


    '''
    # Too complicated to build several cuda module, and then to link *and* use the dlopen mechanism
    def build_wavelets():
        """
        Build the Wavelets tomo C module, based on pywt

        @return: module
        """
        global version
        sources = ["src/wt.cu", "src/common.cu", "src/utils.cu", "src/separable.cu", "src/nonseparable.cu", "src/haar.cu", "src/filters.cpp"]
        sources = [jn(['PyHST', 'Cspace', 'pdwt', tok]) for tok in sources]
        #sources.extend(["PyHST/Cspace/wavelets.cu", "PyHST/Cspace/sinofilters.cu"])

        module = Extension('PyHST2_'+version+'/libwavelets',
                               sources=sources,
                               libraries=["cudart", "cuda", "cublas"],
                               extra_compile_args={'gcc': ["-fPIC", "-O3"],
                                                   'nvcc': CUDA["arch"] + ["--compiler-options", "-fPIC,-O3" ,"-D_FORCE_INLINES"]},
                               include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace'])
        return module
    '''



    def build_segmentation():

        global version

        c_sorgenti_tmp = ["segment_cy"+cython_c_ext, "segment.cc"]
        # c_sorgenti_tmp = ["segment_cy"+cython_c_ext]
        c_sorgenti = [jn(['PyHST', 'segment',  tok]) for tok in c_sorgenti_tmp]

        depends_tmp = [ "segment.h"]
        depends = [jn(['PyHST', 'segment',  tok]) for tok in depends_tmp]

        if sys.version_info > (3, 0):
            cython_ext2 = Extension(
                'PyHST2_'+version+'.segment_cy',
                sources=c_sorgenti,
                depends=depends,
                library_dirs =      mpilibs_dirs,
                libraries=[ "mpi"],
                include_dirs=get_numpy_include_dirs()+ mpi_dirs+[],
                language="c++",             # generate C++ code
                extra_compile_args={'gcc':['-fopenmp',"-fPIC", "-O3"] },
                extra_link_args=['-fopenmp'] ,
                cython_directives={'language_level' : "3"}
            )
        else:
            cython_ext2 = Extension(
                'PyHST2_'+version+'.segment_cy',
                sources=c_sorgenti,
                depends=depends,
                library_dirs =      mpilibs_dirs,
                libraries=[ "mpi"],
                include_dirs=get_numpy_include_dirs()+ mpi_dirs+[],
                language="c++",             # generate C++ code
                extra_compile_args={'gcc':['-fopenmp',"-fPIC", "-O3"] },
                extra_link_args=['-fopenmp'] ,
            )
            
        return cython_ext2

    #############################################################################

# extensions = cythonize(extensions, compiler_directives={'language_level' : "3"})) # or "2" or "3str"


    ###########################################################################################################
    from distutils.command.install_scripts import install_scripts
    class smart_install_scripts(install_scripts):
        def run (self):
            global  version

            install_cmd = self.get_finalized_command('install')
            self.install_dir = getattr(install_cmd, 'install_scripts')
            self.install_lib_dir = getattr(install_cmd, 'install_lib')

            self.outfiles = []
            for filein in glob.glob('scripts/*'):
                if filein in glob.glob('scripts/*~'): continue

                print( "INSTALLO ", filein)

                if not os.path.exists(self.install_dir):
                    os.makedirs(self.install_dir)

                filedest = os.path.join(self.install_dir, os.path.basename(filein+"2_"+version))
                print( os.path.basename(filein+"2_"+version))
                print( filedest)

                if os.path.exists(filedest):
                    os.remove(filedest)

                text = open(filein, 'r').read()
                text=text.replace("import PyHST", "import PyHST2_"+version) 
                text=text.replace("python", sys.executable)                 

                f=open(filedest, 'w')
                f.write(text)
                f.close()
                self.outfiles.append(filedest)

            if os.name == 'posix':
                # Set the executable bits (owner, group, and world) on
                # all the scripts we just installed.
                for file in self.get_outputs():
                    if self.dry_run:
                        pass
                    else:
                        mode = ((os.stat(file)[stat.ST_MODE]) | 0o555) & 0o7777
                        os.chmod(file, mode)


    #############################################################################################################

    cmdclass['install_scripts'] = smart_install_scripts


    if not ONLYCUDA:
        ext_modules.append(build_Cspace())
        ext_modules.append(build_segmentation())
    if DOCUDA:
        ext_modules.append(build_gputomo())
        # ext_modules.append(build_gpuunsharp())
        ext_modules.append(build_projection())
        #ext_modules.append(build_wavelets())


    #######################
    # build_doc commandes #
    #######################

    try:
        import sphinx
        import sphinx.util.console
        sphinx.util.console.color_terminal = lambda: False
        from sphinx.setup_command import BuildDoc
    except ImportError:
        sphinx = None

    if sphinx:
        class build_doc(BuildDoc):

            def run(self):
                # make sure the python path is pointing to the newly built
                # code so that the documentation is built on this and not a
                # previously installed version

                build = self.get_finalized_command('build')
                sys.path.insert(0, os.path.abspath(build.build_lib))
                # we need to reload PyMca from the build directory and not
                # the one from the source directory which does not contain
                # the extensions
                BuildDoc.run(self)
                sys.path.pop(0)
        cmdclass['build_doc'] = build_doc


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """


    post_fix=""
    if DOCUDA==0 and ONLYCUDA==0:
        post_fix="_base"
    elif  DOCUDA==1 and ONLYCUDA==1:
        post_fix="_cudaextensions"

    distrib = setup(name="PyHST2_"+version+post_fix,
                    license="GPL",
                    # Debian-specific version to fit PEP-440
                    version=pep440_version,
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.fr/projects/PyHST",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    ext_modules=ext_modules,
                    cmdclass=cmdclass ,
                    scripts=script_files
                    )




if DO_LINK:
    if DO_LINK==1:
        do_link()
    else: 
        do_link_unstable()
       
else:
    do_pyhst()









# What you basically need to do is to override the build_ext command class in your setup.py and register it in the command classes. In your custom impl of build_ext, configure and call cmake to configure and then build the extension modules. Unfortunately, the official docs are rather laconic about how to implement custom distutils commands (see Extending Distutils); I find it much more helpful to study the commands code directly. For example, here is the source code for the build_ext command.
# Example project

# I have prepared a simple project consisting out of a single C extension foo and a python module spam.eggs:

# so-42585210/
# ├── spam
# │   ├── __init__.py  # empty
# │   ├── eggs.py
# │   ├── foo.c
# │   └── foo.h
# ├── CMakeLists.txt
# └── setup.py

# Files for testing the setup

# These are just some simple stubs I wrote to test the setup script.

# spam/eggs.py (only for testing the library calls):

# from ctypes import cdll
# import pathlib


# def wrap_bar():
#     foo = cdll.LoadLibrary(str(pathlib.Path(__file__).with_name('libfoo.dylib')))
#     return foo.bar()

# spam/foo.c:

# #include "foo.h"

# int bar() {
#     return 42;
# }

# spam/foo.h:

# #ifndef __FOO_H__
# #define __FOO_H__

# int bar();

# #endif

# CMakeLists.txt:

# cmake_minimum_required(VERSION 3.10.1)
# project(spam)
# set(src "spam")
# set(foo_src "spam/foo.c")
# add_library(foo SHARED ${foo_src})

# Setup script

# This is where the magic happens. Of course, there is a lot of room for improvements - you could pass additional options to CMakeExtension class if you need to (for more info on the extensions, see Building C and C++ Extensions), make the CMake options configurable via setup.cfg by overriding methods initialize_options and finalize_options etc.

# import os
# import pathlib

# from setuptools import setup, Extension
# from setuptools.command.build_ext import build_ext as build_ext_orig


# class CMakeExtension(Extension):

#     def __init__(self, name):
#         # don't invoke the original build_ext for this special extension
#         super().__init__(name, sources=[])


# class build_ext(build_ext_orig):

#     def run(self):
#         for ext in self.extensions:
#             self.build_cmake(ext)
#         super().run()

#     def build_cmake(self, ext):
#         cwd = pathlib.Path().absolute()

#         # these dirs will be created in build_py, so if you don't have
#         # any python sources to bundle, the dirs will be missing
#         build_temp = pathlib.Path(self.build_temp)
#         build_temp.mkdir(parents=True, exist_ok=True)
#         extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
#         extdir.mkdir(parents=True, exist_ok=True)

#         # example of cmake args
#         config = 'Debug' if self.debug else 'Release'
#         cmake_args = [
#             '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + str(extdir.parent.absolute()),
#             '-DCMAKE_BUILD_TYPE=' + config
#         ]

#         # example of build args
#         build_args = [
#             '--config', config,
#             '--', '-j4'
#         ]

#         os.chdir(str(build_temp))
#         self.spawn(['cmake', str(cwd)] + cmake_args)
#         if not self.dry_run:
#             self.spawn(['cmake', '--build', '.'] + build_args)
#         os.chdir(str(cwd))


# setup(
#     name='spam',
#     version='0.1',
#     packages=['spam'],
#     ext_modules=[CMakeExtension('spam/foo')],
#     cmdclass={
#         'build_ext': build_ext,
#     }
# )

# Testing

# Build the project's wheel, install it. Test the library is installed:

# $ pip show -f spam
# Name: spam
# Version: 0.1
# Summary: UNKNOWN
# Home-page: UNKNOWN
# Author: UNKNOWN
# Author-email: UNKNOWN
# License: UNKNOWN
# Location: /Users/hoefling/.virtualenvs/stackoverflow/lib/python3.6/site-packages
# Requires: 
# Files:
#   spam-0.1.dist-info/DESCRIPTION.rst
#   spam-0.1.dist-info/INSTALLER
#   spam-0.1.dist-info/METADATA
#   spam-0.1.dist-info/RECORD
#   spam-0.1.dist-info/WHEEL
#   spam-0.1.dist-info/metadata.json
#   spam-0.1.dist-info/top_level.txt
#   spam/__init__.py
#   spam/__pycache__/__init__.cpython-36.pyc
#   spam/__pycache__/eggs.cpython-36.pyc
#   spam/eggs.py
#   spam/libfoo.dylib

# Run the wrapper function from spam.eggs module:

# $ python -c "from spam import eggs; print(eggs.wrap_bar())"
# 42