diff --git a/nipype/interfaces/cmtk/convert.py b/nipype/interfaces/cmtk/convert.py index d77eeed0af..61b8839802 100644 --- a/nipype/interfaces/cmtk/convert.py +++ b/nipype/interfaces/cmtk/convert.py @@ -7,14 +7,26 @@ """ -from nipype.interfaces.base import (BaseInterface, BaseInterfaceInputSpec, traits, - File, TraitedSpec, InputMultiPath, isdefined) -import networkx as nx -import cfflib as cf import os -from nipype.utils.filemanip import split_filename import datetime import string +import warnings +import networkx as nx + +from nipype.interfaces.base import (BaseInterface, BaseInterfaceInputSpec, traits, + File, TraitedSpec, InputMultiPath, isdefined) +from nipype.utils.filemanip import split_filename +from nipype.utils.misc import package_check + +have_cfflib = True +try: + package_check('cfflib') +except Exception, e: + have_cfflib = False + warnings.warn('cfflib not installed') +else: + import cfflib as cf + class CFFConverterInputSpec(BaseInterfaceInputSpec): graphml_networks = InputMultiPath(File(exists=True), desc='list of graphML networks') diff --git a/nipype/interfaces/nipy/__init__.py b/nipype/interfaces/nipy/__init__.py index dd700d6f12..040ef4efe6 100644 --- a/nipype/interfaces/nipy/__init__.py +++ b/nipype/interfaces/nipy/__init__.py @@ -1,2 +1,2 @@ from model import FitGLM, EstimateContrast -from preprocess import ComputeMask \ No newline at end of file +from preprocess import ComputeMask diff --git a/nipype/interfaces/nipy/model.py b/nipype/interfaces/nipy/model.py index 7db0235ed1..d32eb283a1 100644 --- a/nipype/interfaces/nipy/model.py +++ b/nipype/interfaces/nipy/model.py @@ -1,3 +1,4 @@ +import warnings import os import nibabel as nb @@ -5,9 +6,16 @@ import pylab from nipype.utils.misc import package_check -package_check('nipy') -import nipy.modalities.fmri.design_matrix as dm -import nipy.labs.glm as GLM + +have_nipy = True +try: + package_check('nipy') +except Exception, e: + have_nipy = False + warnings.warn('nipy not installed') +else: + import nipy.modalities.fmri.design_matrix as dm + import nipy.labs.glm as GLM from nipype.interfaces.base import (BaseInterface, TraitedSpec, traits, File, OutputMultiPath, BaseInterfaceInputSpec, @@ -16,10 +24,10 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): session_info = traits.List(minlen=1, maxlen=1, exists=True, desc='Session specific information generated by ``modelgen.SpecifyModel``, FitGLM\ does not support multiple runs uless they are concatenated (see SpecifyModel options)') - hrf_model = traits.Enum('Canonical', 'Canonical With Derivative', 'FIR', + hrf_model = traits.Enum('Canonical', 'Canonical With Derivative', 'FIR', desc="that specifies the hemodynamic reponse function it can be 'Canonical', 'Canonical With Derivative' or 'FIR'", usedefault=True) - drift_model = traits.Enum("Cosine", "Polynomial", "Blank", + drift_model = traits.Enum("Cosine", "Polynomial", "Blank", desc = "string that specifies the desired drift model, to be chosen among 'Polynomial', 'Cosine', 'Blank'", usedefault=True) TR = traits.Float(mandatory=True) @@ -29,7 +37,7 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): normalize_design_matrix = traits.Bool(False, desc="normalize (zscore) the regressors before fitting", usedefault=True) save_residuals = traits.Bool(False, usedefault=True) plot_design_matrix = traits.Bool(False, usedefault=True) - + class FitGLMOutputSpec(TraitedSpec): beta = File(exists=True) nvbeta = traits.Any() @@ -40,109 +48,109 @@ class FitGLMOutputSpec(TraitedSpec): reg_names = traits.List() residuals = traits.File() a = File(exists=True) - + class FitGLM(BaseInterface): ''' Fit GLM model based on the specified design. Supports only single or concatenated runs. ''' input_spec = FitGLMInputSpec output_spec = FitGLMOutputSpec - + def _run_interface(self, runtime): - + session_info = self.inputs.session_info - + functional_runs = self.inputs.session_info[0]['scans'] if isinstance(functional_runs, str): functional_runs = [functional_runs] - nii = nb.load(functional_runs[0]) + nii = nb.load(functional_runs[0]) data = nii.get_data() - + if isdefined(self.inputs.mask): mask = nb.load(self.inputs.mask).get_data() > 0 else: mask = np.ones(nii.shape[:3]) == 1 - + timeseries = data.copy()[mask,:] del data - + for functional_run in functional_runs[1:]: nii = nb.load(functional_run) data = nii.get_data() npdata = data.copy() - del data + del data timeseries = np.concatenate((timeseries,npdata[mask,:]), axis=1) del npdata - + nscans = timeseries.shape[1] - + if 'hpf' in session_info[0].keys(): hpf = session_info[0]['hpf'] drift_model=self.inputs.drift_model else: hpf=0 drift_model = "Blank" - + reg_names = [] for reg in session_info[0]['regress']: reg_names.append(reg['name']) - + reg_vals = np.zeros((nscans,len(reg_names))) for i in range(len(reg_names)): reg_vals[:,i] = np.array(session_info[0]['regress'][i]['val']).reshape(1,-1) - - + + frametimes= np.linspace(0, (nscans-1)*self.inputs.TR, nscans) - + conditions = [] onsets = [] duration = [] - + for i,cond in enumerate(session_info[0]['cond']): onsets += cond['onset'] conditions += [cond['name']]*len(cond['onset']) if len(cond['duration']) == 1: duration += cond['duration']*len(cond['onset']) - - + + paradigm = dm.BlockParadigm(con_id=conditions, onset=onsets, duration=duration) design_matrix, self._reg_names = dm.dmtx_light(frametimes, paradigm, drift_model=drift_model, hfcut=hpf, - hrf_model=self.inputs.hrf_model, + hrf_model=self.inputs.hrf_model, add_regs=reg_vals, add_reg_names=reg_names ) if self.inputs.normalize_design_matrix: for i in range(len(self._reg_names)-1): design_matrix[:,i] = (design_matrix[:,i]-design_matrix[:,i].mean())/design_matrix[:,i].std() - + if self.inputs.plot_design_matrix: pylab.pcolor(design_matrix) pylab.savefig("design_matrix.pdf") pylab.close() pylab.clf() - + glm = GLM.glm() glm.fit(timeseries.T, design_matrix, method=self.inputs.method, model=self.inputs.model) - - + + self._beta_file = os.path.abspath("beta.nii") beta = np.zeros(mask.shape + (glm.beta.shape[0],)) beta[mask,:] = glm.beta.T nb.save(nb.Nifti1Image(beta, nii.get_affine()), self._beta_file) - + self._s2_file = os.path.abspath("s2.nii") s2 = np.zeros(mask.shape) s2[mask] = glm.s2 nb.save(nb.Nifti1Image(s2, nii.get_affine()), self._s2_file) - + if self.inputs.save_residuals: explained = np.dot(design_matrix,glm.beta) residuals = np.zeros(mask.shape + (nscans,)) residuals[mask,:] = timeseries - explained.T self._residuals_file = os.path.abspath("residuals.nii") nb.save(nb.Nifti1Image(residuals, nii.get_affine()), self._residuals_file) - + self._nvbeta = glm.nvbeta self._dof = glm.dof self._constants = glm._constants @@ -154,9 +162,9 @@ def _run_interface(self, runtime): nb.save(nb.Nifti1Image(a, nii.get_affine()), self._a_file) self._model = glm.model self._method = glm.method - + return runtime - + def _list_outputs(self): outputs = self._outputs().get() outputs["beta"] = self._beta_file @@ -171,7 +179,7 @@ def _list_outputs(self): if self.inputs.save_residuals: outputs["residuals"] = self._residuals_file return outputs - + class EstimateContrastInputSpec(BaseInterfaceInputSpec): contrasts = traits.List( traits.Either(traits.Tuple(traits.Str, @@ -207,28 +215,28 @@ class EstimateContrastInputSpec(BaseInterfaceInputSpec): axis = traits.Any(mandatory=True) reg_names = traits.List(mandatory=True) mask = traits.File(exists=True) - + class EstimateContrastOutputSpec(TraitedSpec): stat_maps = OutputMultiPath(File(exists=True)) z_maps = OutputMultiPath(File(exists=True)) p_maps = OutputMultiPath(File(exists=True)) - + class EstimateContrast(BaseInterface): ''' Estimate contrast of a fitted model. ''' input_spec = EstimateContrastInputSpec output_spec = EstimateContrastOutputSpec - + def _run_interface(self, runtime): - + beta_nii = nb.load(self.inputs.beta) if isdefined(self.inputs.mask): mask = nb.load(self.inputs.mask).get_data() > 0 else: mask = np.ones(beta_nii.shape[:3]) == 1 - - + + glm = GLM.glm() nii = nb.load(self.inputs.beta) glm.beta = beta_nii.get_data().copy()[mask,:].T @@ -237,9 +245,9 @@ def _run_interface(self, runtime): glm.dof = self.inputs.dof glm._axis = self.inputs.axis glm._constants = self.inputs.constants - + reg_names = self.inputs.reg_names - + self._stat_maps = [] self._p_maps = [] self._z_maps = [] @@ -247,34 +255,34 @@ def _run_interface(self, runtime): name = contrast_def[0] type = contrast_def[1] contrast = np.zeros(len(reg_names)) - + for i, reg_name in enumerate(reg_names): if reg_name in contrast_def[2]: idx = contrast_def[2].index(reg_name) contrast[i] = contrast_def[3][idx] - + est_contrast = glm.contrast(contrast) - + stat_map = np.zeros(mask.shape) stat_map[mask] = est_contrast.stat().T stat_map_file = os.path.abspath(name + "_stat_map.nii") nb.save(nb.Nifti1Image(stat_map, nii.get_affine()), stat_map_file) self._stat_maps.append(stat_map_file) - + p_map = np.zeros(mask.shape) p_map[mask] = est_contrast.pvalue().T p_map_file = os.path.abspath(name + "_p_map.nii") nb.save(nb.Nifti1Image(p_map, nii.get_affine()), p_map_file) self._p_maps.append(p_map_file) - + z_map = np.zeros(mask.shape) z_map[mask] = est_contrast.zscore().T z_map_file = os.path.abspath(name + "_z_map.nii") nb.save(nb.Nifti1Image(z_map, nii.get_affine()), z_map_file) self._z_maps.append(z_map_file) - + return runtime - + def _list_outputs(self): outputs = self._outputs().get() outputs["stat_maps"] = self._stat_maps diff --git a/nipype/interfaces/nipy/preprocess.py b/nipype/interfaces/nipy/preprocess.py index 7af9e8a443..2842e825bd 100644 --- a/nipype/interfaces/nipy/preprocess.py +++ b/nipype/interfaces/nipy/preprocess.py @@ -1,15 +1,22 @@ import os +import warnings import nibabel as nb import numpy as np from nipype.utils.misc import package_check -package_check('nipy') -from nipy.labs.mask import compute_mask + +try: + package_check('nipy') +except Exception, e: + warnings.warn('nipy not installed') +else: + from nipy.labs.mask import compute_mask from nipype.interfaces.base import (TraitedSpec, BaseInterface, traits, BaseInterfaceInputSpec, isdefined, File) + class ComputeMaskInputSpec(BaseInterfaceInputSpec): mean_volume = File(exists=True, mandatory=True, desc="mean EPI image, used to compute the threshold for the mask") reference_volume = File(exists=True, desc="reference volume used to compute the mask. If none is give, the \ diff --git a/nipype/interfaces/nitime/analysis.py b/nipype/interfaces/nitime/analysis.py index 6ecf102aed..33241a0e5b 100644 --- a/nipype/interfaces/nitime/analysis.py +++ b/nipype/interfaces/nitime/analysis.py @@ -10,13 +10,12 @@ """ +import warnings import numpy as np import tempfile from nipype.utils.misc import package_check -package_check('nitime') package_check('matplotlib') - from nipype.interfaces.base import (TraitedSpec, File, InputMultiPath, OutputMultiPath, Undefined, traits, BaseInterface, isdefined, @@ -24,10 +23,18 @@ from nipype.utils.filemanip import fname_presuffix -import nitime.analysis as nta -from nitime.timeseries import TimeSeries -import nitime.viz as viz - +have_nitime = True +try: + package_check('nitime') +except Exception, e: + have_nitime = False + warnings.warn('nitime not installed') +else: + import nitime.analysis as nta + from nitime.timeseries import TimeSeries + import nitime.viz as viz + + class CoherenceAnalyzerInputSpec(BaseInterfaceInputSpec): #Input either csv file, or time-series object and use _xor_inputs to diff --git a/nipype/interfaces/nitime/tests/test_nitime.py b/nipype/interfaces/nitime/tests/test_nitime.py index 80eb12ac25..80158e691d 100644 --- a/nipype/interfaces/nitime/tests/test_nitime.py +++ b/nipype/interfaces/nitime/tests/test_nitime.py @@ -3,22 +3,23 @@ import tempfile import numpy as np +from matplotlib.mlab import csv2rec + +from nipype.utils.misc import package_check -from nipype.testing import (assert_equal, assert_not_equal, assert_raises) +from nipype.testing import (assert_equal, assert_raises, skipif) from nipype.testing import example_data -import nipype.interfaces.nitime as nitime +import nipype.interfaces.nitime as nitime -import nitime.analysis as nta -import nitime.timeseries as ts +no_nitime = not nitime.analysis.have_nitime -from matplotlib.mlab import csv2rec +@skipif(no_nitime) def test_read_csv(): """Test that reading the data from csv file gives you back a reasonable time-series object """ - CA = nitime.CoherenceAnalyzer() CA.inputs.TR = 1.89 # bogus value just to pass traits test CA.inputs.in_file = example_data('fmri_timeseries_nolabels.csv') @@ -29,8 +30,12 @@ def test_read_csv(): yield assert_equal, data[0][0],10125.9 yield assert_equal, roi_names[0],'WM' + +@skipif(no_nitime) def test_coherence_analysis(): """Test that the coherence analyzer works """ + import nitime.analysis as nta + import nitime.timeseries as ts #This is the nipype interface analysis: CA = nitime.CoherenceAnalyzer()