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

Issue:
psd_welch default n_fft value 
I was wondering if this is the intended behaviour for the psd_welch function  

If you run psd_welch on data that has less than 256 time points you get the error message 

> raise ValueError(('If n_per_seg is None n_fft is not allowed to be > '
>                           'n_times. If you want zero-padding, you have to set '
>                           'n_per_seg to relevant length. Got n_fft of %d while'
>                           ' signal length is %d.') % (n_fft, n))

And, the docmentation says:

>     n_fft : int
>         The length of FFT used, must be ``>= n_per_seg`` (default: 256).
>         The segments will be zero-padded if ``n_fft > n_per_seg``.
>     n_per_seg : int | None
>         Length of each Welch segment. The smaller it is with respect to the
>         signal length the smoother are the PSDs. Defaults to None, which sets
>         n_per_seg equal to n_fft.

To me the two solutions seem to be:
- specifying in the documentation that n_fft also has to be <= n_times 
or
- default the n_fft value to n_times 

Thanks!


Discussion:
+1 for :

> specifying in the documentation that n_fft also has to be <= n_times


Resolving patch:
diff --git a/mne/time_frequency/psd.py b/mne/time_frequency/psd.py
--- a/mne/time_frequency/psd.py
+++ b/mne/time_frequency/psd.py
@@ -157,6 +157,8 @@ def psd_welch(inst, fmin=0, fmax=np.inf, tmin=None, tmax=None, n_fft=256,
     n_fft : int
         The length of FFT used, must be ``>= n_per_seg`` (default: 256).
         The segments will be zero-padded if ``n_fft > n_per_seg``.
+        If n_per_seg is None, n_fft must be >= number of time points
+        in the data.
     n_overlap : int
         The number of points of overlap between segments. Will be adjusted
         to be <= n_per_seg. The default value is 0.


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

Issue:
CSD channel names are not read correctly.
I was playing around with the CSD file montages and using the CSD Toolbox lookup table with an ActiChamp EEG. Apparently, "TPP10h" is a standard position. Following that, I found out that the `read_montage` function was not prepared to handle those names out of a .CSD file. It as only parsing 4 chars, thus reading "TPP1".

PR is coming.


Discussion:

Resolving patch:
diff --git a/mne/channels/montage.py b/mne/channels/montage.py
--- a/mne/channels/montage.py
+++ b/mne/channels/montage.py
@@ -247,16 +247,14 @@ def read_montage(kind, ch_names=None, path=None, unit='m', transform=False):
         pos = _sph_to_cart(np.array([np.ones(len(az)) * 85., az, pol]).T)
     elif ext == '.csd':
         # CSD toolbox
-        dtype = [('label', 'S4'), ('theta', 'f8'), ('phi', 'f8'),
-                 ('radius', 'f8'), ('x', 'f8'), ('y', 'f8'), ('z', 'f8'),
-                 ('off_sph', 'f8')]
         try:  # newer version
-            table = np.loadtxt(fname, skip_header=2, dtype=dtype)
+            data = np.genfromtxt(fname, dtype='str', skip_header=2)
         except TypeError:
-            table = np.loadtxt(fname, skiprows=2, dtype=dtype)
-        ch_names_ = table['label']
-        az = np.deg2rad(table['theta'])
-        pol = np.deg2rad(90. - table['phi'])
+            data = np.genfromtxt(fname, dtype='str', skiprows=2)
+
+        ch_names_ = list(data[:, 0])
+        az = np.deg2rad(data[:, 1].astype(float))
+        pol = np.deg2rad(90. - data[:, 2].astype(float))
         pos = _sph_to_cart(np.array([np.ones(len(az)), az, pol]).T)
     elif ext == '.elp':
         # standard BESA spherical


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

Issue:
Remove deprecated imp module
Currently, `mne/commands/utils.py` still uses the deprecated `imp` module, which has long been replaced with `importlib`. According to [this answer on SO](https://stackoverflow.com/a/67692/1112283), the current solution works only on Python 3.5/3.6, and there is a (deprecated) alternative for Python 3.3/3.4. All versions < 3.3 need to use `imp`.

How should this be handled in MNE?


Discussion:
can you send a PR that uses importlib on recent python and imp otherwise?


Resolving patch:
diff --git a/mne/commands/utils.py b/mne/commands/utils.py
--- a/mne/commands/utils.py
+++ b/mne/commands/utils.py
@@ -4,7 +4,7 @@
 #
 # License: BSD (3-clause)
 
-import imp
+import sys
 import os
 import re
 from optparse import OptionParser
@@ -12,6 +12,42 @@
 import mne
 
 
+def load_module(name, path):
+    """Load module from .py/.pyc file.
+
+    Parameters
+    ----------
+    name : str
+        Name of the module.
+    path : str
+        Path to .py/.pyc file.
+
+    Returns
+    -------
+    mod : module
+        Imported module.
+    """
+    if sys.version_info < (3, 3):
+        import imp
+        if path.endswith('.pyc'):
+            return imp.load_compiled(name, path)
+        else:
+            return imp.load_source(name, path)
+    elif sys.version_info < (3, 5):
+        if path.endswith('.pyc'):
+            from importlib.machinery import SourcelessFileLoader
+            return SourcelessFileLoader(name, path).load_module()
+        else:
+            from importlib.machinery import SourceFileLoader
+            return SourceFileLoader(name, path).load_module()
+    else:  # Python 3.5 or greater
+        from importlib.util import spec_from_file_location, module_from_spec
+        spec = spec_from_file_location(name, path)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+
 def get_optparser(cmdpath, usage=None):
     """Create OptionParser with cmd specific settings (e.g. prog value)."""
     command = os.path.basename(cmdpath)
@@ -21,10 +57,7 @@ def get_optparser(cmdpath, usage=None):
         command = command[4:-4]
 
     # Fetch description
-    if cmdpath.endswith('.pyc'):
-        mod = imp.load_compiled('__temp', cmdpath)
-    else:
-        mod = imp.load_source('__temp', cmdpath)
+    mod = load_module('__temp', cmdpath)
     if mod.__doc__:
         doc, description, epilog = mod.__doc__, None, None
 


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

Issue:
BUG: tutorials/plot_artifacts_correction_ica.py is broken on Python3.6
As reported in #4388. We need to make `int` (possibly NumPy int) inputs work on Python3.6 in `ica.fit`.


Discussion:

Resolving patch:
diff --git a/mne/preprocessing/ica.py b/mne/preprocessing/ica.py
--- a/mne/preprocessing/ica.py
+++ b/mne/preprocessing/ica.py
@@ -46,7 +46,7 @@
 from ..io.write import start_file, end_file, write_id
 from ..utils import (check_version, logger, check_fname, verbose,
                      _reject_data_segments, check_random_state,
-                     compute_corr, _get_inst_data,
+                     compute_corr, _get_inst_data, _ensure_int,
                      copy_function_doc_to_method_doc, _pl, warn)
 
 from ..fixes import _get_args
@@ -1560,8 +1560,16 @@ def _check_n_pca_components(self, _n_pca_comp, verbose=None):
 
 def _check_start_stop(raw, start, stop):
     """Aux function."""
-    return [c if (isinstance(c, int) or c is None) else
-            raw.time_as_index(c)[0] for c in (start, stop)]
+    out = list()
+    for st in (start, stop):
+        if st is None:
+            out.append(st)
+        else:
+            try:
+                out.append(_ensure_int(st))
+            except TypeError:  # not int-like
+                out.append(raw.time_as_index(st)[0])
+    return out
 
 
 @verbose
diff --git a/mne/utils.py b/mne/utils.py
--- a/mne/utils.py
+++ b/mne/utils.py
@@ -76,7 +76,7 @@ def nottest(f):
 # RANDOM UTILITIES
 
 
-def _ensure_int(x, name, must_be='an int'):
+def _ensure_int(x, name='unknown', must_be='an int'):
     """Ensure a variable is an integer."""
     # This is preferred over numbers.Integral, see:
     # https://github.com/scipy/scipy/pull/7351#issuecomment-299713159


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

Issue:
find_ch_connectivity doesn't find EEG templates
It looks like `mne.channels.find_ch_connectivity` only searches for MEG template files. This means that it doesn't work for EEG montages such as e.g. "biosemi64", even though a template exists. I think a note should be added in the docstring to clarify this behavior. Also, the note in `mne.channels.read_ch_connectivity` should be changed. Ideally, a good separation of the two functions is that `read_ch_connectivity` reads from template files whereas `find_ch_connectivity` computes connectivity.


Discussion:
PR welcome

OK - I guess clarifying the docstrings is sufficient (the other alternative would be to add support for automatic detection of EEG montages).
if you think the automatic way can have a low enough failure mode sure why
not.


Resolving patch:
diff --git a/mne/channels/channels.py b/mne/channels/channels.py
--- a/mne/channels/channels.py
+++ b/mne/channels/channels.py
@@ -947,8 +947,8 @@ def _recursive_flatten(cell, dtype):
 def read_ch_connectivity(fname, picks=None):
     """Parse FieldTrip neighbors .mat file.
 
-    More information on these neighbor definitions can be found on the
-    related FieldTrip documentation pages:
+    More information on these neighbor definitions can be found on the related
+    FieldTrip documentation pages:
     http://fieldtrip.fcdonders.nl/template/neighbours
 
     Parameters
@@ -973,9 +973,10 @@ def read_ch_connectivity(fname, picks=None):
 
     Notes
     -----
-    This function is closely related to ``find_ch_connectivity``. In case you
-    don't know the correct file for the neighbor definitions, the use of
-    ``find_ch_connectivity`` is preferred.
+    This function is closely related to :func:`find_ch_connectivity`. If you
+    don't know the correct file for the neighbor definitions,
+    :func:`find_ch_connectivity` can compute the connectivity matrix from 2d
+    sensor locations.
     """
     from scipy.io import loadmat
     if not op.isabs(fname):
@@ -1081,6 +1082,11 @@ def find_ch_connectivity(info, ch_type):
     Notes
     -----
     .. versionadded:: 0.15
+    Automatic detection of an appropriate connectivity matrix template only
+    works for MEG data at the moment. This means that the connectivity matrix
+    is always computed for EEG data and never loaded from a template file. If
+    you want to load a template for a given montage use
+    :func:`read_ch_connectivity` directly.
     """
     if ch_type is None:
         picks = channel_indices_by_type(info)


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

Issue:
UserWarning in decoding_rsa example
Running this example, I get the following warning 
    
    decoding_rsa.py:94: RuntimeWarning: More events than colors available. You should pass a list of unique colors.


Discussion:
That's ok I would say. It comes from `plot_events`, and it will happen in many designs because there simply aren't that many distinguishable colours. It's only a warning after all.

Reopen if you disagree.
We should avoid warnings in examples wherever possible. I'd rather we fix
it by doing whatever we would like our users to do in this situation.

+1

remove plot_events, it's unnecessary?
@kingjr can you make a quick PR?
Hello, this still seems to be an issue, and I was wondering if I could help? If the fix is to remove plot_events I can do that in a quick pull request. 
+1 for removing it
go for it


Resolving patch:
diff --git a/examples/decoding/decoding_rsa.py b/examples/decoding/decoding_rsa.py
--- a/examples/decoding/decoding_rsa.py
+++ b/examples/decoding/decoding_rsa.py
@@ -97,7 +97,6 @@
 events = mne.find_events(raw, min_duration=.002)
 
 events = events[events[:, 2] <= max_trigger]
-mne.viz.plot_events(events, sfreq=raw.info['sfreq'])
 
 ##############################################################################
 # Epoch data


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

Issue:
Exception when printing raw.info
Printing the `info` attribute of a raw object, using 5fac33d, throws the following exception:

```
Traceback (most recent call last):
  File "eeg.py", line 361, in <module>
    print(raw.info)
  File "/home/ajw/.local/mne-python/mne/io/meas_info.py", line 410, in __repr__
    entr = _stamp_to_dt(v).strftime('%Y-%m-%d %H:%M:%S') + ' GMT'
  File "/home/ajw/.local/mne-python/mne/io/meas_info.py", line 64, in _stamp_to_dt
    datetime.timedelta(0, 0, stamp[1]))  # day, sec, μs
IndexError: list index out of range
```
I can print the `info` if I go back to 0c0b8de2. I think the commit that causes the problem is e6fd505ef4e35089ab0b31d69fe371028c79cd53 (but I can't go back to that commit).

This is the `info` value:

```
<Info | 19 non-empty fields
    bads : list | 0 items
    buffer_size_sec : float64 | 1.0
    ch_names : list | Fp1, AF7, AF3, F1, F3, F5, F7, FT7, FC5, ...
    chs : list | 65 items (EEG: 64, STIM: 1)
    comps : list | 0 items
    custom_ref_applied : bool | False
    dev_head_t : Transform | 3 items
    events : list | 0 items
    file_id : dict | 4 items
    highpass : float | 0.5 Hz
    hpi_meas : list | 0 items
    hpi_results : list | 0 items
    lowpass : float | 30.0 Hz
    meas_date : ndarray | 2015-02-04 08:21:37
    meas_id : dict | 4 items
    nchan : int | 65
    proc_history : list | 0 items
    projs : list | 0 items
    sfreq : float | 150.0 Hz
    acq_pars : NoneType
    acq_stim : NoneType
    ctf_head_t : NoneType
    description : NoneType
    dev_ctf_t : NoneType
    dig : NoneType
    experimenter : NoneType
    hpi_subsystem : NoneType
    kit_system_id : NoneType
    line_freq : NoneType
    proj_id : NoneType
    proj_name : NoneType
    subject_info : NoneType
    xplotter_layout : NoneType
>

In case it matters, the original data is from a BDF file.





Discussion:
Can you `import pdb; pdb.pm()` to find out what the `info` entry is that is causing the problem? It's probably some malformed timestamp that we can make a fix for.

Resolving patch:
diff --git a/mne/io/meas_info.py b/mne/io/meas_info.py
--- a/mne/io/meas_info.py
+++ b/mne/io/meas_info.py
@@ -60,6 +60,8 @@ def _stamp_to_dt(stamp):
     """Convert timestamp to datetime object in Windows-friendly way."""
     # The min on windows is 86400
     stamp = [int(s) for s in stamp]
+    if len(stamp) == 1:  # In case there is no microseconds information
+        stamp.append(0)
     return (datetime.datetime.utcfromtimestamp(stamp[0]) +
             datetime.timedelta(0, 0, stamp[1]))  # day, sec, μs
 


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

Issue:
BUG: CircleCI 1.0 is retiring
We need to move to 2.0 by August.

We should also switch to using `environment.yml`, which means having a newer version of Mesa (the one of 14.04 is too old to support the necessary OpenGL extensions for VTK7+).


Discussion:

Resolving patch:
diff --git a/examples/datasets/plot_spm_faces_dataset.py b/examples/datasets/spm_faces_dataset.py
similarity index 100%
rename from examples/datasets/plot_spm_faces_dataset.py
rename to examples/datasets/spm_faces_dataset.py
diff --git a/examples/io/plot_objects_from_arrays.py b/examples/io/plot_objects_from_arrays.py
--- a/examples/io/plot_objects_from_arrays.py
+++ b/examples/io/plot_objects_from_arrays.py
@@ -137,7 +137,7 @@
 # The example here uses the ExampleIO object for creating fake data.
 # For actual data and different file formats, consult the NEO documentation.
 reader = neo.io.ExampleIO('fakedata.nof')
-bl = reader.read(cascade=True, lazy=False)[0]
+bl = reader.read(lazy=False)[0]
 
 # Get data from first (and only) segment
 seg = bl.segments[0]
diff --git a/tutorials/plot_stats_cluster_time_frequency_repeated_measures_anova.py b/tutorials/plot_stats_cluster_time_frequency_repeated_measures_anova.py
--- a/tutorials/plot_stats_cluster_time_frequency_repeated_measures_anova.py
+++ b/tutorials/plot_stats_cluster_time_frequency_repeated_measures_anova.py
@@ -190,7 +190,7 @@ def stat_fun(*args):
 
 
 # The ANOVA returns a tuple f-values and p-values, we will pick the former.
-pthresh = 0.00001  # set threshold rather high to save some time
+pthresh = 0.001  # set threshold rather high to save some time
 f_thresh = f_threshold_mway_rm(n_replications, factor_levels, effects,
                                pthresh)
 tail = 1  # f-test, so tail > 0
@@ -202,9 +202,9 @@ def stat_fun(*args):
 ###############################################################################
 # Create new stats image with only significant clusters:
 
-good_clusers = np.where(cluster_p_values < .05)[0]
+good_clusters = np.where(cluster_p_values < .05)[0]
 T_obs_plot = np.ma.masked_array(T_obs,
-                                np.invert(clusters[np.squeeze(good_clusers)]))
+                                np.invert(clusters[np.squeeze(good_clusters)]))
 
 plt.figure()
 for f_image, cmap in zip([T_obs, T_obs_plot], [plt.cm.gray, 'RdBu_r']):


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

Issue:
raw.plot error when there are events and annotations
When I plot raw data with both events and annotations, I get an `IndexError: pop from empty list` in

    mne/viz/raw.py", line 1025, in _plot_raw_traces
        params['ax'].texts.pop(0)

I didn't realize that there could be other texts besides events in `params['ax'].texts`, so I set `params['ax'].texts = []` in [line 1016](https://github.com/mne-tools/mne-python/blob/master/mne/viz/raw.py#L1016).

Any ideas how to fix this are very much appreciated. This is pretty serious, although the plot continues to work even after such an error.


Discussion:
can you provide a snippet to replicate?


Resolving patch:
diff --git a/mne/viz/raw.py b/mne/viz/raw.py
--- a/mne/viz/raw.py
+++ b/mne/viz/raw.py
@@ -1012,17 +1012,18 @@ def _plot_raw_traces(params, color, bad_color, event_lines=None,
             else:
                 line.set_xdata([])
                 line.set_ydata([])
+
+        params['ax'].texts = []   # delete event and annotation texts
+        # don't add event numbers for more than 50 visible events
         if len(event_times) <= 50:
-            params['ax'].texts = []
             for ev_time, ev_num in zip(event_times, event_nums):
                 if -1 in event_color or ev_num in event_color:
                     params['ax'].text(ev_time, -0.05, ev_num, fontsize=8,
                                       ha='center')
 
     if 'segments' in params:
-        while len(params['ax'].collections) > 0:
-            params['ax'].collections.pop(0)
-            params['ax'].texts.pop(0)
+        while len(params['ax'].collections) > 0:  # delete previous annotations
+            params['ax'].collections.pop(-1)
         segments = params['segments']
         times = params['times']
         ylim = params['ax'].get_ylim()
diff --git a/mne/viz/utils.py b/mne/viz/utils.py
--- a/mne/viz/utils.py
+++ b/mne/viz/utils.py
@@ -1829,7 +1829,6 @@ def _plot_annotations(raw, params):
 
     while len(params['ax_hscroll'].collections) > 0:
         params['ax_hscroll'].collections.pop()
-
     segments = list()
     # sort the segments by start time
     ann_order = raw.annotations.onset.argsort(axis=0)


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

Issue:
Undocumented times attribute in Raw and Epoch object
Both `Raw` and `Epoch` classes have a `times` attribute. However, this attribute is not described in the documentation (see [epoch](https://martinos.org/mne/stable/generated/mne.Epochs.html) and [raw](https://martinos.org/mne/stable/generated/mne.io.Raw.html)).

(I can do a PR).


Discussion:
please do

thanks


Resolving patch:
diff --git a/mne/epochs.py b/mne/epochs.py
--- a/mne/epochs.py
+++ b/mne/epochs.py
@@ -1913,6 +1913,10 @@ class Epochs(BaseEpochs):
         or 'USER' for user-defined reasons (see drop method).
     filename : str
         The filename of the object.
+    times :  ndarray
+        Time vector in seconds. Goes from `tmin` to `tmax`. Time interval
+        between consecutive time samples is equal to the inverse of the
+        sampling frequency.
     verbose : bool, str, int, or None
         See above.
 
diff --git a/mne/evoked.py b/mne/evoked.py
--- a/mne/evoked.py
+++ b/mne/evoked.py
@@ -91,6 +91,10 @@ class Evoked(ProjMixin, ContainsMixin, UpdateChannelsMixin,
         Array of time instants in seconds.
     data : array of shape (n_channels, n_times)
         Evoked response.
+    times :  ndarray
+        Time vector in seconds. Goes from `tmin` to `tmax`. Time interval
+        between consecutive time samples is equal to the inverse of the
+        sampling frequency.
     verbose : bool, str, int, or None.
         See above.
 
diff --git a/mne/io/fiff/raw.py b/mne/io/fiff/raw.py
--- a/mne/io/fiff/raw.py
+++ b/mne/io/fiff/raw.py
@@ -61,10 +61,15 @@ class Raw(BaseRaw):
         List of channels' names.
     n_times : int
         Total number of time points in the raw file.
+    times :  ndarray
+        Time vector in seconds. Starts from 0, independently of `first_samp`
+        value. Time interval between consecutive time samples is equal to the
+        inverse of the sampling frequency.
     preload : bool
         Indicates whether raw data are in memory.
     verbose : bool, str, int, or None
         See above.
+
     """
 
     @verbose


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

Issue:
raw.plot error when adding annotation
When I plot raw data, press 'a' and then 'Enter' I get the following error:

```
File "/usr/local/lib/python3.6/site-packages/mne/viz/utils.py", line 1880, in _annotations_closed
    params['ax'].selector.disconnect_events()
AttributeError: 'NoneType' object has no attribute 'disconnect_events'
```

This problem also existed in MNE 0.14.1.


Discussion:
with what data?

Some data set we've recorded. I'm currently trying to replicate with a sample data set (but the download process from OSF is really slow).
OK, this happens with any data.
how do I replicate?

```
import mne
from mne.datasets import sample


data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.plot()
```

Then press 'a' and in the annotations window click on "Add label" - voilà!
I can't replicate in my environment. Maybe it's a `matplotlib` backend issue?
Hm, did you test this on a Mac (with the default `osx` backend)?
No, Linux. On my OSX machine with the MacOSX backend I can't get the button presses to go to the window instead of the terminal (even after clicking in the window, etc.).
I get the same error on Linux. Did you press "a" and then click on the "Add label" button?
And this happens as far back as 0.14, which is before I made any commits to this module :relieved: - probably some update to Matplotlib introduced this error.
> Did you press "a" and then click on the "Add label" button?

Yes

Can't we add a simple conditional `if params['ax'].selector is not None` to fix this?
Strange, maybe you have a different Matplotlib or Qt or some other dependent lib version.

> Can't we add a simple conditional if params['ax'].selector is not None to fix this?

Yes, I'll do that (now that I'm pretty sure it's caused by a change in behavior of either Matplotlib or its deps).

Resolving patch:
diff --git a/mne/viz/utils.py b/mne/viz/utils.py
--- a/mne/viz/utils.py
+++ b/mne/viz/utils.py
@@ -1877,8 +1877,9 @@ def _annotations_closed(event, params):
     import matplotlib as mpl
     import matplotlib.pyplot as plt
     plt.close(params['fig_annotation'])
-    params['ax'].selector.disconnect_events()
-    params['ax'].selector = None
+    if params['ax'].selector is not None:
+        params['ax'].selector.disconnect_events()
+        params['ax'].selector = None
     params['fig_annotation'] = None
     if params['segment_line'] is not None:
         params['segment_line'].remove()


Test patch: