Error in forward solution

Hi there,

I am having an error while computing the forward solution : Unsupported array dtype: >i4

  • MNE version: 1.1.0
  • operating system: Windows 10

The code:

#%% Get file
sample_dir = 'U:/shared/database/meg-ieeg-UNMC/rawdata/sub-ep1050/ses-preop/meg'
raw_fname  = op.join(sample_dir,'sub-ep1050_ses-preop_task-SEFul_run-01_proc-tsss_meg.fif')
raw        = mne.io.read_raw_fif(raw_fname,preload=True)

subjects_dir = 'U:/shared/database/meg-ieeg-UNMC/derivatives/sub-ep1050/ses-preop/'
subject      = 'sample'

#%% Pick types
raw = raw.pick_types(meg=True,eeg=True,eog=True,stim=True,ecg=True)

#%% High pass filter
raw = raw.filter(l_freq=1,h_freq=None)

#%% Filter data (8-40 Hz)
raw.filter(l_freq=8, h_freq=40)
raw.plot()
#%% Find events and create event dictionary
events= mne.find_events(raw, stim_channel='STI101')
len(events[events[:,2]==1])
#%% Create epochs
reject_dict = dict(mag=4000e-15,grad=4000e-13)
epochs= mne.Epochs(raw, events, event_id=1 , tmin=-0.05, tmax=0.25, baseline=(None,0.), preload=True, reject=reject_dict)

#%% Average the epochs to create evoked fields and plot 
evoked= epochs.average()
mne.viz.plot_evoked_topo(evoked)
evoked.plot(picks='meg',spatial_colors=True,gfp=True)

#%% Coregistration
mne.gui.coregistration(subject='sample',subjects_dir=subjects_dir)
#%% Compute covariance
data_rank = raw.info['proc_history'][0]['max_info']['sss_info']['nfree']
ica_rank = len(ica.exclude)
ssp_rank = 2
final_rank = data_rank-ica_rank-ssp_rank
rank = {'meg':final_rank}
noise_cov = mne.compute_covariance(epochs,method='auto',tmin=None,tmax=0,rank=rank)
mne.viz.plot_cov(noise_cov,info=epochs.info)

#%% Transform
trans = op.join(subjects_dir,'transforms','sub-ep1050_ses-preop_task-SEFul_run-01_trans.fif')

#%% Compute surface based source space
src = mne.setup_source_space(subject,subjects_dir=subjects_dir,spacing='ico5',surface='white',n_jobs=None)

#%% Compute BEM
conductivity = (0.3,)
model = mne.make_bem_model(subject='sample',ico=None,conductivity=conductivity,subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)

#%% Compute forward operator
fwd = mne.make_forward_solution(evoked.info,trans=trans,src=src,bem=bem,meg=True,eeg=False,mindist=5.0,n_jobs=None,verbose=True)
fwd = mne.convert_forward_solution(fwd,surf_ori=True,force_fixed=False)
#%% Make inverse operator
inv = mne.minimum_norm.make_inverse_operator(evoked.info,fwd,noise_cov,loose=0.2,depth=0.8,fixed=False,rank=rank)

#%% Estimate snr
snr,snr_est = mne.minimum_norm.estimate_snr(evoked,inv)

#%% Apply inverse operator
method = 'sLORETA'
snr = 3.
lambda2 = 1./snr**2

stc,variance = mne.minimum_norm.apply_inverse(evoked,inv,lambda2,method)

#%% Plot results
brain = stc.plot(surface='pial',hemi='split',views=['lat','med'],subjects_dir=subjects_dir)

I am getting the following error:

File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\numba\core\typing\typeof.py", line 237, in _typeof_ndarray
    dtype = numpy_support.from_dtype(val.dtype)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\numba\np\numpy_support.py", line 114, in from_dtype
    raise errors.NumbaNotImplementedError(dtype)

NumbaNotImplementedError: >i4


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\srdas\AppData\Local\Temp\ipykernel_16864\3712427209.py", line 1, in <module>
    fwd = mne.make_forward_solution(evoked.info,trans=trans,src=src,bem=bem,meg=True,eeg=False,mindist=5.0,n_jobs=None,verbose=True)

  File "<decorator-gen-372>", line 10, in make_forward_solution

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_make_forward.py", line 627, in make_forward_solution
    megfwd, eegfwd = _compute_forwards(rr, bem, coils, ccoils,

  File "<decorator-gen-366>", line 12, in _compute_forwards

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_compute_forward.py", line 921, in _compute_forwards
    _prep_field_computation(rr, bem, fwd_data, n_jobs)

  File "<decorator-gen-365>", line 12, in _prep_field_computation

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_compute_forward.py", line 783, in _prep_field_computation
    solution = _bem_specify_coils(bem, coils, cf, mults,

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_compute_forward.py", line 224, in _bem_specify_coils
    coeff = _lin_field_coeff(surf, mult, r, c, w, b, n_jobs)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_compute_forward.py", line 95, in _lin_field_coeff
    coeffs = parallel(p_fun(surf['rr'], t, tn, ta, rmags, cosmags, ws, bins)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\parallel.py", line 1043, in __call__
    if self.dispatch_one_batch(iterator):

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\parallel.py", line 861, in dispatch_one_batch
    self._dispatch(tasks)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\parallel.py", line 779, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\_parallel_backends.py", line 208, in apply_async
    result = ImmediateResult(func)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\_parallel_backends.py", line 572, in __init__
    self.results = batch()

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\parallel.py", line 262, in __call__
    return [func(*args, **kwargs)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\joblib\parallel.py", line 262, in <listcomp>
    return [func(*args, **kwargs)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\numba\core\dispatcher.py", line 733, in typeof_pyval
    tp = typeof(val, Purpose.argument)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\numba\core\typing\typeof.py", line 31, in typeof
    ty = typeof_impl(val, c)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\functools.py", line 889, in wrapper
    return dispatch(args[0].__class__)(*args, **kw)

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\numba\core\typing\typeof.py", line 239, in _typeof_ndarray
    raise errors.NumbaValueError(f"Unsupported array dtype: {val.dtype}")

NumbaValueError: Unsupported array dtype: >i4

I have run the same code on different machine and it works fine.

mne.sys_info()

Platform:         Windows-10-10.0.19042-SP0
Python:           3.10.5 | packaged by conda-forge | (main, Jun 14 2022, 06:57:19) [MSC v.1929 64 bit (AMD64)]
Executable:       C:\Users\srdas\Anaconda3\envs\mne\python.exe
CPU:              Intel64 Family 6 Model 167 Stepping 1, GenuineIntel: 16 cores
Memory:           31.7 GB

mne:              1.1.0
numpy:            1.22.4 {blas=NO_ATLAS_INFO, lapack=lapack}
scipy:            1.9.0
matplotlib:       3.5.3 {backend=Qt5Agg}

sklearn:          1.1.2
numba:            0.55.2
nibabel:          4.0.1
nilearn:          0.9.1
dipy:             1.5.0
cupy:             Not found
pandas:           1.4.3
pyvista:          0.36.1 {OpenGL 4.5.0 NVIDIA 462.31 via Quadro P400/PCIe/SSE2}
pyvistaqt:        0.9.0
ipyvtklink:       0.2.2
vtk:              9.1.0
qtpy:             2.2.0 {PyQt5=5.15.4}
ipympl:           Not found
pyqtgraph:        0.12.4
pooch:            v1.6.0

mne_bids:         Not found
mne_nirs:         Not found
mne_features:     Not found
mne_qt_browser:   0.3.1
mne_connectivity: Not found
mne_icalabel:     Not found

Hello @Srijita, I don’t know what’s actually causing this error, but it seems to be related to Numba. If you don’t need Numba, you could uninstall the Numba Python package and re-run your code. It should work then!

Hello Richard,
I have tried that but doing so the Anaconda navigator itself does not open!

Hello,

I don’t understand what you’re saying :slight_smile: But you can try to open the Anaconda Prompt and then run

conda uninstall -n mne numba

This will remove numba from the mne conda environment.

Best wishes,
Richard

cc @larsoner @agramfort We may have a bug in Numba support.

@Srijita can you please reduce your code sample? Currently it is 94 lines long. Please eliminate anything that is not strictly necessary to cause the error (e.g., can you skip the ECG and EOG projectors and still see the error? What about the coregistration step? etc etc).

Also, if you want our help debugging this, you should either

  1. edit the code snippet to use one of our built-in datasets, or if those don’t yield the error,
  2. provide a download link to one of your own datafiles that does yield the error (preferably a cropped version, so file size is not too big).

… or if you want to try to debug yourself, when you hit the failure you can do:

import pdb; pdb.pm()

then you’ll be in the stack where the error occurred, with a new prompt like:

(pdb)

Hit u then enter until you reach this stack frame:

  File "C:\Users\srdas\Anaconda3\envs\mne\lib\site-packages\mne\forward\_compute_forward.py", line 224, in _bem_specify_coils
    coeff = _lin_field_coeff(surf, mult, r, c, w, b, n_jobs)

if you do for example

(pdb) p r.dtype

in theory one of these should have a dtype of >i4. If you change it to .astype(np.int64) and it fixes things, we can change the MNE-Python code to do this somewhere!

I did remove the Numba package. After running the program again, I get the following error:

cannot unpack non-iterable SourceEstimate object on the following line

stc,variance = mne.minimum_norm.apply_inverse(evoked,inv,lambda2,method)

Hello Dan,
I did reduce the lines of the code which I found might not be necessarily involved with the error.
I am sorry I cannot upload the link of the datafiles as it is against the IRB protocol.

1 Like

most likely you forgot to specify apply_inverse(..., return_residual=True). Either change that, or change stc, variance = ... to just stc = ...

Please try again. I still see lines like raw.plot() and len(events[events[:,2]==1]) which are almost surely not necessary to reproduce the error. I suspect also the filtering won’t be needed either. Include each line of code ONLY if, when removing it, you no longer get your unsupported dtype <i4 error.

1 Like

Yes, I did forgot to put this. Now the entire code works fine.
Thank you very much to everyone involved.