Skip to content

Commit

Permalink
MRG, MAINT: Clean up use of bool, float, int (#7917)
Browse files Browse the repository at this point in the history
* MAINT: Clean up use of bool, float, int

* MAINT: Clean up use of complex

* FIX: Windows
  • Loading branch information
larsoner authored Jun 22, 2020
1 parent 1719178 commit 959d191
Show file tree
Hide file tree
Showing 71 changed files with 149 additions and 143 deletions.
2 changes: 1 addition & 1 deletion examples/simulation/plot_simulate_evoked_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
###############################################################################
# Generate source time courses from 2 dipoles and the correspond evoked data

times = np.arange(300, dtype=np.float) / raw.info['sfreq'] - 0.1
times = np.arange(300, dtype=np.float64) / raw.info['sfreq'] - 0.1
rng = np.random.RandomState(42)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def data_fun(times, latency, duration):
# event, the second is not used. The third one is the event id, which is
# different for each of the 4 areas.

times = np.arange(150, dtype=np.float) / info['sfreq']
times = np.arange(150, dtype=np.float64) / info['sfreq']
duration = 0.03
rng = np.random.RandomState(7)
source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep)
Expand Down
2 changes: 1 addition & 1 deletion examples/time_frequency/plot_time_frequency_simulated.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
noise = rng.randn(n_epochs, len(ch_names), n_times)

# Add a 50 Hz sinusoidal burst to the noise and ramp it.
t = np.arange(n_times, dtype=np.float) / sfreq
t = np.arange(n_times, dtype=np.float64) / sfreq
signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal
signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing
on_time = np.logical_and(t >= 0.45, t <= 0.55)
Expand Down
2 changes: 1 addition & 1 deletion mne/beamformer/tests/test_dics.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def test_make_dics(tmpdir, _load_forward, idx, mat_tol, vol_tol):
assert isinstance(filters, Beamformer)
assert isinstance(filters_read, Beamformer)
for key in ['tmin', 'tmax']: # deal with strictness of object_diff
setattr(filters['csd'], key, np.float(getattr(filters['csd'], key)))
setattr(filters['csd'], key, np.float64(getattr(filters['csd'], key)))
assert object_diff(filters, filters_read) == ''


Expand Down
2 changes: 1 addition & 1 deletion mne/bem.py
Original file line number Diff line number Diff line change
Expand Up @@ -1341,7 +1341,7 @@ def _read_bem_surface(fid, this, def_coord_frame, s_id=None):
if tag is None:
raise ValueError('Vertex data not found')

res['rr'] = tag.data.astype(np.float) # XXX : double because of mayavi bug
res['rr'] = tag.data.astype(np.float64) # XXX : double because of mayavi
if res['rr'].shape[0] != res['np']:
raise ValueError('Vertex information is incorrect')

Expand Down
2 changes: 1 addition & 1 deletion mne/channels/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ def _set_channel_positions(self, pos, names):
if len(pos) != len(names):
raise ValueError('Number of channel positions not equal to '
'the number of names given.')
pos = np.asarray(pos, dtype=np.float)
pos = np.asarray(pos, dtype=np.float64)
if pos.shape[-1] != 3 or pos.ndim != 2:
msg = ('Channel positions must have the shape (n_points, 3) '
'not %s.' % (pos.shape,))
Expand Down
4 changes: 2 additions & 2 deletions mne/channels/interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ def _interpolate_bads_eeg(inst, origin, verbose=None):
inst : mne.io.Raw, mne.Epochs or mne.Evoked
The data to interpolate. Must be preloaded.
"""
bads_idx = np.zeros(len(inst.ch_names), dtype=np.bool)
goods_idx = np.zeros(len(inst.ch_names), dtype=np.bool)
bads_idx = np.zeros(len(inst.ch_names), dtype=bool)
goods_idx = np.zeros(len(inst.ch_names), dtype=bool)

picks = pick_types(inst.info, meg=False, eeg=True, exclude=[])
inst.info._check_consistency()
Expand Down
4 changes: 2 additions & 2 deletions mne/channels/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def _read_lout(fname):
name = chkind + ' ' + nb
else:
cid, x, y, dx, dy, name = splits
pos.append(np.array([x, y, dx, dy], dtype=np.float))
pos.append(np.array([x, y, dx, dy], dtype=np.float64))
names.append(name)
ids.append(int(cid))

Expand All @@ -147,7 +147,7 @@ def _read_lay(fname):
name = chkind + ' ' + nb
else:
cid, x, y, dx, dy, name = splits
pos.append(np.array([x, y, dx, dy], dtype=np.float))
pos.append(np.array([x, y, dx, dy], dtype=np.float64))
names.append(name)
ids.append(int(cid))

Expand Down
2 changes: 1 addition & 1 deletion mne/chpi.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ def _fit_chpi_amplitudes(raw, time_sl, hpi):
# loads hpi_stim channel
chpi_data = raw[hpi['hpi_pick'], time_sl][0]

ons = (np.round(chpi_data).astype(np.int) &
ons = (np.round(chpi_data).astype(np.int64) &
hpi['on'][:, np.newaxis]).astype(bool)
n_on = ons.all(axis=-1).sum(axis=0)
if not (n_on >= 3).all():
Expand Down
5 changes: 5 additions & 0 deletions mne/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ def pytest_configure(config):
ignore:.*trait.*handler.*deprecated.*:DeprecationWarning
ignore:.*rich_compare.*metadata.*deprecated.*:DeprecationWarning
ignore:.*In future, it will be an error for 'np.bool_'.*:DeprecationWarning
ignore:.*`np.bool` is a deprecated alias.*:DeprecationWarning
ignore:.*`np.int` is a deprecated alias.*:DeprecationWarning
ignore:.*`np.float` is a deprecated alias.*:DeprecationWarning
ignore:.*`np.object` is a deprecated alias.*:DeprecationWarning
ignore:.*`np.long` is a deprecated alias:DeprecationWarning
ignore:.*Converting `np\.character` to a dtype is deprecated.*:DeprecationWarning
ignore:.*sphinx\.util\.smartypants is deprecated.*:
ignore:.*pandas\.util\.testing is deprecated.*:
Expand Down
2 changes: 1 addition & 1 deletion mne/connectivity/effective.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def phase_slope_index(data, indices=None, sfreq=2 * np.pi,
# allocate space for output
out_shape = list(cohy.shape)
out_shape[freq_dim] = n_bands
psi = np.zeros(out_shape, dtype=np.float)
psi = np.zeros(out_shape, dtype=np.float64)

# allocate accumulator
acc_shape = copy.copy(out_shape)
Expand Down
4 changes: 2 additions & 2 deletions mne/connectivity/spectral.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,7 +980,7 @@ def _prepare_connectivity(epoch_block, tmin, tmax, fmin, fmax, sfreq, indices,
raise ValueError('define frequencies of interest using '
'cwt_freqs')
else:
cwt_freqs = cwt_freqs.astype(np.float)
cwt_freqs = cwt_freqs.astype(np.float64)
if any(cwt_freqs > (sfreq / 2.)):
raise ValueError('entries in cwt_freqs cannot be '
'larger than Nyquist (sfreq / 2)')
Expand All @@ -1003,7 +1003,7 @@ def _prepare_connectivity(epoch_block, tmin, tmax, fmin, fmax, sfreq, indices,
5. / np.min(fmin), five_cycle_freq))

# create a frequency mask for all bands
freq_mask = np.zeros(len(freqs_all), dtype=np.bool)
freq_mask = np.zeros(len(freqs_all), dtype=bool)
for f_lower, f_upper in zip(fmin, fmax):
freq_mask |= ((freqs_all >= f_lower) & (freqs_all <= f_upper))

Expand Down
8 changes: 4 additions & 4 deletions mne/cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -846,8 +846,8 @@ def _unpack_epochs(epochs):
# prepare mean covs
n_epoch_types = len(epochs)
data_mean = [0] * n_epoch_types
n_samples = np.zeros(n_epoch_types, dtype=np.int)
n_epochs = np.zeros(n_epoch_types, dtype=np.int)
n_samples = np.zeros(n_epoch_types, dtype=np.int64)
n_epochs = np.zeros(n_epoch_types, dtype=np.int64)

for ii, epochs_t in enumerate(epochs):

Expand Down Expand Up @@ -1757,7 +1757,7 @@ def compute_whitener(noise_cov, info=None, picks=None, rank=None,
nzero = (eig > 0)
eig[~nzero] = 0. # get rid of numerical noise (negative) ones

W = np.zeros((n_chan, 1), dtype=np.float)
W = np.zeros((n_chan, 1), dtype=np.float64)
W[nzero, 0] = 1.0 / np.sqrt(eig[nzero])
# Rows of eigvec are the eigenvectors
W = W * noise_cov['eigvec'] # C ** -0.5
Expand Down Expand Up @@ -1963,7 +1963,7 @@ def _write_cov(fid, cov):
else:
# Store only lower part of covariance matrix
dim = cov['dim']
mask = np.tril(np.ones((dim, dim), dtype=np.bool)) > 0
mask = np.tril(np.ones((dim, dim), dtype=bool)) > 0
vals = cov['data'][mask].ravel()
write_double(fid, FIFF.FIFF_MNE_COV, vals)

Expand Down
2 changes: 1 addition & 1 deletion mne/decoding/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def _set_cv(cv, estimator=None, X=None, y=None):
# Setup CV
from sklearn import model_selection as models
from sklearn.model_selection import (check_cv, StratifiedKFold, KFold)
if isinstance(cv, (int, np.int)):
if isinstance(cv, (int, np.int64)):
XFold = StratifiedKFold if est_is_classifier else KFold
cv = XFold(n_splits=cv)
elif isinstance(cv, str):
Expand Down
2 changes: 1 addition & 1 deletion mne/decoding/tests/test_receptive_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def test_time_delay():
_delay_time_series(X, tmin, tmax, sfreq=[1])
# Delays must be int/float
with pytest.raises(TypeError, match='.*complex.*'):
_delay_time_series(X, np.complex(tmin), tmax, 1)
_delay_time_series(X, np.complex128(tmin), tmax, 1)
# Make sure swapaxes works
start, stop = int(round(tmin * isfreq)), int(round(tmax * isfreq)) + 1
n_delays = stop - start
Expand Down
2 changes: 1 addition & 1 deletion mne/dipole.py
Original file line number Diff line number Diff line change
Expand Up @@ -1306,7 +1306,7 @@ def fit_dipole(evoked, cov, bem, trans=None, min_dist=5., n_jobs=1,
# cov = prepare_noise_cov(cov, info_nb, info_nb['ch_names'], verbose=False)
# nzero = (cov['eig'] > 0)
# n_chan = len(info_nb['ch_names'])
# whitener = np.zeros((n_chan, n_chan), dtype=np.float)
# whitener = np.zeros((n_chan, n_chan), dtype=np.float64)
# whitener[nzero, nzero] = 1.0 / np.sqrt(cov['eig'][nzero])
# whitener = np.dot(whitener, cov['eigvec'])

Expand Down
2 changes: 1 addition & 1 deletion mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ def subtract_evoked(self, evoked=None):
else:
if self._offset is None:
self._offset = np.zeros((len(self.ch_names), len(self.times)),
dtype=np.float)
dtype=np.float64)
self._offset[ep_picks] -= evoked.data[picks]
logger.info('[done]')

Expand Down
10 changes: 5 additions & 5 deletions mne/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def pick_events(events, include=None, exclude=None, step=False):
if include is not None:
if not isinstance(include, list):
include = [include]
mask = np.zeros(len(events), dtype=np.bool)
mask = np.zeros(len(events), dtype=bool)
for e in include:
mask = np.logical_or(mask, events[:, 2] == e)
if step:
Expand All @@ -58,7 +58,7 @@ def pick_events(events, include=None, exclude=None, step=False):
elif exclude is not None:
if not isinstance(exclude, list):
exclude = [exclude]
mask = np.ones(len(events), dtype=np.bool)
mask = np.ones(len(events), dtype=bool)
for e in exclude:
mask = np.logical_and(mask, events[:, 2] != e)
if step:
Expand Down Expand Up @@ -432,7 +432,7 @@ def find_stim_steps(raw, pad_start=None, pad_stop=None, merge=0,
if np.any(data < 0):
warn('Trigger channel contains negative values, using absolute value.')
data = np.abs(data) # make sure trig channel is positive
data = data.astype(np.int)
data = data.astype(np.int64)

return _find_stim_steps(data, raw.first_samp, pad_start=pad_start,
pad_stop=pad_stop, merge=merge)
Expand All @@ -452,9 +452,9 @@ def _find_events(data, first_samp, verbose=None, output='onset',
else:
merge = 0

data = data.astype(np.int)
data = data.astype(np.int64)
if uint_cast:
data = data.astype(np.uint16).astype(np.int)
data = data.astype(np.uint16).astype(np.int64)
if data.min() < 0:
warn('Trigger channel contains negative values, using absolute '
'value. If data were acquired on a Neuromag system with '
Expand Down
6 changes: 3 additions & 3 deletions mne/evoked.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ def __init__(self, data, info, tmin=0., comment='', nave=1, kind='average',
self.first = int(round(tmin * info['sfreq']))
self.last = self.first + np.shape(data)[-1] - 1
self.times = np.arange(self.first, self.last + 1,
dtype=np.float) / info['sfreq']
dtype=np.float64) / info['sfreq']
self.info = info.copy() # do not modify original info
self.nave = nave
self.kind = kind
Expand Down Expand Up @@ -1111,7 +1111,7 @@ def _read_evoked(fname, condition=None, kind='average', allow_maxshield=False):
else:
# Put the old style epochs together
data = np.concatenate([e.data[None, :] for e in epoch], axis=0)
data = data.astype(np.float)
data = data.astype(np.float64)

if first_time is not None and nsamp is not None:
times = first_time + np.arange(nsamp) / info['sfreq']
Expand Down Expand Up @@ -1280,7 +1280,7 @@ def _get_peak(data, times, tmin=None, tmax=None, mode='abs'):
raise ValueError('The tmin must be smaller or equal to tmax')

time_win = (times >= tmin) & (times <= tmax)
mask = np.ones_like(data).astype(np.bool)
mask = np.ones_like(data).astype(bool)
mask[:, time_win] = False

maxfun = np.argmax
Expand Down
4 changes: 2 additions & 2 deletions mne/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def _overlap_add_filter(x, h, n_fft=None, phase='zero', picks=None,
# cost function based on number of multiplications
N = 2 ** np.arange(np.ceil(np.log2(min_fft)),
np.ceil(np.log2(max_fft)) + 1, dtype=int)
cost = (np.ceil(n_x / (N - len(h) + 1).astype(np.float)) *
cost = (np.ceil(n_x / (N - len(h) + 1).astype(np.float64)) *
N * (np.log2(N) + 1))

# add a heuristic term to prevent too-long FFT's which are slow
Expand Down Expand Up @@ -2005,7 +2005,7 @@ def resample(self, sfreq, npad='auto', window='boxcar', n_jobs=1,
lowpass = self.info.get('lowpass')
lowpass = np.inf if lowpass is None else lowpass
self.info['lowpass'] = min(lowpass, sfreq / 2.)
new_times = (np.arange(self._data.shape[-1], dtype=np.float) /
new_times = (np.arange(self._data.shape[-1], dtype=np.float64) /
sfreq + self.times[0])
# adjust indirectly affected variables
if isinstance(self, BaseEpochs):
Expand Down
6 changes: 3 additions & 3 deletions mne/fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,14 @@ def _read_geometry(filepath, read_metadata=False, read_stamp=False):
nvert = _fread3(fobj)
nquad = _fread3(fobj)
(fmt, div) = (">i2", 100.) if magic == QUAD_MAGIC else (">f4", 1.)
coords = np.fromfile(fobj, fmt, nvert * 3).astype(np.float) / div
coords = np.fromfile(fobj, fmt, nvert * 3).astype(np.float64) / div
coords = coords.reshape(-1, 3)
quads = _fread3_many(fobj, nquad * 4)
quads = quads.reshape(nquad, 4)
#
# Face splitting follows
#
faces = np.zeros((2 * nquad, 3), dtype=np.int)
faces = np.zeros((2 * nquad, 3), dtype=np.int64)
nface = 0
for quad in quads:
if (quad[0] % 2) == 0:
Expand All @@ -127,7 +127,7 @@ def _read_geometry(filepath, read_metadata=False, read_stamp=False):
else:
raise ValueError("File does not appear to be a Freesurfer surface")

coords = coords.astype(np.float) # XXX: due to mayavi bug on mac 32bits
coords = coords.astype(np.float64) # XXX: due to mayavi bug on mac 32bits

ret = (coords, faces)
if read_metadata:
Expand Down
2 changes: 1 addition & 1 deletion mne/forward/_make_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ def make_forward_dipole(dipole, bem, info, trans=None, n_jobs=1, verbose=None):
# Check for omissions due to proximity to inner skull in
# make_forward_solution, which will result in an exception
if fwd['src'][0]['nuse'] != len(pos):
inuse = fwd['src'][0]['inuse'].astype(np.bool)
inuse = fwd['src'][0]['inuse'].astype(bool)
head = ('The following dipoles are outside the inner skull boundary')
msg = len(head) * '#' + '\n' + head + '\n'
for (t, pos) in zip(times[np.logical_not(inuse)],
Expand Down
8 changes: 4 additions & 4 deletions mne/forward/forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,12 @@ def _block_diag(A, n):
if na % n > 0:
raise ValueError('Width of matrix must be a multiple of n')

tmp = np.arange(ma * bdn, dtype=np.int).reshape(bdn, ma)
tmp = np.arange(ma * bdn, dtype=np.int64).reshape(bdn, ma)
tmp = np.tile(tmp, (1, n))
ii = tmp.ravel()

jj = np.arange(na, dtype=np.int)[None, :]
jj = jj * np.ones(ma, dtype=np.int)[:, None]
jj = np.arange(na, dtype=np.int64)[None, :]
jj = jj * np.ones(ma, dtype=np.int64)[:, None]
jj = jj.T.ravel() # column indices foreach sparse bd

bd = sparse.coo_matrix((A.T.ravel(), np.c_[ii, jj].T)).tocsc()
Expand Down Expand Up @@ -994,7 +994,7 @@ def compute_orient_prior(forward, loose=0.2, verbose=None):
if not (0 <= loose <= 1):
raise ValueError('loose value should be between 0 and 1, '
'got %s.' % (loose,))
orient_prior = np.ones(n_sources, dtype=np.float)
orient_prior = np.ones(n_sources, dtype=np.float64)
if loose > 0.:
if is_fixed_ori:
raise ValueError('loose must be 0. with forward operator '
Expand Down
4 changes: 2 additions & 2 deletions mne/inverse_sparse/_gamma_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _gamma_map_opt(M, G, alpha, maxit=10000, tol=1e-6, update_mode=1,
M = M.copy()

if gammas is None:
gammas = np.ones(G.shape[1], dtype=np.float)
gammas = np.ones(G.shape[1], dtype=np.float64)

eps = np.finfo(float).eps

Expand Down Expand Up @@ -132,7 +132,7 @@ def denom_fun(x):
gammas = np.repeat(gammas_comb / group_size, group_size)

# compute convergence criterion
gammas_full = np.zeros(n_sources, dtype=np.float)
gammas_full = np.zeros(n_sources, dtype=np.float64)
gammas_full[active_set] = gammas

err = (np.sum(np.abs(gammas_full - gammas_full_old)) /
Expand Down
4 changes: 2 additions & 2 deletions mne/inverse_sparse/mxne_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def mixed_norm(evoked, forward, noise_cov, alpha, loose='auto', depth=0.8,
M_estimated = np.dot(gain[:, active_set], X)

if mask is not None:
active_set_tmp = np.zeros(len(mask), dtype=np.bool)
active_set_tmp = np.zeros(len(mask), dtype=bool)
active_set_tmp[mask] = active_set
active_set = active_set_tmp
del active_set_tmp
Expand Down Expand Up @@ -662,7 +662,7 @@ def tf_mixed_norm(evoked, forward, noise_cov,
M_estimated = np.dot(gain[:, active_set], X)

if mask is not None:
active_set_tmp = np.zeros(len(mask), dtype=np.bool)
active_set_tmp = np.zeros(len(mask), dtype=bool)
active_set_tmp[mask] = active_set
active_set = active_set_tmp
del active_set_tmp
Expand Down
Loading

0 comments on commit 959d191

Please sign in to comment.