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

Issue:
confliciting logic?
Hey there,

I wanted to see with you if I'm missing something when running a spatio_temporal_cluster_test with tail=-1 and tfce thresholds. 

It seems that with tail=-1, one must use negative start and step tfce values:
https://github.com/mne-tools/mne-python/blob/966e862b95861de47ffe259bd66c86feece524f6/mne/stats/cluster_level.py#L301-L306

When doing so, the check if thresholds are monotonic fails.
https://github.com/mne-tools/mne-python/blob/966e862b95861de47ffe259bd66c86feece524f6/mne/stats/cluster_level.py#L335-L336
Should this check be for absolute values?


Discussion:
This does seem like a bug. The check should probably be for `< 0` for the case where `tail=-1` and `> 0` (what's there now) otherwise. PR welcome
Wouldn't it make more sense to require the `start` and `step` values to be always positive? Why should I need to change them just because I want to do a left-tailed test?

Resolving patch:
diff --git a/mne/stats/cluster_level.py b/mne/stats/cluster_level.py
--- a/mne/stats/cluster_level.py
+++ b/mne/stats/cluster_level.py
@@ -332,9 +332,10 @@ def _find_clusters(x, threshold, tail=0, connectivity=None, max_step=1,
     if include is None:
         include = np.ones(x.shape, dtype=bool)
 
-    if not np.all(np.diff(thresholds) > 0):
-        raise RuntimeError('Threshold misconfiguration, must be monotonically'
-                           ' increasing')
+    if tail in [0, 1] and not np.all(np.diff(thresholds) > 0):
+        raise ValueError('Thresholds must be monotonically increasing')
+    if tail == -1 and not np.all(np.diff(thresholds) < 0):
+        raise ValueError('Thresholds must be monotonically decreasing')
 
     # set these here just in case thresholds == []
     clusters = list()


Test patch:
diff --git a/mne/stats/tests/test_cluster_level.py b/mne/stats/tests/test_cluster_level.py
--- a/mne/stats/tests/test_cluster_level.py
+++ b/mne/stats/tests/test_cluster_level.py
@@ -516,4 +516,20 @@ def test_permutation_test_H0():
         assert_equal(len(h0), 2 ** (7 - (tail == 0)))  # exact test
 
 
+def test_tfce_thresholds():
+    rng = np.random.RandomState(0)
+    data = rng.randn(7, 10, 1) - 0.5
+
+    # if tail==-1, step must also be negative
+    assert_raises(ValueError, permutation_cluster_1samp_test, data, tail=-1,
+                  threshold=dict(start=0, step=0.1))
+    # this works (smoke test)
+    permutation_cluster_1samp_test(data, tail=-1,
+                                   threshold=dict(start=0, step=-0.1))
+
+    # thresholds must be monotonically increasing
+    assert_raises(ValueError, permutation_cluster_1samp_test, data, tail=1,
+                  threshold=dict(start=1, step=-0.5))
+
+
 run_tests_if_main()
Repository: mne-tools/mne-python

Issue:
BUG plot_alignment doesn't use `-head.fif` even when exists
Using the default `surfaces` parameter (`'head'`), `plot_alignment` 

```python
mne.viz.plot_alignment(info=fake_info, trans=trans, subject=subject, dig=True,
                       meg=False, src=src, subjects_dir=subjects_dir,
                       surfaces='head')
```

raises an

```python
IOError: No head surface found for subject fsaverage after trying:
/Users/cjb/tmp/subs_dir/fsaverage/bem/outer_skin.surf
/Users/cjb/tmp/subs_dir/fsaverage/bem/flash/outer_skin.surf
```

even though `-head.fif` exists in `bem`. I think there's a simple PR for this...

Context: ran into this when replying to a mail on the list, don't often deal with subjects for which `outer_skin` doesn't exist at this stage of analysis.


Discussion:

Resolving patch:
diff --git a/mne/viz/_3d.py b/mne/viz/_3d.py
--- a/mne/viz/_3d.py
+++ b/mne/viz/_3d.py
@@ -694,6 +694,8 @@ def plot_alignment(info, trans=None, subject=None, subjects_dir=None,
                         op.join(subject_dir, 'bem', 'outer_skin.surf'),
                         op.join(subject_dir, 'bem', 'flash',
                                 'outer_skin.surf'),
+                        op.join(subject_dir, 'bem', '%s-head.fif'
+                                % subject),
                     ]
                 for fname in try_fnames:
                     if op.exists(fname):


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

Issue:
Is scikit-learn required for ICA?
When creating an `ICA` object, I get the following error if scikit-learn is not installed:

    RuntimeError: the scikit-learn package (version >= 0.12)is required for ICA

I think MNE's ICA implementation uses the `FastICA` class from scikit-learn, but AFAIK it ships its own (Extended) Infomax algorithm, in which case scikit-learn should not be required.


Discussion:
Also, there's a space missing in this error message. And the main README says that scikit-learn >= 0.18 is required - which version is it?
>  AFAIK it ships its own (Extended) Infomax algorithm, in which case scikit-learn should not be required.

We also use randomized PCA from `sklearn` for dimensionality reduction and whitening.

> the main README says that scikit-learn >= 0.18 is required - which version is it?

I think the error message is old and should be updated to say 0.18

Resolving patch:
diff --git a/mne/preprocessing/ica.py b/mne/preprocessing/ica.py
--- a/mne/preprocessing/ica.py
+++ b/mne/preprocessing/ica.py
@@ -243,8 +243,8 @@ def __init__(self, n_components=None, max_pca_components=None,
         if method not in methods:
             raise ValueError('`method` must be "%s". You passed: "%s"' %
                              ('" or "'.join(methods), method))
-        if not check_version('sklearn', '0.12'):
-            raise RuntimeError('the scikit-learn package (version >= 0.12)'
+        if not check_version('sklearn', '0.15'):
+            raise RuntimeError('the scikit-learn package (version >= 0.15) '
                                'is required for ICA')
 
         self.noise_cov = noise_cov


Test patch:
diff --git a/mne/decoding/tests/test_transformer.py b/mne/decoding/tests/test_transformer.py
--- a/mne/decoding/tests/test_transformer.py
+++ b/mne/decoding/tests/test_transformer.py
@@ -177,7 +177,7 @@ def test_vectorizer():
                   np.random.rand(102, 12, 12))
 
 
-@requires_version('sklearn', '0.15')
+@requires_version('sklearn', '0.16')
 def test_unsupervised_spatial_filter():
     """Test unsupervised spatial filter."""
     from sklearn.decomposition import PCA
Repository: mne-tools/mne-python

Issue:
Traces in `raw.plot_psd(average=False)` are too faint
The output of `raw.plot_psd(average=False)` currently looks like this:
![psd_current](https://user-images.githubusercontent.com/4377312/33481439-bf2c699c-d694-11e7-913f-1229336055f6.png)

The alpha level is 0.1, which IMO is way to low. I propose changing this value to 0.75, which results in the following much improved output:
![psd_075](https://user-images.githubusercontent.com/4377312/33481452-d6b0466a-d694-11e7-80e5-d7860b855cf9.png)

Or am I missing the reason for setting such a low alpha value?


Discussion:

Resolving patch:
diff --git a/mne/viz/raw.py b/mne/viz/raw.py
--- a/mne/viz/raw.py
+++ b/mne/viz/raw.py
@@ -723,7 +723,7 @@ def plot_raw_psd(raw, tmin=0., tmax=np.inf, fmin=0, fmax=np.inf, proj=False,
         make_label = _set_psd_plot_params(raw.info, proj, picks, ax, area_mode)
     del ax
     if line_alpha is None:
-        line_alpha = 1.0 if average else 0.1
+        line_alpha = 1.0 if average else 0.75
     line_alpha = float(line_alpha)
 
     psd_list = list()


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

Issue:
BUG: default epochs events does not work with list
works:

```python
import numpy as np
epo = mne.Epochs(mne.io.RawArray(np.random.randn(10, 1000),
                                 mne.create_info(10, 1000.)),
                 events=np.array([[100, 0, 1], [200, 0, 1], [300, 0, 1]]))
```


does not work:
```python
import numpy as np
epo = mne.Epochs(mne.io.RawArray(np.random.randn(10, 1000),
                                 mne.create_info(10, 1000.)),
                 events=[[100, 0, 1], [200, 0, 1], [300, 0, 1]])
```

cc @larsoner 


Discussion:
Yes we should cast to `np.array(...)`, check the dtype and shape (raise error if incorrect), and cast to `int`. PR welcome
We actually convert to an array, but it happens later:

https://github.com/mne-tools/mne-python/blob/master/mne/epochs.py#L263

We could change this line:
`            event_id = list(np.unique(events[:, 2]))`
so that it works for arrays and lists, e.g. something like
`event_id = list({id for _, _, id in events})`

I don't think `events` will be large enough for this to become a problem.
We should just convert and check earlier, your suggested code will yield
less clear errors depending on input


Resolving patch:
diff --git a/mne/epochs.py b/mne/epochs.py
--- a/mne/epochs.py
+++ b/mne/epochs.py
@@ -239,6 +239,9 @@ def __init__(self, info, data, events, event_id=None, tmin=-0.2, tmax=0.5,
             raise ValueError('on_missing must be one of: error, '
                              'warning, ignore. Got: %s' % on_missing)
 
+        if events is not None:  # RtEpochs can have events=None
+            events = np.asarray(events)
+
         # check out event_id dict
         if event_id is None:  # convert to int to make typing-checks happy
             event_id = list(np.unique(events[:, 2]))
@@ -260,7 +263,6 @@ def __init__(self, info, data, events, event_id=None, tmin=-0.2, tmax=0.5,
         del event_id
 
         if events is not None:  # RtEpochs can have events=None
-            events = np.asarray(events)
             if events.dtype.kind not in ['i', 'u']:
                 raise ValueError('events must be an array of type int')
             events = events.astype(int)


Test patch:
diff --git a/mne/tests/test_epochs.py b/mne/tests/test_epochs.py
--- a/mne/tests/test_epochs.py
+++ b/mne/tests/test_epochs.py
@@ -2346,4 +2346,12 @@ def assert_metadata_equal(got, exp):
         assert check.all().all()
 
 
+def test_events_list():
+    """Test that events can be a list."""
+    events = [[100, 0, 1], [200, 0, 1], [300, 0, 1]]
+    epochs = mne.Epochs(mne.io.RawArray(np.random.randn(10, 1000),
+                                        mne.create_info(10, 1000.)),
+                        events=events)
+    assert_array_equal(epochs.events, np.array(events))
+
 run_tests_if_main()
Repository: mne-tools/mne-python

Issue:
[ENH] [Doc] Annotations onset 
Based on the documentation, it is unclear if onsets are expressed in seconds or samples (or anything else).

```
Parameters
----------
onset : array of float, shape (n_annotations,)
    Annotation time onsets relative to the ``orig_time``, the starting time
    of annotation acquisition.

```


Discussion:
Indeed, the documentation fails to say that onset should be in seconds.
Ill do PR.
go for it !

Resolving patch:
diff --git a/mne/annotations.py b/mne/annotations.py
--- a/mne/annotations.py
+++ b/mne/annotations.py
@@ -40,8 +40,7 @@ class Annotations(object):
     Parameters
     ----------
     onset : array of float, shape (n_annotations,)
-        Annotation time onsets relative to the ``orig_time``, the starting time
-        of annotation acquisition.
+        The starting time of annotations in seconds after ``orig_time``.
     duration : array of float, shape (n_annotations,)
         Durations of the annotations in seconds.
     description : array of str, shape (n_annotations,) | str


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

Issue:
Improve sEEG visualization when plotting
The following code moocs a raw object to contain `sEEG` data, plots it and generate the figure below:

```py
def get_seeg_dummy_data(n_seeg_channels=5):
    from mne.datasets.testing import data_path
    from mne.io import read_raw_fif
    import os.path as op

    data_dir = op.join(data_path(download=False), 'MEG', 'sample')
    fif_fname = op.join(data_dir, 'sample_audvis_trunc_raw.fif')
    raw = read_raw_fif(fif_fname, verbose=0)
    seeg_channels = dict(zip(raw.ch_names[-n_seeg_channels:],['seeg']*n_seeg_channels))
    raw.info['projs'] = []
    raw.set_channel_types(seeg_channels)

    return raw

xx = get_seeg_dummy_data()
xx.plot()
```
![image](https://user-images.githubusercontent.com/7044835/35642441-6b9129a8-06c3-11e8-8eb8-49713bc8119f.png)

On it, the scale and the legend color of the signals seem off.

cc: @mathurinm, @makkostya, @annesodub


Discussion:
the color I would suggest is : red:0.50 green:0.25 blue:0.00


Resolving patch:
diff --git a/mne/defaults.py b/mne/defaults.py
--- a/mne/defaults.py
+++ b/mne/defaults.py
@@ -9,8 +9,8 @@
 DEFAULTS = dict(
     color=dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m', emg='k',
                ref_meg='steelblue', misc='k', stim='k', resp='k', chpi='k',
-               exci='k', ias='k', syst='k', seeg='k', dipole='k', gof='k',
-               bio='k', ecog='k', hbo='darkblue', hbr='b'),
+               exci='k', ias='k', syst='k', seeg='saddlebrown', dipole='k',
+               gof='k', bio='k', ecog='k', hbo='darkblue', hbr='b'),
     units=dict(eeg='uV', grad='fT/cm', mag='fT', eog='uV', misc='AU',
                seeg='uV', dipole='nAm', gof='GOF', emg='uV', ecg='uV',
                bio='uV', ecog='uV', hbo='uM', hbr='uM'),
@@ -20,7 +20,7 @@
     scalings_plot_raw=dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6,
                            ecg=5e-4, emg=1e-3, ref_meg=1e-12, misc=1e-3,
                            stim=1, resp=1, chpi=1e-4, exci=1, ias=1, syst=1,
-                           seeg=1e-5, bio=1e-6, ecog=1e-4, hbo=10e-6,
+                           seeg=1e-4, bio=1e-6, ecog=1e-4, hbo=10e-6,
                            hbr=10e-6),
     scalings_cov_rank=dict(mag=1e12, grad=1e11, eeg=1e5),
     ylim=dict(mag=(-600., 600.), grad=(-200., 200.), eeg=(-200., 200.),


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

Issue:
plot_compared_evokeds show_sensors & show_legend
Hello, this is the first time I am submitting an issue to git. I noticed that in the dev version, if I try to specify values (False or an int) for show_sensors & show_legend, they do not get taken into account. They just always get plotted in the bottom of the figure (legend on left and sensors on the right). Could this be checked?

Thank you!
Anja


Discussion:
Could you paste a smal code example that reproduces the problem?
Hey, sorry for the delay. Here is an example using the MNE sample data and code and the development version:

```
import os.path as op
import mne

data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evoked = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
print(evoked)
evoked_l_aud = evoked[0]
evoked_r_aud = evoked[1]
evoked_l_vis = evoked[2]
evoked_r_vis = evoked[3]

conditions = ["Left Auditory", "Right Auditory", "Left visual", "Right visual"]
evoked_dict = dict()
for condition in conditions:
    evoked_dict[condition.replace(" ", "/")] = mne.read_evokeds(
        fname, baseline=(None, 0), proj=True, condition=condition)
print(evoked_dict)

colors = dict(Left="Crimson", Right="CornFlowerBlue")
linestyles = dict(Auditory='-', visual='--')
pick = evoked_dict["Left/Auditory"].ch_names.index('MEG 1811')
show_sensors=1
show_legend=2

mne.viz.plot_compare_evokeds(evoked_dict, picks=pick, colors=colors,
                             linestyles=linestyles, show_sensors=show_sensors, show_legend=show_legend)
```
It gives the following figure output: https://helsinkifi-my.sharepoint.com/:i:/g/personal/thiede_ad_helsinki_fi/EU4tyVpXmhROhE11EFSowBAB3cqHHNjMd7WQW13IkZ1RIg?e=KY4eUF

So, now the legend and sensors get plotted (and also they do not get plotted when their value is False), but the sensors should be in a different location (right top corner).

Thank you for checking this out!
Anja
what makes you think it's in the wrong place. If you do:

evoked[0].plot_sensors(show_names=True)

you see that 'MEG 1811' is on the center a bit left.


Resolving patch:
diff --git a/mne/viz/evoked.py b/mne/viz/evoked.py
--- a/mne/viz/evoked.py
+++ b/mne/viz/evoked.py
@@ -1462,10 +1462,12 @@ def pair_and_combine(data):
 def _check_loc_legal(loc, what='your choice'):
     """Check if loc is a legal location for MPL subordinate axes."""
     true_default = {"show_legend": 3, "show_sensors": 4}.get(what, 1)
+    if isinstance(loc, bool) and loc:
+        loc = true_default
     loc_dict = {'upper right': 1, 'upper left': 2, 'lower left': 3,
                 'lower right': 4, 'right': 5, 'center left': 6,
                 'center right': 7, 'lower center': 8, 'upper center': 9,
-                'center': 10, True: true_default}
+                'center': 10}
     loc_ = loc_dict.get(loc, loc)
     if loc_ not in range(11):
         raise ValueError(str(loc) + " is not a legal MPL loc, please supply"


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

Issue:
Link to github gist is broken (404) in .resample method doc
https://github.com/mne-tools/mne-python/blob/e84b316cb188043c69a4958b74884bfb556d78d8/mne/io/base.py#L1410-L1411



Discussion:
it should be : https://gist.github.com/larsoner/01642cb3789992fbca59

PR welcome


Resolving patch:
diff --git a/mne/io/base.py b/mne/io/base.py
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -1408,7 +1408,7 @@ def resample(self, sfreq, npad='auto', window='boxcar', stim_picks=None,
                      but instead epoch and then downsample, as epoching
                      downsampled data jitters triggers.
                      For more, see
-                     `this illustrative gist <https://gist.github.com/Eric89GXL/01642cb3789992fbca59>`_.
+                     `this illustrative gist <https://gist.github.com/larsoner/01642cb3789992fbca59>`_.
 
                      If resampling the continuous data is desired, it is
                      recommended to construct events using the original data.


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

Issue:
pns_idx referenced before assignment, raw.plot_psd()

Hi,

I'm reading in EGI mff data with an ECG lead.  When I try to raw.plot_psd() I get the following error

/mne-python/mne/io/egi/egimff.py in _read_segment_file(self, data, idx, fi, start, stop, cals, mult)
    571                     s_end = s_start + samples_read
    572 
--> 573                     data_view = data[n_data1_channels:, s_start:s_end]
    574                     _mult_cal_one(data_view, block_data[:n_pns_channels],
    575                                   pns_idx,

UnboundLocalError: local variable 'pns_idx' referenced before assignment

I can make the plot if after I:
del raw._raw_extras[0]['pns_names']

because that's the variable whose length is checked in that case, however this is likely not the best solution.


Discussion:
Is it easy for you share a small file that we can use to reproduce locally?
Attached is a smallish file.

raw = mne.io.read_raw_egi('_20170725_094007_mrr_qrs_obs.mff')
raw.plot_psd()

should reproduce the error (in '0.15.dev0').  The actual cap only has 128 channels so 129 is 'dead', still tracking down why the EGI file comes out that way...  There are 4 'stim' channels that show up too, which were originally events...

(what is the best way to debug these modules? I have a few other things I'm interested in adding but my print statement additions and module reload as a quick check to see what's happening don't seem to work... will try pdb next..) 

Thanks.

[test_data.zip](https://github.com/mne-tools/mne-python/files/1408795/test_data.zip)



> will try pdb next.

This is how I usually do it. You can use an IDE to set debug points, or if/when you hit an error do post-mortem debugging with `import pdb; pdb.pm()`
So I think the bug is on ~line 518 in egimff.py.  The pns data is read regardless of whether it is required ( or in chs_to_read => pns_chans is empty and pns_idx doesn't get assigned. )  Adding the check for len(pns_idx) (or just using that as the switch) on this line should fix things - at least it does for me in this instance.

if 'pns_names' in egi_info and len(pns_chans) > 0: 


That fix sounds reasonable to me, can you make a PR to fix it?

Resolving patch:
diff --git a/mne/io/egi/egimff.py b/mne/io/egi/egimff.py
--- a/mne/io/egi/egimff.py
+++ b/mne/io/egi/egimff.py
@@ -466,6 +466,7 @@ def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
                 pns_idx = idx[pns_chans] - n_eeg_channels
         else:
             eeg_idx = idx
+            pns_idx = []
 
         with open(self._filenames[fi], 'rb', buffering=0) as fid:
             # Go to starting block


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

Issue:
[RFC] crop behaviour
I was playing with crop and I found weird that based on this description the raw object gets modified:
```
Signature: reference_mne_data.crop(tmin=0.0, tmax=None)
Docstring:
Crop raw data file.

Limit the data from the raw file to go between specific times. Note
that the new tmin is assumed to be t=0 for all subsequently called
functions (e.g., time_as_index, or Epochs). New first_samp and
last_samp are set accordingly.

Parameters
----------
tmin : float
    New start time in seconds (must be >= 0).
tmax : float | None
    New end time in seconds of the data (cannot exceed data duration).

Returns
-------
raw : instance of Raw
    The cropped raw object.
```

Then going through the snipped provided in #4697 I realized that I might not be the only one having issues with it. Take a look at the following user code:

```
old_raw = raw.copy()
new_raw = raw.copy().crop(raw.times[times_start[0]],
                          raw.times[times_end[0]])

for idx in range(1, len(times_start)):
    cropped_raw = raw.copy().crop(raw.times[times_start[idx]],
                                  raw.times[times_end[idx]])
    mne.concatenate_raws([new_raw, cropped_raw])
```
either `old_raw` or `raw.copy()` should be unnecessary. 

So do you think we should change crop behavior or it's better to leave it as it is to keep backward compatibility?


Discussion:
We can improve the documentation and make explicit that it returns self, that is the modified raw object. 
yes I think that this line:

old_raw = raw.copy()

is unnecessary. raw.crop indeed returns self.

Closing as addressed, feel free to reopen if I'm wrong @massich 
I don't think it is fixed no?


Resolving patch:
diff --git a/mne/io/base.py b/mne/io/base.py
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -1556,6 +1556,9 @@ def crop(self, tmin=0.0, tmax=None):
         functions (e.g., time_as_index, or Epochs). New first_samp and
         last_samp are set accordingly.
 
+        Thus function operates in-place on the instance.
+        Use :meth:`mne.Raw.copy` if operation on a copy is desired.
+
         Parameters
         ----------
         tmin : float
@@ -1566,7 +1569,7 @@ def crop(self, tmin=0.0, tmax=None):
         Returns
         -------
         raw : instance of Raw
-            The cropped raw object.
+            The cropped raw object, modified in-place.
         """
         max_time = (self.n_times - 1) / self.info['sfreq']
         if tmax is None:


Test patch: