Repository: mne-tools/mne-python

Issue:
Resizing after dropping flat epochs fails - does not own its data
Hi,

I get the following error:

```
4 bad epochs dropped
Traceback (most recent call last):

  File "<ipython-input-11-6faf2142abd0>", line 13, in <module>
    epochs.drop_bad(flat=dict(seeg=100e-10))

  File "<string>", line 2, in drop_bad

  File "c:\users\user\documents\github\mne-python\mne\utils.py", line 725, in verbose
    return function(*args, **kwargs)

  File "c:\users\user\documents\github\mne-python\mne\epochs.py", line 1053, in drop_bad
    self._get_data(out=False)

  File "<string>", line 2, in _get_data

  File "c:\users\user\documents\github\mne-python\mne\utils.py", line 725, in verbose
    return function(*args, **kwargs)

  File "c:\users\user\documents\github\mne-python\mne\epochs.py", line 1254, in _get_data
    data.resize((n_out,) + data.shape[1:], refcheck=False)

ValueError: cannot resize this array: it does not own its data
```

A similar case has been reported [here](https://github.com/mne-tools/mne-python/pull/2211). @larsoner provided a [fix](https://github.com/mne-tools/mne-python/pull/2211/commits/3b3a68b9591de1240da90f8e137473d0a05dfda7) back then.


Discussion:
A workaround:

`epochs = epochs.copy().drop_bad(flat=dict(seeg=100e-10))`
Can you make a minimal `gist` from `sample` or (better) `testing` data showing the problem?
I'm sorry for the delay:

As a gist:
https://gist.github.com/stfnrpplngr/3460831b982bffbb1ac9405f39cf25fc

As code here:
```
import mne
from mne.datasets import sample

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)
raw.load_data()

events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, preload=True)

epochs.resample(512.)
epochs.crop(tmin=-0.25, tmax=1.25)

# This would be a workaround
# =============================================================================
# epochs = mne.EpochsArray(events=epochs.events, event_id=epochs.event_id,
#                          data=epochs.get_data(),
#                          info=epochs.info, tmin=epochs.tmin)
# =============================================================================

epochs.drop_bad(flat=dict(eeg=100e-8))
epochs.drop_bad(reject=dict(eeg=100e-5))
```

Resolving patch:
diff --git a/mne/epochs.py b/mne/epochs.py
--- a/mne/epochs.py
+++ b/mne/epochs.py
@@ -1251,7 +1251,12 @@ def _get_data(self, out=True, verbose=None):
 
             # adjust the data size if there is a reason to (output or update)
             if out or self.preload:
-                data.resize((n_out,) + data.shape[1:], refcheck=False)
+                if data.flags['OWNDATA'] and data.flags['C_CONTIGUOUS']:
+                    data.resize((n_out,) + data.shape[1:], refcheck=False)
+                else:
+                    data = data[:n_out]
+                    if self.preload:
+                        self._data = data
 
         return data if out else None
 


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
@@ -304,6 +304,34 @@ def test_reject():
         raw.annotations = None
 
 
+def test_own_data():
+    """Test for epochs data ownership (gh-5346)."""
+    raw, events = _get_data()[:2]
+    n_epochs = 10
+    events = events[:n_epochs]
+    epochs = mne.Epochs(raw, events, preload=True)
+    assert epochs._data.flags['C_CONTIGUOUS']
+    assert epochs._data.flags['OWNDATA']
+
+    epochs.crop(tmin=-0.1, tmax=0.4)
+    assert len(epochs) == epochs._data.shape[0] == len(epochs.events)
+    assert len(epochs) == n_epochs
+    assert not epochs._data.flags['OWNDATA']
+
+    # data ownership value error
+    epochs.drop_bad(flat=dict(eeg=8e-6))
+    n_now = len(epochs)
+    assert 5 < n_now < n_epochs
+    assert len(epochs) == epochs._data.shape[0] == len(epochs.events)
+
+    good_chan = epochs.copy().pick_channels([epochs.ch_names[0]])
+    good_chan.rename_channels({good_chan.ch_names[0]: 'good'})
+    epochs.add_channels([good_chan])
+    # "ValueError: resize only works on single-segment arrays"
+    epochs.drop_bad(flat=dict(eeg=10e-6))
+    assert 1 < len(epochs) < n_now
+
+
 def test_decim():
     """Test epochs decimation."""
     # First with EpochsArray