Exemplo n.º 1
0
def requires_lib(lib):
    val = False
    try:
        importlib.import_module(lib)
    except Exception:
        val = True
    return skipif(val, 'Needs %s' % lib)
Exemplo n.º 2
0
def requires_lib(lib):
    val = False
    try:
        importlib.import_module(lib)
    except Exception:
        val = True
    return skipif(val, 'Needs %s' % lib)
Exemplo n.º 3
0
def requires_avbin():
    try:
        from pyglet.media.avbin import AVbinSource
        del AVbinSource
        _has_avbin = True
    except ImportError:
        _has_avbin = False
    return skipif(not _has_avbin, 'Requires AVbin')
Exemplo n.º 4
0
def requires_avbin():
    try:
        from pyglet.media.avbin import AVbinSource
        del AVbinSource
        _has_avbin = True
    except ImportError:
        _has_avbin = False
    return skipif(not _has_avbin, 'Requires AVbin')
Exemplo n.º 5
0
def needs_nibabel_data(subdir=None):
    """ Decorator for tests needing nibabel-data

    Parameters
    ----------
    subdir : None or str
        Subdirectory we need in nibabel-data directory.  If None, only require
        nibabel-data directory itself.

    Returns
    -------
    skip_dec : decorator
        Decorator skipping tests if required directory not present
    """
    nibabel_data = get_nibabel_data()
    if nibabel_data == '':
        return skipif(True, "Need nibabel-data directory for this test")
    if subdir is None:
        return skipif(False)
    required_path = pjoin(nibabel_data, subdir)
    # Path should not be empty (as is the case for not-updated submodules)
    have_files = exists(required_path) and len(listdir(required_path)) > 0
    return skipif(not have_files,
                  "Need files in {0} for these tests".format(required_path))
Exemplo n.º 6
0
        ret = function(*args, **kwargs)
        return ret


def requires_avbin():
    try:
        from pyglet.media.avbin import AVbinSource
        del AVbinSource
        _has_avbin = True
    except ImportError:
        _has_avbin = False
    return skipif(not _has_avbin, 'Requires AVbin')


_is_appveyor = (os.getenv('APPVEYOR', 'False').lower() == 'true')
requires_pandas = skipif(has_pandas is False, 'Requires pandas')
requires_h5py = skipif(has_h5py is False, 'Requires h5py')
requires_joblib = skipif(has_joblib is False, 'Requires joblib')
requires_opengl21 = skipif(_is_appveyor, 'Appveyor OpenGL too old')


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))


def _hide_window(function):
    """Decorator to hide expyfun windows during testing"""
    import nose

    def dec(*args, **kwargs):
        orig_val = os.getenv('_EXPYFUN_WIN_INVISIBLE')
Exemplo n.º 7
0
Test that we can run executable scripts that have been installed with numpy.
"""
from __future__ import division, print_function, absolute_import

import os
from os.path import join as pathjoin, isfile, dirname, basename
import sys
from subprocess import Popen, PIPE
import numpy as np
from numpy.compat.py3k import basestring, asbytes
from nose.tools import assert_equal
from numpy.testing.decorators import skipif
from numpy.testing import assert_

skipif_inplace = skipif(isfile(pathjoin(dirname(np.__file__),  '..', 'setup.py')))

def run_command(cmd, check_code=True):
    """ Run command sequence `cmd` returning exit code, stdout, stderr

    Parameters
    ----------
    cmd : str or sequence
        string with command name or sequence of strings defining command
    check_code : {True, False}, optional
        If True, raise error for non-zero return code

    Returns
    -------
    returncode : int
        return code from execution of `cmd`
Exemplo n.º 8
0
from nibabel.nifti1 import Nifti1Image
from nibabel.nifti2 import Nifti2Image
from nibabel.orientations import flip_axis, inv_ornt_aff
from nibabel.affines import AffineError, from_matvec, to_matvec, apply_affine
from nibabel.eulerangles import euler2mat

from numpy.testing import (assert_almost_equal, assert_array_equal)
from numpy.testing.decorators import skipif

from nose.tools import (assert_true, assert_false, assert_raises, assert_equal,
                        assert_not_equal)

from nibabel.tests.test_spaces import assert_all_in, get_outspace_params
from nibabel.testing import assert_allclose_safely

needs_scipy = skipif(not have_scipy, 'These tests need scipy')

DATA_DIR = pjoin(dirname(__file__), 'data')


def test_sigma2fwhm():
    # Test from constant
    assert_almost_equal(sigma2fwhm(1), 2.3548200)
    assert_almost_equal(sigma2fwhm([1, 2, 3]), np.arange(1, 4) * 2.3548200)
    assert_almost_equal(fwhm2sigma(2.3548200), 1)
    assert_almost_equal(fwhm2sigma(np.arange(1, 4) * 2.3548200), [1, 2, 3])
    # direct test fwhm2sigma and sigma2fwhm are inverses of each other
    fwhm = np.arange(1.0, 5.0, 0.1)
    sigma = np.arange(1.0, 5.0, 0.1)
    assert_true(np.allclose(sigma2fwhm(fwhm2sigma(fwhm)), fwhm))
    assert_true(np.allclose(fwhm2sigma(sigma2fwhm(sigma)), sigma))
Exemplo n.º 9
0
from nibabel.orientations import flip_axis, inv_ornt_aff
from nibabel.affines import (AffineError, from_matvec, to_matvec, apply_affine,
                             voxel_sizes)
from nibabel.eulerangles import euler2mat

from numpy.testing import (assert_almost_equal,
                           assert_array_equal)
from numpy.testing.decorators import skipif

from nose.tools import (assert_true, assert_false, assert_raises,
                        assert_equal, assert_not_equal)

from nibabel.tests.test_spaces import assert_all_in, get_outspace_params
from nibabel.testing import assert_allclose_safely

needs_scipy = skipif(not have_scipy, 'These tests need scipy')

DATA_DIR = pjoin(dirname(__file__), 'data')

# 3D MINC work correctly with processing, but not 4D MINC
from .test_imageclasses import MINC_3DS, MINC_4DS

# Filenames of other images that should work correctly with processing
OTHER_IMGS = ('anatomical.nii', 'functional.nii',
              'example4d.nii.gz', 'example_nifti2.nii.gz',
              'phantom_EPI_asc_CLEAR_2_1.PAR')


def test_sigma2fwhm():
    # Test from constant
    assert_almost_equal(sigma2fwhm(1), 2.3548200)
Exemplo n.º 10
0
    if verbose_level is not None:
        old_level = set_log_level(verbose_level, True)
        # set it back if we get an exception
        try:
            ret = function(*args, **kwargs)
        except:
            set_log_level(old_level)
            raise
        set_log_level(old_level)
        return ret
    else:
        ret = function(*args, **kwargs)
        return ret


requires_pylink = skipif(has_pylink is False, 'Requires functional pylink')
requires_pandas = skipif(has_pandas is False, 'Requires pandas')
requires_pytables = skipif(has_pytables is False, 'Requires pytables')


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))


def _hide_window(function):
    """Decorator to hide expyfun windows during testing"""
    import nose

    def dec(*args, **kwargs):
        orig_val = os.getenv('_EXPYFUN_WIN_INVISIBLE')
        try:
Exemplo n.º 11
0
 def skip_func(func):
     return skipif(True, msg)(func)
Exemplo n.º 12
0
def runif_extra_has(test_str):
    """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str"""
    return skipif(test_str not in EXTRA_SET,
                  "Skip {0} tests.".format(test_str))
Exemplo n.º 13
0
from ...utils.six.moves import xrange

from dipy.core.sphere import (Sphere, HemiSphere, unique_edges, unique_sets,
                              faces_from_sphere_vertices, HemiSphere,
                              disperse_charges, _get_forces, unit_octahedron,
                              unit_icosahedron)
from dipy.core.subdivide_octahedron import create_unit_sphere
from dipy.core.geometry import cart2sphere, sphere2cart, vector_norm

from numpy.testing.decorators import skipif

try:
    from scipy.spatial import Delaunay
except ImportError:
    needs_delaunay = skipif(True, "Need scipy.spatial.Delaunay")
else:
    needs_delaunay = skipif(False)

verts = unit_octahedron.vertices
edges = unit_octahedron.edges
oct_faces = unit_octahedron.faces
r, theta, phi = cart2sphere(*verts.T)


def test_sphere_construct_args():
    nt.assert_raises(ValueError, Sphere)
    nt.assert_raises(ValueError, Sphere, x=1, theta=1)
    nt.assert_raises(ValueError, Sphere, xyz=1, theta=1)
    nt.assert_raises(ValueError, Sphere, xyz=1, theta=1, phi=1)
Exemplo n.º 14
0
        ret = function(*args, **kwargs)
        return ret


def requires_avbin():
    try:
        from pyglet.media.avbin import AVbinSource
        del AVbinSource
        _has_avbin = True
    except ImportError:
        _has_avbin = False
    return skipif(not _has_avbin, 'Requires AVbin')


_is_appveyor = (os.getenv('APPVEYOR', 'False').lower() == 'true')
requires_opengl21 = skipif(_is_appveyor, 'Appveyor OpenGL too old')


def requires_lib(lib):
    val = False
    try:
        importlib.import_module(lib)
    except Exception:
        val = True
    return skipif(val, 'Needs %s' % lib)


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))

Exemplo n.º 15
0
from nibabel.tmpdirs import InTemporaryDirectory

from nipy import load_image, save_image
from nipy.core.api import rollimg

from nose.tools import assert_true, assert_false, assert_equal, assert_raises

from ..testing import funcfile
from numpy.testing import decorators, assert_almost_equal

from nipy.testing.decorators import make_label_dec

from nibabel.optpkg import optional_package

matplotlib, HAVE_MPL, _ = optional_package('matplotlib')
needs_mpl = decorators.skipif(not HAVE_MPL, "Test needs matplotlib")
script_test = make_label_dec('script_test')

from .scriptrunner import ScriptRunner

runner = ScriptRunner(debug_print_var='NIPY_DEBUG_PRINT')
run_command = runner.run_command


@needs_mpl
@script_test
def test_nipy_diagnose():
    # Test nipy diagnose script
    fimg = load_image(funcfile)
    ncomps = 12
    with InTemporaryDirectory() as tmpdir:
Exemplo n.º 16
0
 def skip_func(func):
     return skipif(True, msg)(func)
Exemplo n.º 17
0
        ret = function(*args, **kwargs)
        return ret


def requires_avbin():
    try:
        from pyglet.media.avbin import AVbinSource
        del AVbinSource
        _has_avbin = True
    except ImportError:
        _has_avbin = False
    return skipif(not _has_avbin, 'Requires AVbin')


_is_appveyor = (os.getenv('APPVEYOR', 'False').lower() == 'true')
requires_opengl21 = skipif(_is_appveyor, 'Appveyor OpenGL too old')


def requires_lib(lib):
    val = False
    try:
        importlib.import_module(lib)
    except Exception:
        val = True
    return skipif(val, 'Needs %s' % lib)


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))

Exemplo n.º 18
0
def if_datasource(ds, msg):
    try:
        ds.get_filename()
    except DataError:
        return skipif(True, msg)
    return lambda f: f
Exemplo n.º 19
0
import numpy.testing as nt
import warnings

from dipy.core.sphere import (Sphere, HemiSphere, unique_edges, unique_sets,
                              faces_from_sphere_vertices, HemiSphere,
                              disperse_charges, _get_forces,
                              unit_octahedron, unit_icosahedron)
from dipy.core.subdivide_octahedron import create_unit_sphere
from dipy.core.geometry import cart2sphere, sphere2cart, vector_norm

from numpy.testing.decorators import skipif

try:
    from scipy.spatial import Delaunay
except ImportError:
    needs_delaunay = skipif(True, "Need scipy.spatial.Delaunay")
else:
    needs_delaunay = skipif(False)

verts = unit_octahedron.vertices
edges = unit_octahedron.edges
oct_faces = unit_octahedron.faces
r, theta, phi = cart2sphere(*verts.T)

def test_sphere_construct_args():
    nt.assert_raises(ValueError, Sphere)
    nt.assert_raises(ValueError, Sphere, x=1, theta=1)
    nt.assert_raises(ValueError, Sphere, xyz=1, theta=1)
    nt.assert_raises(ValueError, Sphere, xyz=1, theta=1, phi=1)

Exemplo n.º 20
0
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import numpy as np
from collections import namedtuple as nt

from ..optpkg import optional_package
from ..viewers import OrthoSlicer3D

from numpy.testing.decorators import skipif
from numpy.testing import assert_array_equal, assert_equal

from nose.tools import assert_raises, assert_true

matplotlib, has_mpl = optional_package('matplotlib')[:2]
needs_mpl = skipif(not has_mpl, 'These tests need matplotlib')
if has_mpl:
    matplotlib.use('Agg')


@needs_mpl
def test_viewer():
    # Test viewer
    plt = optional_package('matplotlib.pyplot')[0]
    a = np.sin(np.linspace(0, np.pi, 20))
    b = np.sin(np.linspace(0, np.pi * 5, 30))
    data = (np.outer(a, b)[..., np.newaxis] * a)[:, :, :, np.newaxis]
    data = data * np.array([1., 2.])  # give it a # of volumes > 1
    v = OrthoSlicer3D(data)
    assert_array_equal(v.position, (0, 0, 0))
    assert_true('OrthoSlicer3D' in repr(v))
Exemplo n.º 21
0
def if_datasource(ds, msg):
    try:
        ds.get_filename()
    except DataError:
        return skipif(True, msg)
    return lambda f: f
Exemplo n.º 22
0
def runif_extra_has(test_str):
    """Decorator checks to see if NIPY_EXTRA_TESTS env var contains test_str"""
    return skipif(test_str not in EXTRA_SET,
                  "Skip {0} tests.".format(test_str))
Exemplo n.º 23
0
        old_level = set_log_level(verbose_level, True)
        # set it back if we get an exception
        try:
            ret = function(*args, **kwargs)
        except:
            set_log_level(old_level)
            raise
        set_log_level(old_level)
        return ret
    else:
        ret = function(*args, **kwargs)
        return ret


_is_appveyor = (os.getenv('APPVEYOR', 'False').lower() == 'true')
requires_pandas = skipif(has_pandas is False, 'Requires pandas')
requires_h5py = skipif(has_h5py is False, 'Requires h5py')
requires_joblib = skipif(has_joblib is False, 'Requires joblib')
requires_opengl21 = skipif(_is_appveyor, 'Appveyor OpenGL too old')


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))


def _hide_window(function):
    """Decorator to hide expyfun windows during testing"""
    import nose

    def dec(*args, **kwargs):
        orig_val = os.getenv('_EXPYFUN_WIN_INVISIBLE')
Exemplo n.º 24
0
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import numpy as np
from collections import namedtuple as nt

from ..optpkg import optional_package
from ..viewers import OrthoSlicer3D

from numpy.testing.decorators import skipif
from numpy.testing import assert_array_equal

from nose.tools import assert_raises, assert_true

matplotlib, has_mpl = optional_package('matplotlib')[:2]
needs_mpl = skipif(not has_mpl, 'These tests need matplotlib')
if has_mpl:
    matplotlib.use('Agg')

from ..gui import OrthoSlicer3D, ElectrodeGUI, GridGUI

@needs_mpl
def test_elec_gui():
    raise NotImplementedError()  # TODO

@needs_mpl
def test_grid_gui():
    raise NotImplementedError()  # TODO


@needs_mpl
Exemplo n.º 25
0
import nibabel as nib
from nibabel import AnalyzeImage, Spm2AnalyzeImage, Nifti1Pair, Nifti1Image
from nibabel.tmpdirs import InTemporaryDirectory

from nipy import load_image
from nipy.io.nifti_ref import NiftiError
from ..commands import parse_fname_axes, tsdiffana, diagnose
from ..timediff import time_slice_diffs_image

from numpy.testing import (assert_almost_equal, assert_array_equal, decorators)

from nibabel.optpkg import optional_package

matplotlib, HAVE_MPL, _ = optional_package('matplotlib')
needs_mpl = decorators.skipif(not HAVE_MPL, "Test needs matplotlib")

from nose import SkipTest
from nose.tools import (assert_true, assert_false, assert_raises,
                        assert_equal, assert_not_equal)

from nipy.testing import funcfile

def test_parse_fname_axes():
    # Test logic for setting time and slice axis defaults
    # We need real images for the tests because nipy will load them
    # For simplicity, we can create them
    shape = (4, 5, 6, 20)
    arr = np.arange(np.prod(shape), dtype=float).reshape(shape)
    zooms = (2., 3., 4., 2.1)
    with InTemporaryDirectory():
Exemplo n.º 26
0
    if verbose_level is not None:
        old_level = set_log_level(verbose_level, True)
        # set it back if we get an exception
        try:
            ret = function(*args, **kwargs)
        except:
            set_log_level(old_level)
            raise
        set_log_level(old_level)
        return ret
    else:
        ret = function(*args, **kwargs)
        return ret


requires_pandas = skipif(has_pandas is False, 'Requires pandas')
requires_h5py = skipif(has_h5py is False, 'Requires h5py')
requires_joblib = skipif(has_joblib is False, 'Requires joblib')


def _has_scipy_version(version):
    return (LooseVersion(sp.__version__) >= LooseVersion(version))


def _hide_window(function):
    """Decorator to hide expyfun windows during testing"""
    import nose

    def dec(*args, **kwargs):
        orig_val = os.getenv('_EXPYFUN_WIN_INVISIBLE')
        try:
Exemplo n.º 27
0
from os.path import join as pjoin

import numpy as np
import numpy.testing.decorators as dec

from scipy.io.netcdf import netcdf_file as netcdf

from nipy.io.imageformats import load, MincHeader, Nifti1Image

from nose.tools import assert_true, assert_equal, assert_false
from numpy.testing import assert_array_equal

try:
    import imagedata
except ImportError:
    decimg = dec.skipif(True, 'no imagedata package on python path')
else:
    decimg = lambda x : x
    

@decimg
def test_eg_img():
    mnc_fname = pjoin(imagedata.minc_path, 'avg152T1.mnc')
    mnc = MincHeader(netcdf(mnc_fname, 'r'))
    yield assert_equal, mnc.get_data_dtype().type, np.uint8
    yield assert_equal, mnc.get_data_shape(), (91, 109, 91)
    yield assert_equal, mnc.get_zooms(), (2.0, 2.0, 2.0)
    aff = np.array([[0, 0, 2.0, -90],
                    [0, 2.0, 0, -126],
                    [2.0, 0, 0, -72],
                    [0, 0, 0, 1]])