def test_required_package_installation(): for package_specs in REQUIRED_MODULE_METADATA: package = package_specs[0] min_version = package_specs[1]['min_version'] imported_package = __import__(package) installed_version = imported_package.__version__ assert _compare_version(installed_version, '>=', min_version) print(package, 'min:', min_version, 'installed:', installed_version)
def test_deprecation_warning_compute_multi_gray_matter_mask(): imgs = [ Nifti1Image(np.ones((9, 9, 9)), np.eye(4)), Nifti1Image(np.ones((9, 9, 9)), np.eye(4)) ] if _compare_version(sklearn.__version__, '<', '0.22'): with pytest.deprecated_call(): masking.compute_multi_gray_matter_mask(imgs) else: with pytest.warns(FutureWarning, match="renamed to 'compute_multi_brain_mask'"): masking.compute_multi_gray_matter_mask(imgs)
def pytest_collection_modifyitems(items): # numpy changed the str/repr formatting of numpy arrays in 1.14. # We want to run doctests only for numpy >= 1.14.Adapted from scikit-learn if _compare_version(np.__version__, '<', '1.14'): reason = 'doctests are only run for numpy >= 1.14' skip_doctests = True else: skip_doctests = False if skip_doctests: skip_marker = pytest.mark.skip(reason=reason) for item in items: if isinstance(item, DoctestItem): item.add_marker(skip_marker)
def plot_brain_schematics(ax, direction, **kwargs): """Creates matplotlib patches from a json custom format and plots them on a matplotlib Axes. Parameters ---------- ax : A MPL axes instance The axes in which the plots will be drawn. direction : {'x', 'y', 'z', 'l', 'r'} The directions of the view. **kwargs : Passed to the matplotlib patches constructor. Returns ------- object_bounds : (xmin, xmax, ymin, ymax) tuple Useful for the caller to be able to set axes limits. """ if _compare_version(matplotlib.__version__, '>=', "2.0"): get_axis_bg_color = ax.get_facecolor() else: get_axis_bg_color = ax.get_axis_bgcolor() black_bg = colors.colorConverter.to_rgba(get_axis_bg_color) \ == colors.colorConverter.to_rgba('k') json_filename, transform = _get_json_and_transform(direction) with open(json_filename) as json_file: json_content = json.loads(json_file.read()) mpl_patches = _get_mpl_patches(json_content, transform=transform + ax.transData, invert_color=black_bg, **kwargs) for mpl_patch in mpl_patches: ax.add_patch(mpl_patch) object_bounds = _get_object_bounds(json_content, transform) return object_bounds
# For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. # Documents to append as an appendix to all manuals. #latex_appendices = [] latex_elements = { 'classoptions': ',oneside', 'babel': '\\usepackage[english]{babel}', # Get completely rid of index 'printindex': '', } if _compare_version(sphinx.__version__, '<', '1.5'): latex_preamble = r""" \usepackage{amsmath}\usepackage{amsfonts}\usepackage{bm}\usepackage{morefloats} \let\oldfootnote\footnote \def\footnote#1{\oldfootnote{\small #1}} """ else: latex_elements['preamble'] = r""" \usepackage{amsmath}\usepackage{amsfonts}\usepackage{bm}\usepackage{morefloats} \let\oldfootnote\footnote \def\footnote#1{\oldfootnote{\small #1}} """ # If false, no module index is generated. if _compare_version(sphinx.__version__, '<', '1.5'): latex_use_modindex = False
def _safe_cache(memory, func, **kwargs): """A wrapper for mem.cache that flushes the cache if the version number of nibabel has changed. """ ''' Workaround for https://github.com/scikit-learn-contrib/imbalanced-learn/issues/482 joblib throws a spurious warning with newer scikit-learn. This code uses the recommended method first and the deprecated one if that fails, ensuring th warning is not generated in any case. ''' try: location = os.path.join(memory.location, 'joblib') except AttributeError: location = memory.location except TypeError: location = None if location is None or location in __CACHE_CHECKED: return memory.cache(func, **kwargs) version_file = os.path.join(location, 'module_versions.json') versions = dict() if os.path.exists(version_file): with open(version_file, 'r') as _version_file: versions = json.load(_version_file) modules = (nibabel, ) # Keep only the major + minor version numbers my_versions = dict((m.__name__, m.__version__) for m in modules) commons = set(versions.keys()).intersection(set(my_versions.keys())) collisions = [ m for m in commons if not _compare_version(versions[m], '==', my_versions[m]) ] # Flush cache if version collision if len(collisions) > 0: if nilearn.CHECK_CACHE_VERSION: warnings.warn("Incompatible cache in %s: " "different version of nibabel. Deleting " "the cache. Put nilearn.CHECK_CACHE_VERSION " "to false to avoid this behavior." % location) try: tmp_dir = (os.path.split(location)[:-1] + ('old_%i' % os.getpid(), )) tmp_dir = os.path.join(*tmp_dir) # We use rename + unlink to be more robust to race # conditions os.rename(location, tmp_dir) shutil.rmtree(tmp_dir) except OSError: # Another process could have removed this dir pass try: os.makedirs(location) except OSError: # File exists? pass else: warnings.warn("Incompatible cache in %s: " "old version of nibabel." % location) # Write json files if configuration is different if versions != my_versions: with open(version_file, 'w') as _version_file: json.dump(my_versions, _version_file) __CACHE_CHECKED[location] = True return memory.cache(func, **kwargs)
def test_compare_version(version_a, operator, version_b): assert _compare_version(version_a, operator, version_b)
def test_compare_version_error(): with pytest.raises(ValueError, match=("'_compare_version' received an " "unexpected operator <>.")): _compare_version('0.1.0', '<>', '1.1.0')
def test_butterworth(): rng = np.random.RandomState(42) n_features = 20000 n_samples = 100 sampling = 100 low_pass = 30 high_pass = 10 # Compare output for different options. # single timeseries data = rng.standard_normal(size=n_samples) data_original = data.copy() ''' May be only on py3.5: Bug in scipy 1.1.0 generates an unavoidable FutureWarning. (More info: https://github.com/scipy/scipy/issues/9086) The number of warnings generated is overwhelming TravisCI's log limit, causing it to fail tests. This hack prevents that and will be removed in future. ''' buggy_scipy = (_compare_version(scipy.__version__, '<', '1.2') and _compare_version(scipy.__version__, '>', '1.0')) if buggy_scipy: warnings.simplefilter('ignore') ''' END HACK ''' out_single = nisignal.butterworth(data, sampling, low_pass=low_pass, high_pass=high_pass, copy=True) np.testing.assert_almost_equal(data, data_original) nisignal.butterworth(data, sampling, low_pass=low_pass, high_pass=high_pass, copy=False) np.testing.assert_almost_equal(out_single, data) np.testing.assert_(id(out_single) != id(data)) # multiple timeseries data = rng.standard_normal(size=(n_samples, n_features)) data[:, 0] = data_original # set first timeseries to previous data data_original = data.copy() out1 = nisignal.butterworth(data, sampling, low_pass=low_pass, high_pass=high_pass, copy=True) np.testing.assert_almost_equal(data, data_original) np.testing.assert_(id(out1) != id(data_original)) # check that multiple- and single-timeseries filtering do the same thing. np.testing.assert_almost_equal(out1[:, 0], out_single) nisignal.butterworth(data, sampling, low_pass=low_pass, high_pass=high_pass, copy=False) np.testing.assert_almost_equal(out1, data) # Test nyquist frequency clipping, issue #482 out1 = nisignal.butterworth(data, sampling, low_pass=50., copy=True) out2 = nisignal.butterworth( data, sampling, low_pass=80., # Greater than nyq frequency copy=True) np.testing.assert_almost_equal(out1, out2) np.testing.assert_(id(out1) != id(out2))