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

Issue:
MAINT: deprecate mne maxfilter command line tool
I'm actually inclined to deprecate this instead and remove it after 1.6. We have had `mne.preprocessing.maxwell_filter` for some time which should be more fully featured and it's what we want to support going forward. If people want to use the command-line `maxfilter` from MEGIN I think it's okay nowadays to have them do it from the command line directly -- `mne maxwell_filter` does not actually do much for people, so the workaround for deprecation is actually pretty straightforward -- use `maxfilter` directly with nearly identical args. The only extra thing it does is write out an `origin` and this can be done pretty easily with minimal MNE code already I think.

_Originally posted by @larsoner in https://github.com/mne-tools/mne-python/pull/11937#pullrequestreview-1603222289_
            


Discussion:
+1 for this.  We should also add a small example to the docs, so we can point people to the "recipe" for the workaround, in case they were relying on `mne maxfilter`
I'll do this quickly now

Resolving patch:
diff --git a/mne/preprocessing/maxfilter.py b/mne/preprocessing/maxfilter.py
--- a/mne/preprocessing/maxfilter.py
+++ b/mne/preprocessing/maxfilter.py
@@ -8,7 +8,7 @@
 
 from ..bem import fit_sphere_to_headshape
 from ..io import read_raw_fif
-from ..utils import logger, verbose, warn
+from ..utils import logger, verbose, warn, deprecated
 
 
 def _mxwarn(msg):
@@ -19,6 +19,11 @@ def _mxwarn(msg):
     )
 
 
+@deprecated(
+    "apply_maxfilter will be removed in 1.7, use mne.preprocessing.maxwell_filter or "
+    "the MEGIN command-line utility maxfilter and mne.bem.fit_sphere_to_headshape "
+    "instead."
+)
 @verbose
 def apply_maxfilter(
     in_fname,


Test patch:
diff --git a/mne/tests/test_docstring_parameters.py b/mne/tests/test_docstring_parameters.py
--- a/mne/tests/test_docstring_parameters.py
+++ b/mne/tests/test_docstring_parameters.py
@@ -242,7 +242,6 @@ def test_tabs():
 UpdateChannelsMixin
 activate_proj
 adjust_axes
-apply_maxfilter
 apply_trans
 channel_type
 combine_kit_markers
Repository: mne-tools/mne-python

Issue:
BUG: MNEBadsList causes pickling problems
https://github.com/autoreject/autoreject/issues/316

I'll look soon


Discussion:

Resolving patch:
diff --git a/mne/_fiff/meas_info.py b/mne/_fiff/meas_info.py
--- a/mne/_fiff/meas_info.py
+++ b/mne/_fiff/meas_info.py
@@ -963,7 +963,13 @@ def __init__(self, *, bads, info):
     def extend(self, iterable):
         if not isinstance(iterable, list):
             iterable = list(iterable)
-        _check_bads_info_compat(iterable, self._mne_info)
+        # can happen during pickling
+        try:
+            info = self._mne_info
+        except AttributeError:
+            pass  # can happen during pickling
+        else:
+            _check_bads_info_compat(iterable, info)
         return super().extend(iterable)
 
     def append(self, x):
@@ -1551,6 +1557,7 @@ def __getstate__(self):
     def __setstate__(self, state):
         """Set state (for pickling)."""
         self._unlocked = state["_unlocked"]
+        self["bads"] = MNEBadsList(bads=self["bads"], info=self)
 
     def __setitem__(self, key, val):
         """Attribute setter."""


Test patch:
diff --git a/mne/_fiff/tests/test_meas_info.py b/mne/_fiff/tests/test_meas_info.py
--- a/mne/_fiff/tests/test_meas_info.py
+++ b/mne/_fiff/tests/test_meas_info.py
@@ -1070,21 +1070,27 @@ def test_channel_name_limit(tmp_path, monkeypatch, fname):
     apply_inverse(evoked, inv)  # smoke test
 
 
+@pytest.mark.parametrize("protocol", ("highest", "default"))
 @pytest.mark.parametrize("fname_info", (raw_fname, "create_info"))
 @pytest.mark.parametrize("unlocked", (True, False))
-def test_pickle(fname_info, unlocked):
+def test_pickle(fname_info, unlocked, protocol):
     """Test that Info can be (un)pickled."""
     if fname_info == "create_info":
         info = create_info(3, 1000.0, "eeg")
     else:
         info = read_info(fname_info)
+    protocol = getattr(pickle, f"{protocol.upper()}_PROTOCOL")
+    assert isinstance(info["bads"], MNEBadsList)
+    info["bads"] = info["ch_names"][:1]
     assert not info._unlocked
     info._unlocked = unlocked
-    data = pickle.dumps(info)
+    data = pickle.dumps(info, protocol=protocol)
     info_un = pickle.loads(data)  # nosec B301
     assert isinstance(info_un, Info)
     assert_object_equal(info, info_un)
     assert info_un._unlocked == unlocked
+    assert isinstance(info_un["bads"], MNEBadsList)
+    assert info_un["bads"]._mne_info is info_un
 
 
 def test_info_bad():
Repository: mne-tools/mne-python

Issue:
"array-like" check incorrectly accepts strings
### Description of the problem

`_validate_type()` accepts a string parameter value "array-like" to allow checking for array-like input. However, the implementation of this recent addition is incorrect by considering any `Sequence` as `array-like`

https://github.com/mne-tools/mne-python/blob/8c003e843717e316ba85008eff2298917489bbd1/mne/utils/check.py#L545

### Steps to reproduce

```Python
# %%
from typing import Sequence

isinstance("test", Sequence)
```


### Link to data

_No response_

### Expected results

`False`: A string should not be considered `array-like`, at least not for our purposes here.

### Actual results

`True`, as a string is a `Sequence`

### Additional information

cc @cbrnr


Discussion:

Resolving patch:
diff --git a/mne/utils/check.py b/mne/utils/check.py
--- a/mne/utils/check.py
+++ b/mne/utils/check.py
@@ -8,7 +8,6 @@
 import os
 import re
 from builtins import input  # no-op here but facilitates testing
-from collections.abc import Sequence
 from difflib import get_close_matches
 from importlib import import_module
 from importlib.metadata import version
@@ -542,7 +541,7 @@ def __instancecheck__(cls, other):
     "path-like": path_like,
     "int-like": (int_like,),
     "callable": (_Callable(),),
-    "array-like": (Sequence, np.ndarray),
+    "array-like": (list, tuple, set, np.ndarray),
 }
 
 


Test patch:
diff --git a/mne/utils/tests/test_check.py b/mne/utils/tests/test_check.py
--- a/mne/utils/tests/test_check.py
+++ b/mne/utils/tests/test_check.py
@@ -212,6 +212,11 @@ def test_validate_type():
     _validate_type(1, "int-like")
     with pytest.raises(TypeError, match="int-like"):
         _validate_type(False, "int-like")
+    _validate_type([1, 2, 3], "array-like")
+    _validate_type((1, 2, 3), "array-like")
+    _validate_type({1, 2, 3}, "array-like")
+    with pytest.raises(TypeError, match="array-like"):
+        _validate_type("123", "array-like")  # a string is not array-like
 
 
 def test_check_range():
Repository: mne-tools/mne-python

Issue:
error code for example
### Proposed documentation enhancement

https://mne.tools/stable/auto_tutorials/clinical/60_sleep.html#design-a-scikit-learn-transformer-from-a-python-function


```
a=eeg_power_band(epochs)
a.shape
```

This is shown to return the shape of (n, 5). 5 is probably the frequency band. Here, 5 bands are defined, but I come up with 10.

![image](https://github.com/mne-tools/mne-python/assets/93689515/32f64c82-e94a-41d4-9610-3648d1a4b859)



Discussion:
Hello! 👋 Thanks for opening your first issue here! ❤️ We will try to get back to you soon. 🚴


Resolving patch:
diff --git a/tutorials/clinical/60_sleep.py b/tutorials/clinical/60_sleep.py
--- a/tutorials/clinical/60_sleep.py
+++ b/tutorials/clinical/60_sleep.py
@@ -249,7 +249,7 @@ def eeg_power_band(epochs):
 
     Returns
     -------
-    X : numpy array of shape [n_samples, 5]
+    X : numpy array of shape [n_samples, 5 * n_channels]
         Transformed data.
     """
     # specific frequency bands


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

Issue:
permutation test docstrings should link to spatial_src_adjacency
### Proposed documentation enhancement

currently the docstring (under the `adjacency` parameter) includes a link to `find_ch_adjacency` (for sensor-space data) but not to `spatial_src_adjacency` (for source-space data). It should have both.


Discussion:
There's actually numerous adjacency-calculating functions that we probably should mention:

### spatial
- `spatial_src_adjacency`
- `spatial_tris_adjacency`
- `spatial_dist_adjacency`
- `spatial_inter_hemi_adjacency`

### spatio-temporal
- `spatio_temporal_src_adjacency`
- `spatio_temporal_tris_adjacency`
- `spatio_temporal_dist_adjacency`

Interestingly, none of them is prefixed with `find_`, contrary to `find_ch_adjacency`.

I would like to perform this task.  Can you give me some directions?

I don't think the `*_tris_*` and `*_dist_*` are worth mentioning actually --- the `*_dist_*` functionality is already available in the `*_src_*` functions (they simply default to `dist=None`), and in the context of permutation testing, users won't be working with `tris`. But adding `spatio_temporal_src_adjacency` makes sense, and `spatial_inter_hemi_adjacency` makes sense for completeness, I guess.
> I would like to perform this task. Can you give me some directions?

Find the docstring of `permutation_*_test` and `spatio_temporal_*_test` functions, and add to the `adjacency` parameter description cross-references to:

- spatial_src_adjacency
- spatio_temporal_src_adjacency
- spatial_inter_hemi_adjacency

(...with appropriate context for when each might be used)
I will be starting working on this, as #11469 is almost finished. I will have to go through the documentations a little, in order to understand the appropriate contexts for those functionalities. 

> (...with appropriate context for when each might be used)




Resolving patch:
diff --git a/mne/utils/docs.py b/mne/utils/docs.py
--- a/mne/utils/docs.py
+++ b/mne/utils/docs.py
@@ -101,8 +101,11 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75):
 ] = """
 adjacency : scipy.sparse.spmatrix | None | False
     Defines adjacency between locations in the data, where "locations" can be
-    spatial vertices, frequency bins, time points, etc. For spatial vertices,
-    see: :func:`mne.channels.find_ch_adjacency`. If ``False``, assumes
+    spatial vertices, frequency bins, time points, etc. For spatial vertices
+    (i.e. sensor space data), see :func:`mne.channels.find_ch_adjacency` or
+    :func:`mne.spatial_inter_hemi_adjacency`. For source space data, see
+    :func:`mne.spatial_src_adjacency` or
+    :func:`mne.spatio_temporal_src_adjacency`. If ``False``, assumes
     no adjacency (each location is treated as independent and unconnected).
     If ``None``, a regular lattice adjacency is assumed, connecting
     each {sp} location to its neighbor(s) along the last dimension


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

Issue:
Small error in interpolation tutorial
### Proposed documentation enhancement

https://mne.tools/dev/auto_tutorials/preprocessing/15_handling_bad_channels.html#interpolation-in-mne-python

Says:

> Note that we used the exclude=[] trick in the call to [pick_types()](https://mne.tools/dev/generated/mne.io.Raw.html#mne.io.Raw.pick_types) to make sure the bad channels were not automatically dropped from the selection.

But `pick_types()` isn't used anymore (we switched to `inst.pick()`)


Discussion:
@hoechenberger  i am a newbie for this repo, could i work on this issue :)
Absolutely! Feel free to ask if you have any questions 👌

Resolving patch:
diff --git a/tutorials/preprocessing/15_handling_bad_channels.py b/tutorials/preprocessing/15_handling_bad_channels.py
--- a/tutorials/preprocessing/15_handling_bad_channels.py
+++ b/tutorials/preprocessing/15_handling_bad_channels.py
@@ -238,8 +238,9 @@
     fig.suptitle(title, size="xx-large", weight="bold")
 
 # %%
-# Note that we used the ``exclude=[]`` trick in the call to
-# :meth:`~mne.io.Raw.pick_types` to make sure the bad channels were not
+# Note that the method :meth:`~mne.io.Raw.pick()` default
+# arguments includes ``exclude=()`` which ensures that bad
+# channels are not
 # automatically dropped from the selection. Here is the corresponding example
 # with the interpolated gradiometer channel; since there are more channels
 # we'll use a more transparent gray color this time:


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

Issue:
Epochs metadata FutureWarning
This line https://github.com/mne-tools/mne-python/blob/4750f0dd5dc81c15704230c785541ab09fa5373b/mne/epochs.py#L2984

is yielding the traceback:

```
mne\tests\test_epochs.py:4105: in test_make_metadata_bounded_by_row_events
    metadata, events_new, event_id_new = mne.epochs.make_metadata(
mne\epochs.py:2984: in make_metadata
    metadata.iloc[:, 0] = ""
C:\hostedtoolcache\windows\Python\3.11.7\x64\Lib\site-packages\pandas\core\indexing.py:912: in __setitem__
    iloc._setitem_with_indexer(indexer, value, self.name)
C:\hostedtoolcache\windows\Python\3.11.7\x64\Lib\site-packages\pandas\core\indexing.py:1946: in _setitem_with_indexer
    self._setitem_with_indexer_split_path(indexer, value, name)
C:\hostedtoolcache\windows\Python\3.11.7\x64\Lib\site-packages\pandas\core\indexing.py:2039: in _setitem_with_indexer_split_path
    self._setitem_single_column(loc, value, pi)
C:\hostedtoolcache\windows\Python\3.11.7\x64\Lib\site-packages\pandas\core\indexing.py:2158: in _setitem_single_column
    warnings.warn(
E   FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value '' has dtype incompatible with float64, please explicitly cast to a compatible dtype first.
```

I'm not a big `panda` or `metadata` user, not sure how best to solve it.

Appeared in https://github.com/mne-tools/mne-python/pull/12345


Discussion:

Resolving patch:
diff --git a/mne/epochs.py b/mne/epochs.py
--- a/mne/epochs.py
+++ b/mne/epochs.py
@@ -2977,11 +2977,11 @@ def _ensure_list(x):
         *last_cols,
     ]
 
-    data = np.empty((len(events_df), len(columns)))
+    data = np.empty((len(events_df), len(columns)), float)
     metadata = pd.DataFrame(data=data, columns=columns, index=events_df.index)
 
     # Event names
-    metadata.iloc[:, 0] = ""
+    metadata["event_name"] = ""
 
     # Event times
     start_idx = 1
@@ -2990,7 +2990,7 @@ def _ensure_list(x):
 
     # keep_first and keep_last names
     start_idx = stop_idx
-    metadata.iloc[:, start_idx:] = None
+    metadata[columns[start_idx:]] = ""
 
     # We're all set, let's iterate over all events and fill in in the
     # respective cells in the metadata. We will subset this to include only


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

Issue:
[ENH] Speed up `read_raw_neuralynx()` when Neuralynx recording has many gaps
### Describe the new feature or enhancement

Using a larger non-public dataset (~1.7GB, cca 1 hour recording at 32Khz) with a large number of missing samples, I noticed that `read_raw_neuralynx(..., preload=False)` was talking quite long to return (tens of minutes). The bottleneck is the way search for samples corresponding to gap onsets was implemented.

It turns out to map detected gap starts onto sample numbers in the recording, it is using `gap_onsets = [np.where(samples == idx) for idx in gap_indices]` which will take long (tens of minutes) if a) there is a huge number to `samples` to search over and b) a large number of `gap_indies` to search for.

### Describe your proposed implementation

PR: #12371

The proposal is to drop `np.where` and infer gap sample onsets by cumulatively summing the segment sample sizes using `np.cumsum(segment_sizes)`. See PR for details.

Replacing `np.where` for `np.cumsum` removes the bottleneck:
![image](https://github.com/mne-tools/mne-python/assets/14061041/951eb941-a216-41da-9382-490c74106a2f)


### Describe possible alternatives

I'm sure there's even more efficient methods out there. But this is already a substantial improvement and removes the bottleneck.

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/mne/io/neuralynx/neuralynx.py b/mne/io/neuralynx/neuralynx.py
--- a/mne/io/neuralynx/neuralynx.py
+++ b/mne/io/neuralynx/neuralynx.py
@@ -223,11 +223,8 @@ def __init__(
             [np.full(shape=(n,), fill_value=i) for i, n in enumerate(sizes_sorted)]
         )
 
-        # construct Annotations()
-        gap_seg_ids = np.unique(sample2segment)[gap_indicator]
-        gap_start_ids = np.array(
-            [np.where(sample2segment == seg_id)[0][0] for seg_id in gap_seg_ids]
-        )
+        # get the start sample index for each gap segment ()
+        gap_start_ids = np.cumsum(np.hstack([[0], sizes_sorted[:-1]]))[gap_indicator]
 
         # recreate time axis for gap annotations
         mne_times = np.arange(0, len(sample2segment)) / info["sfreq"]


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

Issue:
BUG: Report TOC with many items has last few invisible
From a long report in MNE-BIDS-Pipeline, there are three items in the TOC that cannot be seen here:

![Screenshot from 2024-01-30 12-24-50](https://github.com/mne-tools/mne-python/assets/2365790/78bd8369-46c0-4221-8191-86c7d29635e8)

I'll try to replicate soon with `sample` and fix unless someone else beats me to it.


Discussion:
... can be seen in Chrome on Linux for me at least in for example:

https://mne.tools/mne-bids-pipeline/stable/examples/ds000248_base/sub-01_task-audiovisual_report.html#Raw__maxwell_filtered___run__01_

@hoechenberger if you have any immediate ideas let me know!

Resolving patch:
diff --git a/mne/report/report.py b/mne/report/report.py
--- a/mne/report/report.py
+++ b/mne/report/report.py
@@ -143,7 +143,7 @@
 html_include_dir = Path(__file__).parent / "js_and_css"
 template_dir = Path(__file__).parent / "templates"
 JAVASCRIPT = (html_include_dir / "report.js").read_text(encoding="utf-8")
-CSS = (html_include_dir / "report.sass").read_text(encoding="utf-8")
+CSS = (html_include_dir / "report.css").read_text(encoding="utf-8")
 
 MAX_IMG_RES = 100  # in dots per inch
 MAX_IMG_WIDTH = 850  # in pixels


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

Issue:
'custom_ref_applied' is True even if the offline rereferencing is an average
### Proposed documentation enhancement

Hello,

contrary to what is written in the doc, `'custom_ref_applied'` is True event if the offline rereferencing is an average one.

`set_eeg_reference(ref_channels="average")` raises the flag `'custom_ref_applied'` even so it is said for this Attribute on https://mne.tools/stable/generated/mne.Info.html:

> custom_ref_applied:
>     Whether a custom (=other than average) reference has been applied to the EEG data. This flag is checked by some algorithms that require an average reference to be set.

I find it strange that this flag is raised by an 'average' reref (which rereferencing does not raise it then ?) but I am guessing that there are reasons about this. if anyone could enlighten me as to the reason behind it, I'd be grateful :).
But in any case i think that this little doc paragraphe should be changed to reflect how it really works.
Since I'm already on this similar [issue](https://github.com/mne-tools/mne-python/issues/12401) I volunteer to continue to spot and correct the little contradictions around rereferencing and projections in the doc.


Discussion:
Yeah it should say "a custom (=other than average projector)` or similar. It's for inverse modeling reasons, we need to make sure an average reference over the remaining good channels is applied. Adding an average reference projector as the reference is a safe way to do this.

> I find it strange that this flag is raised by an 'average' reref (which rereferencing does not raise it then ?) but I am guessing that there are reasons about this. if anyone could enlighten me as to the reason behind it, I'd be grateful :).

Let's discuss this over in #12369.

Ok thanks for the link , I'll follow the discussion https://github.com/mne-tools/mne-python/issues/12369.
I'll open a PR to add this detail on the doc

Resolving patch:
diff --git a/mne/_fiff/meas_info.py b/mne/_fiff/meas_info.py
--- a/mne/_fiff/meas_info.py
+++ b/mne/_fiff/meas_info.py
@@ -1104,9 +1104,9 @@ class Info(dict, SetChannelsMixin, MontageMixin, ContainsMixin):
         The transformation from 4D/CTF head coordinates to Neuromag head
         coordinates. This is only present in 4D/CTF data.
     custom_ref_applied : int
-        Whether a custom (=other than average) reference has been applied to
-        the EEG data. This flag is checked by some algorithms that require an
-        average reference to be set.
+        Whether a custom (=other than an average projector) reference has been
+        applied to the EEG data. This flag is checked by some algorithms that
+        require an average reference to be set.
     description : str | None
         String description of the recording.
     dev_ctf_t : Transform | None


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

Issue:
EDF reader intermittent CI failure
We have a test failure happening that can only fail on Feb 29 of a leap year 😂 

https://github.com/mne-tools/mne-python/blob/f2fa901ca6f87eaadca6acd45f4c460f1c92f8fe/mne/io/edf/edf.py#L1269-L1272

We're using `datetime.now()` and then trying to change the year to a non-leap year a few lines down.


cc @nbara and @SveaMeyer13 --- I'll handle fixing it but I thought you might get a chuckle out of this since you're the last two folks to have touched the relevant lines


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
@@ -1269,7 +1269,9 @@ def _read_gdf_header(fname, exclude, include=None):
             if patient["birthday"] != datetime(1, 1, 1, 0, 0, tzinfo=timezone.utc):
                 today = datetime.now(tz=timezone.utc)
                 patient["age"] = today.year - patient["birthday"].year
-                today = today.replace(year=patient["birthday"].year)
+                # fudge the day by -1 if today happens to be a leap day
+                day = 28 if today.month == 2 and today.day == 29 else today.day
+                today = today.replace(year=patient["birthday"].year, day=day)
                 if today < patient["birthday"]:
                     patient["age"] -= 1
             else:


Test patch: