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

Issue:
BUG IO EDF File
when trying to read this [EDF file](https://www.dropbox.com/s/dwweynikaz9nlxd/EEG_170711_142159.edf?dl=0) with mne I get garbage while EEGLAB can import data that looks like data...

I had to make this f1294e4a9 to have the reader not crash.

anyone has time to look? @jaeilepp ? @teonbrooks ?


Discussion:

Resolving patch:
diff --git a/mne/io/edf/edf.py b/mne/io/edf/edf.py
--- a/mne/io/edf/edf.py
+++ b/mne/io/edf/edf.py
@@ -463,6 +463,7 @@ def _get_info(fname, stim_channel, annot, annotmap, eog, misc, exclude,
     for idx, ch_info in enumerate(zip(ch_names, physical_ranges, cals)):
         ch_name, physical_range, cal = ch_info
         chan_info = {}
+        logger.debug('  %s: range=%s cal=%s' % (ch_name, physical_range, cal))
         chan_info['cal'] = cal
         chan_info['logno'] = idx + 1
         chan_info['scanno'] = idx + 1
@@ -539,7 +540,12 @@ def _get_info(fname, stim_channel, annot, annotmap, eog, misc, exclude,
         elif highpass[0] == 'DC':
             info['highpass'] = 0.
         else:
-            info['highpass'] = float(highpass[0])
+            hp = highpass[0]
+            try:
+                hp = float(hp)
+            except Exception:
+                hp = 0.
+            info['highpass'] = hp
     else:
         info['highpass'] = float(np.max(highpass))
         warn('Channels contain different highpass filters. Highest filter '
@@ -609,7 +615,8 @@ def _read_edf_header(fname, annot, annotmap, exclude):
         subtype = os.path.splitext(fname)[1][1:].lower()
 
         n_records = int(fid.read(8).decode())
-        record_length = np.array([float(fid.read(8)), 1.])  # in seconds
+        record_length = fid.read(8).decode().strip('\x00').strip()
+        record_length = np.array([float(record_length), 1.])  # in seconds
         if record_length[0] == 0:
             record_length = record_length[0] = 1.
             warn('Header information is incorrect for record length. Default '


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

Issue:
evoked.plot displays ms instad of s



Discussion:
pb is here:

https://github.com/mne-tools/mne-python/blob/master/mne/viz/evoked.py#L138

basically we still display in "ms" even though we now use seconds. the time_unit should be passed here.
@massich do you have time to fix it?

Resolving patch:
diff --git a/mne/viz/evoked.py b/mne/viz/evoked.py
--- a/mne/viz/evoked.py
+++ b/mne/viz/evoked.py
@@ -80,7 +80,7 @@ def _butterfly_on_button_press(event, params):
 
 
 def _line_plot_onselect(xmin, xmax, ch_types, info, data, times, text=None,
-                        psd=False):
+                        psd=False, time_unit='s'):
     """Draw topomaps from the selected area."""
     import matplotlib.pyplot as plt
     ch_types = [type_ for type_ in ch_types if type_ in ('eeg', 'grad', 'mag')]
@@ -134,7 +134,7 @@ def _line_plot_onselect(xmin, xmax, ch_types, info, data, times, text=None,
         plot_topomap(this_data, pos, cmap=cmap, vmin=vmin, vmax=vmax,
                      axes=axarr[0][idx], show=False)
 
-    unit = 'Hz' if psd else 'ms'
+    unit = 'Hz' if psd else time_unit
     fig.suptitle('Average over %.2f%s - %.2f%s' % (xmin, unit, xmax, unit),
                  y=0.1)
     tight_layout(pad=2.0, fig=fig)
@@ -273,7 +273,8 @@ def _plot_evoked(evoked, picks, exclude, unit, show, ylim, proj, xlim, hline,
         _plot_lines(evoked.data, info, picks, fig, axes, spatial_colors, unit,
                     units, scalings, hline, gfp, types, zorder, xlim, ylim,
                     times, bad_ch_idx, titles, ch_types_used, selectable,
-                    False, line_alpha=1., nave=evoked.nave)
+                    False, line_alpha=1., nave=evoked.nave,
+                    time_unit=time_unit)
         plt.setp(axes, xlabel='Time (%s)' % time_unit)
 
     elif plot_type == 'image':
@@ -305,7 +306,7 @@ def _plot_evoked(evoked, picks, exclude, unit, show, ylim, proj, xlim, hline,
 def _plot_lines(data, info, picks, fig, axes, spatial_colors, unit, units,
                 scalings, hline, gfp, types, zorder, xlim, ylim, times,
                 bad_ch_idx, titles, ch_types_used, selectable, psd,
-                line_alpha, nave):
+                line_alpha, nave, time_unit='ms'):
     """Plot data as butterfly plot."""
     from matplotlib import patheffects, pyplot as plt
     from matplotlib.widgets import SpanSelector
@@ -456,7 +457,7 @@ def _plot_lines(data, info, picks, fig, axes, spatial_colors, unit, units,
             callback_onselect = partial(_line_plot_onselect,
                                         ch_types=ch_types_used, info=info,
                                         data=data, times=times, text=text,
-                                        psd=psd)
+                                        psd=psd, time_unit=time_unit)
             blit = False if plt.get_backend() == 'MacOSX' else True
             minspan = 0 if len(times) < 2 else times[1] - times[0]
             ax._span_selector = SpanSelector(


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

Issue:
Wrong title layout when calling historgram
When calling histogram by `h` in an epochs plot the axis labels do not render properly. 

```py
import mne
data_path = mne.datasets.sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
picks = mne.pick_types(raw.info, meg=True, eeg=True, eog=True, stim=False, exclude='bads')
mag_picks = mne.pick_types(raw.info, meg='mag', eog=True, exclude='bads')
grad_picks = mne.pick_types(raw.info, meg='grad', eog=True, exclude='bads')
event_id = dict(aud_l=1, aud_r=2)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)event_id = dict(aud_l=1, aud_r=2)  # event trigger and conditions
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,preload=False, reject=reject)
epochs.plot()

```

![image](https://user-images.githubusercontent.com/7044835/40617026-5905e80c-628d-11e8-863b-fdb0797c57b2.png)



Discussion:
Sorry, what is the problem? That it needs a somewhat diff. layout?
The space between the plots does not allow to read **uV** and **fT** which ends underneath **Magnetometers** and **Gradiometers**
layout need to be adjusted in
https://github.com/mne-tools/mne-python/blob/master/mne/viz/epochs.py#L1926

@massich can you take care of it?


Resolving patch:
diff --git a/mne/viz/epochs.py b/mne/viz/epochs.py
--- a/mne/viz/epochs.py
+++ b/mne/viz/epochs.py
@@ -1974,6 +1974,7 @@ def _plot_histogram(params):
         pass
     if params['fig_proj'] is not None:
         params['fig_proj'].canvas.draw()
+    plt.tight_layout(h_pad=0.7, pad=2)
 
 
 def _label2idx(params, pos):


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

Issue:
invert_y is broken in epochs.plot_image
:|


Discussion:

Resolving patch:
diff --git a/mne/viz/epochs.py b/mne/viz/epochs.py
--- a/mne/viz/epochs.py
+++ b/mne/viz/epochs.py
@@ -139,7 +139,8 @@ def plot_epochs_image(epochs, picks=None, sigma=0., vmin=None,
         Arguments passed to a call to `mne.viz.plot_compare_evoked` to style
         the evoked plot below the image. Defaults to an empty dictionary,
         meaning `plot_compare_evokeds` will be called with default parameters
-        (yaxis truncation will be turned off).
+        (yaxis truncation will be turned off, and inversion of the y axis
+        via `invert_y=True` will raise an error).
     title : None | str
         If str, will be plotted as figure title. Else, the channels will be
         indicated.
@@ -173,6 +174,10 @@ def plot_epochs_image(epochs, picks=None, sigma=0., vmin=None,
     else:
         picks = np.atleast_1d(picks)
 
+    if "invert_y" in ts_args:
+        raise NotImplementedError("'invert_y' found in 'ts_args'. "
+                                  "This is currently not implemented.")
+
     manual_ylims = "ylim" in ts_args
     vlines = ts_args.get(
         "vlines", [0] if (epochs.times[0] < 0 < epochs.times[-1]) else [])


Test patch:
diff --git a/mne/viz/tests/test_epochs.py b/mne/viz/tests/test_epochs.py
--- a/mne/viz/tests/test_epochs.py
+++ b/mne/viz/tests/test_epochs.py
@@ -12,6 +12,7 @@
 
 import numpy as np
 from numpy.testing import assert_equal
+import pytest
 
 from mne import read_events, Epochs, pick_types, read_cov
 from mne.channels import read_layout
@@ -171,6 +172,8 @@ def test_plot_epochs_image():
                       ts_args=ts_args)
         warnings.simplefilter('always')
     assert_equal(len(w), 1)
+    with pytest.raises(NotImplementedError, match='currently'):
+        epochs.plot_image(ts_args=dict(invert_y=True))
 
     plt.close('all')
Repository: mne-tools/mne-python

Issue:
Allow vlines=None in mne.viz.plot_compare_evokeds
I think we should allow for a `vlines='None'` argument in mne.viz.plot_compare_evokeds. Because in (arguably rare) some cases you would not want to have any vlines ...

It can be solved by a simple `if-clause` around the code here:

https://github.com/mne-tools/mne-python/blob/e4c995b4517089f7f105a9afb997f1b05a4e3653/mne/viz/evoked.py#L2087-L2096

we just wouldn't plot anything and pass `vlines=[]`to [`_setup_ax_spines`](https://github.com/mne-tools/mne-python/blob/55da4e49709ca6d5189cdceffba84c107b0ac517/mne/viz/utils.py#L2250)

And then also some additional `if-clause` some lines before that, when the input is being checked:

https://github.com/mne-tools/mne-python/blob/e4c995b4517089f7f105a9afb997f1b05a4e3653/mne/viz/evoked.py#L1859-L1861

This can just be skipped if we don't want vlines.


Discussion:
2 remarks:
- you can still remove these lines after the plot using the fig object
- if you argue it's too complicated no strong objection for a PR

Can you pass an empty list already to `plot_compare_evokeds`? If not, maybe we should just make that possible by adding an if before the `ax.vlines`.

Resolving patch:
diff --git a/mne/viz/evoked.py b/mne/viz/evoked.py
--- a/mne/viz/evoked.py
+++ b/mne/viz/evoked.py
@@ -2110,8 +2110,9 @@ def plot_compare_evokeds(evokeds, picks=None, gfp=False, colors=None,
         upper_v, lower_v = -ymax_bound, ax.get_ylim()[-1]
     else:
         upper_v, lower_v = ax.get_ylim()[0], ymax_bound
-    ax.vlines(vlines, upper_v, lower_v, linestyles='--', colors='k',
-              linewidth=1., zorder=1)
+    if vlines:
+        ax.vlines(vlines, upper_v, lower_v, linestyles='--', colors='k',
+                  linewidth=1., zorder=1)
 
     _setup_ax_spines(ax, vlines, tmin, tmax, invert_y, ymax_bound, unit,
                      truncate_xaxis)


Test patch:
diff --git a/mne/viz/tests/test_evoked.py b/mne/viz/tests/test_evoked.py
--- a/mne/viz/tests/test_evoked.py
+++ b/mne/viz/tests/test_evoked.py
@@ -225,7 +225,8 @@ def test_plot_evoked():
     red.data *= 1.1
     blue.data *= 0.9
     plot_compare_evokeds([red, blue], picks=3)  # list of evokeds
-    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True)
+    plot_compare_evokeds([red, blue], picks=3, truncate_yaxis=True,
+                         vlines=[])  # also testing empty vlines here
     plot_compare_evokeds([[red, evoked], [blue, evoked]],
                          picks=3)  # list of lists
     # test picking & plotting grads
Repository: mne-tools/mne-python

Issue:
CTF regularization parameter unnecessarily fixed
https://github.com/mne-tools/mne-python/blob/dc8fab44153c7e01cfc339dc65e17de538d391ec/mne/minimum_norm/psf_ctf.py#L243-L244

Parameter lambda2 is ignored by overwriting the variable in _get_matrix_from_inverse_operator(). The default value for lambda2 is already 1/3**2, so the same default functionality could be maintained by removing these lines.


Discussion:
Agreed that line should not be there
PR welcome. thanks


Resolving patch:
diff --git a/mne/minimum_norm/psf_ctf.py b/mne/minimum_norm/psf_ctf.py
--- a/mne/minimum_norm/psf_ctf.py
+++ b/mne/minimum_norm/psf_ctf.py
@@ -240,9 +240,6 @@ def _get_matrix_from_inverse_operator(inverse_operator, forward, labels=None,
     # convert identity matrix to evoked data type (pretending it's an epoch)
     ev_id = EvokedArray(id_mat, info=info, tmin=0.)
 
-    snr = 3.0
-    lambda2 = 1.0 / snr ** 2
-
     # apply inverse operator to identity matrix in order to get inverse matrix
     # free orientation constraint not possible because apply_inverse would
     # combined components


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

Issue:
DOC: Explain core MNE concepts in glossary.rst file
We have a few terms that are MNE specific, or for which multiple names would make sense, but we've settled on one. We don't have a doc page going through all of them, right?

Would it make sense to have such a page?

Thinking of:
- selection
- group_by
- picks
- raw
- epochs
- evoked
- info
- montage
- events (explain markers, triggers, stim channel ... here)
- ...


Discussion:
+1 ... I was confused by "picks" in the beginning
+100

like sklearn glossary: http://scikit-learn.org/dev/glossary.html

can you start this?

And even more basic things like raw, epoch, evoked, projection/projector, ...
ok I edited a bit the issue to start listing things we should put in the
glossary. Can you complement?

I guess it should live in tutorials, and be referenced from the manual? I can make a sketch PR soon.
would be great


Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -158,6 +158,7 @@
         ("Install", "getting_started"),
         ("Documentation", "documentation"),
         ("API", "python_reference"),
+        ("Glossary", "glossary"),
         ("Examples", "auto_examples/index"),
         ("Contribute", "contributing"),
     ],


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

Issue:
browse_raw command line should take '--preload' as parameter instead of '--preload=True'



Discussion:

Resolving patch:
diff --git a/mne/commands/mne_browse_raw.py b/mne/commands/mne_browse_raw.py
--- a/mne/commands/mne_browse_raw.py
+++ b/mne/commands/mne_browse_raw.py
@@ -44,7 +44,7 @@ def run():
                       "('type' or 'original')", default='type')
     parser.add_option("-p", "--preload", dest="preload",
                       help="Preload raw data (for faster navigaton)",
-                      default=False)
+                      default=False, action="store_true")
     parser.add_option("-s", "--show_options", dest="show_options",
                       help="Show projection options dialog",
                       default=False)


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

Issue:
Modified the call to browse_raw parameters to accept --preload param
#### Reference issue
Fixes #5655 .


#### What does this implement/fix?
Changed the call to the add_option of the parser to set a flag to true instead of value


Discussion:

Resolving patch:
diff --git a/mne/commands/mne_browse_raw.py b/mne/commands/mne_browse_raw.py
--- a/mne/commands/mne_browse_raw.py
+++ b/mne/commands/mne_browse_raw.py
@@ -64,7 +64,8 @@ def run():
                       help="Enable trace clipping mode, either 'clip' or "
                       "'transparent'", default=None)
     parser.add_option("--filterchpi", dest="filterchpi",
-                      help="Enable filtering cHPI signals.", default=None)
+                      help="Enable filtering cHPI signals.", default=None,
+                      action="store_true")
 
     options, args = parser.parse_args()
 


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

Issue:
ENH: Add spatial pattern plot to SPoC example
Based on a brief discussion on gitter last week, it sounded like it would be useful to use CSP's plot_patterns to plot the spatial patterns that contributed to the predicted data in the SPoC example.




Discussion:

Resolving patch:
diff --git a/examples/decoding/plot_decoding_spoc_CMC.py b/examples/decoding/plot_decoding_spoc_CMC.py
--- a/examples/decoding/plot_decoding_spoc_CMC.py
+++ b/examples/decoding/plot_decoding_spoc_CMC.py
@@ -31,6 +31,7 @@
 from mne import Epochs
 from mne.decoding import SPoC
 from mne.datasets.fieldtrip_cmc import data_path
+from mne.channels import read_layout
 
 from sklearn.pipeline import make_pipeline
 from sklearn.linear_model import Ridge
@@ -62,9 +63,8 @@
 y = emg_epochs.get_data().var(axis=2)[:, 0]  # target is EMG power
 
 # Classification pipeline with SPoC spatial filtering and Ridge Regression
-clf = make_pipeline(SPoC(n_components=2, log=True, reg='oas',
-                         rank='full'), Ridge())
-
+spoc = SPoC(n_components=2, log=True, reg='oas', rank='full')
+clf = make_pipeline(spoc, Ridge())
 # Define a two fold cross-validation
 cv = KFold(n_splits=2, shuffle=False)
 
@@ -82,3 +82,10 @@
 plt.legend()
 mne.viz.tight_layout()
 plt.show()
+
+##############################################################################
+# Plot the contributions to the detected components (i.e., the forward model)
+
+spoc.fit(X, y)
+layout = read_layout('CTF151.lay')
+spoc.plot_patterns(meg_epochs.info, layout=layout)


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

Issue:
regression in plot_sleep.py due to #5841
Circle CI is red. I've no idea why was not red in #5841.

```sh
~/code/mne-python master*
(mne) ❯ python tutorials/plot_sleep.py   
/home/sik/miniconda3/envs/mne/lib/python3.6/site-packages/sklearn/externals/joblib/externals/cloudpickle/cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  import imp
Traceback (most recent call last):
  File "tutorials/plot_sleep.py", line 90, in <module>
    raw_train.plot(duration=60, scalings='auto')
  File "/home/sik/code/mne-python/mne/io/base.py", line 1873, in plot
    event_id=event_id)
  File "/home/sik/code/mne-python/mne/viz/raw.py", line 265, in plot_raw
    scalings = _compute_scalings(scalings, raw)
  File "/home/sik/code/mne-python/mne/viz/utils.py", line 1634, in _compute_scalings
    data = inst._read_segment(tmin, tmax)
  File "/home/sik/code/mne-python/mne/io/base.py", line 561, in _read_segment
    cals, mult)
  File "<string>", line 2, in _read_segment_file
  File "/home/sik/code/mne-python/mne/utils.py", line 953, in verbose
    return function(*args, **kwargs)
  File "/home/sik/code/mne-python/mne/io/edf/edf.py", line 284, in _read_segment_file
    if ci in stim_channel:
TypeError: argument of type 'NoneType' is not iterable

```


Discussion:
I did not see that @larsoner catch it just 1h ago https://github.com/mne-tools/mne-python/pull/5841#issuecomment-457190398

> I've no idea why was not red in #5841.

Due to time limitations, CircleCI on PRs only runs examples that have changed, not all examples. Once code is merged, all examples are run.

Resolving patch:
diff --git a/mne/io/edf/edf.py b/mne/io/edf/edf.py
--- a/mne/io/edf/edf.py
+++ b/mne/io/edf/edf.py
@@ -281,7 +281,7 @@ def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
                     d_sidx = d_lims[ai][0]
                     d_eidx = d_lims[ai + n_read - 1][1]
                     if n_samps[ci] != buf_len:
-                        if ci in stim_channel:
+                        if stim_channel is not None and ci in stim_channel:
                             # Stim channel will be interpolated
                             old = np.linspace(0, 1, n_samps[ci] + 1, True)
                             new = np.linspace(0, 1, buf_len, False)


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

Issue:
Loading BDF file fails on UTF-8 decoding error
#### Describe the bug
Please provide a clear and concise description of the bug.

The header of my BDF file has a patient with a name that contains the character `è`, which causes line 600 of `io/edf/edf.py` to fail with error:

```python
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 4: invalid continuation byte
```

#### Steps and/or code to reproduce

Loading any `.bdf` file with that accent causes the issue. The issue occurs with the most recent pip package and the current head of master.

#### Additional information

We temporarily solved our issue by changing the line to:

```python
# patient ID
pid = fid.read(80).decode(errors='ignore')
```

However, it may be worthwhile to replace the offending character with a space or something harmless.


Discussion:
This suggests that EDF does not encode using UTF-8. We should find out what encoding they use, and `decode()` with that.
how did you write the edf file? is utf-8 accepted by the standard? is there
a way to know if the edf file should be decoded in latin1 or utf-8?

>

AFAIK the standard does not mention which encoding should be used. We've stumbled into a similar issue for GDF files, which we solved by using `.decode('latin-1')`. This should take care of the accent (and other special characters).
cool. Who sends the PR and shares a test file?

>

I can do the PR if nobody else beats me to it.
go for it please


Resolving patch:
diff --git a/mne/io/edf/edf.py b/mne/io/edf/edf.py
--- a/mne/io/edf/edf.py
+++ b/mne/io/edf/edf.py
@@ -597,7 +597,7 @@ def _read_edf_header(fname, exclude):
         fid.read(8)  # version (unused here)
 
         # patient ID
-        pid = fid.read(80).decode()
+        pid = fid.read(80).decode('latin-1')
         pid = pid.split(' ', 2)
         patient = {}
         if len(pid) >= 2:
@@ -636,14 +636,14 @@ def _read_edf_header(fname, exclude):
 
         nchan = int(fid.read(4).decode())
         channels = list(range(nchan))
-        ch_names = [fid.read(16).strip().decode() for ch in channels]
+        ch_names = [fid.read(16).strip().decode('latin-1') for ch in channels]
         exclude = _find_exclude_idx(ch_names, exclude)
         tal_idx = _find_tal_idx(ch_names)
         exclude = np.concatenate([exclude, tal_idx])
         sel = np.setdiff1d(np.arange(len(ch_names)), exclude)
         for ch in channels:
             fid.read(80)  # transducer
-        units = [fid.read(8).strip().decode() for ch in channels]
+        units = [fid.read(8).strip().decode('latin-1') for ch in channels]
         edf_info['units'] = list()
         for i, unit in enumerate(units):
             if i in exclude:


Test patch: