예제 #1
0
 def close(self):
     """Close the viewer figures
     """
     self._cleanup()
     plt, _, _ = optional_package('matplotlib.pyplot')
     for f in self._figs:
         plt.close(f)
예제 #2
0
def test_versions():
    fake_name = '_a_fake_package'
    fake_pkg = types.ModuleType(fake_name)
    assert_false('fake_pkg' in sys.modules)
    # Not inserted yet
    assert_bad(fake_name)
    try:
        sys.modules[fake_name] = fake_pkg
        # No __version__ yet
        assert_good(fake_name)  # With no version check
        assert_bad(fake_name, '1.0')
        # We can make an arbitrary callable to check version
        assert_good(fake_name, lambda pkg: True)
        # Now add a version
        fake_pkg.__version__ = '2.0'
        # We have fake_pkg > 1.0
        for min_ver in (None, '1.0', LooseVersion('1.0'), lambda pkg: True):
            assert_good(fake_name, min_ver)
        # We never have fake_pkg > 100.0
        for min_ver in ('100.0', LooseVersion('100.0'), lambda pkg: False):
            assert_bad(fake_name, min_ver)
        # Check error string for bad version
        pkg, _, _ = optional_package(fake_name, min_version='3.0')
        try:
            pkg.some_method
        except TripWireError as err:
            assert_equal(str(err),
                         'These functions need _a_fake_package version >= 3.0')
    finally:
        del sys.modules[fake_name]
예제 #3
0
def test_versions():
    fake_name = '_a_fake_package'
    fake_pkg = types.ModuleType(fake_name)
    assert 'fake_pkg' not in sys.modules
    # Not inserted yet
    assert_bad(fake_name)
    try:
        sys.modules[fake_name] = fake_pkg
        # No __version__ yet
        assert_good(fake_name)  # With no version check
        assert_bad(fake_name, '1.0')
        # We can make an arbitrary callable to check version
        assert_good(fake_name, lambda pkg: True)
        # Now add a version
        fake_pkg.__version__ = '2.0'
        # We have fake_pkg > 1.0
        for min_ver in (None, '1.0', LooseVersion('1.0'), lambda pkg: True):
            assert_good(fake_name, min_ver)
        # We never have fake_pkg > 100.0
        for min_ver in ('100.0', LooseVersion('100.0'), lambda pkg: False):
            assert_bad(fake_name, min_ver)
        # Check error string for bad version
        pkg, _, _ = optional_package(fake_name, min_version='3.0')
        try:
            pkg.some_method
        except TripWireError as err:
            assert str(
                err) == 'These functions need _a_fake_package version >= 3.0'
    finally:
        del sys.modules[fake_name]
예제 #4
0
def assert_bad(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert not have_pkg
    assert isinstance(pkg, TripWire)
    with pytest.raises(TripWireError):
        pkg.a_method
    with pytest.raises(SkipTest):
        setup()
예제 #5
0
"""
A scripting wrapper around 4D registration (SpaceTimeRealign)
"""
from __future__ import absolute_import

import os
import os.path as op
import numpy as np
import numpy.linalg as npl

import nibabel as nib
from nibabel.filename_parser import splitext_addext
import nibabel.eulerangles as euler
from nibabel.optpkg import optional_package

matplotlib, HAVE_MPL, _ = optional_package("matplotlib")

from .groupwise_registration import SpaceTimeRealign
import nipy.algorithms.slicetiming as st
from nipy.io.api import save_image

timefuncs = st.timefuncs.SLICETIME_FUNCTIONS

__all__ = ["space_time_realign", "aff2euler"]


def aff2euler(affine):
    """
    Compute Euler angles from 4 x 4 `affine`

    Parameters
예제 #6
0
    def __init__(self, data, affine=None, axes=None, title=None):
        """
        Parameters
        ----------
        data : array-like
            The data that will be displayed by the slicer. Should have 3+
            dimensions.
        affine : array-like or None, optional
            Affine transform for the data. This is used to determine
            how the data should be sliced for plotting into the sagittal,
            coronal, and axial view axes. If None, identity is assumed.
            The aspect ratio of the data are inferred from the affine
            transform.
        axes : tuple of mpl.Axes or None, optional
            3 or 4 axes instances for the 3 slices plus volumes,
            or None (default).
        title : str or None, optional
            The title to display. Can be None (default) to display no
            title.
        """
        # Use these late imports of matplotlib so that we have some hope that
        # the test functions are the first to set the matplotlib backend. The
        # tests set the backend to something that doesn't require a display.
        self._plt = plt = optional_package('matplotlib.pyplot')[0]
        mpl_patch = optional_package('matplotlib.patches')[0]
        self._title = title
        self._closed = False

        data = np.asanyarray(data)
        if data.ndim < 3:
            raise ValueError('data must have at least 3 dimensions')
        if np.iscomplexobj(data):
            raise TypeError("Complex data not supported")
        affine = np.array(affine, float) if affine is not None else np.eye(4)
        if affine.shape != (4, 4):
            raise ValueError('affine must be a 4x4 matrix')
        # determine our orientation
        self._affine = affine
        codes = axcodes2ornt(aff2axcodes(self._affine))
        self._order = np.argsort([c[0] for c in codes])
        self._flips = np.array([c[1] < 0 for c in codes])[self._order]
        self._flips = list(self._flips) + [False]  # add volume dim
        self._scalers = voxel_sizes(self._affine)
        self._inv_affine = np.linalg.inv(affine)
        # current volume info
        self._volume_dims = data.shape[3:]
        self._current_vol_data = data[:, :, :, 0] if data.ndim > 3 else data
        self._data = data
        self._clim = np.percentile(data, (1., 99.))
        del data

        if axes is None:  # make the axes
            # ^ +---------+   ^ +---------+
            # | |         |   | |         |
            #   |   Sag   |     |   Cor   |
            # S |    0    |   S |    1    |
            #   |         |     |         |
            #   |         |     |         |
            #   +---------+     +---------+
            #        A  -->     <--  R
            # ^ +---------+     +---------+
            # | |         |     |         |
            #   |  Axial  |     |   Vol   |
            # A |    2    |     |    3    |
            #   |         |     |         |
            #   |         |     |         |
            #   +---------+     +---------+
            #   <--  R          <--  t  -->

            fig, axes = plt.subplots(2, 2)
            fig.set_size_inches((8, 8), forward=True)
            self._axes = [axes[0, 0], axes[0, 1], axes[1, 0], axes[1, 1]]
            plt.tight_layout(pad=0.1)
            if self.n_volumes <= 1:
                fig.delaxes(self._axes[3])
                self._axes.pop(-1)
            if self._title is not None:
                fig.canvas.set_window_title(str(title))
        else:
            self._axes = [axes[0], axes[1], axes[2]]
            if len(axes) > 3:
                self._axes.append(axes[3])

        # Start midway through each axis, idx is current slice number
        self._ims, self._data_idx = list(), list()

        # set up axis crosshairs
        self._crosshairs = [None] * 3
        r = [self._scalers[self._order[2]] / self._scalers[self._order[1]],
             self._scalers[self._order[2]] / self._scalers[self._order[0]],
             self._scalers[self._order[1]] / self._scalers[self._order[0]]]
        self._sizes = [self._data.shape[order] for order in self._order]
        for ii, xax, yax, ratio, label in zip([0, 1, 2], [1, 0, 0], [2, 2, 1],
                                              r, ('SAIP', 'SLIR', 'ALPR')):
            ax = self._axes[ii]
            d = np.zeros((self._sizes[yax], self._sizes[xax]))
            im = self._axes[ii].imshow(
                d, vmin=self._clim[0], vmax=self._clim[1], aspect=1,
                cmap='gray', interpolation='nearest', origin='lower')
            self._ims.append(im)
            vert = ax.plot([0] * 2, [-0.5, self._sizes[yax] - 0.5],
                           color=(0, 1, 0), linestyle='-')[0]
            horiz = ax.plot([-0.5, self._sizes[xax] - 0.5], [0] * 2,
                            color=(0, 1, 0), linestyle='-')[0]
            self._crosshairs[ii] = dict(vert=vert, horiz=horiz)
            # add text labels (top, right, bottom, left)
            lims = [0, self._sizes[xax], 0, self._sizes[yax]]
            bump = 0.01
            poss = [[lims[1] / 2., lims[3]],
                    [(1 + bump) * lims[1], lims[3] / 2.],
                    [lims[1] / 2., 0],
                    [lims[0] - bump * lims[1], lims[3] / 2.]]
            anchors = [['center', 'bottom'], ['left', 'center'],
                       ['center', 'top'], ['right', 'center']]
            for pos, anchor, lab in zip(poss, anchors, label):
                ax.text(pos[0], pos[1], lab,
                        horizontalalignment=anchor[0],
                        verticalalignment=anchor[1])
            ax.axis(lims)
            ax.set_aspect(ratio)
            ax.patch.set_visible(False)
            ax.set_frame_on(False)
            ax.axes.get_yaxis().set_visible(False)
            ax.axes.get_xaxis().set_visible(False)
            self._data_idx.append(0)
        self._data_idx.append(-1)  # volume

        # Set up volumes axis
        if self.n_volumes > 1 and len(self._axes) > 3:
            ax = self._axes[3]
            try:
                ax.set_facecolor('k')
            except AttributeError:  # old mpl
                ax.set_axis_bgcolor('k')
            ax.set_title('Volumes')
            y = np.zeros(self.n_volumes + 1)
            x = np.arange(self.n_volumes + 1) - 0.5
            step = ax.step(x, y, where='post', color='y')[0]
            ax.set_xticks(np.unique(np.linspace(0, self.n_volumes - 1,
                                                5).astype(int)))
            ax.set_xlim(x[0], x[-1])
            yl = [self._data.min(), self._data.max()]
            yl = [l + s * np.diff(lims)[0] for l, s in zip(yl, [-1.01, 1.01])]
            patch = mpl_patch.Rectangle([-0.5, yl[0]], 1., np.diff(yl)[0],
                                        fill=True, facecolor=(0, 1, 0),
                                        edgecolor=(0, 1, 0), alpha=0.25)
            ax.add_patch(patch)
            ax.set_ylim(yl)
            self._volume_ax_objs = dict(step=step, patch=patch)

        self._figs = set([a.figure for a in self._axes])
        for fig in self._figs:
            fig.canvas.mpl_connect('scroll_event', self._on_scroll)
            fig.canvas.mpl_connect('motion_notify_event', self._on_mouse)
            fig.canvas.mpl_connect('button_press_event', self._on_mouse)
            fig.canvas.mpl_connect('key_press_event', self._on_keypress)
            fig.canvas.mpl_connect('close_event', self._cleanup)

        # actually set data meaningfully
        self._position = np.zeros(4)
        self._position[3] = 1.  # convenience for affine multiplication
        self._changing = False  # keep track of status to avoid loops
        self._links = []  # other viewers this one is linked to
        self._plt.draw()
        for fig in self._figs:
            fig.canvas.draw()
        self._set_volume_index(0, update_slices=False)
        self._set_position(0., 0., 0.)
        self._draw()
예제 #7
0
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
A scripting wrapper around 4D registration (SpaceTimeRealign)
"""
from __future__ import absolute_import

import os
import os.path as op
import numpy as np
import numpy.linalg as npl

import nibabel as nib
from nibabel.filename_parser import splitext_addext
import nibabel.eulerangles as euler
from nibabel.optpkg import optional_package
matplotlib, HAVE_MPL, _ = optional_package('matplotlib')

if HAVE_MPL:
    import matplotlib.pyplot as plt

from .groupwise_registration import SpaceTimeRealign
import nipy.algorithms.slicetiming as st
from nipy.io.api import save_image

timefuncs = st.timefuncs.SLICETIME_FUNCTIONS

__all__ = ["space_time_realign", "aff2euler"]


def aff2euler(affine):
    """
예제 #8
0
try:
    import numpy
except ImportError:
    raise ImportError(
        'Could not find numpy, which is required for building. \nTry running pip install numpy'
    )

try:
    from nibabel.optpkg import optional_package
except ImportError:
    raise ImportError(
        'Could not find nibabel, which is required for building. \nTry running pip install nibabel'
    )

cython_gsl, have_cython_gsl, _ = optional_package("cython_gsl")

if not have_cython_gsl:
    raise ImportError(
        'cannot find gsl package (required for hyp1f1), \n'
        'try pip install cythongsl and sudo apt-get install libgsl0-dev libgsl0ldbl'
    )

# Check for local version of dipy if it exists, since it would replace a locally built
# but not installed version.
dipy, have_dipy, _ = optional_package("dipy")

if have_dipy:
    print('Found local version of dipy in ' + dipy.__file__)
    if LooseVersion(dipy.__version__) < LooseVersion('0.11'):
        raise ValueError(
예제 #9
0
def assert_good(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert_true(have_pkg)
    assert_equal(sys.modules[pkg_name], pkg)
    assert_equal(setup(), None)
예제 #10
0
RMS resliced Phantom_EPI_3mm_tra_-30AP_10RL_20FH_SENSE_14_1.PAR   : 32.0602533689
RMS resliced Phantom_EPI_3mm_tra_15FH_SENSE_9_1.PAR               : 28.8953071672
RMS resliced Phantom_EPI_3mm_tra_15RL_SENSE_10_1.PAR              : 29.0793602478

The *_cor_SENSE* image has a higher RMS because the back of the phantom is out
of the field of view.
"""
import glob
import numpy as np
import numpy.linalg as npl

import nibabel as nib
from nibabel import parrec
from nibabel.affines import to_matvec
from nibabel.optpkg import optional_package
_, have_scipy, _ = optional_package('scipy')


def resample_img2img(img_to, img_from, order=1, out_class=nib.Nifti1Image):
    if not have_scipy:
        raise Exception('Scipy must be installed to run resample_img2img.')

    from scipy import ndimage as spnd
    vox2vox = npl.inv(img_from.affine).dot(img_to.affine)
    rzs, trans = to_matvec(vox2vox)
    data = spnd.affine_transform(img_from.get_data(),
                                 rzs,
                                 trans,
                                 img_to.shape,
                                 order=order)
    return out_class(data, img_to.affine)
예제 #11
0
def assert_good(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert have_pkg
    assert sys.modules[pkg_name] == pkg
    assert setup() is None
예제 #12
0
파일: scripting.py 프로젝트: Lx37/nipy
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:

"""
A scripting wrapper around 4D registration (SpaceTimeRealign)
"""

import os
import os.path as op
import numpy as np
import numpy.linalg as npl

import nibabel as nib
import nibabel.eulerangles as euler
from nibabel.optpkg import optional_package
matplotlib, HAVE_MPL, _ = optional_package('matplotlib')

if HAVE_MPL:
    import matplotlib.pyplot as plt

from .groupwise_registration import SpaceTimeRealign
import nipy.externals.argparse as argparse
import nipy.algorithms.slicetiming as st
timefuncs = st.timefuncs.SLICETIME_FUNCTIONS

__all__ = ["space_time_realign", "aff2euler"]


def aff2euler(affine):
    """
    Compute Euler angles from 4 x 4 `affine`
예제 #13
0
def assert_bad(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert_false(have_pkg)
    assert_true(isinstance(pkg, TripWire))
    assert_raises(TripWireError, getattr, pkg, 'a_method')
    assert_raises(SkipTest, setup)
예제 #14
0
from os.path import join
from os import path
from itertools import chain

from nibabel.optpkg import optional_package
graphviz, has_graphviz, _ = optional_package("graphviz")

import os
import numpy as np
import pytest

from bids.modeling import BIDSStatsModelsGraph
from bids.modeling.statsmodels import ContrastInfo
from bids.layout import BIDSLayout
from bids.tests import get_test_data_path
from bids.variables import BIDSVariableCollection


@pytest.fixture
def graph():
    layout_path = join(get_test_data_path(), "ds005")
    layout = BIDSLayout(layout_path)
    json_file = join(layout_path, "models", "ds-005_type-test_model.json")
    graph = BIDSStatsModelsGraph(layout, json_file)
    graph.load_collections(scan_length=480, subject=["01", "02"])
    return graph


@pytest.mark.skipif(not has_graphviz, reason="Test requires graphviz")
def test_write_graph(graph, tmp_path):
    from graphviz import Digraph
예제 #15
0
def assert_good(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert_true(have_pkg)
    assert_equal(sys.modules[pkg_name], pkg)
    assert_equal(setup(), None)
예제 #16
0
import nibabel as nib
from nibabel.analyze import AnalyzeImage
from nibabel.nifti1 import Nifti1Image
from nibabel.nifti2 import Nifti2Image

from nibabel import imageclasses
from nibabel.imageclasses import spatial_axes_first, class_map, ext_map

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

from nibabel.testing import clear_and_catch_warnings


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

have_h5py = optional_package('h5py')[1]

MINC_3DS = ('minc1_1_scale.mnc',)
MINC_4DS = ('minc1_4d.mnc',)
if have_h5py:
    MINC_3DS = MINC_3DS + ('minc2_1_scale.mnc',)
    MINC_4DS = MINC_4DS + ('minc2_4d.mnc',)


def test_spatial_axes_first():
    # Function tests is spatial axes are first three axes in image
    # Always True for Nifti and friends
    affine = np.eye(4)
    for shape in ((2, 3), (4, 3, 2), (5, 4, 1, 2), (2, 3, 5, 2, 1)):
        for img_class in (AnalyzeImage, Nifti1Image, Nifti2Image):
            data = np.zeros(shape)
예제 #17
0
    def __init__(self, data, affine=None, axes=None, cmap='gray',
                 pcnt_range=(1., 99.), figsize=(8, 8), title=None):
        """
        Parameters
        ----------
        data : ndarray
            The data that will be displayed by the slicer. Should have 3+
            dimensions.
        affine : array-like | None
            Affine transform for the data. This is used to determine
            how the data should be sliced for plotting into the saggital,
            coronal, and axial view axes. If None, identity is assumed.
            The aspect ratio of the data are inferred from the affine
            transform.
        axes : tuple of mpl.Axes | None, optional
            3 or 4 axes instances for the 3 slices plus volumes,
            or None (default).
        cmap : str | instance of cmap, optional
            String or cmap instance specifying colormap.
        pcnt_range : array-like, optional
            Percentile range over which to scale image for display.
        figsize : tuple
            Figure size (in inches) to use if axes are None.
        """
        # Nest imports so that matplotlib.use() has the appropriate
        # effect in testing
        plt, _, _ = optional_package('matplotlib.pyplot')
        mpl_img, _, _ = optional_package('matplotlib.image')
        mpl_patch, _, _ = optional_package('matplotlib.patches')
        self._title = title
        self._closed = False

        data = np.asanyarray(data)
        if data.ndim < 3:
            raise ValueError('data must have at least 3 dimensions')
        affine = np.array(affine, float) if affine is not None else np.eye(4)
        if affine.ndim != 2 or affine.shape != (4, 4):
            raise ValueError('affine must be a 4x4 matrix')
        # determine our orientation
        self._affine = affine.copy()
        codes = axcodes2ornt(aff2axcodes(self._affine))
        self._order = np.argsort([c[0] for c in codes])
        self._flips = np.array([c[1] < 0 for c in codes])[self._order]
        self._flips = list(self._flips) + [False]  # add volume dim
        self._scalers = np.abs(self._affine).max(axis=0)[:3]
        self._inv_affine = np.linalg.inv(affine)
        # current volume info
        self._volume_dims = data.shape[3:]
        self._current_vol_data = data[:, :, :, 0] if data.ndim > 3 else data
        self._data = data
        vmin, vmax = np.percentile(data, pcnt_range)
        del data

        if axes is None:  # make the axes
            # ^ +---------+   ^ +---------+
            # | |         |   | |         |
            #   |   Sag   |     |   Cor   |
            # S |    0    |   S |    1    |
            #   |         |     |         |
            #   |         |     |         |
            #   +---------+     +---------+
            #        A  -->     <--  R
            # ^ +---------+     +---------+
            # | |         |     |         |
            #   |  Axial  |     |   Vol   |
            # A |    2    |     |    3    |
            #   |         |     |         |
            #   |         |     |         |
            #   +---------+     +---------+
            #   <--  R          <--  t  -->

            fig, axes = plt.subplots(2, 2)
            fig.set_size_inches(figsize, forward=True)
            self._axes = [axes[0, 0], axes[0, 1], axes[1, 0], axes[1, 1]]
            plt.tight_layout(pad=0.1)
            if self.n_volumes <= 1:
                fig.delaxes(self._axes[3])
                self._axes.pop(-1)
            if self._title is not None:
                fig.canvas.set_window_title(str(title))
        else:
            self._axes = [axes[0], axes[1], axes[2]]
            if len(axes) > 3:
                self._axes.append(axes[3])

        # Start midway through each axis, idx is current slice number
        self._ims, self._data_idx = list(), list()

        # set up axis crosshairs
        self._crosshairs = [None] * 3
        r = [self._scalers[self._order[2]] / self._scalers[self._order[1]],
             self._scalers[self._order[2]] / self._scalers[self._order[0]],
             self._scalers[self._order[1]] / self._scalers[self._order[0]]]
        self._sizes = [self._data.shape[o] for o in self._order]
        for ii, xax, yax, ratio, label in zip([0, 1, 2], [1, 0, 0], [2, 2, 1],
                                              r, ('SAIP', 'SLIR', 'ALPR')):
            ax = self._axes[ii]
            d = np.zeros((self._sizes[yax], self._sizes[xax]))
            im = self._axes[ii].imshow(d, vmin=vmin, vmax=vmax, aspect=1,
                                       cmap=cmap, interpolation='nearest',
                                       origin='lower')
            self._ims.append(im)
            vert = ax.plot([0] * 2, [-0.5, self._sizes[yax] - 0.5],
                           color=(0, 1, 0), linestyle='-')[0]
            horiz = ax.plot([-0.5, self._sizes[xax] - 0.5], [0] * 2,
                            color=(0, 1, 0), linestyle='-')[0]
            self._crosshairs[ii] = dict(vert=vert, horiz=horiz)
            # add text labels (top, right, bottom, left)
            lims = [0, self._sizes[xax], 0, self._sizes[yax]]
            bump = 0.01
            poss = [[lims[1] / 2., lims[3]],
                    [(1 + bump) * lims[1], lims[3] / 2.],
                    [lims[1] / 2., 0],
                    [lims[0] - bump * lims[1], lims[3] / 2.]]
            anchors = [['center', 'bottom'], ['left', 'center'],
                       ['center', 'top'], ['right', 'center']]
            for pos, anchor, lab in zip(poss, anchors, label):
                ax.text(pos[0], pos[1], lab,
                        horizontalalignment=anchor[0],
                        verticalalignment=anchor[1])
            ax.axis(lims)
            ax.set_aspect(ratio)
            ax.patch.set_visible(False)
            ax.set_frame_on(False)
            ax.axes.get_yaxis().set_visible(False)
            ax.axes.get_xaxis().set_visible(False)
            self._data_idx.append(0)
        self._data_idx.append(-1)  # volume

        # Set up volumes axis
        if self.n_volumes > 1 and len(self._axes) > 3:
            ax = self._axes[3]
            ax.set_axis_bgcolor('k')
            ax.set_title('Volumes')
            y = np.zeros(self.n_volumes + 1)
            x = np.arange(self.n_volumes + 1) - 0.5
            step = ax.step(x, y, where='post', color='y')[0]
            ax.set_xticks(np.unique(np.linspace(0, self.n_volumes - 1,
                                                5).astype(int)))
            ax.set_xlim(x[0], x[-1])
            yl = [self._data.min(), self._data.max()]
            yl = [l + s * np.diff(lims)[0] for l, s in zip(yl, [-1.01, 1.01])]
            patch = mpl_patch.Rectangle([-0.5, yl[0]], 1., np.diff(yl)[0],
                                        fill=True, facecolor=(0, 1, 0),
                                        edgecolor=(0, 1, 0), alpha=0.25)
            ax.add_patch(patch)
            ax.set_ylim(yl)
            self._volume_ax_objs = dict(step=step, patch=patch)

        self._figs = set([a.figure for a in self._axes])
        for fig in self._figs:
            fig.canvas.mpl_connect('scroll_event', self._on_scroll)
            fig.canvas.mpl_connect('motion_notify_event', self._on_mouse)
            fig.canvas.mpl_connect('button_press_event', self._on_mouse)
            fig.canvas.mpl_connect('key_press_event', self._on_keypress)
            fig.canvas.mpl_connect('close_event', self._cleanup)

        # actually set data meaningfully
        self._position = np.zeros(4)
        self._position[3] = 1.  # convenience for affine multn
        self._changing = False  # keep track of status to avoid loops
        self._links = []  # other viewers this one is linked to
        plt.draw()
        for fig in self._figs:
            fig.canvas.draw()
        self._set_volume_index(0, update_slices=False)
        self._set_position(0., 0., 0.)
        self._draw()
예제 #18
0
#   See COPYING file distributed along with the NiBabel package for the
#   copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
""" Test we can correctly import example MINC2_PATH files
"""
from __future__ import print_function, absolute_import

import os
from os.path import join as pjoin

import numpy as np

from nibabel.optpkg import optional_package

h5py, have_h5py, setup_module = optional_package('h5py')

from .nibabel_data import get_nibabel_data, needs_nibabel_data
from .. import load as top_load, Nifti1Image

from nose.tools import assert_equal
from numpy.testing import (assert_array_equal, assert_almost_equal)

MINC2_PATH = pjoin(get_nibabel_data(), 'nitest-minc2')


def _make_affine(coses, zooms, starts):
    R = np.column_stack(coses)
    Z = np.diag(zooms)
    affine = np.eye(4)
    affine[:3, :3] = np.dot(R, Z)
예제 #19
0
#   See COPYING file distributed along with the NiBabel package for the
#   copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
""" Test we can correctly import example MINC2_PATH files
"""
from __future__ import print_function, absolute_import

import os
from os.path import join as pjoin

import numpy as np

from nibabel.optpkg import optional_package

h5py, have_h5py, setup_module = optional_package('h5py')

from .nibabel_data import get_nibabel_data, needs_nibabel_data
from .. import load as top_load, Nifti1Image

from nose.tools import assert_equal
from numpy.testing import (assert_array_equal, assert_almost_equal)

MINC2_PATH = pjoin(get_nibabel_data(), 'nitest-minc2')


def _make_affine(coses, zooms, starts):
    R = np.column_stack(coses)
    Z = np.diag(zooms)
    affine = np.eye(4)
    affine[:3, :3] = np.dot(R, Z)
예제 #20
0
#
#   See COPYING file distributed along with the NiBabel package for the
#   copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
""" Testing processing module
"""
from __future__ import division, print_function

from os.path import dirname, join as pjoin

import numpy as np
import numpy.linalg as npl

from nibabel.optpkg import optional_package
spnd, have_scipy, _ = optional_package('scipy.ndimage')

import nibabel as nib
from nibabel.processing import (sigma2fwhm, fwhm2sigma, adapt_affine,
                                resample_from_to, resample_to_output, smooth_image)
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,
                             voxel_sizes)
from nibabel.eulerangles import euler2mat

from numpy.testing import (assert_almost_equal,
                           assert_array_equal)
from ..testing import skipif
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from nibabel.optpkg import optional_package
import pytest

_, have_rdflib5, _ = optional_package("rdflib", min_version="5.0.0")

from nipype.utils.provenance import ProvStore, safe_encode

needs_rdflib5 = pytest.mark.skipif(
    not have_rdflib5, reason="Test requires rdflib 5.0.0 or higher")


@needs_rdflib5
@pytest.mark.timeout(60)
def test_provenance(tmpdir):
    from nipype.interfaces.base import CommandLine

    tmpdir.chdir()
    ps = ProvStore()
    results = CommandLine("echo hello").run()
    ps.add_results(results)
    provn = ps.g.get_provn()
    assert "echo hello" in provn


@needs_rdflib5
@pytest.mark.timeout(60)
def test_provenance_exists(tmpdir):
예제 #22
0
#
#   See COPYING file distributed along with the NiBabel package for the
#   copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import unittest

import pytest

import nibabel as nib
from nibabel.testing import test_data
from nibabel.cmdline.conform import main
from nibabel.optpkg import optional_package

_, have_scipy, _ = optional_package('scipy.ndimage')
needs_scipy = unittest.skipUnless(have_scipy, 'These tests need scipy')


@needs_scipy
def test_default(tmpdir):
    infile = test_data(fname="anatomical.nii")
    outfile = tmpdir / "output.nii.gz"
    main([str(infile), str(outfile)])
    assert outfile.isfile()
    c = nib.load(outfile)
    assert c.shape == (256, 256, 256)
    assert c.header.get_zooms() == (1, 1, 1)
    assert nib.orientations.aff2axcodes(c.affine) == ('R', 'A', 'S')

    with pytest.raises(FileExistsError):
예제 #23
0
RMS resliced Phantom_EPI_3mm_tra_-30AP_10RL_20FH_SENSE_14_1.PAR   : 32.0602533689
RMS resliced Phantom_EPI_3mm_tra_15FH_SENSE_9_1.PAR               : 28.8953071672
RMS resliced Phantom_EPI_3mm_tra_15RL_SENSE_10_1.PAR              : 29.0793602478

The *_cor_SENSE* image has a higher RMS because the back of the phantom is out
of the field of view.
"""
import glob
import numpy as np
import numpy.linalg as npl

import nibabel as nib
from nibabel import parrec
from nibabel.affines import to_matvec
from nibabel.optpkg import optional_package
_, have_scipy, _ = optional_package('scipy')


def resample_img2img(img_to, img_from, order=1, out_class=nib.Nifti1Image):
    if not have_scipy:
        raise Exception('Scipy must be installed to run resample_img2img.')

    from scipy import ndimage as spnd
    vox2vox = npl.inv(img_from.affine).dot(img_to.affine)
    rzs, trans = to_matvec(vox2vox)
    data = spnd.affine_transform(img_from.get_data(),
                                 rzs,
                                 trans,
                                 img_to.shape,
                                 order=order)
    return out_class(data, img_to.affine)
예제 #24
0
def assert_bad(pkg_name, min_version=None):
    pkg, have_pkg, setup = optional_package(pkg_name, min_version=min_version)
    assert_false(have_pkg)
    assert_true(isinstance(pkg, TripWire))
    assert_raises(TripWireError, getattr, pkg, 'a_method')
    assert_raises(SkipTest, setup)
예제 #25
0
 def show(self):
     """Show the slicer in blocking mode; convenience for ``plt.show()``
     """
     plt, _, _ = optional_package('matplotlib.pyplot')
     plt.show()
예제 #26
0
def _zstd_open(filename, mode="r", *, level_or_option=None, zstd_dict=None):
    pyzstd = optional_package("pyzstd")[0]
    return pyzstd.ZstdFile(filename, mode,
                           level_or_option=level_or_option, zstd_dict=zstd_dict)
예제 #27
0
import nibabel as nib
from nibabel.analyze import AnalyzeImage
from nibabel.nifti1 import Nifti1Image
from nibabel.nifti2 import Nifti2Image

from nibabel import imageclasses
from nibabel.imageclasses import spatial_axes_first, class_map, ext_map

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

from nibabel.testing import clear_and_catch_warnings

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

have_h5py = optional_package('h5py')[1]

MINC_3DS = ('minc1_1_scale.mnc', )
MINC_4DS = ('minc1_4d.mnc', )
if have_h5py:
    MINC_3DS = MINC_3DS + ('minc2_1_scale.mnc', )
    MINC_4DS = MINC_4DS + ('minc2_4d.mnc', )


def test_spatial_axes_first():
    # Function tests is spatial axes are first three axes in image
    # Always True for Nifti and friends
    affine = np.eye(4)
    for shape in ((2, 3), (4, 3, 2), (5, 4, 1, 2), (2, 3, 5, 2, 1)):
        for img_class in (AnalyzeImage, Nifti1Image, Nifti2Image):
            data = np.zeros(shape)