Skip to content

Commit 1eeabd3

Browse files
authored
Merge pull request #2809 from effigies/maint/lazy_imports
MAINT: Delayed imports to reduce import time
2 parents 9f0ca09 + 5c4e266 commit 1eeabd3

File tree

19 files changed

+107
-103
lines changed

19 files changed

+107
-103
lines changed

nipype/algorithms/confounds.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import nibabel as nb
1515
import numpy as np
1616
from numpy.polynomial import Legendre
17-
from scipy import linalg
1817

1918
from .. import config, logging
2019
from ..external.due import BibTeX
@@ -1186,7 +1185,7 @@ def compute_noise_components(imgseries, mask_images, num_components,
11861185

11871186
# "The covariance matrix C = MMT was constructed and decomposed into its
11881187
# principal components using a singular value decomposition."
1189-
u, _, _ = linalg.svd(M, full_matrices=False)
1188+
u, _, _ = np.linalg.svd(M, full_matrices=False)
11901189
if components is None:
11911190
components = u[:, :num_components]
11921191
else:

nipype/algorithms/icc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
import os
66
import numpy as np
77
from numpy import ones, kron, mean, eye, hstack, dot, tile
8+
from numpy.linalg import pinv
89
import nibabel as nb
9-
from scipy.linalg import pinv
1010
from ..interfaces.base import BaseInterfaceInputSpec, TraitedSpec, \
1111
BaseInterface, traits, File
1212
from ..utils import NUMPY_MMAP

nipype/algorithms/metrics.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@
1414

1515
import nibabel as nb
1616
import numpy as np
17-
from scipy.ndimage.morphology import binary_erosion
18-
from scipy.spatial.distance import cdist, euclidean, dice, jaccard
19-
from scipy.ndimage.measurements import center_of_mass, label
2017

2118
from .. import config, logging
2219

@@ -74,6 +71,7 @@ class Distance(BaseInterface):
7471
_hist_filename = "hist.pdf"
7572

7673
def _find_border(self, data):
74+
from scipy.ndimage.morphology import binary_erosion
7775
eroded = binary_erosion(data)
7876
border = np.logical_and(data, np.logical_not(eroded))
7977
return border
@@ -87,6 +85,7 @@ def _get_coordinates(self, data, affine):
8785
return coordinates[:3, :]
8886

8987
def _eucl_min(self, nii1, nii2):
88+
from scipy.spatial.distance import cdist, euclidean
9089
origdata1 = nii1.get_data().astype(np.bool)
9190
border1 = self._find_border(origdata1)
9291

@@ -105,6 +104,8 @@ def _eucl_min(self, nii1, nii2):
105104
set1_coordinates.T[point1, :], set2_coordinates.T[point2, :])
106105

107106
def _eucl_cog(self, nii1, nii2):
107+
from scipy.spatial.distance import cdist
108+
from scipy.ndimage.measurements import center_of_mass, label
108109
origdata1 = np.logical_and(nii1.get_data() != 0,
109110
np.logical_not(np.isnan(nii1.get_data())))
110111
cog_t = np.array(center_of_mass(origdata1.copy())).reshape(-1, 1)
@@ -128,6 +129,7 @@ def _eucl_cog(self, nii1, nii2):
128129
return np.mean(dist_matrix)
129130

130131
def _eucl_mean(self, nii1, nii2, weighted=False):
132+
from scipy.spatial.distance import cdist
131133
origdata1 = nii1.get_data().astype(np.bool)
132134
border1 = self._find_border(origdata1)
133135

@@ -154,6 +156,7 @@ def _eucl_mean(self, nii1, nii2, weighted=False):
154156
return np.mean(min_dist_matrix)
155157

156158
def _eucl_max(self, nii1, nii2):
159+
from scipy.spatial.distance import cdist
157160
origdata1 = nii1.get_data()
158161
origdata1 = np.logical_not(
159162
np.logical_or(origdata1 == 0, np.isnan(origdata1)))
@@ -287,6 +290,7 @@ class Overlap(BaseInterface):
287290
output_spec = OverlapOutputSpec
288291

289292
def _bool_vec_dissimilarity(self, booldata1, booldata2, method):
293+
from scipy.spatial.distance import dice, jaccard
290294
methods = {'dice': dice, 'jaccard': jaccard}
291295
if not (np.any(booldata1) or np.any(booldata2)):
292296
return 0

nipype/algorithms/misc.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@
1515
import nibabel as nb
1616
import numpy as np
1717
from math import floor, ceil
18-
from scipy.ndimage.morphology import grey_dilation
19-
import scipy.io as sio
2018
import itertools
21-
import scipy.stats as stats
2219
import warnings
2320

2421
from .. import logging
@@ -103,6 +100,7 @@ def _get_brodmann_area(self):
103100
newdata[:int(ceil(float(origdata.shape[0]) / 2)), :, :] = 0
104101

105102
if self.inputs.dilation_size != 0:
103+
from scipy.ndimage.morphology import grey_dilation
106104
newdata = grey_dilation(newdata,
107105
(2 * self.inputs.dilation_size + 1,
108106
2 * self.inputs.dilation_size + 1,
@@ -356,6 +354,7 @@ class Matlab2CSV(BaseInterface):
356354
output_spec = Matlab2CSVOutputSpec
357355

358356
def _run_interface(self, runtime):
357+
import scipy.io as sio
359358
in_dict = sio.loadmat(op.abspath(self.inputs.in_file))
360359

361360
# Check if the file has multiple variables in it. If it does, loop
@@ -393,6 +392,7 @@ def _run_interface(self, runtime):
393392
return runtime
394393

395394
def _list_outputs(self):
395+
import scipy.io as sio
396396
outputs = self.output_spec().get()
397397
in_dict = sio.loadmat(op.abspath(self.inputs.in_file))
398398
saved_variables = list()
@@ -909,6 +909,7 @@ def calc_moments(timeseries_file, moment):
909909
timeseries_file -- text file with white space separated timepoints in rows
910910
911911
"""
912+
import scipy.stats as stats
912913
timeseries = np.genfromtxt(timeseries_file)
913914

914915
m2 = stats.moment(timeseries, 2, axis=0)

nipype/algorithms/modelgen.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
from nibabel import load
2222
import numpy as np
23-
from scipy.special import gammaln
2423

2524
from ..utils import NUMPY_MMAP
2625
from ..interfaces.base import (BaseInterface, TraitedSpec, InputMultiPath,
@@ -84,6 +83,7 @@ def spm_hrf(RT, P=None, fMRI_T=16):
8483
-1.46257507e-04]
8584
8685
"""
86+
from scipy.special import gammaln
8787
p = np.array([6, 16, 1, 1, 6, 0, 32], dtype=float)
8888
if P is not None:
8989
p[0:len(P)] = P

nipype/algorithms/rapidart.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@
2121

2222
from nibabel import load, funcs, Nifti1Image
2323
import numpy as np
24-
from scipy import signal
25-
import scipy.io as sio
2624

2725
from ..utils import NUMPY_MMAP
2826
from ..interfaces.base import (BaseInterface, traits, InputMultiPath,
@@ -151,7 +149,8 @@ def _calc_norm_affine(affines, use_differences, brain_pts=None):
151149
(3, all_pts.shape[1])),
152150
axis=0)))
153151
else:
154-
newpos = np.abs(signal.detrend(newpos, axis=0, type='constant'))
152+
from scipy.signal import detrend
153+
newpos = np.abs(detrend(newpos, axis=0, type='constant'))
155154
normdata = np.sqrt(np.mean(np.power(newpos, 2), axis=1))
156155
return normdata, displacement
157156

@@ -411,6 +410,7 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None):
411410
"""
412411
Core routine for detecting outliers
413412
"""
413+
from scipy import signal
414414
if not cwd:
415415
cwd = os.getcwd()
416416

@@ -750,6 +750,7 @@ def _get_spm_submatrix(self, spmmat, sessidx, rows=None):
750750
def _run_interface(self, runtime):
751751
"""Execute this module.
752752
"""
753+
import scipy.io as sio
753754
motparamlist = self.inputs.realignment_parameters
754755
intensityfiles = self.inputs.intensity_values
755756
spmmat = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False)

nipype/interfaces/base/core.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1164,12 +1164,10 @@ class LibraryBaseInterface(BaseInterface):
11641164
def __init__(self, check_import=True, *args, **kwargs):
11651165
super(LibraryBaseInterface, self).__init__(*args, **kwargs)
11661166
if check_import:
1167-
import importlib
1167+
import pkgutil
11681168
failed_imports = []
11691169
for pkg in (self._pkg,) + tuple(self.imports):
1170-
try:
1171-
importlib.import_module(pkg)
1172-
except ImportError:
1170+
if pkgutil.find_loader(pkg) is None:
11731171
failed_imports.append(pkg)
11741172
if failed_imports:
11751173
iflogger.warning('Unable to import %s; %s interface may fail to '

nipype/interfaces/cmtk/cmtk.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import numpy as np
1212
import nibabel as nb
1313
import networkx as nx
14-
import scipy.io as sio
1514

1615
from ... import logging
1716
from ...utils.filemanip import split_filename
@@ -178,6 +177,7 @@ def cmat(track_file,
178177
endpoint_name,
179178
intersections=False):
180179
""" Create the connection matrix for each resolution using fibers and ROIs. """
180+
import scipy.io as sio
181181

182182
stats = {}
183183
iflogger.info('Running cmat function')

nipype/interfaces/cmtk/nx.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111
import numpy as np
1212
import networkx as nx
13-
import scipy.io as sio
1413

1514
from ... import logging
1615
from ...utils.filemanip import split_filename
@@ -94,6 +93,7 @@ def average_networks(in_files, ntwk_res_file, group_id):
9493
"""
9594
import networkx as nx
9695
import os.path as op
96+
import scipy.io as sio
9797
iflogger.info('Creating average network for group: %s', group_id)
9898
matlab_network_list = []
9999
if len(in_files) == 1:
@@ -442,6 +442,7 @@ class NetworkXMetrics(BaseInterface):
442442
output_spec = NetworkXMetricsOutputSpec
443443

444444
def _run_interface(self, runtime):
445+
import scipy.io as sio
445446
global gpickled, nodentwks, edgentwks, kntwks, matlab
446447
gpickled = list()
447448
nodentwks = list()

nipype/interfaces/image.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
33
# vi: set ft=python sts=4 ts=4 sw=4 et:
44

5-
import numpy as np
6-
import nibabel as nb
7-
85
from ..utils.filemanip import fname_presuffix
96
from .base import (SimpleInterface, TraitedSpec, BaseInterfaceInputSpec,
107
traits, File)
@@ -63,6 +60,9 @@ class Rescale(SimpleInterface):
6360
output_spec = RescaleOutputSpec
6461

6562
def _run_interface(self, runtime):
63+
import numpy as np
64+
import nibabel as nb
65+
6666
img = nb.load(self.inputs.in_file)
6767
data = img.get_data()
6868
ref_data = nb.load(self.inputs.ref_file).get_data()
@@ -171,6 +171,8 @@ class Reorient(SimpleInterface):
171171
output_spec = ReorientOutputSpec
172172

173173
def _run_interface(self, runtime):
174+
import numpy as np
175+
import nibabel as nb
174176
from nibabel.orientations import (
175177
axcodes2ornt, ornt_transform, inv_ornt_aff)
176178

@@ -211,6 +213,8 @@ def _run_interface(self, runtime):
211213

212214
def _as_reoriented_backport(img, ornt):
213215
"""Backport of img.as_reoriented as of nibabel 2.2.0"""
216+
import numpy as np
217+
import nibabel as nb
214218
from nibabel.orientations import inv_ornt_aff
215219
if np.array_equal(ornt, [[0, 1], [1, 1], [2, 1]]):
216220
return img

0 commit comments

Comments
 (0)