internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: mne-tools/mne-python

Issue:
BUG: report render bem broken if one surface is missing, a.k.a. homog
line 1752 returns a gray MRI image once one surface is not there.

cc @teonlamont @jaeilepp @agramfort 



Discussion:

Resolving patch:
diff --git a/mne/report.py b/mne/report.py
--- a/mne/report.py
+++ b/mne/report.py
@@ -1745,12 +1745,13 @@ def _render_bem(self, subject, subjects_dir, decim, n_jobs,
         for surf_name in ['*inner_skull', '*outer_skull', '*outer_skin']:
             surf_fname = glob(op.join(bem_path, surf_name + '.surf'))
             if len(surf_fname) > 0:
-                surf_fname = surf_fname[0]
+                surf_fnames.append(surf_fname[0])
             else:
                 warnings.warn('No surface found for %s.' % surf_name)
-                return self._render_image(mri_fname, cmap='gray')
-            surf_fnames.append(surf_fname)
-
+                continue
+        if len(surf_fnames) == 0:
+            warnings.warn('No surfaces found at all, rendering empty MRI')
+            return self._render_image(mri_fname, cmap='gray')
         # XXX : find a better way to get max range of slices
         nim = nib.load(mri_fname)
         data = nim.get_data()


Test patch:
Repository: mne-tools/mne-python

Issue:
BUG: something wrong with spatial_colors legend
Something wrong with the legend in files that should be fairly regular - no bad channels, all EEG ... but the legend colors seem completely random. (The line colors are fine!)

The tests look fine and another experiment of mine looks fine, it's only for some layouts.

![unknown-34](https://cloud.githubusercontent.com/assets/4321826/11744173/53a4a37e-a00e-11e5-8067-96259449c623.png)

I'll see if I can find what it's about, but I'm also attaching an evoked file that has the issue: [bad_example-ave.fif.gz](https://github.com/mne-tools/mne-python/files/59396/bad_example-ave.fif.gz)
@jaeilepp 



Discussion:
Jakko, the problem is  that `names = np.intersect1d(layout.names, used_nm)` returns a sorted list, but we don't want them to be sorted, but in original order (10/20 EEG chans have nonalphabetic order, it only works for MEG and some EEG layouts due to alphabetic channel layouts) . I'm not sure I understand the exact purpose of the line, and what could happen for specific channel types (the ones we need `_clean_names` for). Can we do `names = [name for name in layout.names if name in used_nm]` instead, or does that break something? It fixes my problems.

sounds like the good fix !

A


Resolving patch:
diff --git a/mne/viz/evoked.py b/mne/viz/evoked.py
--- a/mne/viz/evoked.py
+++ b/mne/viz/evoked.py
@@ -281,7 +281,8 @@ def _plot_evoked(evoked, picks, exclude, unit, show,
                         layout = find_layout(info, ch_type=t, exclude=[])
                         # drop channels that are not in the data
                         used_nm = np.array(_clean_names(info['ch_names']))[idx]
-                        names = np.intersect1d(layout.names, used_nm)
+                        names = np.asarray([name for name in layout.names
+                                            if name in used_nm])
                         name_idx = [layout.names.index(name) for name in names]
                         if len(name_idx) < len(chs):
                             logger.warning('Could not find layout for '


Test patch:
Repository: mne-tools/mne-python

Issue:
Evoked.get_peak
Hi
I think there is a bug in Evoked.get_peak() function, when using ch_type :
In    : ev.get_peak('mag',tmin=tmin,tmax=tmax)
Out : ('MEG0122',0.178999)
ch_idx is related to data[picks] instead of self.data and the function should return 
self.ch_names[picks[ch_idx]] instead of self.ch_names[ch_idx]



Discussion:

Resolving patch:
diff --git a/mne/evoked.py b/mne/evoked.py
--- a/mne/evoked.py
+++ b/mne/evoked.py
@@ -900,11 +900,15 @@ def get_peak(self, ch_type=None, tmin=None, tmax=None, mode='abs',
             picks = pick_types(self.info, meg=meg, eeg=eeg, misc=misc,
                                seeg=seeg, ref_meg=False)
 
-        data = self.data if picks is None else self.data[picks]
+        data = self.data
+        ch_names = self.ch_names
+        if picks is not None:
+            data = data[picks]
+            ch_names = [ch_names[k] for k in picks]
         ch_idx, time_idx = _get_peak(data, self.times, tmin,
                                      tmax, mode)
 
-        return (self.ch_names[ch_idx],
+        return (ch_names[ch_idx],
                 time_idx if time_as_index else self.times[time_idx])
 
 


Test patch:
diff --git a/mne/tests/test_evoked.py b/mne/tests/test_evoked.py
--- a/mne/tests/test_evoked.py
+++ b/mne/tests/test_evoked.py
@@ -267,13 +267,14 @@ def test_get_peak():
     assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')
     assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')
 
-    ch_idx, time_idx = evoked.get_peak(ch_type='mag')
-    assert_true(ch_idx in evoked.ch_names)
+    ch_name, time_idx = evoked.get_peak(ch_type='mag')
+    assert_true(ch_name in evoked.ch_names)
     assert_true(time_idx in evoked.times)
 
-    ch_idx, time_idx = evoked.get_peak(ch_type='mag',
-                                       time_as_index=True)
+    ch_name, time_idx = evoked.get_peak(ch_type='mag',
+                                        time_as_index=True)
     assert_true(time_idx < len(evoked.times))
+    assert_equal(ch_name, 'MEG 1421')
 
     data = np.array([[0., 1.,  2.],
                      [0., -3.,  0]])
Repository: mne-tools/mne-python

Issue:
BUG: read_raw_brainvision fails for Brain Vision Data Exchange Header File Version 1.0
``` Python

/opt/anaconda3/lib/python3.4/site-packages/mne/io/brainvision/brainvision.py in _get_vhdr_info(vhdr_fname, eog, misc, scale, montage)
    350         unit = unit.replace(u'\xc2', u'')  # Remove unwanted control characters
    351         cals[n] = float(resolution)
--> 352         ranges[n] = _unit_dict.get(unit, unit) * scale
    353 
    354     # create montage

TypeError: can't multiply sequence by non-int of type 'float'
```

Digging into it:

``` Python
ipdb> unit
'uV'
ipdb> scale
1.0
ipdb> _unit_dict
{'V': 1.0, 'µV': 1e-06}
```

So it looks like 'uV' is not defined in the unit dictionary.

I can make a PR if this is a bug and not a problem of my files. I've got several of them.



Discussion:
Make a PR I'd say.

Are your BV files created by BV recorder?


Resolving patch:
diff --git a/mne/io/brainvision/brainvision.py b/mne/io/brainvision/brainvision.py
--- a/mne/io/brainvision/brainvision.py
+++ b/mne/io/brainvision/brainvision.py
@@ -251,7 +251,7 @@ def _check_mrk_version(header):
 _fmt_dict = dict(INT_16='short', INT_32='int', IEEE_FLOAT_32='single')
 _fmt_byte_dict = dict(short=2, int=4, single=4)
 _fmt_dtype_dict = dict(short='<i2', int='<i4', single='<f4')
-_unit_dict = {'V': 1., u'µV': 1e-6}
+_unit_dict = {'V': 1., u'µV': 1e-6, 'uV': 1e-6}
 
 
 def _get_vhdr_info(vhdr_fname, eog, misc, scale, montage):


Test patch:
Repository: mne-tools/mne-python

Issue:
BUG: utils._time_mask is not well tested enough
the defaults with None will create np.inf, these willl generate infs in turn if sfreq is None, and give you masks full of false.

A potential fix would be to replace np.inf with times[-1] and -np.inf with times[0]

cc @jaeilepp @Eric89GXL I think your edits are behind this, in November 2015 or so this code was still working under the described conditions.

``` Python
mne.utils._time_mask(np.arange(5))
# array([False, False, False, False,  True], dtype=bool)
# but should be  array([True, True, True, True,  True], dtype=bool)
```



Discussion:
Fix is coming.


Resolving patch:
diff --git a/mne/utils.py b/mne/utils.py
--- a/mne/utils.py
+++ b/mne/utils.py
@@ -1923,16 +1923,14 @@ def _time_mask(times, tmin=None, tmax=None, sfreq=None):
     """Helper to safely find sample boundaries"""
     tmin = -np.inf if tmin is None else tmin
     tmax = np.inf if tmax is None else tmax
+    if not np.isfinite(tmin):
+        tmin = times[0]
+    if not np.isfinite(tmax):
+        tmax = times[-1]
     if sfreq is not None:
         # Push to nearest sample first
-        if np.isfinite(tmin):
-            tmin = round(tmin * sfreq) / sfreq
-        else:
-            tmin = times[0]
-        if np.isfinite(tmax):
-            tmax = round(tmax * sfreq) / sfreq
-        else:
-            tmax = times[-1]
+        tmin = round(tmin * sfreq) / sfreq
+        tmax = round(tmax * sfreq) / sfreq
     deltas = np.abs(times - tmax)  # Find nearest times
     tmax = times[np.where(deltas == deltas.min())[0]][-1]
     deltas = np.abs(times - tmin)


Test patch:
diff --git a/mne/tests/test_utils.py b/mne/tests/test_utils.py
--- a/mne/tests/test_utils.py
+++ b/mne/tests/test_utils.py
@@ -511,6 +511,10 @@ def test_time_mask():
     x = np.arange(N).astype(float)
     assert_equal(_time_mask(x, 0, N - 1).sum(), N)
     assert_equal(_time_mask(x - 1e-10, 0, N - 1).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, N - 1).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, None).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, -np.inf, None).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, np.inf).sum(), N)
 
 
 def test_random_permutation():
Repository: mne-tools/mne-python

Issue:
plot_evoked_topomap use _time_mask
When figuring out which time points to plot, a straight comparison 

```
evoked.times >= t_desired
```

is used. This is not rounding-safe: if `t_desired` happens to be the last sample in `evoked.times` AND there's rounding error making the result an empty list.

Fix (now actually working) proposed in #2895 



Discussion:

Resolving patch:
diff --git a/mne/viz/topomap.py b/mne/viz/topomap.py
--- a/mne/viz/topomap.py
+++ b/mne/viz/topomap.py
@@ -1168,7 +1168,10 @@ def plot_evoked_topomap(evoked, times="auto", ch_type=None, layout=None,
     fig = axes[0].get_figure()
     fig.subplots_adjust(left=w_frame, right=1 - w_frame, bottom=0,
                         top=1 - top_frame)
-    time_idx = [np.where(evoked.times >= t)[0][0] for t in times]
+    # find first index that's >= (to rounding error) to each time point
+    time_idx = [np.where(_time_mask(evoked.times, tmin=t,
+                         tmax=None, sfreq=evoked.info['sfreq']))[0][0]
+                for t in times]
 
     if proj is True and evoked.proj is not True:
         data = evoked.copy().apply_proj().data


Test patch:
Repository: mne-tools/mne-python

Issue:
Writing error
@Eric89GXL did you happen to check #2869 against the data segment I provided. After merging the fix worked for the missing channels during `maxwell_filter` but the writing process generates following trace for the trouble file as well as other...

> File "/home/ktavabi/Projects/mne-python/mne/utils.py", line 596, in verbose
> return function(args, *kwargs)
> File "/home/ktavabi/Projects/mne-python/mne/io/base.py", line 1284, in save
> drop_small_buffer, split_size, 0, None)
> File "/home/ktavabi/Projects/mne-python/mne/io/base.py", line 1942, in _write_raw
> reset_range)
> File "/home/ktavabi/Projects/mne-python/mne/io/base.py", line 2085, in _start_writing_raw
> write_meas_info(fid, info, data_type=data_type, reset_range=reset_range)
> File "/home/ktavabi/Projects/mne-python/mne/io/meas_info.py", line 1248, in write_meas_info
> write_ch_info(fid, c)
> File "/home/ktavabi/Projects/mne-python/mne/io/write.py", line 325, in write_ch_info
> fid.write(np.array(ch['loc'], dtype='>f4').tostring()) # writing 12 values
> KeyError: 'loc'



Discussion:

Resolving patch:
diff --git a/mne/preprocessing/maxwell.py b/mne/preprocessing/maxwell.py
--- a/mne/preprocessing/maxwell.py
+++ b/mne/preprocessing/maxwell.py
@@ -620,7 +620,7 @@ def _copy_preload_add_channels(raw, add_channels):
             dict(ch_name='CHPI%03d' % (ii + 1), logno=ii + 1,
                  scanno=off + ii + 1, unit_mul=-1, range=1., unit=-1,
                  kind=kinds[ii], coord_frame=FIFF.FIFFV_COORD_UNKNOWN,
-                 cal=1. / 10000., coil_type=FIFF.FWD_COIL_UNKNOWN)
+                 cal=1e-4, coil_type=FIFF.FWD_COIL_UNKNOWN, loc=np.zeros(12))
             for ii in range(len(kinds))]
         raw.info['chs'].extend(chpi_chs)
         raw.info._check_consistency()


Test patch:
diff --git a/mne/preprocessing/tests/test_maxwell.py b/mne/preprocessing/tests/test_maxwell.py
--- a/mne/preprocessing/tests/test_maxwell.py
+++ b/mne/preprocessing/tests/test_maxwell.py
@@ -106,6 +106,7 @@ def _assert_n_free(raw_sss, lower, upper=None):
 @testing.requires_testing_data
 def test_movement_compensation():
     """Test movement compensation"""
+    temp_dir = _TempDir()
     lims = (0, 4)
     with warnings.catch_warnings(record=True):  # maxshield
         raw = Raw(raw_fname, allow_maxshield=True, preload=True).crop(*lims)
@@ -118,6 +119,12 @@ def test_movement_compensation():
                              regularize=None, bad_condition='ignore')
     assert_meg_snr(raw_sss, Raw(sss_movecomp_fname).crop(*lims),
                    4.6, 12.4, chpi_med_tol=58)
+    # IO
+    temp_fname = op.join(temp_dir, 'test_raw_sss.fif')
+    raw_sss.save(temp_fname)
+    raw_sss = Raw(temp_fname)
+    assert_meg_snr(raw_sss, Raw(sss_movecomp_fname).crop(*lims),
+                   4.6, 12.4, chpi_med_tol=58)
 
     #
     # Movement compensation,    regularization, no tSSS
Repository: mne-tools/mne-python

Issue:
BUG: _time_mask does not work properly for non-uniformly spaced inputs
See:

``` Python
>>> from mne import _time_mask
>>> import numpy as np
>>> _time_mask(np.array([0.4]), tmin=1., sfreq=1000.)
array([ True], dtype=bool)
>>> _time_mask(np.array([0.4, 1]), tmin=1., sfreq=1000.)
array([False,  True], dtype=bool)
>>> _time_mask(np.array([0.4, 1]), tmin=0.5, sfreq=1000.)
array([ True,  True], dtype=bool)
```

@jaeilepp I think you wrote the `deltas.min()` stuff that causes this, can you fix it?



Discussion:
(in case it's not clear, the first and third cases are bugs, but the middle one is fine)


Resolving patch:
diff --git a/mne/utils.py b/mne/utils.py
--- a/mne/utils.py
+++ b/mne/utils.py
@@ -1928,13 +1928,10 @@ def _time_mask(times, tmin=None, tmax=None, sfreq=None):
     if not np.isfinite(tmax):
         tmax = times[-1]
     if sfreq is not None:
-        # Push to nearest sample first
-        tmin = round(tmin * sfreq) / sfreq
-        tmax = round(tmax * sfreq) / sfreq
-    deltas = np.abs(times - tmax)  # Find nearest times
-    tmax = times[np.where(deltas == deltas.min())[0]][-1]
-    deltas = np.abs(times - tmin)
-    tmin = times[np.where(deltas == deltas.min())[0]][-1]
+        # Push to a bit past the nearest sample boundary first
+        sfreq = float(sfreq)
+        tmin = int(round(tmin * sfreq)) / sfreq - 0.5 / sfreq
+        tmax = int(round(tmax * sfreq)) / sfreq + 0.5 / sfreq
     mask = (times >= tmin)
     mask &= (times <= tmax)
     return mask


Test patch:
diff --git a/mne/tests/test_utils.py b/mne/tests/test_utils.py
--- a/mne/tests/test_utils.py
+++ b/mne/tests/test_utils.py
@@ -510,11 +510,20 @@ def test_time_mask():
     N = 10
     x = np.arange(N).astype(float)
     assert_equal(_time_mask(x, 0, N - 1).sum(), N)
-    assert_equal(_time_mask(x - 1e-10, 0, N - 1).sum(), N)
-    assert_equal(_time_mask(x - 1e-10, None, N - 1).sum(), N)
-    assert_equal(_time_mask(x - 1e-10, None, None).sum(), N)
-    assert_equal(_time_mask(x - 1e-10, -np.inf, None).sum(), N)
-    assert_equal(_time_mask(x - 1e-10, None, np.inf).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, 0, N - 1, sfreq=1000.).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, N - 1, sfreq=1000.).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, None, sfreq=1000.).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, -np.inf, None, sfreq=1000.).sum(), N)
+    assert_equal(_time_mask(x - 1e-10, None, np.inf, sfreq=1000.).sum(), N)
+    # non-uniformly spaced inputs
+    x = np.array([4, 10])
+    assert_equal(_time_mask(x[:1], tmin=10, sfreq=1).sum(), 0)
+    assert_equal(_time_mask(x, tmin=10, sfreq=1).sum(), 1)
+    assert_equal(_time_mask(x, tmin=6, sfreq=1).sum(), 1)
+    assert_equal(_time_mask(x, tmin=5, sfreq=1).sum(), 1)
+    assert_equal(_time_mask(x, tmin=4.5001, sfreq=1).sum(), 1)
+    assert_equal(_time_mask(x, tmin=4.4999, sfreq=1).sum(), 2)
+    assert_equal(_time_mask(x, tmin=4, sfreq=1).sum(), 2)
 
 
 def test_random_permutation():
Repository: mne-tools/mne-python

Issue:
fixed warning message in set_channel_types() that caused KeyError whe…
…n unit_old was not a key in the _unit2human dict.



Discussion:
this is a fix for https://github.com/mne-tools/mne-python/issues/2878

Style should be fixed, and I added the unknown unit to the dict as you suggested. However I'm not sure about this behavior: in the example I presented in #2878, the unit type is 0, and this code would result in a unit type of '0' (with value '0') being added to the dictionary. As another commenter on the issue mentioned, the underlying file reader might be the cause of the weird unit. I had simply intended to make the warning message not cause an error...

what file reader did you use?

look up FIFF constants

We actually don't have a `_UNIT_` with value 0, so whatever converter wrote the FIF file wrote some unit type we don't understand. You should be able to add `0: 'unknown'` to the dict around line 182 to fix the problem. Can you try it?


Resolving patch:
diff --git a/mne/channels/channels.py b/mne/channels/channels.py
--- a/mne/channels/channels.py
+++ b/mne/channels/channels.py
@@ -286,6 +286,10 @@ def set_channel_types(self, mapping):
             _check_set(self.info['chs'][c_ind], self.info['projs'], ch_type)
             unit_old = self.info['chs'][c_ind]['unit']
             unit_new = _human2unit[ch_type]
+            if unit_old not in _unit2human:
+                raise ValueError("Channel '%s' has unknown unit (%s). Please "
+                                 "fix the measurement info of your data."
+                                 % (ch_name, unit_old))
             if unit_old != _human2unit[ch_type]:
                 warn("The unit for channel %s has changed from %s to %s."
                      % (ch_name, _unit2human[unit_old], _unit2human[unit_new]))


Test patch:
diff --git a/mne/channels/tests/test_channels.py b/mne/channels/tests/test_channels.py
--- a/mne/channels/tests/test_channels.py
+++ b/mne/channels/tests/test_channels.py
@@ -106,6 +106,11 @@ def test_set_channel_types():
         assert_true(info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_V)
         assert_true(info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_EEG)
 
+    # Test meaningful error when setting channel type with unknown unit
+    raw.info['chs'][0]['unit'] = 0.
+    ch_types = {raw.ch_names[0]: 'misc'}
+    assert_raises(ValueError, raw.set_channel_types, ch_types)
+
 
 def test_read_ch_connectivity():
     "Test reading channel connectivity templates"
Repository: mne-tools/mne-python

Issue:
Memory consumption / scipy fft
`time_frequency/plot_epochs_spectra.py` consumes over 2GB of memory. I tracked it down to  https://github.com/mne-tools/mne-python/blob/master/mne/time_frequency/multitaper.py#L440
Then I tried breaking it to parts so that one signal at a time is transformed. That reduced the memory consumption, but I noticed that the results are less smooth. Here are plots from `plot_epochs_spectra.py`
On master:
![figure_1-4](https://cloud.githubusercontent.com/assets/3456414/13422160/2b088a9c-df93-11e5-8219-11198b9b2d60.png)
One signal at a time:
![figure_1-1](https://cloud.githubusercontent.com/assets/3456414/13422168/339af94c-df93-11e5-978d-1777c185c95c.png)

Any idea what's going on?



Discussion:
open a PR so we can see the diff.

it does not seem obvious looking at your plots.


Resolving patch:
diff --git a/mne/time_frequency/multitaper.py b/mne/time_frequency/multitaper.py
--- a/mne/time_frequency/multitaper.py
+++ b/mne/time_frequency/multitaper.py
@@ -437,7 +437,13 @@ def _mt_spectra(x, dpss, sfreq, n_fft=None):
 
     # remove mean (do not use in-place subtraction as it may modify input x)
     x = x - np.mean(x, axis=-1)[:, np.newaxis]
-    x_mt = fftpack.fft(x[:, np.newaxis, :] * dpss, n=n_fft)
+
+    # The following is equivalent to this, but uses less memory:
+    # x_mt = fftpack.fft(x[:, np.newaxis, :] * dpss, n=n_fft)
+    n_tapers = dpss.shape[0] if dpss.ndim > 1 else 1
+    x_mt = np.zeros((len(x), n_tapers, n_fft), dtype=complex)
+    for idx, sig in enumerate(x):
+        x_mt[idx] = fftpack.fft(sig[np.newaxis, :] * dpss, n=n_fft)
 
     # only keep positive frequencies
     freqs = fftpack.fftfreq(n_fft, 1. / sfreq)


Test patch:
Repository: mne-tools/mne-python

Issue:
BUG in raw.save
If you are saving a file that gets split into two, and if you have a period in the name of your file before the extension, then there will be an incorrect filename parsing.
e.g. `A0106_OLDT_calm_iir_hp0.51_lp40_filt-raw.fif` and its extension `A0106_OLDT_calm_iir_hp0-1.51_lp40_filt-raw.fif`. I will see if I can find the corresponding line of code to be addressed



Discussion:

Resolving patch:
diff --git a/mne/io/base.py b/mne/io/base.py
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -1925,10 +1925,8 @@ def _write_raw(fname, raw, info, picks, fmt, data_type, reset_range, start,
 
     if part_idx > 0:
         # insert index in filename
-        path, base = op.split(fname)
-        idx = base.find('.')
-        use_fname = op.join(path, '%s-%d.%s' % (base[:idx], part_idx,
-                                                base[idx + 1:]))
+        base, ext = op.splitext(fname)
+        use_fname = '%s-%d%s' % (base, part_idx, ext)
     else:
         use_fname = fname
     logger.info('Writing %s' % use_fname)


Test patch:
Repository: mne-tools/mne-python

Issue:
Timing error 
@Eric89GXL what is `_time_mask` in #2927 doing? I am on commit e1b90ef13a and still hitting this for a case where chpi T0 is 22 and first sample offset is 23, and another case for the comparison 20.8330 < 20.8333 that is identical to initial problem.



Discussion:
Can you put the pos and raw file somewhere for me to look at?

@Eric89GXL were you able to access the files on Kasga? 

Uploaded two raw files to 

> kasga::/data01/kam/sandbox

Haven't had time to look for/at the files yet


Resolving patch:
diff --git a/mne/preprocessing/maxwell.py b/mne/preprocessing/maxwell.py
--- a/mne/preprocessing/maxwell.py
+++ b/mne/preprocessing/maxwell.py
@@ -686,7 +686,9 @@ def _check_pos(pos, head_frame, raw, st_fixed, sfreq):
     t_off = raw.first_samp / raw.info['sfreq']
     if not np.array_equal(t, np.unique(t)):
         raise ValueError('Time points must unique and in ascending order')
-    if not _time_mask(t, tmin=t_off, tmax=None, sfreq=sfreq).all():
+    # We need an extra 1e-3 (1 ms) here because MaxFilter outputs values
+    # only out to 3 decimal places
+    if not _time_mask(t, tmin=t_off - 1e-3, tmax=None, sfreq=sfreq).all():
         raise ValueError('Head position time points must be greater than '
                          'first sample offset, but found %0.4f < %0.4f'
                          % (t[0], t_off))


Test patch:
diff --git a/mne/preprocessing/tests/test_maxwell.py b/mne/preprocessing/tests/test_maxwell.py
--- a/mne/preprocessing/tests/test_maxwell.py
+++ b/mne/preprocessing/tests/test_maxwell.py
@@ -172,10 +172,10 @@ def test_movement_compensation():
     head_pos_bad[0, 0] = raw.first_samp / raw.info['sfreq'] - 1e-2
     assert_raises(ValueError, maxwell_filter, raw, head_pos=head_pos_bad)
     # make sure numerical error doesn't screw it up, though
-    head_pos_bad[0, 0] = raw.first_samp / raw.info['sfreq'] - 1e-4
+    head_pos_bad[0, 0] = raw.first_samp / raw.info['sfreq'] - 5e-4
     raw_sss_tweak = maxwell_filter(raw, head_pos=head_pos_bad,
                                    origin=mf_head_origin)
-    assert_meg_snr(raw_sss_tweak, raw_sss, 2., 10.)
+    assert_meg_snr(raw_sss_tweak, raw_sss, 2., 10., chpi_med_tol=11)
 
 
 @slow_test