def main():
    print("SCT info:")
    print("- version: {}".format(sct.__version__))
    print("- path: {0}".format(sct.__sct_dir__))

    # initialization
    install_software = 0
    e = 0
    complete_test = param.complete_test
    os_running = 'not identified'

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse_args()
    if arguments.complete:
        complete_test = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # complete test
    if complete_test:
        print(sct.run('date', verbose))
        print(sct.run('whoami', verbose))
        print(sct.run('pwd', verbose))
        bash_profile = os.path.expanduser("~/.bash_profile")
        if os.path.isfile(bash_profile):
            with io.open(bash_profile, "r") as f:
                print(f.read())
        bashrc = os.path.expanduser("~/.bashrc")
        if os.path.isfile(bashrc):
            with io.open(bashrc, "r") as f:
                print(f.read())

    # check OS
    platform_running = sys.platform
    if platform_running.find('darwin') != -1:
        os_running = 'osx'
    elif platform_running.find('linux') != -1:
        os_running = 'linux'

    print('OS: ' + os_running + ' (' + platform.platform() + ')')

    # Check number of CPU cores
    from multiprocessing import cpu_count
    output = int(os.getenv('ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0))
    print('CPU cores: Available: {}, Used by SCT: {}'.format(
        cpu_count(), output))

    # check RAM
    sct.checkRAM(os_running, 0)

    # check if Python path is within SCT path
    print_line('Check Python executable')
    path_python = sys.executable
    if sct.__sct_dir__ in path_python:
        print_ok()
        print('  Using bundled python {} at {}'.format(sys.version,
                                                       path_python))
    else:
        print_warning()
        print('  Using system python which is unsupported: {}'.format(
            path_python))

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.path.isdir(sct.__data_dir__):
        print_ok()
    else:
        print_fail()

    for dep_pkg, dep_ver_spec in get_dependencies():
        if dep_ver_spec is None:
            print_line('Check if %s is installed' % (dep_pkg))
        else:
            print_line('Check if %s (%s) is installed' %
                       (dep_pkg, dep_ver_spec))

        try:
            module_name, suppress_stderr = resolve_module(dep_pkg)
            module = module_import(module_name, suppress_stderr)
            version = get_version(module)

            if dep_ver_spec is None and version is not None:
                ver_pip_setup = dict(
                    get_dependencies(
                        os.path.join(sct.__sct_dir__,
                                     "requirements.txt"))).get(dep_pkg, None)
                if ver_pip_setup is None:
                    print_ok(more=(" (%s)" % version))
                elif ver_pip_setup is not None and version.startswith(
                        ver_pip_setup):
                    print_ok(more=(" (%s)" % version))
                else:
                    print_warning(more=(" (%s != %s reference version))" %
                                        (version, ver_pip_setup)))

            elif dep_ver_spec == version:
                print_ok()

            else:
                print_warning(more=(" (%s != %s mandated version))" %
                                    (version, dep_ver_spec)))

        except ImportError as err:
            print_fail()
            print(err)
            install_software = 1

    print_line('Check if spinalcordtoolbox is installed')
    try:
        importlib.import_module('spinalcordtoolbox')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    status, output = sct.run(cmd, verbose=0, raise_exception=False)
    if status == 0:
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print('>> ' + cmd)
        print((status, output), '\n')

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    status, output = sct.run('isct_propseg',
                             verbose=0,
                             raise_exception=False,
                             is_sct_binary=True)
    if status in (0, 1):
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print((status, output), '\n')

    print_line('Check if DISPLAY variable is set')
    try:
        os.environ['DISPLAY']
        print_ok()

        # Further check with PyQt specifically
        print_line('Check if figure can be opened with PyQt')
        from PyQt5.QtWidgets import QApplication, QLabel
        try:
            app = QApplication([])
            label = QLabel('Hello World!')
            label.show()
            label.close()
            print_ok()
        except Exception as err:
            print_fail()
            print(err)

    except KeyError:
        print_fail()

    print('')
    sys.exit(e + install_software)
def main():


    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    # isct_c3d_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    print

    # Check input parameters
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hlc')
    except getopt.GetoptError:
        usage()
    for opt, arg in opts:
        if opt == '-h':
            usage()
        elif opt in ('-c'):
            complete_test = 1
        elif opt in ('-l'):
            create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test
    
    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check if user is root (should not be!)
    if os.geteuid() == 0:
       print 'Looks like you are root. Please run this script without sudo. Exit program\n'
       sys.exit(2)

    # check OS
    print 'Check which OS is running... '
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print '  '+os_running+' ('+platform.platform()+')'

    # check RAM
    print 'Check RAM... '
    sct.checkRAM(os_running)

    # check installation packages
    print 'Check which Python is running ... '
    print '  '+sys.executable

    # get path of the toolbox
    status, output = sct.run('echo $SCT_DIR', verbose)
    path_sct = output
    if complete_test:
        print (status, output), '\n'

    # fetch version of the toolbox
    print 'Fetch version of the Spinal Cord Toolbox... '
    with open (path_sct+"/version.txt", "r") as myfile:
        version_sct = myfile.read().replace('\n', '')
    print "  version: "+version_sct

    # check pillow
    print_line("Check if pillow is installed ")
    try:
        import PIL
        print_ok()
    except ImportError:
        print_fail()
        print '  pillow is not installed! Please install it via miniconda (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check numpy
    print_line('Check if numpy is installed ')
    try:
        import numpy
        print_ok()
    except ImportError:
        print_fail()
        print '  numpy is not installed! Please install it via miniconda (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check scipy
    print_line('Check if scipy is installed ')
    try:
        import scipy
        print_ok()
    except ImportError:
        print_fail()
        print '  scipy is not installed! Please install it via miniconda (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check sympy
    print_line('Check if sympy is installed ')
    try:
        import sympy
        print_ok()
    except ImportError:
        print_fail()
        print '  sympy is not installed! Please install it via miniconda (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check matplotlib
    print_line('Check if matplotlib is installed ')
    try:
        import matplotlib
        print_ok()
    except ImportError:
        print_fail()
        print '  matplotlib is not installed! Please install it via miniconda (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check nibabel
    print_line('Check if nibabel is installed ')
    try:
        import nibabel
        print_ok()
    except ImportError:
        print_fail()
        print '  nibabel is not installed! See instructions (https://sourceforge.net/p/spinalcordtoolbox/wiki/install_python/)'
        install_software = 1

    # check dipy
    print_line('Check if dipy is installed ')
    try:
        import dipy
        print_ok()
    except ImportError:
        print_fail()
        print '  dipy is not installed! You can install it using: http://nipy.org/dipy/installation.html'
        install_software = 1

    # check if FSL is declared
    print_line('Check if FSL is declared ')
    cmd = 'which fsl'
    status, output = commands.getstatusoutput(cmd)
    if output:
        print_ok()
        path_fsl = output[:-7]
        print '  '+path_fsl
    else:
        print_fail()
        print '  FSL is either not installed or not declared.'
        print '  - To install it: http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation.'
        print '  - To declare it: http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation/ShellSetup'
        e = 1

    # check if git is installed
    print_line('Check if git is installed ')
    cmd = 'which git'
    status, output = commands.getstatusoutput(cmd)
    if output:
        print_ok()
    else:
        print_fail()
        print '  git is not installed.'
        print '  - To install it: http://git-scm.com/book/en/v1/Getting-Started-Installing-Git'
        e = 1

    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # # check if FSL is installed
    # if not fsl_is_working:
    #     print_line('Check if FSL is installed ')
    #     # check first under /usr for faster search
    #     (status, output) = commands.getstatusoutput('find /usr -name "flirt" -type f -print -quit 2>/dev/null')
    #     if output:
    #         print_ok()
    #         path_fsl = output[:-10]
    #         print '  '+path_fsl
    #     else:
    #         # some users might have installed it under /home, so check it...
    #         (status, output) = commands.getstatusoutput('find /home -name "flirt" -type f -print -quit 2>/dev/null')
    #         if output:
    #             print_ok()
    #             path_fsl = output[:-10]
    #             print '  '+path_fsl
    #         else:
    #             print_fail()
    #             print '  FSL is either not installed.'
    #             print '  - To install it: http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation.'
    #             fsl_is_installed = 0
    #             install_software = 1

    # # check ANTs
    # print_line('Check which ANTs is running ')
    # # (status, output) = commands.getstatusoutput('command -v isct_antsRegistration >/dev/null 2>&1 || { echo >&2 "nope";}')
    # cmd = 'which isct_antsRegistration'
    # status, output = commands.getstatusoutput(cmd)
    # if output:
    #     print_ok()
    #     path_ants = output[:-20]
    #     print '  '+path_ants
    # else:
    #     print_warning()
    #     print '  ANTs is not declared.'
    #     e = 1
    # if complete_test:
    #     print '>> '+cmd
    #     print (status, output), '\n'

    # check if ANTs is compatible with OS
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_antsRegistration'
    status, output = commands.getstatusoutput(cmd)
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # # check isct_c3d
    # print_line('Check which isct_c3d is running ')
    # # (status, output) = commands.getstatusoutput('command -v isct_c3d >/dev/null 2>&1 || { echo >&2 "nope";}')
    # status, output = commands.getstatusoutput('which isct_c3d')
    # if output:
    #     print_ok()
    #     path_isct_c3d = output[:-7]
    #     print '  '+path_isct_c3d
    # else:
    #     print_warning()
    #     print '  isct_c3d is not installed or not declared.'
    #     install_software = 1
    # if complete_test:
    #     print (status, output), '\n'

    # check isct_c3d compatibility with OS
    print_line('Check c3d compatibility with OS ')
    (status, output) = commands.getstatusoutput('isct_c3d -h')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        install_software = 1
    if complete_test:
        print (status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('sct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print (status, output), '\n'

    # Check ANTs integrity
    print_line('Check integrity of ANTs output ')
    cmd_ants_test = 'isct_test_ants'
    # if not complete_test:
    #     cmd_ants_test += ' -v 0'
    (status, output) = commands.getstatusoutput(cmd_ants_test)
    if status in [0]:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print (status, output), '\n'
    print
    
    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: "+file_log+'\n'

    sys.exit(e + install_software)
def main():
    print("SCT info:")
    print("- version: {}".format(sct.__version__))
    print("- path: {0}".format(sct.__sct_dir__))

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    dipy_version = '0.10.0dev'

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse_args()
    if arguments.complete:
        complete_test = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # complete test
    if complete_test:
        print(sct.run('date', verbose))
        print(sct.run('whoami', verbose))
        print(sct.run('pwd', verbose))
        bash_profile = os.path.expanduser("~/.bash_profile")
        if os.path.isfile(bash_profile):
            with io.open(bash_profile, "r") as f:
                print(f.read())
        bashrc = os.path.expanduser("~/.bashrc")
        if os.path.isfile(bashrc):
            with io.open(bashrc, "r") as f:
                print(f.read())

    # check OS
    platform_running = sys.platform
    if platform_running.find('darwin') != -1:
        os_running = 'osx'
    elif platform_running.find('linux') != -1:
        os_running = 'linux'

    print('OS: ' + os_running + ' (' + platform.platform() + ')')

    # Check number of CPU cores
    from multiprocessing import cpu_count
    output = int(os.getenv('ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0))
    print('CPU cores: Available: {}, Used by SCT: {}'.format(cpu_count(), output))

    # check RAM
    sct.checkRAM(os_running, 0)

    # check if Python path is within SCT path
    print_line('Check Python executable')
    path_python = sys.executable
    if sct.__sct_dir__ in path_python:
        print_ok()
        print('  Using bundled python {} at {}'.format(sys.version, path_python))
    else:
        print_warning()
        print('  Using system python which is unsupported: {}'.format(path_python))

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.path.isdir(sct.__data_dir__):
        print_ok()
    else:
        print_fail()

    for dep_pkg, dep_ver_spec in get_dependencies():
        if dep_ver_spec is None:
            print_line('Check if %s is installed' % (dep_pkg))
        else:
            print_line('Check if %s (%s) is installed' % (dep_pkg, dep_ver_spec))

        try:
            module_name, suppress_stderr = resolve_module(dep_pkg)
            module = module_import(module_name, suppress_stderr)
            version = getattr(module, "__version__", getattr(module, "__VERSION__", None))

            if dep_ver_spec is None and version is not None:
                ver_pip_setup = dict(get_dependencies(os.path.join(sct.__sct_dir__, "requirements.txt"))).get(dep_pkg, None)
                if ver_pip_setup is None:
                    print_ok(more=(" (%s)" % version))
                elif ver_pip_setup is not None and version.startswith(ver_pip_setup):
                    print_ok(more=(" (%s)" % version))
                else:
                    print_warning(more=(" (%s != %s reference version))" % (version, ver_pip_setup)))

            elif dep_ver_spec == version:
                print_ok()
            else:
                print_warning(more=(" (%s != %s mandated version))" % (version, dep_ver_spec)))

        except ImportError:
            print_fail()
            install_software = 1


    print_line('Check if spinalcordtoolbox is installed')
    try:
        importlib.import_module('spinalcordtoolbox')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # CHECK EXTERNAL MODULES:

    # Check if dipy is installed
    # print_line('Check if dipy ('+dipy_version+') is installed')
    # try:
    #     module = importlib.import_module('dipy')
    #     if module.__version__ == dipy_version:
    #         print_ok()
    #     else:
    #         print_warning()
    #         print('  Detected version: '+version+'. Required version: '+dipy_version)
    # except ImportError:
    #     print_fail()
    #     install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    status, output = sct.run(cmd, verbose=0, raise_exception=False)
    if status == 0:
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print('>> ' + cmd)
        print((status, output), '\n')

    # check if ANTs is compatible with OS
    # print_line('Check ANTs compatibility with OS ')
    # cmd = 'isct_antsRegistration'
    # status, output = sct.run(cmd)
    # if status in [0, 256]:
    #     print_ok()
    # else:
    #     print_fail()
    #     e = 1
    # if complete_test:
    #     print('>> '+cmd)
    #     print((status, output), '\n')

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    status, output = sct.run('isct_propseg', verbose=0, raise_exception=False, is_sct_binary=True)
    if status in (0, 1):
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print((status, output), '\n')

    # check if figure can be opened (in case running SCT via ssh connection)
    print_line('Check if figure can be opened')
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        import matplotlib.pyplot as plt
        try:
            plt.figure()
            plt.close()
            print_ok()
        except Exception:
            print_fail()

    print('')
    sys.exit(e + install_software)
Exemple #4
0
def main():

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    # isct_c3d_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    print

    # Check input parameters
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hlc')
    except getopt.GetoptError:
        usage()
    for opt, arg in opts:
        if opt == '-h':
            usage()
        elif opt in ('-c'):
            complete_test = 1
        elif opt in ('-l'):
            create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check if user is root (should not be!)
    if os.geteuid() == 0:
        print 'Looks like you are root. Please run this script without sudo. Exit program\n'
        sys.exit(2)

    # check OS
    print 'Check which OS is running... '
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print '  ' + os_running + ' (' + platform.platform() + ')'

    # check RAM
    print 'Check RAM... '
    sct.checkRAM(os_running)

    # check installation packages
    print 'Check which Python is running ... '
    print '  ' + sys.executable

    # get path of the toolbox
    status, output = sct.run('echo $SCT_DIR', verbose)
    path_sct = output
    if complete_test:
        print(status, output), '\n'

    # fetch version of the toolbox
    print 'Fetch version of the Spinal Cord Toolbox... '
    with open(path_sct + "/version.txt", "r") as myfile:
        version_sct = myfile.read().replace('\n', '')
    print "  version: " + version_sct

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        if i == 'pillow':
            module = 'PIL'
        else:
            module = i
        print_line('Check if ' + i + ' (' + version_requirements.get(i) +
                   ') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            if i == 'pillow':
                version = module.PILLOW_VERSION
            else:
                version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: ' + version + '. Required version: ' + version_requirements[
                    i]
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:
        if i == 'scikit-image':
            module = 'skimage'
        else:
            module = i
        print_line('Check if ' + i + ' (' + version_requirements_pip.get(i) +
                   ') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: ' + version + '. Required version: ' + version_requirements_pip[
                    i]
        except ImportError:
            print_fail()
            install_software = 1

    # check if git is installed
    print_line('Check if git is installed ')
    cmd = 'which git'
    status, output = commands.getstatusoutput(cmd)
    if output:
        print_ok()
    else:
        print_fail()
        print '  git is not installed.'
        print '  - To install it: http://git-scm.com/book/en/v1/Getting-Started-Installing-Git'
        e = 1

    if complete_test:
        print '>> ' + cmd
        print(status, output), '\n'

    # check if ANTs is compatible with OS
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_antsRegistration'
    status, output = commands.getstatusoutput(cmd)
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print '>> ' + cmd
        print(status, output), '\n'

    # check isct_c3d compatibility with OS
    print_line('Check c3d compatibility with OS ')
    (status, output) = commands.getstatusoutput('isct_c3d -h')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        install_software = 1
    if complete_test:
        print(status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('sct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print(status, output), '\n'

    # Check ANTs integrity
    print_line('Check integrity of ANTs output ')
    cmd_ants_test = 'isct_test_ants'
    # if not complete_test:
    #     cmd_ants_test += ' -v 0'
    (status, output) = commands.getstatusoutput(cmd_ants_test)
    if status in [0]:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print(status, output), '\n'
    print

    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: " + file_log + '\n'

    sys.exit(e + install_software)
    sct.log.info('Hostname: {}'.format(platform.node()))

    # Check number of CPU cores
    sct.log.info('CPU Thread on local machine: {} '.format(cpu_count()))

    sct.log.info('    Requested threads:       {} '.format(jobs))

    if __MPI__:
        sct.log.info(
            "Running in MPI mode with mpi4py.futures's MPIPoolExecutor")
    else:
        sct.log.info(
            "Running with python concurrent.futures's ProcessPoolExecutor")

    # check RAM
    sct.checkRAM(os_running, 0)

    # display command
    sct.log.info('\nCommand(s):')
    for args in list_args:
        sct.log.info('  ' + function_to_test + ' ' + args)
    sct.log.info('Dataset: ' + path_data)
    sct.log.info('Test integrity: ' + str(test_integrity))

    # test function
    try:
        # retrieve subjects list
        list_subj = get_list_subj(path_data,
                                  data_specifications=data_specifications,
                                  fname_database=fname_database)
        # during testing, redirect to standard output to avoid stacking error messages in the general log
def main():
    path_sct = os.environ.get("SCT_DIR",
                              os.path.dirname(os.path.dirname(__file__)))
    print("SCT info:")
    print("- version: {}".format(sct.__version__))
    print("- path: {0}".format(path_sct))

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    dipy_version = '0.10.0dev'

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse_args()
    if arguments.complete:
        complete_test = 1
    if arguments.generate_log:
        create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # redirect to log file
    if create_log_file:
        handle_log = sct.ForkStdoutToFile(file_log)

    # complete test
    if complete_test:
        print(sct.run('date', verbose))
        print(sct.run('whoami', verbose))
        print(sct.run('pwd', verbose))
        bash_profile = os.path.expanduser("~/.bash_profile")
        if os.path.isfile(bash_profile):
            with io.open(bash_profile, "r") as f:
                print(f.read())
        bashrc = os.path.expanduser("~/.bashrc")
        if os.path.isfile(bashrc):
            with io.open(bashrc, "r") as f:
                print(f.read())

    # check OS
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'

    print('OS: ' + os_running + ' (' + platform.platform() + ')')

    # Check number of CPU cores
    from multiprocessing import cpu_count
    output = int(os.getenv('ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0))
    print('CPU cores: Available: {}, Used by SCT: {}'.format(
        cpu_count(), output))

    # check RAM
    sct.checkRAM(os_running, 0)

    # check if Python path is within SCT path
    print_line('Check Python executable')
    path_python = sys.executable
    if path_sct in path_python:
        print_ok()
        print('  Using bundled python {} at {}'.format(sys.version,
                                                       path_python))
    else:
        print_warning()
        print('  Using system python which is unsupported: {}'.format(
            path_python))

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.listdir(os.path.join(path_sct, "data")):
        print_ok()
    else:
        print_fail()

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        module_name, suppress_stderr = resolve_module(i)
        if module_name is None:
            continue
        print_line('Check if %s (%s) is installed' %
                   (i, version_requirements.get(i)))
        try:
            module = module_import(module_name, suppress_stderr)
            # get version
            try:
                version = module.__version__
            except:
                try:
                    version = module.__VERSION__
                except:
                    # skip if module doesn't have __version__ nor __VERSION__ (e.g., xlutils)
                    version = version_requirements[i]
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print('  Detected version: ' + version +
                      '. Required version: ' + version_requirements[i])
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:

        module_name, suppress_stderr = resolve_module(i)

        print_line('Check if ' + i + ' (' + version_requirements_pip.get(i) +
                   ') is installed')
        try:
            module = module_import(module_name, suppress_stderr)
            if module_name in ("raven", ):
                version = module.VERSION
            else:
                try:
                    version = module.__version__
                except AttributeError:
                    # Futures package as no embedded version info
                    version = version_requirements_pip[i]

            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print('  Detected version: ' + version +
                      '. Required version: ' + version_requirements_pip[i])
        except ImportError:
            print_fail()
            install_software = 1

    # CHECK DEPENDENT MODULES (installed by nibabel/dipy):
    sys.stdout.write('Check if numpy is installed')
    sys.stdout.flush()
    try:
        np = importlib.import_module('numpy')
        sys.stdout.write(' ({})'.format(np.__version__).ljust(25, '.'))
        print_ok()
    except ImportError:
        sys.stdout.write(' (........................')
        print_fail()
        install_software = 1
    sys.stdout.write('Check if scipy is installed')
    sys.stdout.flush()
    try:
        sp = importlib.import_module('scipy')
        sys.stdout.write(' ({})'.format(sp.__version__).ljust(25, '.'))
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1
    print_line('Check if spinalcordtoolbox is installed')
    try:
        importlib.import_module('spinalcordtoolbox')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # CHECK EXTERNAL MODULES:

    # Check if dipy is installed
    # print_line('Check if dipy ('+dipy_version+') is installed')
    # try:
    #     module = importlib.import_module('dipy')
    #     if module.__version__ == dipy_version:
    #         print_ok()
    #     else:
    #         print_warning()
    #         print('  Detected version: '+version+'. Required version: '+dipy_version)
    # except ImportError:
    #     print_fail()
    #     install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    status, output = sct.run(cmd, verbose=0, raise_exception=False)
    if status == 0:
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print('>> ' + cmd)
        print((status, output), '\n')

    # check if ANTs is compatible with OS
    # print_line('Check ANTs compatibility with OS ')
    # cmd = 'isct_antsRegistration'
    # status, output = sct.run(cmd)
    # if status in [0, 256]:
    #     print_ok()
    # else:
    #     print_fail()
    #     e = 1
    # if complete_test:
    #     print('>> '+cmd)
    #     print((status, output), '\n')

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    status, output = sct.run('isct_propseg', verbose=0, raise_exception=False)
    if status in (0, 1):
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print((status, output), '\n')

    # check if figure can be opened (in case running SCT via ssh connection)
    print_line('Check if figure can be opened')
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        import matplotlib.pyplot as plt
        try:
            plt.figure()
            plt.close()
            print_ok()
        except Exception:
            if "MPLBACKEND" not in os.environ:
                print("\nSecond attempt to plot ...")
                print("\nOverwriting environment variable $MPLBACKEND=agg")
                try:
                    os.environ["MPLBACKEND"] = "agg"
                    plt.figure()
                    plt.close()
                    print_ok()
                except Exception:
                    print_fail()
                    print(sys.exc_info())
            else:
                print(
                    "Please try manually setting environment variable $MPLBACKEND=agg"
                )
                print_fail()

    print('')
    sys.exit(e + install_software)
Exemple #7
0
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print 'OS: '+os_running+' ('+platform.platform()+')'

    # check hostname
    print 'Hostname:', platform.node()

    # Check number of CPU cores
    from multiprocessing import cpu_count
    # status, output = sct.run('echo $ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0)
    print 'CPU cores: ' + str(cpu_count())  # + ', Used by SCT: '+output

    # check RAM
    sct.checkRAM(os_running, 0)

    # test function
    try:
        results = test_function(function_to_test, dataset, parameters, nb_cpu, json_requirements, verbose)
        pd.set_option('display.max_rows', 500)
        pd.set_option('display.max_columns', 500)
        pd.set_option('display.width', 1000)
        results_subset = results.drop('script', 1).drop('dataset', 1).drop('parameters', 1).drop('output', 1)
        results_display = results_subset

        # save panda structure
        if create_log:
            results_subset.to_pickle(file_log+'.pickle')

        # mean
def main():

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    print

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse(sys.argv[1:])
    if '-c' in arguments:
        complete_test = 1
    if '-log' in arguments:
        create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test
    
    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check if user is root (should not be!)
    if os.geteuid() == 0:
       print 'Looks like you are root. Please run this script without sudo. Exit program\n'
       sys.exit(2)

    # check OS
    print 'Check which OS is running... '
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print '.. '+os_running+' ('+platform.platform()+')'

    # Check number of CPU cores
    print 'Check number of CPU cores...'
    from multiprocessing import cpu_count
    print '.. Available: ' + str(cpu_count())
    status, output = sct.run('echo $ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0)
    print '.. Used by SCT: ' + output

    # check RAM
    print 'Check RAM... '
    sct.checkRAM(os_running)

    # check installation packages
    print 'Check which Python is running...'
    print '.. '+sys.executable

    # get path of the toolbox
    print 'Check SCT path...'
    status, output = sct.run('echo $SCT_DIR', verbose)
    path_sct = output
    print '.. '+path_sct

    # fetch version of the toolbox
    print 'Check SCT version... '
    with open (path_sct+"/version.txt", "r") as myfile:
        version_sct = myfile.read().replace('\n', '')
    print ".. "+version_sct

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        if i == 'scikit-image':
            module = 'skimage'
        else:
            module = i
        print_line('Check if '+i+' ('+version_requirements.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements[i]
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:
        module = i
        print_line('Check if '+i+' ('+version_requirements_pip.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements_pip[i]
        except ImportError:
            print_fail()
            install_software = 1

    # CHECK EXTERNAL MODULES:
    # Check if ornlm is installed
    print_line('Check if ornlm is installed')
#    sys.path.append(path_sct + '/external/denoise/ornlm')  # append to PYTHONPATH
    try:
        importlib.import_module('ornlm')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # Check if dipy is installed
    print_line('Check if dipy is installed')
    try:
        importlib.import_module('dipy')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # check if ANTs is compatible with OS
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_antsRegistration'
    status, output = commands.getstatusoutput(cmd)
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('sct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print (status, output), '\n'

    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: "+file_log+'\n'

    print ''
    sys.exit(e + install_software)
def main():
    print("SCT info:")
    print("- version: {}".format(sct.__version__))
    print("- path: {0}".format(sct.__sct_dir__))

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    dipy_version = '0.10.0dev'

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse_args()
    if arguments.complete:
        complete_test = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # complete test
    if complete_test:
        print(sct.run('date', verbose))
        print(sct.run('whoami', verbose))
        print(sct.run('pwd', verbose))
        bash_profile = os.path.expanduser("~/.bash_profile")
        if os.path.isfile(bash_profile):
            with io.open(bash_profile, "r") as f:
                print(f.read())
        bashrc = os.path.expanduser("~/.bashrc")
        if os.path.isfile(bashrc):
            with io.open(bashrc, "r") as f:
                print(f.read())

    # check OS
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'

    print('OS: ' + os_running + ' (' + platform.platform() + ')')

    # Check number of CPU cores
    from multiprocessing import cpu_count
    output = int(os.getenv('ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0))
    print('CPU cores: Available: {}, Used by SCT: {}'.format(cpu_count(), output))

    # check RAM
    sct.checkRAM(os_running, 0)

    # check if Python path is within SCT path
    print_line('Check Python executable')
    path_python = sys.executable
    if sct.__sct_dir__ in path_python:
        print_ok()
        print('  Using bundled python {} at {}'.format(sys.version, path_python))
    else:
        print_warning()
        print('  Using system python which is unsupported: {}'.format(path_python))

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.path.isdir(sct.__data_dir__):
        print_ok()
    else:
        print_fail()

    for dep_pkg, dep_ver_spec in get_dependencies():
        if dep_ver_spec is None:
            print_line('Check if %s is installed' % (dep_pkg))
        else:
            print_line('Check if %s (%s) is installed' % (dep_pkg, dep_ver_spec))

        try:
            module_name, suppress_stderr = resolve_module(dep_pkg)
            module = module_import(module_name, suppress_stderr)
            version = getattr(module, "__version__", getattr(module, "__VERSION__", None))

            if dep_ver_spec is None and version is not None:
                ver_pip_setup = dict(get_dependencies(os.path.join(sct.__sct_dir__, "requirements.txt"))).get(dep_pkg, None)
                if ver_pip_setup is None:
                    print_ok(more=(" (%s)" % version))
                elif ver_pip_setup is not None and version.startswith(ver_pip_setup):
                    print_ok(more=(" (%s)" % version))
                else:
                    print_warning(more=(" (%s != %s reference version))" % (version, ver_pip_setup)))

            elif dep_ver_spec == version:
                print_ok()
            else:
                print_warning(more=(" (%s != %s mandated version))" % (version, dep_ver_spec)))

        except ImportError:
            print_fail()
            install_software = 1


    print_line('Check if spinalcordtoolbox is installed')
    try:
        importlib.import_module('spinalcordtoolbox')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # CHECK EXTERNAL MODULES:

    # Check if dipy is installed
    # print_line('Check if dipy ('+dipy_version+') is installed')
    # try:
    #     module = importlib.import_module('dipy')
    #     if module.__version__ == dipy_version:
    #         print_ok()
    #     else:
    #         print_warning()
    #         print('  Detected version: '+version+'. Required version: '+dipy_version)
    # except ImportError:
    #     print_fail()
    #     install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    status, output = sct.run(cmd, verbose=0, raise_exception=False)
    if status == 0:
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print('>> ' + cmd)
        print((status, output), '\n')

    # check if ANTs is compatible with OS
    # print_line('Check ANTs compatibility with OS ')
    # cmd = 'isct_antsRegistration'
    # status, output = sct.run(cmd)
    # if status in [0, 256]:
    #     print_ok()
    # else:
    #     print_fail()
    #     e = 1
    # if complete_test:
    #     print('>> '+cmd)
    #     print((status, output), '\n')

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    status, output = sct.run('isct_propseg', verbose=0, raise_exception=False, is_sct_binary=True)
    if status in (0, 1):
        print_ok()
    else:
        print_fail()
        print(output)
        e = 1
    if complete_test:
        print((status, output), '\n')

    # check if figure can be opened (in case running SCT via ssh connection)
    print_line('Check if figure can be opened')
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        import matplotlib.pyplot as plt
        try:
            plt.figure()
            plt.close()
            print_ok()
        except Exception:
            print_fail()

    print('')
    sys.exit(e + install_software)
Exemple #10
0
def main():

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    dipy_version = '0.10.0dev'
    print

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse(sys.argv[1:])
    if '-c' in arguments:
        complete_test = 1
    if '-log' in arguments:
        create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test
    
    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check OS
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print 'OS: '+os_running+' ('+platform.platform()+')'

    # Check number of CPU cores
    from multiprocessing import cpu_count
    status, output = sct.run('echo $ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0)
    print 'CPU cores: Available: ' + str(cpu_count()) + ', Used by SCT: '+output

    # check RAM
    sct.checkRAM(os_running, 0)

    # get path of the toolbox
    path_sct = os.path.dirname(os.path.dirname(__file__))
    if path_sct is None:
        raise EnvironmentError("SCT_DIR, which is the path SCT install needs to be set")
    print ('SCT path: {0}'.format(path_sct))

    # fetch true commit number and branch (do not use commit.txt which is wrong)
    path_curr = os.path.abspath(os.curdir)
    os.chdir(path_sct)
    # first, make sure there is a .git folder
    if os.path.isdir('.git'):
        print 'Installation type: git'
        sct_commit = commands.getoutput('git rev-parse HEAD')
        sct_branch = commands.getoutput('git branch | grep \*').strip('* ')
        if not (sct_commit.isalnum()):
            sct_commit = 'unknown'
            sct_branch = 'unknown'
        print '  commit: '+sct_commit
        print '  branch: '+sct_branch
    else:
        print 'Installation type: package'
        # fetch version
        with open(path_sct + '/version.txt', 'r') as myfile:
            version_sct = myfile.read().replace('\n', '')
        print '  version: '+version_sct

    os.chdir(path_curr)

    # # fetch version of the toolbox
    # with open (path_sct+"/version.txt", "r") as myfile:
    #     version_sct = myfile.read().replace('\n', '')
    # with open (path_sct+"/commit.txt", "r") as myfile:
    #     commit_sct = myfile.read().replace('\n', '')
    # print "SCT version: "+version_sct+'-'+commit_sct

    # check if Python path is within SCT path
    print_line('Check Python path')
    path_python = sys.executable
    if path_sct in path_python:
        print_ok()
    else:
        print_fail()
        print '  Python path: '+path_python

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.listdir(path_sct+"/data"):
        print_ok()
    else:
        print_fail()

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        # need to adapt import name and module name in specific cases
        if i == 'scikit-image':
            module = 'skimage'
        elif i == 'scikit-learn':
            module = 'sklearn'
        elif i == 'pyqt':
            module = 'PyQt4'
        else:
            module = i
        print_line('Check if '+i+' ('+version_requirements.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            try:
                version = module.__version__
            except:
                try:
                    version = module.__VERSION__
                except:
                    # skip if module doesn't have __version__ nor __VERSION__ (e.g., xlutils)
                    version = version_requirements[i]
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements[i]
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:
        module = i
        print_line('Check if '+i+' ('+version_requirements_pip.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements_pip[i]
        except ImportError:
            print_fail()
            install_software = 1


    # CHECK DEPENDENT MODULES (installed by nibabel/dipy):
    print_line('Check if numpy is installed')
    try:
        importlib.import_module('numpy')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1
    print_line('Check if scipy is installed')
    try:
        importlib.import_module('scipy')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # CHECK EXTERNAL MODULES:
    
    # Check if dipy is installed
    # print_line('Check if dipy ('+dipy_version+') is installed')
    # try:
    #     module = importlib.import_module('dipy')
    #     if module.__version__ == dipy_version:
    #         print_ok()
    #     else:
    #         print_warning()
    #         print '  Detected version: '+version+'. Required version: '+dipy_version
    # except ImportError:
    #     print_fail()
    #     install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    # here, cannot use commands.getstatusoutput because status is wrong (because of launcher)
    # status = os.system(cmd+" &> /dev/null")
    # status, output = sct.run(cmd, 0)
    # import subprocess
    # process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # status = subprocess.call(cmd, shell=True)
    # status = process.returncode
    (status, output) = commands.getstatusoutput(cmd)
    # from subprocess import call
    # status, output = call(cmd)
    # print status
    # print output
    # if status in [0, 256]:
    if status == 0:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # check if ANTs is compatible with OS
    # print_line('Check ANTs compatibility with OS ')
    # cmd = 'isct_antsRegistration'
    # status, output = commands.getstatusoutput(cmd)
    # if status in [0, 256]:
    #     print_ok()
    # else:
    #     print_fail()
    #     e = 1
    # if complete_test:
    #     print '>> '+cmd
    #     print (status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('isct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print (status, output), '\n'

    # check if figure can be opened (in case running SCT via ssh connection)
    print_line('Check if figure can be opened')
    try:
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            import matplotlib.pyplot as plt
            plt.figure()
            plt.close()
            print_ok()
    except:
        print_fail()
        print sys.exc_info()

    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: "+file_log+'\n'
    print ''
    sys.exit(e + install_software)
def main():

    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    dipy_version = '0.10.0dev'
    print

    # Check input parameters
    parser = get_parser()
    arguments = parser.parse(sys.argv[1:])
    if '-c' in arguments:
        complete_test = 1
    if '-log' in arguments:
        create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test

    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check OS
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print 'OS: ' + os_running + ' (' + platform.platform() + ')'

    # Check number of CPU cores
    from multiprocessing import cpu_count
    status, output = sct.run('echo $ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS', 0)
    print 'CPU cores: Available: ' + str(
        cpu_count()) + ', Used by SCT: ' + output

    # check RAM
    sct.checkRAM(os_running, 0)

    # get path of the toolbox
    path_sct = os.path.dirname(os.path.dirname(__file__))
    if path_sct is None:
        raise EnvironmentError(
            "SCT_DIR, which is the path SCT install needs to be set")
    print('SCT path: {0}'.format(path_sct))

    # fetch true commit number and branch (do not use commit.txt which is wrong)
    path_curr = os.path.abspath(os.curdir)
    os.chdir(path_sct)
    # first, make sure there is a .git folder
    if os.path.isdir('.git'):
        print 'Installation type: git'
        sct_commit = commands.getoutput('git rev-parse HEAD')
        sct_branch = commands.getoutput('git branch | grep \*').strip('* ')
        if not (sct_commit.isalnum()):
            sct_commit = 'unknown'
            sct_branch = 'unknown'
        print '  commit: ' + sct_commit
        print '  branch: ' + sct_branch
    else:
        print 'Installation type: package'
        # fetch version
        with open(path_sct + '/version.txt', 'r') as myfile:
            version_sct = myfile.read().replace('\n', '')
        print '  version: ' + version_sct

    os.chdir(path_curr)

    # # fetch version of the toolbox
    # with open (path_sct+"/version.txt", "r") as myfile:
    #     version_sct = myfile.read().replace('\n', '')
    # with open (path_sct+"/commit.txt", "r") as myfile:
    #     commit_sct = myfile.read().replace('\n', '')
    # print "SCT version: "+version_sct+'-'+commit_sct

    # check if Python path is within SCT path
    print_line('Check Python path')
    path_python = sys.executable
    if path_sct in path_python:
        print_ok()
    else:
        print_fail()
        print '  Python path: ' + path_python

    # check if data folder is empty
    print_line('Check if data are installed')
    if os.listdir(path_sct + "/data"):
        print_ok()
    else:
        print_fail()

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        # need to adapt import name and module name in specific cases
        if i == 'scikit-image':
            module = 'skimage'
        elif i == 'scikit-learn':
            module = 'sklearn'
        elif i == 'pyqt':
            module = 'PyQt4'
        else:
            module = i
        print_line('Check if ' + i + ' (' + version_requirements.get(i) +
                   ') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            try:
                version = module.__version__
            except:
                try:
                    version = module.__VERSION__
                except:
                    # skip if module doesn't have __version__ nor __VERSION__ (e.g., xlutils)
                    version = version_requirements[i]
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: ' + version + '. Required version: ' + version_requirements[
                    i]
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:
        module = i
        print_line('Check if ' + i + ' (' + version_requirements_pip.get(i) +
                   ') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: ' + version + '. Required version: ' + version_requirements_pip[
                    i]
        except ImportError:
            print_fail()
            install_software = 1

    # CHECK DEPENDENT MODULES (installed by nibabel/dipy):
    print_line('Check if numpy is installed')
    try:
        importlib.import_module('numpy')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1
    print_line('Check if scipy is installed')
    try:
        importlib.import_module('scipy')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1
    print_line('Check if spinalcordtoolbox is installed')
    try:
        importlib.import_module('spinalcordtoolbox')
        print_ok()
    except ImportError:
        print_fail()
        install_software = 1

    # CHECK EXTERNAL MODULES:

    # Check if dipy is installed
    # print_line('Check if dipy ('+dipy_version+') is installed')
    # try:
    #     module = importlib.import_module('dipy')
    #     if module.__version__ == dipy_version:
    #         print_ok()
    #     else:
    #         print_warning()
    #         print '  Detected version: '+version+'. Required version: '+dipy_version
    # except ImportError:
    #     print_fail()
    #     install_software = 1

    # Check ANTs integrity
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_test_ants'
    # here, cannot use commands.getstatusoutput because status is wrong (because of launcher)
    # status = os.system(cmd+" &> /dev/null")
    # status, output = sct.run(cmd, 0)
    # import subprocess
    # process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # status = subprocess.call(cmd, shell=True)
    # status = process.returncode
    (status, output) = commands.getstatusoutput(cmd)
    # from subprocess import call
    # status, output = call(cmd)
    # print status
    # print output
    # if status in [0, 256]:
    if status == 0:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print '>> ' + cmd
        print(status, output), '\n'

    # check if ANTs is compatible with OS
    # print_line('Check ANTs compatibility with OS ')
    # cmd = 'isct_antsRegistration'
    # status, output = commands.getstatusoutput(cmd)
    # if status in [0, 256]:
    #     print_ok()
    # else:
    #     print_fail()
    #     e = 1
    # if complete_test:
    #     print '>> '+cmd
    #     print (status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('isct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print(status, output), '\n'

    # check if figure can be opened (in case running SCT via ssh connection)
    print_line('Check if figure can be opened')
    try:
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            import matplotlib.pyplot as plt
            plt.figure()
            plt.close()
            print_ok()
    except:
        print_fail()
        print sys.exc_info()

    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: " + file_log + '\n'
    print ''
    sys.exit(e + install_software)
def main():


    # initialization
    fsl_is_working = 1
    # ants_is_installed = 1
    # isct_c3d_is_installed = 1
    install_software = 0
    e = 0
    restart_terminal = 0
    create_log_file = param.create_log_file
    file_log = 'sct_check_dependencies.log'
    complete_test = param.complete_test
    os_running = 'not identified'
    print

    # Check input parameters
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hlc')
    except getopt.GetoptError:
        usage()
    for opt, arg in opts:
        if opt == '-h':
            usage()
        elif opt in ('-c'):
            complete_test = 1
        elif opt in ('-l'):
            create_log_file = 1

    # use variable "verbose" when calling sct.run for more clarity
    verbose = complete_test
    
    # redirect to log file
    if create_log_file:
        orig_stdout = sys.stdout
        handle_log = file(file_log, 'w')
        sys.stdout = handle_log

    # complete test
    if complete_test:
        print sct.run('date', verbose)
        print sct.run('whoami', verbose)
        print sct.run('pwd', verbose)
        if os.path.isfile('~/.bash_profile'):
            (status, output) = sct.run('more ~/.bash_profile', verbose)
            print output
        if os.path.isfile('~/.bashrc'):
            (status, output) = sct.run('more ~/.bashrc', verbose)
            print output

    # check if user is root (should not be!)
    if os.geteuid() == 0:
       print 'Looks like you are root. Please run this script without sudo. Exit program\n'
       sys.exit(2)

    # check OS
    print 'Check which OS is running... '
    platform_running = sys.platform
    if (platform_running.find('darwin') != -1):
        os_running = 'osx'
    elif (platform_running.find('linux') != -1):
        os_running = 'linux'
    print '  '+os_running+' ('+platform.platform()+')'

    # check RAM
    print 'Check RAM... '
    sct.checkRAM(os_running)

    # check installation packages
    print 'Check which Python is running ... '
    print '  '+sys.executable

    # get path of the toolbox
    status, output = sct.run('echo $SCT_DIR', verbose)
    path_sct = output
    if complete_test:
        print (status, output), '\n'

    # fetch version of the toolbox
    print 'Fetch version of the Spinal Cord Toolbox... '
    with open (path_sct+"/version.txt", "r") as myfile:
        version_sct = myfile.read().replace('\n', '')
    print "  version: "+version_sct

    # loop across python packages -- CONDA
    version_requirements = get_version_requirements()
    for i in version_requirements:
        if i == 'pillow':
            module = 'PIL'
        else:
            module = i
        print_line('Check if '+i+' ('+version_requirements.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            if i == 'pillow':
                version = module.PILLOW_VERSION
            else:
                version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements[i]
        except ImportError:
            print_fail()
            install_software = 1

    # loop across python packages -- PIP
    version_requirements_pip = get_version_requirements_pip()
    for i in version_requirements_pip:
        if i == 'scikit-image':
            module = 'skimage'
        else:
            module = i
        print_line('Check if '+i+' ('+version_requirements_pip.get(i)+') is installed')
        try:
            module = importlib.import_module(module)
            # get version
            version = module.__version__
            # check if version matches requirements
            if check_package_version(version, version_requirements_pip, i):
                print_ok()
            else:
                print_warning()
                print '  Detected version: '+version+'. Required version: '+version_requirements_pip[i]
        except ImportError:
            print_fail()
            install_software = 1


    # check if git is installed
    print_line('Check if git is installed ')
    cmd = 'which git'
    status, output = commands.getstatusoutput(cmd)
    if output:
        print_ok()
    else:
        print_fail()
        print '  git is not installed.'
        print '  - To install it: http://git-scm.com/book/en/v1/Getting-Started-Installing-Git'
        e = 1

    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # check if ANTs is compatible with OS
    print_line('Check ANTs compatibility with OS ')
    cmd = 'isct_antsRegistration'
    status, output = commands.getstatusoutput(cmd)
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print '>> '+cmd
        print (status, output), '\n'

    # check isct_c3d compatibility with OS
    print_line('Check c3d compatibility with OS ')
    (status, output) = commands.getstatusoutput('isct_c3d -h')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        install_software = 1
    if complete_test:
        print (status, output), '\n'

    # check PropSeg compatibility with OS
    print_line('Check PropSeg compatibility with OS ')
    (status, output) = commands.getstatusoutput('sct_propseg')
    if status in [0, 256]:
        print_ok()
    else:
        print_fail()
        e = 1
    if complete_test:
        print (status, output), '\n'

    # Check ANTs integrity
    print_line('Check integrity of ANTs output ')
    cmd_ants_test = 'isct_test_ants'
    # if not complete_test:
    #     cmd_ants_test += ' -v 0'
    (status, output) = commands.getstatusoutput(cmd_ants_test)
    if status in [0]:
        print_ok()
    else:
        print_fail()
        print output
        e = 1
    if complete_test:
        print (status, output), '\n'
    print
    
    # close log file
    if create_log_file:
        sys.stdout = orig_stdout
        handle_log.close()
        print "File generated: "+file_log+'\n'

    sys.exit(e + install_software)