Skip to content

neuro_py.detectors

DetectDS

Bases: object

Class for detecting dentate spikes

Parameters:

Name Type Description Default
basepath str

Path to the folder containing the data

required
hilus_ch int

Channel number of the hilus signal (0 indexing)

required
mol_ch int

Channel number of the mol signal (0 indexing)

required
noise_ch int

Channel number of the noise signal or signal far from dentate (0 indexing)

None
lowcut float

Low cut frequency for the signal filter

10
highcut float

High cut frequency for the signal filter

250
filter_signal_bool bool

If True, the signal will be filtered

True
primary_threshold float

Primary threshold for detecting the dentate spikes (difference method only)

5
secondary_threshold float

Secondary threshold for detecting the dentate spikes (difference method only)

required
primary_thres_mol float

Primary threshold for detecting the dentate spikes in the mol signal

2
primary_thres_hilus float

Primary threshold for detecting the dentate spikes in the hilus signal

5
min_duration float

Minimum duration of the dentate spikes

0.005
max_duration float

Maximum duration of the dentate spikes

0.05
filter_order int

Order of the filter

4
filter_rs int

Resonance frequency of the filter

20
method str

Method for detecting the dentate spikes. "difference" for detecting the dentate spikes by difference between the hilus and mol signal "seperately" for detecting the dentate spikes by the hilus and mol signal separately

'seperately'
clean_lfp bool

If True, the LFP signal will be cleaned

False
emg_threshold float

Threshold for the EMG signal to remove dentate spikes

0.9

Attributes:

Name Type Description
lfp AnalogSignalArray

LFP signal

filtered_lfp AnalogSignalArray

Filtered LFP signal

mol_hilus_diff AnalogSignalArray

Difference between the hilus and mol signal

ds_epoch EpochArray

EpochArray with the dentate spikes

peak_val ndarray

Peak value of the dentate spikes

Methods:

Name Description
load_lfp

Load the LFP signal

filter_signal

Filter the LFP signal

get_filtered_lfp

Get the filtered LFP signal

get_lfp_diff

Get the difference between the hilus and mol signal

detect_ds_difference

Detect the dentate spikes by difference between the hilus and mol signal

detect_ds_seperately

Detect the dentate spikes by the hilus and mol signal separately

save_ds_epoch

Save the dentate spikes as an EpochArray

Examples:

In IDE or python console

>>> from ds_swr.detection.detect_dentate_spike import DetectDS
>>> from neuro_py.io import loading
>>> channel_tags = loading.load_channel_tags(basepath)
>>> dds = DetectDS(
    basepath,
    channel_tags["hilus"]["channels"] - 1,
    channel_tags["mol"]["channels"] - 1
)
>>> dds.detect_ds()
>>> dds.save_ds_epoch()
>>> dds
<DetectDS at 0x17fe787c640: dentate spikes 5,769> of length 1:11:257 minutes

In command line

>>> python detect_dentate_spike.py Z:/Data/Can/OML22/day20
Source code in neuro_py/detectors/dentate_spike.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
class DetectDS(object):
    """
    Class for detecting dentate spikes

    Parameters
    ----------
    basepath : str
        Path to the folder containing the data
    hilus_ch : int
        Channel number of the hilus signal (0 indexing)
    mol_ch : int
        Channel number of the mol signal (0 indexing)
    noise_ch : int, optional
        Channel number of the noise signal or signal far from dentate (0 indexing)
    lowcut : float, optional
        Low cut frequency for the signal filter
    highcut : float, optional
        High cut frequency for the signal filter
    filter_signal_bool : bool, optional
        If True, the signal will be filtered
    primary_threshold : float, optional
        Primary threshold for detecting the dentate spikes (difference method only)
    secondary_threshold : float, optional
        Secondary threshold for detecting the dentate spikes (difference method only)
    primary_thres_mol : float, optional
        Primary threshold for detecting the dentate spikes in the mol signal
    primary_thres_hilus : float, optional
        Primary threshold for detecting the dentate spikes in the hilus signal
    min_duration : float, optional
        Minimum duration of the dentate spikes
    max_duration : float, optional
        Maximum duration of the dentate spikes
    filter_order : int, optional
        Order of the filter
    filter_rs : int, optional
        Resonance frequency of the filter
    method : str, optional
        Method for detecting the dentate spikes.
        "difference" for detecting the dentate spikes by difference between the hilus and mol signal
        "seperately" for detecting the dentate spikes by the hilus and mol signal separately
    clean_lfp : bool, optional
        If True, the LFP signal will be cleaned
    emg_threshold : float, optional
        Threshold for the EMG signal to remove dentate spikes


    Attributes
    ----------
    lfp : nelpy.AnalogSignalArray
        LFP signal
    filtered_lfp : nelpy.AnalogSignalArray
        Filtered LFP signal
    mol_hilus_diff : nelpy.AnalogSignalArray
        Difference between the hilus and mol signal
    ds_epoch : nelpy.EpochArray
        EpochArray with the dentate spikes
    peak_val : np.ndarray
        Peak value of the dentate spikes


    Methods
    -------
    load_lfp()
        Load the LFP signal
    filter_signal()
        Filter the LFP signal
    get_filtered_lfp()
        Get the filtered LFP signal
    get_lfp_diff()
        Get the difference between the hilus and mol signal
    detect_ds_difference()
        Detect the dentate spikes by difference between the hilus and mol signal
    detect_ds_seperately()
        Detect the dentate spikes by the hilus and mol signal separately
    save_ds_epoch()
        Save the dentate spikes as an EpochArray

    Examples
    --------
    In IDE or python console

    >>> from ds_swr.detection.detect_dentate_spike import DetectDS
    >>> from neuro_py.io import loading
    >>> channel_tags = loading.load_channel_tags(basepath)
    >>> dds = DetectDS(
        basepath,
        channel_tags["hilus"]["channels"] - 1,
        channel_tags["mol"]["channels"] - 1
    )
    >>> dds.detect_ds()
    >>> dds.save_ds_epoch()
    >>> dds
    <DetectDS at 0x17fe787c640: dentate spikes 5,769> of length 1:11:257 minutes


    In command line

    >>> python detect_dentate_spike.py Z:/Data/Can/OML22/day20
    """

    def __init__(
        self,
        basepath: str,
        hilus_ch: int,
        mol_ch: int,
        noise_ch: Union[int, None] = None,
        lowcut: int = 10,
        highcut: int = 250,
        filter_signal_bool: bool = True,
        primary_threshold: Union[int, float] = 5,
        primary_thres_mol: Union[int, float] = 2,
        primary_thres_hilus: Union[int, float] = 5,
        min_duration: float = 0.005,
        max_duration: float = 0.05,
        filter_order: int = 4,
        filter_rs: int = 20,
        method: str = "seperately",
        clean_lfp: bool = False,
        emg_threshold: float = 0.9,
    ) -> None:
        # adding all the parameters to the class
        self.__dict__.update(locals())
        del self.__dict__["self"]
        # setting the type name
        self.type_name = self.__class__.__name__
        self.get_xml_data()

    def get_xml_data(self):
        """
        Load the XML file to get the number of channels, sampling frequency and shank to channel mapping
        """
        nChannels, fs, fs_dat, shank_to_channel = loading.loadXML(self.basepath)
        self.nChannels = nChannels
        self.fs = fs
        self.fs_dat = fs_dat
        self.shank_to_channel = shank_to_channel

    def load_lfp(self):
        """
        Load the LFP signal
        """

        lfp, timestep = loading.loadLFP(
            self.basepath,
            n_channels=self.nChannels,
            frequency=self.fs,
            ext="lfp",
        )

        if self.noise_ch is None:
            channels = [self.hilus_ch, self.mol_ch]
        else:
            channels = [self.hilus_ch, self.mol_ch, self.noise_ch]

        self.lfp = nel.AnalogSignalArray(
            data=lfp[:, channels].T,
            timestamps=timestep,
            fs=self.fs,
            support=nel.EpochArray(np.array([min(timestep), max(timestep)])),
        )
        if self.clean_lfp:
            self.lfp._data = np.array(
                [
                    clean_lfp(self.lfp.signals[0]),
                    clean_lfp(self.lfp.signals[1]),
                ]
            )

    def filter_signal(self):
        """
        Filter the LFP signal

        Returns
        -------
        np.ndarray
            Filtered LFP signal
        """
        if not hasattr(self, "lfp"):
            self.load_lfp()

        b, a = cheby2(
            self.filter_order,
            self.filter_rs,
            [self.lowcut, self.highcut],
            fs=self.fs,
            btype="bandpass",
        )
        return filtfilt(b, a, self.lfp.data)

    def get_filtered_lfp(self):
        if not hasattr(self, "lfp"):
            self.load_lfp()

        self.filtered_lfp = deepcopy(self.lfp)
        self.filtered_lfp._data = self.filter_signal()

    def get_lfp_diff(self):
        if self.filter_signal_bool:
            y = self.filter_signal()
        else:
            if not hasattr(self, "lfp"):
                self.load_lfp()
            y = self.lfp.data

        self.mol_hilus_diff = nel.AnalogSignalArray(
            data=y[0, :] - y[1, :],
            timestamps=self.lfp.abscissa_vals,
            fs=self.fs,
            support=nel.EpochArray(
                np.array([min(self.lfp.abscissa_vals), max(self.lfp.abscissa_vals)])
            ),
        )

    def detect_ds_difference(self):
        if not hasattr(self, "mol_hilus_diff"):
            self.get_lfp_diff()

        PrimaryThreshold = (
            self.mol_hilus_diff.mean()
            + self.primary_threshold * self.mol_hilus_diff.std()
        )
        SecondaryThreshold = (
            self.mol_hilus_diff.mean()
            + self.secondary_threshold * self.mol_hilus_diff.std()
        )
        bounds, self.peak_val, _ = nel.utils.get_events_boundaries(
            x=self.mol_hilus_diff.data,
            PrimaryThreshold=PrimaryThreshold,
            SecondaryThreshold=SecondaryThreshold,
            minThresholdLength=0,
            minLength=self.min_duration,
            maxLength=self.max_duration,
            ds=1 / self.mol_hilus_diff.fs,
        )
        # convert bounds to time in seconds
        timebounds = self.mol_hilus_diff.time[bounds]
        # add 1/fs to stops for open interval
        timebounds[:, 1] += 1 / self.mol_hilus_diff.fs
        # create EpochArray with bounds
        self.ds_epoch = nel.EpochArray(timebounds)

        # remove ds in high emg
        _, high_emg_epoch, _ = loading.load_emg(self.basepath, self.emg_threshold)
        if not high_emg_epoch.isempty:
            idx = find_intersecting_intervals(self.ds_epoch, high_emg_epoch)
            self.ds_epoch._data = self.ds_epoch.data[~idx]
            self.peak_val = self.peak_val[~idx]

    def detect_ds_seperately(self):
        if not hasattr(self, "filtered_lfp"):
            self.get_filtered_lfp()

        # min and max time width of ds (converted to samples for find_peaks)
        time_widths = [
            int(self.min_duration * self.filtered_lfp.fs),
            int(self.max_duration * self.filtered_lfp.fs),
        ]

        # detect ds in hilus
        PrimaryThreshold = (
            self.filtered_lfp.data[0, :].mean()
            + self.primary_thres_hilus * self.filtered_lfp.data[0, :].std()
        )

        peaks, properties = find_peaks(
            self.filtered_lfp.data[0, :],
            height=PrimaryThreshold,
            width=time_widths,
        )
        self.peaks = peaks / self.filtered_lfp.fs
        self.peak_val = properties["peak_heights"]

        # create EpochArray with bounds
        hilus_epoch = nel.EpochArray(
            np.array([properties["left_ips"], properties["right_ips"]]).T
            / self.filtered_lfp.fs
        )

        # detect ds in mol
        PrimaryThreshold = (
            self.filtered_lfp.data[1, :].mean()
            + self.primary_thres_mol * self.filtered_lfp.data[1, :].std()
        )

        peaks, properties = find_peaks(
            -self.filtered_lfp.data[1, :],
            height=PrimaryThreshold,
            width=time_widths,
        )
        mol_epoch_peak = peaks / self.filtered_lfp.fs
        # create EpochArray with bounds
        mol_epoch = nel.EpochArray(
            np.array([properties["left_ips"], properties["right_ips"]]).T
            / self.filtered_lfp.fs
        )

        # detect ds in noise channel
        if self.noise_ch is not None:
            PrimaryThreshold = (
                self.filtered_lfp.data[2, :].mean()
                + self.primary_thres_hilus * self.filtered_lfp.data[2, :].std()
            )

            peaks, properties = find_peaks(
                self.filtered_lfp.data[2, :],
                height=PrimaryThreshold,
                width=time_widths,
            )

            # create EpochArray with bounds
            noise_epoch = nel.EpochArray(
                np.array([properties["left_ips"], properties["right_ips"]]).T
                / self.filtered_lfp.fs
            )

        # remove hilus spikes that are not overlapping with mol spikes
        # first, find mol peaks that are within hilus epoch
        idx = in_intervals(mol_epoch_peak, hilus_epoch.data)
        mol_epoch._data = mol_epoch.data[idx]

        overlap = find_intersecting_intervals(
            hilus_epoch, mol_epoch, return_indices=True
        )
        self.ds_epoch = nel.EpochArray(hilus_epoch.data[overlap])
        self.peak_val = self.peak_val[overlap]
        self.peaks = self.peaks[overlap]

        # remove dentate spikes that are overlapping with noise spikes
        if self.noise_ch is not None:
            overlap = find_intersecting_intervals(
                self.ds_epoch, noise_epoch, return_indices=True
            )
            self.ds_epoch = nel.EpochArray(self.ds_epoch.data[~overlap])
            self.peak_val = self.peak_val[~overlap]
            self.peaks = self.peaks[~overlap]

        # remove ds in high emg
        _, high_emg_epoch, _ = loading.load_emg(self.basepath, self.emg_threshold)
        if not high_emg_epoch.isempty:
            idx = find_intersecting_intervals(self.ds_epoch, high_emg_epoch)
            self.ds_epoch._data = self.ds_epoch.data[~idx]
            self.peak_val = self.peak_val[~idx]
            self.peaks = self.peaks[~idx]

    def detect_ds(self):
        """
        Detect the dentate spikes based on the method provided
        """
        if self.method == "difference":
            # deprecated
            raise NotImplementedError
            # self.detect_ds_difference()
        elif self.method == "seperately":
            self.detect_ds_seperately()
        else:
            raise ValueError(f"Method {self.method} not recognized")

    def save_ds_epoch(self):
        """
        Save the dentate spikes as a cellexplorer mat file
        """

        filename = os.path.join(
            self.basepath, os.path.basename(self.basepath) + ".DS2.events.mat"
        )
        data = {}
        data["DS2"] = {}
        data["DS2"]["detectorinfo"] = {}
        data["DS2"]["timestamps"] = self.ds_epoch.data
        data["DS2"]["peaks"] = self.peaks
        data["DS2"]["amplitudes"] = self.peak_val.T
        data["DS2"]["amplitudeUnits"] = "mV"
        data["DS2"]["eventID"] = []
        data["DS2"]["eventIDlabels"] = []
        data["DS2"]["eventIDbinary"] = []
        data["DS2"]["duration"] = self.ds_epoch.durations.T
        data["DS2"]["center"] = np.median(self.ds_epoch.data, axis=1).T
        data["DS2"]["detectorinfo"]["detectorname"] = "DetectDS"
        data["DS2"]["detectorinfo"]["detectionparms"] = []
        data["DS2"]["detectorinfo"]["detectionintervals"] = []
        data["DS2"]["detectorinfo"]["ml_channel"] = self.mol_ch
        data["DS2"]["detectorinfo"]["h_channel"] = self.hilus_ch
        if self.noise_ch is not None:
            data["DS2"]["detectorinfo"]["noise_channel"] = self.noise_ch

        savemat(filename, data, long_field_names=True)

    def get_average_trace(self, shank=None, window=[-0.15, 0.15]):
        """
        Get the average LFP trace around the dentate spikes

        Parameters
        ----------
        shank : int, optional
            Shank number of the hilus signal
        window : list, optional
            Window around the dentate spikes

        Returns
        -------
        np.ndarray
            Average LFP trace around the dentate spikes
        np.ndarray
            Time lags around the dentate spikes
        """

        lfp, _ = loading.loadLFP(
            self.basepath,
            n_channels=self.nChannels,
            frequency=self.fs,
            ext="lfp",
        )

        if shank is None:
            hilus_shank = [
                k for k, v in self.shank_to_channel.items() if self.hilus_ch in v
            ][0]

        ds_average, time_lags = event_triggered_average_fast(
            signal=lfp[:, self.shank_to_channel[hilus_shank]].T,
            events=self.ds_epoch.starts,
            sampling_rate=self.fs,
            window=window,
            return_average=True,
        )
        return ds_average, time_lags

    def plot(self, ax=None, window=[-0.15, 0.15], channel_offset=9e4):
        """
        Plot the average LFP trace around the dentate spikes

        Parameters
        ----------
        ax : matplotlib.axes._subplots.AxesSubplot, optional
            Axis to plot the average LFP trace
        window : list, optional
            Window around the dentate spikes
        channel_offset : float, optional
            Offset between the channels

        Returns
        -------
        matplotlib.axes._subplots.AxesSubplot
            Axis with the average LFP trace
        """

        import matplotlib.pyplot as plt

        ds_average, time_lags = self.get_average_trace(window=window)

        if ax is None:
            fig, ax = plt.subplots(figsize=(5, 10))

        ax.plot(
            time_lags,
            ds_average.T - np.linspace(0, channel_offset, ds_average.shape[0]),
            alpha=0.75,
        )
        return ax

    def _detach(self):
        """Detach the data from the object to allow for pickling"""
        self.filtered_lfp = None
        self.lfp = None
        self.mol_hilus_diff = None

    def save(self, filename: str):
        """
        Save the DetectDS object as a pickle file

        Parameters
        ----------
        filename : str
            Path to the file where the DetectDS object will be saved

        Returns
        -------
        None

        """
        self._detach()
        with open(filename, "wb") as f:
            pickle.dump(self, f)

    @classmethod
    def load(cls, filename: str):
        """
        Load a DetectDS object from a pickle file

        Parameters
        ----------
        filename : str
            Path to the file where the DetectDS object is saved

        Returns
        -------
        DetectDS
            The loaded DetectDS object

        """
        with open(filename, "rb") as f:
            return pickle.load(f)

    def __repr__(self) -> str:
        address_str = " at " + str(hex(id(self)))

        if not hasattr(self, "ds_epoch"):
            return "<%s%s>" % (self.type_name, address_str)

        if self.ds_epoch.isempty:
            return "<%s%s: empty>" % self.type_name

        dentate_spikes = f"dentate spikes {self.ds_epoch.n_intervals}"
        dstr = f"of length {self.ds_epoch.length}"

        return "<%s%s: %s> %s" % (self.type_name, address_str, dentate_spikes, dstr)

    def __str__(self) -> str:
        return self.__repr__()

    def __len__(self) -> int:
        if not hasattr(self, "ds_epoch"):
            return 0
        return self.ds_epoch.n_intervals

    def __getitem__(self, key):
        if not hasattr(self, "ds_epoch"):
            raise IndexError("No dentate spikes detected yet")
        return self.ds_epoch[key]

    def __iter__(self):
        if not hasattr(self, "ds_epoch"):
            raise IndexError("No dentate spikes detected yet")
        return iter(self.ds_epoch)

    def __contains__(self, item):
        if not hasattr(self, "ds_epoch"):
            raise IndexError("No dentate spikes detected yet")
        return item in self.ds_epoch

detect_ds()

Detect the dentate spikes based on the method provided

Source code in neuro_py/detectors/dentate_spike.py
362
363
364
365
366
367
368
369
370
371
372
373
def detect_ds(self):
    """
    Detect the dentate spikes based on the method provided
    """
    if self.method == "difference":
        # deprecated
        raise NotImplementedError
        # self.detect_ds_difference()
    elif self.method == "seperately":
        self.detect_ds_seperately()
    else:
        raise ValueError(f"Method {self.method} not recognized")

filter_signal()

Filter the LFP signal

Returns:

Type Description
ndarray

Filtered LFP signal

Source code in neuro_py/detectors/dentate_spike.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def filter_signal(self):
    """
    Filter the LFP signal

    Returns
    -------
    np.ndarray
        Filtered LFP signal
    """
    if not hasattr(self, "lfp"):
        self.load_lfp()

    b, a = cheby2(
        self.filter_order,
        self.filter_rs,
        [self.lowcut, self.highcut],
        fs=self.fs,
        btype="bandpass",
    )
    return filtfilt(b, a, self.lfp.data)

get_average_trace(shank=None, window=[-0.15, 0.15])

Get the average LFP trace around the dentate spikes

Parameters:

Name Type Description Default
shank int

Shank number of the hilus signal

None
window list

Window around the dentate spikes

[-0.15, 0.15]

Returns:

Type Description
ndarray

Average LFP trace around the dentate spikes

ndarray

Time lags around the dentate spikes

Source code in neuro_py/detectors/dentate_spike.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def get_average_trace(self, shank=None, window=[-0.15, 0.15]):
    """
    Get the average LFP trace around the dentate spikes

    Parameters
    ----------
    shank : int, optional
        Shank number of the hilus signal
    window : list, optional
        Window around the dentate spikes

    Returns
    -------
    np.ndarray
        Average LFP trace around the dentate spikes
    np.ndarray
        Time lags around the dentate spikes
    """

    lfp, _ = loading.loadLFP(
        self.basepath,
        n_channels=self.nChannels,
        frequency=self.fs,
        ext="lfp",
    )

    if shank is None:
        hilus_shank = [
            k for k, v in self.shank_to_channel.items() if self.hilus_ch in v
        ][0]

    ds_average, time_lags = event_triggered_average_fast(
        signal=lfp[:, self.shank_to_channel[hilus_shank]].T,
        events=self.ds_epoch.starts,
        sampling_rate=self.fs,
        window=window,
        return_average=True,
    )
    return ds_average, time_lags

get_xml_data()

Load the XML file to get the number of channels, sampling frequency and shank to channel mapping

Source code in neuro_py/detectors/dentate_spike.py
145
146
147
148
149
150
151
152
153
def get_xml_data(self):
    """
    Load the XML file to get the number of channels, sampling frequency and shank to channel mapping
    """
    nChannels, fs, fs_dat, shank_to_channel = loading.loadXML(self.basepath)
    self.nChannels = nChannels
    self.fs = fs
    self.fs_dat = fs_dat
    self.shank_to_channel = shank_to_channel

load(filename) classmethod

Load a DetectDS object from a pickle file

Parameters:

Name Type Description Default
filename str

Path to the file where the DetectDS object is saved

required

Returns:

Type Description
DetectDS

The loaded DetectDS object

Source code in neuro_py/detectors/dentate_spike.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
@classmethod
def load(cls, filename: str):
    """
    Load a DetectDS object from a pickle file

    Parameters
    ----------
    filename : str
        Path to the file where the DetectDS object is saved

    Returns
    -------
    DetectDS
        The loaded DetectDS object

    """
    with open(filename, "rb") as f:
        return pickle.load(f)

load_lfp()

Load the LFP signal

Source code in neuro_py/detectors/dentate_spike.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def load_lfp(self):
    """
    Load the LFP signal
    """

    lfp, timestep = loading.loadLFP(
        self.basepath,
        n_channels=self.nChannels,
        frequency=self.fs,
        ext="lfp",
    )

    if self.noise_ch is None:
        channels = [self.hilus_ch, self.mol_ch]
    else:
        channels = [self.hilus_ch, self.mol_ch, self.noise_ch]

    self.lfp = nel.AnalogSignalArray(
        data=lfp[:, channels].T,
        timestamps=timestep,
        fs=self.fs,
        support=nel.EpochArray(np.array([min(timestep), max(timestep)])),
    )
    if self.clean_lfp:
        self.lfp._data = np.array(
            [
                clean_lfp(self.lfp.signals[0]),
                clean_lfp(self.lfp.signals[1]),
            ]
        )

plot(ax=None, window=[-0.15, 0.15], channel_offset=90000.0)

Plot the average LFP trace around the dentate spikes

Parameters:

Name Type Description Default
ax AxesSubplot

Axis to plot the average LFP trace

None
window list

Window around the dentate spikes

[-0.15, 0.15]
channel_offset float

Offset between the channels

90000.0

Returns:

Type Description
AxesSubplot

Axis with the average LFP trace

Source code in neuro_py/detectors/dentate_spike.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def plot(self, ax=None, window=[-0.15, 0.15], channel_offset=9e4):
    """
    Plot the average LFP trace around the dentate spikes

    Parameters
    ----------
    ax : matplotlib.axes._subplots.AxesSubplot, optional
        Axis to plot the average LFP trace
    window : list, optional
        Window around the dentate spikes
    channel_offset : float, optional
        Offset between the channels

    Returns
    -------
    matplotlib.axes._subplots.AxesSubplot
        Axis with the average LFP trace
    """

    import matplotlib.pyplot as plt

    ds_average, time_lags = self.get_average_trace(window=window)

    if ax is None:
        fig, ax = plt.subplots(figsize=(5, 10))

    ax.plot(
        time_lags,
        ds_average.T - np.linspace(0, channel_offset, ds_average.shape[0]),
        alpha=0.75,
    )
    return ax

save(filename)

Save the DetectDS object as a pickle file

Parameters:

Name Type Description Default
filename str

Path to the file where the DetectDS object will be saved

required

Returns:

Type Description
None
Source code in neuro_py/detectors/dentate_spike.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def save(self, filename: str):
    """
    Save the DetectDS object as a pickle file

    Parameters
    ----------
    filename : str
        Path to the file where the DetectDS object will be saved

    Returns
    -------
    None

    """
    self._detach()
    with open(filename, "wb") as f:
        pickle.dump(self, f)

save_ds_epoch()

Save the dentate spikes as a cellexplorer mat file

Source code in neuro_py/detectors/dentate_spike.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def save_ds_epoch(self):
    """
    Save the dentate spikes as a cellexplorer mat file
    """

    filename = os.path.join(
        self.basepath, os.path.basename(self.basepath) + ".DS2.events.mat"
    )
    data = {}
    data["DS2"] = {}
    data["DS2"]["detectorinfo"] = {}
    data["DS2"]["timestamps"] = self.ds_epoch.data
    data["DS2"]["peaks"] = self.peaks
    data["DS2"]["amplitudes"] = self.peak_val.T
    data["DS2"]["amplitudeUnits"] = "mV"
    data["DS2"]["eventID"] = []
    data["DS2"]["eventIDlabels"] = []
    data["DS2"]["eventIDbinary"] = []
    data["DS2"]["duration"] = self.ds_epoch.durations.T
    data["DS2"]["center"] = np.median(self.ds_epoch.data, axis=1).T
    data["DS2"]["detectorinfo"]["detectorname"] = "DetectDS"
    data["DS2"]["detectorinfo"]["detectionparms"] = []
    data["DS2"]["detectorinfo"]["detectionintervals"] = []
    data["DS2"]["detectorinfo"]["ml_channel"] = self.mol_ch
    data["DS2"]["detectorinfo"]["h_channel"] = self.hilus_ch
    if self.noise_ch is not None:
        data["DS2"]["detectorinfo"]["noise_channel"] = self.noise_ch

    savemat(filename, data, long_field_names=True)

bimodal_thresh(bimodal_data, max_thresh=np.inf, schmidt=False, max_hist_bins=25, start_bins=10, set_thresh=None, nboot=100, force_bimodal=False)

BimodalThresh: Find threshold between bimodal data modes (e.g., UP vs DOWN states) and return crossing times (UP/DOWN onset/offset times).

Parameters:

Name Type Description Default
bimodal_data array - like

Vector of bimodal data

required
max_thresh float

Maximum threshold value (default: inf)

inf
schmidt bool

Use Schmidt trigger with halfway points between trough and peaks (default: False)

False
max_hist_bins int

Maximum number of histogram bins to try before giving up (default: 25)

25
start_bins int

Minimum number of histogram bins for initial histogram (default: 10)

10
set_thresh float

Manually set your own threshold (default: None)

None
nboot int

Number of bootstrap iterations for dip test (default: 100)

100
force_bimodal bool

If True, skip bimodality test and proceed with threshold detection (default: False)

False

Returns:

Name Type Description
thresh float

Threshold value between modes

cross dict

Dictionary with keys: - 'upints': array of UP state intervals [onsets, offsets] - 'downints': array of DOWN state intervals [onsets, offsets]

bihist dict

Dictionary with keys: - 'bins': bin centers - 'hist': counts

diptest_result dict

Dictionary with keys: - 'dip': Hartigan's dip test statistic - 'p': p-value for bimodal distribution

Example

data = np.concatenate([np.random.normal(0, 1, 1000), ... np.random.normal(5, 1, 1000)]) thresh, cross, bihist, diptest_result = bimodal_thresh(data)

Notes

Python translation of BimodalThresh.m from MehrotraLevenstein_2023

Source code in neuro_py/detectors/up_down_state.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def bimodal_thresh(
    bimodal_data,
    max_thresh=np.inf,
    schmidt=False,
    max_hist_bins=25,
    start_bins=10,
    set_thresh=None,
    nboot=100,
    force_bimodal=False,
):
    """
    BimodalThresh: Find threshold between bimodal data modes (e.g., UP vs DOWN states)
    and return crossing times (UP/DOWN onset/offset times).

    Parameters
    ----------
    bimodal_data : array-like
        Vector of bimodal data
    max_thresh : float, optional
        Maximum threshold value (default: inf)
    schmidt : bool, optional
        Use Schmidt trigger with halfway points between trough and peaks (default: False)
    max_hist_bins : int, optional
        Maximum number of histogram bins to try before giving up (default: 25)
    start_bins : int, optional
        Minimum number of histogram bins for initial histogram (default: 10)
    set_thresh : float, optional
        Manually set your own threshold (default: None)
    nboot : int, optional
        Number of bootstrap iterations for dip test (default: 100)
    force_bimodal : bool, optional
        If True, skip bimodality test and proceed with threshold detection (default: False)

    Returns
    -------
    thresh : float
        Threshold value between modes
    cross : dict
        Dictionary with keys:
        - 'upints': array of UP state intervals [onsets, offsets]
        - 'downints': array of DOWN state intervals [onsets, offsets]
    bihist : dict
        Dictionary with keys:
        - 'bins': bin centers
        - 'hist': counts
    diptest_result : dict
        Dictionary with keys:
        - 'dip': Hartigan's dip test statistic
        - 'p': p-value for bimodal distribution

    Example
    -------
    >>> data = np.concatenate([np.random.normal(0, 1, 1000),
    ...                        np.random.normal(5, 1, 1000)])
    >>> thresh, cross, bihist, diptest_result = bimodal_thresh(data)

    Notes
    -----
    Python translation of BimodalThresh.m from MehrotraLevenstein_2023

    """

    # Initialize
    bimodal_data = np.array(bimodal_data).flatten()
    bimodal_data = bimodal_data[~np.isnan(bimodal_data)]

    # Run Hartigan's dip test for bimodality
    dip_stat, p_value = hartigan_diptest(bimodal_data, n_boot=nboot)
    diptest_result = {"dip": dip_stat, "p": p_value}

    # If not bimodal, return empty (unless forced)
    if p_value > 0.05 and not force_bimodal:
        cross = {"upints": np.array([]), "downints": np.array([])}
        hist_counts, bin_edges = np.histogram(bimodal_data, bins=start_bins)
        bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
        bihist = {"hist": hist_counts, "bins": bin_centers}
        return np.nan, cross, bihist, diptest_result

    # Remove data over max threshold
    bimodal_data = bimodal_data[bimodal_data < max_thresh]

    # Find histogram with exactly 2 peaks
    num_peaks = 1
    num_bins = start_bins

    while num_peaks != 2:
        hist_counts, bin_edges = np.histogram(bimodal_data, bins=num_bins)
        bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2

        # Find peaks (add zeros at edges for edge detection)
        padded_hist = np.concatenate([[0], hist_counts, [0]])
        peaks, _ = find_peaks(padded_hist, distance=1)
        peaks = np.sort(peaks) - 1  # Adjust for padding

        # Keep only top 2 peaks
        if len(peaks) > 2:
            peak_heights = hist_counts[peaks]
            top_2_idx = np.argsort(peak_heights)[-2:]
            peaks = np.sort(peaks[top_2_idx])

        num_peaks = len(peaks)
        num_bins += 1

        if num_bins >= max_hist_bins and set_thresh is None:
            print("Unable to find trough")
            cross = {"upints": np.array([]), "downints": np.array([])}
            bihist = {"hist": hist_counts, "bins": bin_centers}
            return np.nan, cross, bihist, diptest_result

    bihist = {"hist": hist_counts, "bins": bin_centers}

    # Find trough between peaks
    between_peaks = bin_centers[peaks[0] : peaks[1] + 1]
    between_hist = hist_counts[peaks[0] : peaks[1] + 1]

    # Find minimum (trough)
    trough_idx = np.argmin(between_hist)

    if set_thresh is not None:
        thresh = set_thresh
    else:
        thresh = between_peaks[trough_idx]

    # Schmidt trigger: use halfway points between trough and peaks
    if schmidt:
        thresh_up = thresh + 0.5 * (between_peaks[-1] - thresh)
        thresh_down = thresh + 0.5 * (between_peaks[0] - thresh)

        over_up = bimodal_data > thresh_up
        over_down = bimodal_data > thresh_down

        cross_up = np.where(np.diff(over_up.astype(int)) == 1)[0]
        cross_down = np.where(np.diff(over_down.astype(int)) == -1)[0]

        # Check for empty crossings before vstack
        if len(cross_up) == 0 or len(cross_down) == 0:
            cross = {
                "upints": np.array([]).reshape(0, 2),
                "downints": np.array([]).reshape(0, 2),
            }
            return thresh, cross, bihist, diptest_result

        # Delete incomplete (repeat) crossings
        all_crossings = np.vstack(
            [
                np.column_stack([cross_up, np.ones(len(cross_up))]),
                np.column_stack([cross_down, np.zeros(len(cross_down))]),
            ]
        )

        sort_order = np.argsort(all_crossings[:, 0])
        all_crossings = all_crossings[sort_order]

        up_down_switch = np.diff(all_crossings[:, 1])
        same_state = np.where(up_down_switch == 0)[0] + 1
        all_crossings = np.delete(all_crossings, same_state, axis=0)

        cross_up = all_crossings[all_crossings[:, 1] == 1, 0].astype(int)
        cross_down = all_crossings[all_crossings[:, 1] == 0, 0].astype(int)
    else:
        over_ind = bimodal_data > thresh
        cross_up = np.where(np.diff(over_ind.astype(int)) == 1)[0]
        cross_down = np.where(np.diff(over_ind.astype(int)) == -1)[0]

    # If only one crossing, return empty
    if len(cross_up) == 0 or len(cross_down) == 0:
        cross = {
            "upints": np.array([]).reshape(0, 2),
            "downints": np.array([]).reshape(0, 2),
        }
        return thresh, cross, bihist, diptest_result

    # Create interval arrays
    up_for_up = cross_up.copy()
    up_for_down = cross_up.copy()
    down_for_up = cross_down.copy()
    down_for_down = cross_down.copy()

    # Adjust for proper pairing
    if cross_up[0] < cross_down[0]:
        up_for_down = up_for_down[1:]
    if cross_down[-1] > cross_up[-1]:
        down_for_down = down_for_down[:-1]
    if cross_down[0] < cross_up[0]:
        down_for_up = down_for_up[1:]
    if cross_up[-1] > cross_down[-1]:
        up_for_up = up_for_up[:-1]

    # Ensure equal length for pairing
    min_len_up = min(len(up_for_up), len(down_for_up))
    min_len_down = min(len(down_for_down), len(up_for_down))

    # Check if pairing resulted in any valid intervals
    if min_len_up == 0 or min_len_down == 0:
        cross = {
            "upints": np.array([]).reshape(0, 2),
            "downints": np.array([]).reshape(0, 2),
        }
        return thresh, cross, bihist, diptest_result

    upints = np.column_stack([up_for_up[:min_len_up], down_for_up[:min_len_up]])
    downints = np.column_stack(
        [down_for_down[:min_len_down], up_for_down[:min_len_down]]
    )

    cross = {"upints": upints, "downints": downints}

    return thresh, cross, bihist, diptest_result

detect_sharp_wave_ripples(basepath=None, ripple_signal=None, fs=None, timestamps=None, ripple_channel=None, sharp_wave_signal=None, sharp_wave_channel=None, noise_signal=None, noise_channel=None, detection_epochs=None, ripple_band=(80.0, 250.0), sharp_wave_band=(2.0, 50.0), smooth_sigma=0.004, sharp_wave_smooth_sigma=0.0, low_threshold=1.0, high_threshold=2.5, sharp_wave_low_threshold=0.4, sharp_wave_high_threshold=2.5, noise_threshold=None, min_duration=0.015, max_duration=0.25, sharp_wave_min_duration=0.02, sharp_wave_max_duration=0.5, min_inter_event_interval=0.025, merge_gap=0.001, peak_window=0.15, boundary_mode='union', filter_order=4, threshold_mode='global', local_window=5.0, reject_edge_events=True, edge_buffer=None, reject_artifacts=True, saturation_fraction=0.05, flat_std_threshold=None, sharp_wave_polarity='negative', require_sharp_wave=True, save_mat=True, overwrite=False, return_epoch_array=False, event_name='ripples')

Detect sharp wave ripple events from a ripple-band LFP channel.

The detector follows a compact joint SWR workflow by default: detect candidate ripple intervals from ripple-band power, require a nearby sharp-wave event on a companion low-frequency channel difference, and then validate ripple and sharp-wave durations separately before returning final events. Set require_sharp_wave=False to run explicit ripple-only detection when no sharp-wave channel is available.

Parameters:

Name Type Description Default
basepath str

Session folder used to load LFP data and optionally save a CellExplorer event file. Required when save_mat=True or when ripple_signal is not provided.

None
ripple_signal ndarray

One-dimensional ripple detection signal. If omitted, the signal is loaded from basepath using ripple_channel.

None
fs float

Sampling rate in Hz. Required when ripple_signal is provided.

None
timestamps ndarray

Timestamps in seconds for ripple_signal. If omitted, they are inferred from fs.

None
ripple_channel int

Zero-indexed ripple channel. When omitted during file-backed detection, the detector tries to infer it from CellExplorer channel tags.

None
sharp_wave_signal ndarray

Optional companion signal used to measure low-frequency sharp-wave amplitude at ripple peaks.

None
sharp_wave_channel int

Zero-indexed sharp-wave channel used when loading from basepath.

None
noise_signal ndarray

Optional ripple-band noise channel. Events are rejected when the noise-band power within the event exceeds noise_threshold.

None
noise_channel int

Zero-indexed noise channel used when loading from basepath.

None
detection_epochs EpochArray or ndarray

Detection intervals in seconds. File-backed detection uses these intervals to restrict LFP loading; in-memory detection filters final events to these intervals.

None
ripple_band tuple of float

Ripple passband in Hz.

(80.0, 250.0)
sharp_wave_band tuple of float

Sharp-wave passband in Hz used for the low-frequency difference signal.

(2.0, 50.0)
smooth_sigma float

Gaussian smoothing width for the ripple envelope, in seconds.

0.004
sharp_wave_smooth_sigma float

Optional Gaussian smoothing width for the sharp-wave difference signal, in seconds.

0.0
low_threshold float

Lower z-scored ripple-envelope threshold used to mark candidate ripple boundaries.

1.0
high_threshold float

Peak z-scored ripple-envelope threshold required to accept an event.

2.5
sharp_wave_low_threshold float

Lower z-scored sharp-wave threshold used to mark candidate sharp-wave boundaries.

0.4
sharp_wave_high_threshold float

Peak z-scored sharp-wave threshold required to accept an event.

2.5
noise_threshold float

Maximum tolerated z-scored noise envelope for accepted events.

None
min_duration float

Minimum ripple duration in seconds.

0.015
max_duration float

Maximum ripple duration in seconds.

0.25
sharp_wave_min_duration float

Minimum sharp-wave duration in seconds.

0.02
sharp_wave_max_duration float

Maximum sharp-wave duration in seconds.

0.5
min_inter_event_interval float

Minimum time between accepted event peaks in seconds. Stronger events are kept first and weaker direct conflicts are removed. Set to 0 to disable.

0.025
merge_gap float

Merge candidate events separated by less than this gap, in seconds.

0.001
peak_window float

Maximum association window around the ripple candidate, in seconds, used to find the nearest/overlapping sharp-wave partner.

0.15
boundary_mode ('sharp_wave', 'union')

Whether final event boundaries follow the sharp-wave interval or the union of ripple and sharp-wave intervals.

"sharp_wave"
filter_order int

Butterworth filter order for ripple-band filtering.

4
threshold_mode ('global', 'local')

Use global z-scored features or MATLAB-like local median/std validation around each candidate event.

"global"
local_window float

Half-window in seconds used for local threshold validation when threshold_mode="local".

5.0
reject_edge_events bool

If True, reject candidate events too close to signal boundaries.

True
edge_buffer float

Boundary buffer in seconds. If omitted, uses at least peak_window and uses local_window when local thresholds are enabled.

None
reject_artifacts bool

If True, reject event windows with non-finite, saturated, or flat required signals.

True
saturation_fraction float

Maximum tolerated fraction of event-window samples at the local minimum or maximum before the window is treated as clipped.

0.05
flat_std_threshold float

Minimum allowed event-window standard deviation. Defaults to a near-zero variation check.

None
sharp_wave_polarity ('negative', 'positive', 'both')

Polarity of sharp-wave deflections. The default expects downward sharp waves and scores them positively. Ripples remain polarity independent because they are detected from envelope power.

"negative"
require_sharp_wave bool

If True, require a sharp-wave signal or inferable sharp-wave channel for joint SWR detection. If False, allow ripple-only detection when sharp-wave data are unavailable. Ripple-only detections should be interpreted cautiously because the sharp-wave criterion helps reject ripple-band noise.

True
save_mat bool

If True and basepath is provided, save a CellExplorer event file. In-memory detections without a basepath still run normally but do not write an event file.

True
overwrite bool

If False and the target event file already exists, load and return the existing file instead of redetecting.

False
return_epoch_array bool

If True, return the detected events as a nel.EpochArray.

False
event_name str

Name of the CellExplorer event struct written to disk.

'ripples'

Returns:

Type Description
DataFrame or EpochArray

Detected ripple events.

Examples:

Detect joint SWRs from a CellExplorer session folder and save the default *.ripples.events.mat file. The ripple, sharp-wave, and noise channels are inferred from channel tags when available.

>>> from neuro_py.detectors.sharp_wave_ripple import detect_sharp_wave_ripples
>>> ripples = detect_sharp_wave_ripples(
...     basepath=r"S:\data\HMC\HMC1\day8",
...     low_threshold=0.75,
...     high_threshold=2.5,
...     sharp_wave_low_threshold=0.4,
...     sharp_wave_high_threshold=2.5,
...     overwrite=True,
... )

Restrict detection to a time interval and return only the event table without writing a CellExplorer file.

>>> ripples = detect_sharp_wave_ripples(
...     basepath=r"S:\data\HMC\HMC1\day8",
...     detection_epochs=np.array([[250.0, 350.0]]),
...     save_mat=False,
... )

Run on in-memory LFP arrays. This is useful for simulations or when data have already been loaded by another pipeline.

>>> ripples = detect_sharp_wave_ripples(
...     ripple_signal=ripple_lfp,
...     sharp_wave_signal=sharp_wave_lfp,
...     fs=1250.0,
...     timestamps=timestamps,
...     save_mat=False,
... )

If no sharp-wave channel is available, ripple-only detection must be requested explicitly.

>>> ripples = detect_sharp_wave_ripples(
...     ripple_signal=ripple_lfp,
...     fs=1250.0,
...     save_mat=False,
...     require_sharp_wave=False,
... )
Source code in neuro_py/detectors/sharp_wave_ripple.py
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
def detect_sharp_wave_ripples(
    basepath: Optional[str] = None,
    ripple_signal: Optional[np.ndarray] = None,
    fs: Optional[float] = None,
    timestamps: Optional[np.ndarray] = None,
    ripple_channel: Optional[int] = None,
    sharp_wave_signal: Optional[np.ndarray] = None,
    sharp_wave_channel: Optional[int] = None,
    noise_signal: Optional[np.ndarray] = None,
    noise_channel: Optional[int] = None,
    detection_epochs: Optional[Union[nel.EpochArray, np.ndarray]] = None,
    ripple_band: tuple[float, float] = (80.0, 250.0),
    sharp_wave_band: tuple[float, float] = (2.0, 50.0),
    smooth_sigma: float = 0.004,
    sharp_wave_smooth_sigma: float = 0.0,
    low_threshold: float = 1.0,
    high_threshold: float = 2.5,
    sharp_wave_low_threshold: float = 0.4,
    sharp_wave_high_threshold: float = 2.5,
    noise_threshold: Optional[float] = None,
    min_duration: float = 0.015,
    max_duration: float = 0.250,
    sharp_wave_min_duration: float = 0.020,
    sharp_wave_max_duration: float = 0.500,
    min_inter_event_interval: float = 0.025,
    merge_gap: float = 0.001,
    peak_window: float = 0.150,
    boundary_mode: str = "union",
    filter_order: int = 4,
    threshold_mode: str = "global",
    local_window: float = 5.0,
    reject_edge_events: bool = True,
    edge_buffer: Optional[float] = None,
    reject_artifacts: bool = True,
    saturation_fraction: float = 0.05,
    flat_std_threshold: Optional[float] = None,
    sharp_wave_polarity: str = "negative",
    require_sharp_wave: bool = True,
    save_mat: bool = True,
    overwrite: bool = False,
    return_epoch_array: bool = False,
    event_name: str = "ripples",
) -> Union[pd.DataFrame, nel.EpochArray]:
    """
    Detect sharp wave ripple events from a ripple-band LFP channel.

    The detector follows a compact joint SWR workflow by default: detect
    candidate ripple intervals from ripple-band power, require a nearby
    sharp-wave event on a companion low-frequency channel difference, and then
    validate ripple and sharp-wave durations separately before returning final
    events. Set ``require_sharp_wave=False`` to run explicit ripple-only
    detection when no sharp-wave channel is available.

    Parameters
    ----------
    basepath : str, optional
        Session folder used to load LFP data and optionally save a CellExplorer
        event file. Required when ``save_mat=True`` or when ``ripple_signal`` is
        not provided.
    ripple_signal : np.ndarray, optional
        One-dimensional ripple detection signal. If omitted, the signal is loaded
        from ``basepath`` using ``ripple_channel``.
    fs : float, optional
        Sampling rate in Hz. Required when ``ripple_signal`` is provided.
    timestamps : np.ndarray, optional
        Timestamps in seconds for ``ripple_signal``. If omitted, they are inferred
        from ``fs``.
    ripple_channel : int, optional
        Zero-indexed ripple channel. When omitted during file-backed detection, the
        detector tries to infer it from CellExplorer channel tags.
    sharp_wave_signal : np.ndarray, optional
        Optional companion signal used to measure low-frequency sharp-wave
        amplitude at ripple peaks.
    sharp_wave_channel : int, optional
        Zero-indexed sharp-wave channel used when loading from ``basepath``.
    noise_signal : np.ndarray, optional
        Optional ripple-band noise channel. Events are rejected when the noise-band
        power within the event exceeds ``noise_threshold``.
    noise_channel : int, optional
        Zero-indexed noise channel used when loading from ``basepath``.
    detection_epochs : nel.EpochArray or np.ndarray, optional
        Detection intervals in seconds. File-backed detection uses these intervals
        to restrict LFP loading; in-memory detection filters final events to these
        intervals.
    ripple_band : tuple of float, optional
        Ripple passband in Hz.
    sharp_wave_band : tuple of float, optional
        Sharp-wave passband in Hz used for the low-frequency difference signal.
    smooth_sigma : float, optional
        Gaussian smoothing width for the ripple envelope, in seconds.
    sharp_wave_smooth_sigma : float, optional
        Optional Gaussian smoothing width for the sharp-wave difference signal,
        in seconds.
    low_threshold : float, optional
        Lower z-scored ripple-envelope threshold used to mark candidate ripple
        boundaries.
    high_threshold : float, optional
        Peak z-scored ripple-envelope threshold required to accept an event.
    sharp_wave_low_threshold : float, optional
        Lower z-scored sharp-wave threshold used to mark candidate sharp-wave
        boundaries.
    sharp_wave_high_threshold : float, optional
        Peak z-scored sharp-wave threshold required to accept an event.
    noise_threshold : float, optional
        Maximum tolerated z-scored noise envelope for accepted events.
    min_duration : float, optional
        Minimum ripple duration in seconds.
    max_duration : float, optional
        Maximum ripple duration in seconds.
    sharp_wave_min_duration : float, optional
        Minimum sharp-wave duration in seconds.
    sharp_wave_max_duration : float, optional
        Maximum sharp-wave duration in seconds.
    min_inter_event_interval : float, optional
        Minimum time between accepted event peaks in seconds. Stronger events
        are kept first and weaker direct conflicts are removed. Set to 0 to
        disable.
    merge_gap : float, optional
        Merge candidate events separated by less than this gap, in seconds.
    peak_window : float, optional
        Maximum association window around the ripple candidate, in seconds,
        used to find the nearest/overlapping sharp-wave partner.
    boundary_mode : {"sharp_wave", "union"}, optional
        Whether final event boundaries follow the sharp-wave interval or the
        union of ripple and sharp-wave intervals.
    filter_order : int, optional
        Butterworth filter order for ripple-band filtering.
    threshold_mode : {"global", "local"}, optional
        Use global z-scored features or MATLAB-like local median/std validation
        around each candidate event.
    local_window : float, optional
        Half-window in seconds used for local threshold validation when
        ``threshold_mode="local"``.
    reject_edge_events : bool, optional
        If True, reject candidate events too close to signal boundaries.
    edge_buffer : float, optional
        Boundary buffer in seconds. If omitted, uses at least ``peak_window`` and
        uses ``local_window`` when local thresholds are enabled.
    reject_artifacts : bool, optional
        If True, reject event windows with non-finite, saturated, or flat
        required signals.
    saturation_fraction : float, optional
        Maximum tolerated fraction of event-window samples at the local minimum
        or maximum before the window is treated as clipped.
    flat_std_threshold : float, optional
        Minimum allowed event-window standard deviation. Defaults to a
        near-zero variation check.
    sharp_wave_polarity : {"negative", "positive", "both"}, optional
        Polarity of sharp-wave deflections. The default expects downward
        sharp waves and scores them positively. Ripples remain polarity
        independent because they are detected from envelope power.
    require_sharp_wave : bool, optional
        If True, require a sharp-wave signal or inferable sharp-wave channel for
        joint SWR detection. If False, allow ripple-only detection when
        sharp-wave data are unavailable. Ripple-only detections should be
        interpreted cautiously because the sharp-wave criterion helps reject
        ripple-band noise.
    save_mat : bool, optional
        If True and ``basepath`` is provided, save a CellExplorer event file.
        In-memory detections without a ``basepath`` still run normally but do
        not write an event file.
    overwrite : bool, optional
        If False and the target event file already exists, load and return the
        existing file instead of redetecting.
    return_epoch_array : bool, optional
        If True, return the detected events as a ``nel.EpochArray``.
    event_name : str, optional
        Name of the CellExplorer event struct written to disk.

    Returns
    -------
    pandas.DataFrame or nel.EpochArray
        Detected ripple events.

    Examples
    --------
    Detect joint SWRs from a CellExplorer session folder and save the default
    ``*.ripples.events.mat`` file. The ripple, sharp-wave, and noise channels
    are inferred from channel tags when available.

    >>> from neuro_py.detectors.sharp_wave_ripple import detect_sharp_wave_ripples
    >>> ripples = detect_sharp_wave_ripples(
    ...     basepath=r"S:\\data\\HMC\\HMC1\\day8",
    ...     low_threshold=0.75,
    ...     high_threshold=2.5,
    ...     sharp_wave_low_threshold=0.4,
    ...     sharp_wave_high_threshold=2.5,
    ...     overwrite=True,
    ... )

    Restrict detection to a time interval and return only the event table
    without writing a CellExplorer file.

    >>> ripples = detect_sharp_wave_ripples(
    ...     basepath=r"S:\\data\\HMC\\HMC1\\day8",
    ...     detection_epochs=np.array([[250.0, 350.0]]),
    ...     save_mat=False,
    ... )

    Run on in-memory LFP arrays. This is useful for simulations or when data
    have already been loaded by another pipeline.

    >>> ripples = detect_sharp_wave_ripples(
    ...     ripple_signal=ripple_lfp,
    ...     sharp_wave_signal=sharp_wave_lfp,
    ...     fs=1250.0,
    ...     timestamps=timestamps,
    ...     save_mat=False,
    ... )

    If no sharp-wave channel is available, ripple-only detection must be
    requested explicitly.

    >>> ripples = detect_sharp_wave_ripples(
    ...     ripple_signal=ripple_lfp,
    ...     fs=1250.0,
    ...     save_mat=False,
    ...     require_sharp_wave=False,
    ... )
    """
    if basepath is None and ripple_signal is None:
        raise ValueError("Provide either `basepath` or `ripple_signal` for detection.")
    if boundary_mode not in {"sharp_wave", "union"}:
        raise ValueError("`boundary_mode` must be either 'sharp_wave' or 'union'.")
    if threshold_mode not in {"global", "local"}:
        raise ValueError("`threshold_mode` must be either 'global' or 'local'.")
    if sharp_wave_polarity not in {"negative", "positive", "both"}:
        raise ValueError(
            "`sharp_wave_polarity` must be 'negative', 'positive', or 'both'."
        )
    if min_inter_event_interval < 0:
        raise ValueError("`min_inter_event_interval` must be non-negative.")
    if local_window <= 0:
        raise ValueError("`local_window` must be positive.")
    if not 0 < saturation_fraction <= 1:
        raise ValueError("`saturation_fraction` must be in the interval (0, 1].")
    if edge_buffer is not None and edge_buffer < 0:
        raise ValueError("`edge_buffer` must be non-negative.")

    should_save_mat = bool(save_mat and basepath is not None)

    if should_save_mat and not overwrite:
        event_path = os.path.join(
            basepath,
            os.path.basename(basepath) + f".{event_name}.events.mat",
        )
        if os.path.exists(event_path):
            if event_name == "ripples":
                existing = loading.load_ripples_events(basepath)
            else:
                existing = loading.load_events(basepath, event_name, load_pandas=True)
                if existing is None:
                    existing = pd.DataFrame()
                else:
                    existing = existing.rename(
                        columns={"starts": "start", "stops": "stop"}
                    )
            if return_epoch_array:
                if existing.empty:
                    return nel.EpochArray(np.empty((0, 2), dtype=float))
                return nel.EpochArray(existing[["start", "stop"]].to_numpy(dtype=float))
            return existing

    if ripple_signal is None:
        ripple_signal, timestamps, fs, ripple_channel, loaded_signals = _load_signals(
            basepath=basepath,
            ripple_channel=ripple_channel,
            sharp_wave_channel=sharp_wave_channel,
            noise_channel=noise_channel,
            detection_epochs=detection_epochs,
        )
        sharp_wave_signal = loaded_signals["sharp_wave_signal"]
        noise_signal = loaded_signals["noise_signal"]
    else:
        if fs is None:
            raise ValueError("`fs` is required when `ripple_signal` is provided.")
        ripple_signal = np.asarray(ripple_signal, dtype=float)
        if ripple_signal.ndim != 1:
            raise ValueError("`ripple_signal` must be one-dimensional.")
        if timestamps is None:
            timestamps = np.arange(ripple_signal.size, dtype=float) / float(fs)
        else:
            timestamps = np.asarray(timestamps, dtype=float)
        if timestamps.shape[0] != ripple_signal.shape[0]:
            raise ValueError(
                "`timestamps` must have the same length as `ripple_signal`."
            )
        if sharp_wave_signal is not None:
            sharp_wave_signal = np.asarray(sharp_wave_signal, dtype=float)
        if noise_signal is not None:
            noise_signal = np.asarray(noise_signal, dtype=float)

    if require_sharp_wave and sharp_wave_signal is None:
        raise ValueError(
            "Joint SWR detection requires a sharp-wave signal. Pass "
            "`sharp_wave_signal`, provide `sharp_wave_channel`, add a "
            "CellExplorer SharpWave channel tag, or set "
            "`require_sharp_wave=False` for explicit ripple-only detection."
        )

    ripple_filtered, envelope, ripple_phase = _compute_envelope(
        signal_in=ripple_signal,
        fs=float(fs),
        ripple_band=ripple_band,
        smooth_sigma=smooth_sigma,
        filter_order=filter_order,
    )
    power = _zscore(envelope)

    candidate_bounds = _find_true_bounds(power >= low_threshold)
    candidate_bounds = _merge_bounds(
        candidate_bounds,
        gap_samples=max(1, int(round(merge_gap * float(fs)))),
    )

    sharp_wave_trace = None
    sharp_wave_power = None
    sharp_wave_bounds = None
    if sharp_wave_signal is not None:
        sharp_wave_trace, sharp_wave_power = _compute_sharp_wave_difference(
            ripple_signal=ripple_signal,
            sharp_wave_signal=sharp_wave_signal,
            fs=float(fs),
            sharp_wave_band=sharp_wave_band,
            filter_order=filter_order,
            smooth_sigma=sharp_wave_smooth_sigma,
            sharp_wave_polarity=sharp_wave_polarity,
        )
        sharp_wave_bounds = _find_true_bounds(
            sharp_wave_power >= sharp_wave_low_threshold
        )
        sharp_wave_bounds = _merge_bounds(
            sharp_wave_bounds,
            gap_samples=max(1, int(round(merge_gap * float(fs)))),
        )

    noise_power = None
    if noise_signal is not None:
        _, noise_envelope, _ = _compute_envelope(
            signal_in=noise_signal,
            fs=float(fs),
            ripple_band=ripple_band,
            smooth_sigma=smooth_sigma,
            filter_order=filter_order,
        )
        noise_power = _zscore(noise_envelope)

    effective_edge_buffer = peak_window if edge_buffer is None else float(edge_buffer)
    if threshold_mode == "local":
        effective_edge_buffer = max(effective_edge_buffer, float(local_window))

    events = _events_to_dataframe(
        ripple_bounds=candidate_bounds,
        ripple_power=power,
        ripple_envelope=envelope,
        ripple_filtered=ripple_filtered,
        ripple_phase=ripple_phase,
        ripple_signal=ripple_signal,
        timestamps=timestamps,
        fs=float(fs),
        ripple_min_duration=min_duration,
        ripple_max_duration=max_duration,
        ripple_high_threshold=high_threshold,
        ripple_channel=ripple_channel,
        sharp_wave_bounds=sharp_wave_bounds,
        sharp_wave_power=sharp_wave_power,
        sharp_wave_trace=sharp_wave_trace,
        sharp_wave_low_threshold=sharp_wave_low_threshold,
        sharp_wave_high_threshold=sharp_wave_high_threshold,
        sharp_wave_min_duration=sharp_wave_min_duration,
        sharp_wave_max_duration=sharp_wave_max_duration,
        search_window=peak_window,
        boundary_mode=boundary_mode,
        noise_power=noise_power,
        noise_signal=noise_signal,
        noise_threshold=noise_threshold,
        sharp_wave_signal=sharp_wave_signal,
        threshold_mode=threshold_mode,
        local_window=local_window,
        reject_edge_events=reject_edge_events,
        edge_buffer=effective_edge_buffer,
        reject_artifacts=reject_artifacts,
        saturation_fraction=saturation_fraction,
        flat_std_threshold=flat_std_threshold,
    )

    events = _filter_events_to_detection_epochs(events, detection_epochs)
    events = _enforce_min_inter_event_interval(events, min_inter_event_interval)

    if should_save_mat:
        detection_params = {
            "ripple_band": np.asarray(ripple_band, dtype=float),
            "sharp_wave_band": np.asarray(sharp_wave_band, dtype=float),
            "smooth_sigma": float(smooth_sigma),
            "sharp_wave_smooth_sigma": float(sharp_wave_smooth_sigma),
            "low_threshold": float(low_threshold),
            "high_threshold": float(high_threshold),
            "sharp_wave_low_threshold": float(sharp_wave_low_threshold),
            "sharp_wave_high_threshold": float(sharp_wave_high_threshold),
            "noise_threshold": noise_threshold,
            "min_duration": float(min_duration),
            "max_duration": float(max_duration),
            "sharp_wave_min_duration": float(sharp_wave_min_duration),
            "sharp_wave_max_duration": float(sharp_wave_max_duration),
            "min_inter_event_interval": float(min_inter_event_interval),
            "merge_gap": float(merge_gap),
            "peak_window": float(peak_window),
            "boundary_mode": boundary_mode,
            "threshold_mode": threshold_mode,
            "local_window": float(local_window),
            "reject_edge_events": bool(reject_edge_events),
            "edge_buffer": effective_edge_buffer,
            "reject_artifacts": bool(reject_artifacts),
            "saturation_fraction": float(saturation_fraction),
            "flat_std_threshold": flat_std_threshold,
            "sharp_wave_polarity": sharp_wave_polarity,
            "require_sharp_wave": bool(require_sharp_wave),
            "filter_order": int(filter_order),
        }
        if ripple_channel is not None:
            detection_params["channel"] = int(ripple_channel)

        save_ripple_events(
            events=events,
            basepath=basepath,
            detection_name="detect_sharp_wave_ripples",
            detection_params=detection_params,
            ripple_channel=ripple_channel,
            detection_epochs=detection_epochs,
            event_name=event_name,
        )

    if return_epoch_array:
        if events.empty:
            return nel.EpochArray(np.empty((0, 2), dtype=float))
        return nel.EpochArray(events[["start", "stop"]].to_numpy(dtype=float))

    return events

detect_up_down_states(basepath=None, st=None, nrem_epochs=None, region='ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX', min_dur=0.03, max_dur=0.5, percentile=20, bin_size=0.01, smooth_sigma=0.02, min_cells=10, save_mat=True, epoch_by_epoch=False, beh_epochs=None, show_figure=False, overwrite=False)

Detect UP and DOWN states in neural data.

UP and DOWN states are identified by computing the total firing rate of all simultaneously recorded neurons in bins of 10 ms, smoothed with a Gaussian kernel of 20 ms s.d. Epochs with a firing rate below the specified percentile threshold are considered DOWN states, while the intervals between DOWN states are classified as UP states. Epochs shorter than min_dur or longer than max_dur are discarded.

Parameters:

Name Type Description Default
basepath str

Base directory path where event files and neural data are stored.

None
st Optional[SpikeTrain]

Spike train data. If None, spike data will be loaded based on specified regions.

None
nrem_epochs Optional[EpochArray]

NREM epochs. If None, epochs will be loaded from the basepath.

None
region str

Brain regions for loading spikes. The first region is prioritized.

"ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC"
min_dur float

Minimum duration for DOWN states, in seconds.

0.03
max_dur float

Maximum duration for DOWN states, in seconds.

0.5
percentile float

Percentile threshold for determining DOWN states based on firing rate.

20
bin_size float

Bin size for computing firing rates, in seconds.

0.01
smooth_sigma float

Standard deviation for Gaussian kernel smoothing, in seconds.

0.02
min_cells int

Minimum number of neurons required for analysis.

10
save_mat bool

Whether to save the detected UP and DOWN states to .mat files.

True
epoch_by_epoch bool

Whether to perform detection epoch by epoch. If True, detection will be performed separately for each sleep epoch.

False
beh_epochs Optional[EpochArray]

Optional behavioral epochs to use for epoch-by-epoch detection. If None, sleep epochs will be loaded and used.

None
show_figure bool

Whether to display a figure showing firing rates during detected UP and DOWN states.

False
overwrite bool

Whether to overwrite existing .mat files when saving detected states.

False

Returns:

Type Description
Tuple[Optional[EpochArray], Optional[EpochArray]]

A tuple containing the detected DOWN state epochs and UP state epochs. Returns (None, None) if no suitable states are found or insufficient data is available.

Examples:

>>> down_state, up_state = detect_up_down_states(basepath="/path/to/data", show_figure=True)

From command line: $ python up_down_state.py /path/to/data

Notes

Detection method based on https://doi.org/10.1038/s41467-020-15842-4

Source code in neuro_py/detectors/up_down_state.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def detect_up_down_states(
    basepath: Optional[str] = None,
    st: Optional[nel.SpikeTrainArray] = None,
    nrem_epochs: Optional[nel.EpochArray] = None,
    region: str = "ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX",
    min_dur: float = 0.03,
    max_dur: float = 0.5,
    percentile: float = 20,
    bin_size: float = 0.01,
    smooth_sigma: float = 0.02,
    min_cells: int = 10,
    save_mat: bool = True,
    epoch_by_epoch: bool = False,
    beh_epochs: Optional[nel.EpochArray] = None,
    show_figure: bool = False,
    overwrite: bool = False,
) -> Tuple[Optional[nel.EpochArray], Optional[nel.EpochArray]]:
    """
    Detect UP and DOWN states in neural data.

    UP and DOWN states are identified by computing the total firing rate of all
    simultaneously recorded neurons in bins of 10 ms, smoothed with a Gaussian kernel
    of 20 ms s.d. Epochs with a firing rate below the specified percentile threshold
    are considered DOWN states, while the intervals between DOWN states are classified
    as UP states. Epochs shorter than `min_dur` or longer than `max_dur` are discarded.

    Parameters
    ----------
    basepath : str
        Base directory path where event files and neural data are stored.
    st : Optional[nel.SpikeTrain], default=None
        Spike train data. If None, spike data will be loaded based on specified regions.
    nrem_epochs : Optional[nel.EpochArray], default=None
        NREM epochs. If None, epochs will be loaded from the basepath.
    region : str, default="ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC"
        Brain regions for loading spikes. The first region is prioritized.
    min_dur : float, default=0.03
        Minimum duration for DOWN states, in seconds.
    max_dur : float, default=0.5
        Maximum duration for DOWN states, in seconds.
    percentile : float, default=20
        Percentile threshold for determining DOWN states based on firing rate.
    bin_size : float, default=0.01
        Bin size for computing firing rates, in seconds.
    smooth_sigma : float, default=0.02
        Standard deviation for Gaussian kernel smoothing, in seconds.
    min_cells : int, default=10
        Minimum number of neurons required for analysis.
    save_mat : bool, default=True
        Whether to save the detected UP and DOWN states to .mat files.
    epoch_by_epoch : bool, default=False
        Whether to perform detection epoch by epoch. If True, detection will be performed separately for each sleep epoch.
    beh_epochs : Optional[nel.EpochArray], default=None
        Optional behavioral epochs to use for epoch-by-epoch detection. If None, sleep epochs will be loaded and used.
    show_figure : bool, default=False
        Whether to display a figure showing firing rates during detected UP and DOWN states.
    overwrite : bool, default=False
        Whether to overwrite existing .mat files when saving detected states.

    Returns
    -------
    Tuple[Optional[nel.EpochArray], Optional[nel.EpochArray]]
        A tuple containing the detected DOWN state epochs and UP state epochs.
        Returns (None, None) if no suitable states are found or insufficient data is available.

    Examples
    --------
    >>> down_state, up_state = detect_up_down_states(basepath="/path/to/data", show_figure=True)

    From command line:
    $ python up_down_state.py /path/to/data

    Notes
    -----
    Detection method based on https://doi.org/10.1038/s41467-020-15842-4
    """

    def _detect_states(bst_segment: nel.AnalogSignalArray, domain: nel.EpochArray):
        """Detect down/up states within a given domain using shared logic."""

        down_state_epochs = bst_segment.bin_centers[
            find_interval(
                bst_segment.data.flatten()
                < np.percentile(bst_segment.data.T, percentile)
            )
        ]
        if down_state_epochs.shape[0] == 0:
            return None, None

        durations = down_state_epochs[:, 1] - down_state_epochs[:, 0]
        down_state_epochs = down_state_epochs[durations > bin_size]

        down_state_epochs = (
            nel.EpochArray(data=down_state_epochs).merge(gap=bin_size * 2).data
        )
        durations = down_state_epochs[:, 1] - down_state_epochs[:, 0]
        down_state_epochs = down_state_epochs[
            ~((durations < min_dur) | (durations > max_dur)), :
        ]
        if down_state_epochs.shape[0] == 0:
            return None, None

        down_state_epochs = nel.EpochArray(data=down_state_epochs, domain=domain)

        up_state_epochs = ~down_state_epochs
        up_state_epochs = up_state_epochs.data
        # make sure up states are longer than bin size
        durations = up_state_epochs[:, 1] - up_state_epochs[:, 0]
        up_state_epochs = up_state_epochs[durations > bin_size]
        # merge nearby up states that are closer than 2*bin_size
        up_state_epochs = nel.EpochArray(data=up_state_epochs, domain=domain).merge(
            gap=bin_size * 2
        )

        return down_state_epochs, up_state_epochs

    # check for existence of event files
    if save_mat and not overwrite:
        filename_downstate = os.path.join(
            basepath, os.path.basename(basepath) + "." + "down_state" + ".events.mat"
        )
        filename_upstate = os.path.join(
            basepath, os.path.basename(basepath) + "." + "up_state" + ".events.mat"
        )
        if os.path.exists(filename_downstate) & os.path.exists(filename_upstate):
            down_state = loading.load_events(basepath=basepath, epoch_name="down_state")
            up_state = loading.load_events(basepath=basepath, epoch_name="up_state")
            return down_state, up_state

    # load brain states
    if nrem_epochs is None:
        state_dict = loading.load_SleepState_states(basepath)
        nrem_epochs = nel.EpochArray(state_dict["NREMstate"])

    if nrem_epochs.isempty:
        print(f"No NREM epochs found for {basepath}")
        return None, None

    # load spikes
    if st is None:
        st, _ = loading.load_spikes(basepath, brainRegion=region)

    # check if there are enough cells
    if st is None or st.isempty or st.data.shape[0] < min_cells:
        print(f"No spikes found for {basepath} {region}")
        return None, None

    # flatten spikes
    st = st[nrem_epochs].flatten()

    # bin and smooth
    bst = st.bin(ds=bin_size).smooth(sigma=smooth_sigma)

    if epoch_by_epoch:
        if beh_epochs is None:
            epoch_df = npy.io.load_epoch(basepath)
            epoch_df = npy.session.compress_repeated_epochs(epoch_df)
            epoch_df = epoch_df.query("environment == 'sleep'")
            beh_epochs = nel.EpochArray(epoch_df[["startTime", "stopTime"]].values)

        down_state_epochs = []
        up_state_epochs = []
        for ep in beh_epochs:
            domain = nrem_epochs & ep
            if domain.isempty:
                continue

            down_state_epochs_, up_state_epochs_ = _detect_states(bst[domain], domain)
            if down_state_epochs_ is None or up_state_epochs_ is None:
                continue

            down_state_epochs.append(down_state_epochs_.data)
            up_state_epochs.append(up_state_epochs_.data)

        if len(down_state_epochs) == 0 or len(up_state_epochs) == 0:
            print(f"No down states found for {basepath}")
            return None, None

        down_state_epochs = nel.EpochArray(
            data=np.concatenate(down_state_epochs), domain=nrem_epochs
        )
        up_state_epochs = nel.EpochArray(
            data=np.concatenate(up_state_epochs), domain=nrem_epochs
        )
    else:
        down_state_epochs, up_state_epochs = _detect_states(bst, nrem_epochs)
        if down_state_epochs is None or up_state_epochs is None:
            print(f"No down states found for {basepath}")
            return None, None

    # save to cell explorer mat file
    if save_mat:
        epoch_to_mat(down_state_epochs, basepath, "down_state", "detect_up_down_states")
        epoch_to_mat(up_state_epochs, basepath, "up_state", "detect_up_down_states")

    # optional figure to show firing rate during up and down states
    if show_figure:
        from matplotlib import pyplot as plt

        plt.figure()
        ax = plt.gca()
        psth = npy.process.compute_psth(st.data, down_state_epochs.starts, n_bins=500)
        psth.columns = ["Down states"]
        psth.plot(ax=ax)

        psth = npy.process.compute_psth(st.data, up_state_epochs.starts, n_bins=500)
        psth.columns = ["Up states"]

        psth.plot(ax=ax)
        ax.legend(loc="upper right", frameon=False)
        ax.axvline(0, color="k", linestyle="--")

        ax.set_xlabel("Time from state transition (s)")
        ax.set_ylabel("Firing rate (Hz)")

    return down_state_epochs, up_state_epochs

detect_up_down_states_bimodal_thresh(basepath=None, st=None, nrem_epochs=None, region='ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX', bin_size=0.01, smooth_sigma=0.02, min_cells=10, save_mat=True, epoch_by_epoch=False, beh_epochs=None, show_figure=False, overwrite=False, schmidt=False, nboot=100, force_bimodal=False)

Detect UP and DOWN states using bimodal_thresh on firing rate distribution.

Uses the same data loading and epoch-by-epoch logic as detect_up_down_states, but applies Hartigan's dip test and bimodal threshold detection instead of a fixed percentile. This is useful when UP/DOWN states form a clear bimodal distribution in the firing rate histogram.

Parameters:

Name Type Description Default
basepath str

Base directory path where event files and neural data are stored.

None
st Optional[SpikeTrainArray]

Spike train data. If None, spike data will be loaded based on specified regions.

None
nrem_epochs Optional[EpochArray]

NREM epochs. If None, epochs will be loaded from the basepath.

None
region str

Brain regions for loading spikes. The first region is prioritized.

"ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX"
bin_size float

Bin size for computing firing rates, in seconds.

0.01
smooth_sigma float

Standard deviation for Gaussian kernel smoothing, in seconds.

0.02
min_cells int

Minimum number of neurons required for analysis.

10
save_mat bool

Whether to save the detected UP and DOWN states to .mat files.

True
epoch_by_epoch bool

Whether to perform detection epoch by epoch.

False
beh_epochs Optional[EpochArray]

Optional behavioral epochs to use for epoch-by-epoch detection.

None
show_figure bool

Whether to display a figure showing firing rates during detected UP and DOWN states.

False
overwrite bool

Whether to overwrite existing .mat files when saving detected states.

False
schmidt bool

Use Schmidt trigger (hysteresis) for state transitions in bimodal_thresh.

False
nboot int

Number of bootstrap iterations for Hartigan's dip test. Reduce further (e.g., 50) for very long recordings to improve performance.

100
force_bimodal bool

If True, skip the bimodality test and force threshold detection even if the distribution appears unimodal. Use with caution.

False

Returns:

Type Description
Tuple[Optional[EpochArray], Optional[EpochArray]]

A tuple containing the detected DOWN state epochs and UP state epochs. Returns (None, None) if no suitable states are found or insufficient data is available.

Source code in neuro_py/detectors/up_down_state.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def detect_up_down_states_bimodal_thresh(
    basepath: Optional[str] = None,
    st: Optional[nel.SpikeTrainArray] = None,
    nrem_epochs: Optional[nel.EpochArray] = None,
    region: str = "ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX",
    bin_size: float = 0.01,
    smooth_sigma: float = 0.02,
    min_cells: int = 10,
    save_mat: bool = True,
    epoch_by_epoch: bool = False,
    beh_epochs: Optional[nel.EpochArray] = None,
    show_figure: bool = False,
    overwrite: bool = False,
    schmidt: bool = False,
    nboot: int = 100,
    force_bimodal: bool = False,
) -> Tuple[Optional[nel.EpochArray], Optional[nel.EpochArray]]:
    """
    Detect UP and DOWN states using bimodal_thresh on firing rate distribution.

    Uses the same data loading and epoch-by-epoch logic as `detect_up_down_states`,
    but applies Hartigan's dip test and bimodal threshold detection instead of a
    fixed percentile. This is useful when UP/DOWN states form a clear bimodal
    distribution in the firing rate histogram.

    Parameters
    ----------
    basepath : str
        Base directory path where event files and neural data are stored.
    st : Optional[nel.SpikeTrainArray], default=None
        Spike train data. If None, spike data will be loaded based on specified regions.
    nrem_epochs : Optional[nel.EpochArray], default=None
        NREM epochs. If None, epochs will be loaded from the basepath.
    region : str, default="ILA|PFC|PL|EC1|EC2|EC3|EC4|EC5|MEC|CTX"
        Brain regions for loading spikes. The first region is prioritized.
    bin_size : float, default=0.01
        Bin size for computing firing rates, in seconds.
    smooth_sigma : float, default=0.02
        Standard deviation for Gaussian kernel smoothing, in seconds.
    min_cells : int, default=10
        Minimum number of neurons required for analysis.
    save_mat : bool, default=True
        Whether to save the detected UP and DOWN states to .mat files.
    epoch_by_epoch : bool, default=False
        Whether to perform detection epoch by epoch.
    beh_epochs : Optional[nel.EpochArray], default=None
        Optional behavioral epochs to use for epoch-by-epoch detection.
    show_figure : bool, default=False
        Whether to display a figure showing firing rates during detected UP and DOWN states.
    overwrite : bool, default=False
        Whether to overwrite existing .mat files when saving detected states.
    schmidt : bool, default=False
        Use Schmidt trigger (hysteresis) for state transitions in bimodal_thresh.
    nboot : int, default=100
        Number of bootstrap iterations for Hartigan's dip test. Reduce further (e.g., 50)
        for very long recordings to improve performance.
    force_bimodal : bool, default=False
        If True, skip the bimodality test and force threshold detection even if
        the distribution appears unimodal. Use with caution.

    Returns
    -------
    Tuple[Optional[nel.EpochArray], Optional[nel.EpochArray]]
        A tuple containing the detected DOWN state epochs and UP state epochs.
        Returns (None, None) if no suitable states are found or insufficient data is available.
    """

    # check for existence of event files
    if save_mat and not overwrite:
        filename_downstate = os.path.join(
            basepath,
            os.path.basename(basepath) + "." + "down_state" + ".events.mat",
        )
        filename_upstate = os.path.join(
            basepath,
            os.path.basename(basepath) + "." + "up_state" + ".events.mat",
        )
        if os.path.exists(filename_downstate) & os.path.exists(filename_upstate):
            down_state = loading.load_events(basepath=basepath, epoch_name="down_state")
            up_state = loading.load_events(basepath=basepath, epoch_name="up_state")
            return down_state, up_state

    # load brain states
    if nrem_epochs is None:
        state_dict = loading.load_SleepState_states(basepath)
        nrem_epochs = nel.EpochArray(state_dict["NREMstate"])

    if nrem_epochs.isempty:
        print(f"No NREM epochs found for {basepath}")
        return None, None

    # load spikes
    if st is None:
        st, _ = loading.load_spikes(basepath, brainRegion=region)

    # check if there are enough cells
    if st is None or st.isempty or st.data.shape[0] < min_cells:
        print(f"No spikes found for {basepath} {region}")
        return None, None

    # flatten spikes
    st = st[nrem_epochs].flatten()

    # bin and smooth
    bst = st.bin(ds=bin_size).smooth(sigma=smooth_sigma)

    def _detect_states_bimodal(
        bst_segment: nel.AnalogSignalArray, domain: nel.EpochArray
    ):
        """Detect down/up states using bimodal_thresh within a given domain."""

        # Get firing rate time series
        firing_rates = bst_segment.data.flatten()
        if firing_rates.size == 0:
            return None, None

        # Apply bimodal_thresh to the firing rates
        thresh, cross, bihist, diptest_result = bimodal_thresh(
            firing_rates, schmidt=schmidt, nboot=nboot, force_bimodal=force_bimodal
        )

        # If not bimodal or no threshold found
        if np.isnan(thresh):
            return None, None

        # Get bin centers (times)
        bin_centers = bst_segment.bin_centers

        # Extract downints and upints from cross
        downints = cross["downints"]  # indices into firing_rates array [n_intervals, 2]
        upints = cross["upints"]

        # Convert indices to time intervals using bin_centers
        if downints.size == 0:
            return None, None

        # Clip indices to valid range to prevent out-of-bounds access
        n_bins = len(bin_centers)
        downints_clipped = np.clip(downints.astype(int), 0, n_bins - 1)
        upints_clipped = (
            np.clip(upints.astype(int), 0, n_bins - 1)
            if upints.size > 0
            else np.array([], dtype=int).reshape(0, 2)
        )

        # Convert index intervals to time intervals
        # downints has shape [n, 2] where each row is [start_idx, end_idx]
        down_state_times = np.column_stack(
            [
                bin_centers[downints_clipped[:, 0]],
                bin_centers[downints_clipped[:, 1]],
            ]
        )
        down_state_epochs = nel.EpochArray(data=down_state_times, domain=domain)

        if upints.size == 0:
            # Generate up states as complement
            up_state_epochs = ~down_state_epochs
        else:
            up_state_times = np.column_stack(
                [
                    bin_centers[upints_clipped[:, 0]],
                    bin_centers[upints_clipped[:, 1]],
                ]
            )
            up_state_epochs = nel.EpochArray(data=up_state_times, domain=domain)

        return down_state_epochs, up_state_epochs

    if epoch_by_epoch:
        if beh_epochs is None:
            epoch_df = npy.io.load_epoch(basepath)
            epoch_df = npy.session.compress_repeated_epochs(epoch_df)
            epoch_df = epoch_df.query("environment == 'sleep'")
            beh_epochs = nel.EpochArray(epoch_df[["startTime", "stopTime"]].values)

        down_state_epochs = []
        up_state_epochs = []
        for ep in beh_epochs:
            domain = nrem_epochs & ep
            if domain.isempty:
                continue

            down_state_epochs_, up_state_epochs_ = _detect_states_bimodal(
                bst[domain], domain
            )
            if down_state_epochs_ is None or up_state_epochs_ is None:
                continue

            down_state_epochs.append(down_state_epochs_.data)
            up_state_epochs.append(up_state_epochs_.data)

        if len(down_state_epochs) == 0 or len(up_state_epochs) == 0:
            print(f"No down states found for {basepath}")
            return None, None

        down_state_epochs = nel.EpochArray(
            data=np.concatenate(down_state_epochs), domain=nrem_epochs
        )
        up_state_epochs = nel.EpochArray(
            data=np.concatenate(up_state_epochs), domain=nrem_epochs
        )
    else:
        down_state_epochs, up_state_epochs = _detect_states_bimodal(
            bst[nrem_epochs], nrem_epochs
        )
        if down_state_epochs is None or up_state_epochs is None:
            print(f"No down states found for {basepath}")
            return None, None

    # save to cell explorer mat file
    if save_mat:
        epoch_to_mat(
            down_state_epochs,
            basepath,
            "down_state",
            "detect_up_down_states_bimodal_thresh",
        )
        epoch_to_mat(
            up_state_epochs,
            basepath,
            "up_state",
            "detect_up_down_states_bimodal_thresh",
        )

    # optional figure to show firing rate during up and down states
    if show_figure:
        from matplotlib import pyplot as plt

        plt.figure()
        ax = plt.gca()
        psth = npy.process.compute_psth(st.data, down_state_epochs.starts, n_bins=500)
        psth.columns = ["Down states"]
        psth.plot(ax=ax)

        psth = npy.process.compute_psth(st.data, up_state_epochs.starts, n_bins=500)
        psth.columns = ["Up states"]

        psth.plot(ax=ax)
        ax.legend(loc="upper right", frameon=False)
        ax.axvline(0, color="k", linestyle="--")

        ax.set_xlabel("Time from state transition (s)")
        ax.set_ylabel("Firing rate (Hz)")

    return down_state_epochs, up_state_epochs

hartigan_diptest(data, n_boot=100, seed=None)

Dependency-free approximation of Hartigan's dip test with bootstrap p-value.

This implementation uses a simple piecewise-linear unimodal fit to approximate the dip statistic and estimates the p-value via bootstrap draws from a unimodal Gaussian null. It avoids the external diptest package while preserving the API footprint needed by bimodal_thresh.

Parameters:

Name Type Description Default
data ndarray

Input data array (1-D). NaN values are automatically removed.

required
n_boot int

Number of bootstrap samples drawn from a unimodal Gaussian null to estimate the p-value (default: 100).

100
seed int

Random seed for reproducibility (default: None).

None

Returns:

Name Type Description
dip float

Hartigan's dip statistic. Lower values indicate more unimodal distributions.

p_value float

Bootstrap p-value. Values < 0.05 suggest a significantly bimodal distribution.

Notes

For large datasets (n > 10000), consider reducing n_boot further or downsampling the data to improve performance. The function automatically caps bootstrap sample size at 2000 to maintain computational efficiency.

Source code in neuro_py/detectors/up_down_state.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def hartigan_diptest(
    data: np.ndarray, n_boot: int = 100, seed: Optional[int] = None
) -> Tuple[float, float]:
    """
    Dependency-free approximation of Hartigan's dip test with bootstrap p-value.

    This implementation uses a simple piecewise-linear unimodal fit to approximate
    the dip statistic and estimates the p-value via bootstrap draws from a
    unimodal Gaussian null. It avoids the external ``diptest`` package while
    preserving the API footprint needed by ``bimodal_thresh``.

    Parameters
    ----------
    data : np.ndarray
        Input data array (1-D). NaN values are automatically removed.
    n_boot : int, optional
        Number of bootstrap samples drawn from a unimodal Gaussian null to estimate
        the p-value (default: 100).
    seed : int, optional
        Random seed for reproducibility (default: None).

    Returns
    -------
    dip : float
        Hartigan's dip statistic. Lower values indicate more unimodal distributions.
    p_value : float
        Bootstrap p-value. Values < 0.05 suggest a significantly bimodal distribution.

    Notes
    -----
    For large datasets (n > 10000), consider reducing n_boot further or
    downsampling the data to improve performance. The function automatically
    caps bootstrap sample size at 2000 to maintain computational efficiency.
    """

    rng = np.random.default_rng(seed)
    x = np.asarray(data, dtype=float).ravel()
    x = x[~np.isnan(x)]
    n = x.size
    if n < 3:
        return 0.0, 1.0

    x = np.sort(x)
    ecdf = (np.arange(1, n + 1)) / n

    def _candidate_dip(mode_idx: int) -> float:
        # Build a unimodal CDF that rises linearly to the candidate mode
        # and then linearly to 1.0; dip is the sup norm against the ECDF.
        left_span = max(x[mode_idx] - x[0], 1e-12)
        right_span = max(x[-1] - x[mode_idx], 1e-12)

        left_mass = mode_idx / n
        right_mass = 1.0 - left_mass

        left_mask = x <= x[mode_idx]
        u = np.empty_like(x, dtype=float)
        u[left_mask] = ((x[left_mask] - x[0]) / left_span) * left_mass
        u[~left_mask] = (
            left_mass + ((x[~left_mask] - x[mode_idx]) / right_span) * right_mass
        )
        u = np.clip(u, 0.0, 1.0)

        return float(np.max(np.abs(ecdf - u)))

    # Scan candidate modes (skip endpoints so both sides have support)
    # For performance, sample candidate modes instead of checking all for large n
    if n > 1000:
        candidate_modes = np.linspace(1, n - 2, min(100, n - 2), dtype=int)
    else:
        candidate_modes = range(1, n - 1)

    dip_stat = float(min(_candidate_dip(m) for m in candidate_modes))

    # Bootstrap p-value under a unimodal Gaussian null
    # Downsample for very large datasets to maintain reasonable runtime
    boot_n = min(n, 2000)  # Cap bootstrap sample size
    boot_dips = np.empty(max(int(n_boot), 1), dtype=float)

    for i in range(boot_dips.size):
        boot_sample = rng.standard_normal(boot_n)
        boot_sample.sort()
        boot_ecdf = (np.arange(1, boot_n + 1)) / boot_n

        # Sample candidate modes for large bootstrap samples
        if boot_n > 1000:
            boot_candidates = np.linspace(
                1, boot_n - 2, min(100, boot_n - 2), dtype=int
            )
        else:
            boot_candidates = range(1, boot_n - 1)

        def _boot_candidate(mode_idx: int) -> float:
            left_span = max(boot_sample[mode_idx] - boot_sample[0], 1e-12)
            right_span = max(boot_sample[-1] - boot_sample[mode_idx], 1e-12)
            left_mass = mode_idx / boot_n
            right_mass = 1.0 - left_mass
            left_mask = boot_sample <= boot_sample[mode_idx]
            u = np.empty_like(boot_sample, dtype=float)
            u[left_mask] = (
                (boot_sample[left_mask] - boot_sample[0]) / left_span
            ) * left_mass
            u[~left_mask] = (
                left_mass
                + ((boot_sample[~left_mask] - boot_sample[mode_idx]) / right_span)
                * right_mass
            )
            u = np.clip(u, 0.0, 1.0)
            return float(np.max(np.abs(boot_ecdf - u)))

        boot_dips[i] = min(_boot_candidate(m) for m in boot_candidates)

    p_value = float(np.mean(boot_dips >= dip_stat))

    return dip_stat, p_value

save_ripple_events(events, basepath, detection_name='detect_sharp_wave_ripples', detection_params=None, ripple_channel=None, detection_epochs=None, event_name='ripples', amplitude_units='a.u.')

Save ripple events to a CellExplorer *.events.mat file.

Parameters:

Name Type Description Default
events DataFrame

Ripple event table returned by :func:detect_sharp_wave_ripples.

required
basepath str

Session folder where the event file will be written.

required
detection_name str

Name stored in detectorinfo.detectorname.

'detect_sharp_wave_ripples'
detection_params dict

Detection parameters stored in detectorinfo.detectionparms.

None
ripple_channel int

Zero-indexed ripple detection channel.

None
detection_epochs EpochArray or ndarray

Detection intervals in seconds.

None
event_name str

Name of the CellExplorer event struct.

'ripples'
amplitude_units str

Units for the saved ripple amplitude.

'a.u.'

Returns:

Type Description
str

Path to the saved *.events.mat file.

Source code in neuro_py/detectors/sharp_wave_ripple.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def save_ripple_events(
    events: pd.DataFrame,
    basepath: str,
    detection_name: str = "detect_sharp_wave_ripples",
    detection_params: Optional[dict] = None,
    ripple_channel: Optional[int] = None,
    detection_epochs: Optional[Union[nel.EpochArray, np.ndarray]] = None,
    event_name: str = "ripples",
    amplitude_units: str = "a.u.",
) -> str:
    """
    Save ripple events to a CellExplorer ``*.events.mat`` file.

    Parameters
    ----------
    events : pd.DataFrame
        Ripple event table returned by :func:`detect_sharp_wave_ripples`.
    basepath : str
        Session folder where the event file will be written.
    detection_name : str, optional
        Name stored in ``detectorinfo.detectorname``.
    detection_params : dict, optional
        Detection parameters stored in ``detectorinfo.detectionparms``.
    ripple_channel : int, optional
        Zero-indexed ripple detection channel.
    detection_epochs : nel.EpochArray or np.ndarray, optional
        Detection intervals in seconds.
    event_name : str, optional
        Name of the CellExplorer event struct.
    amplitude_units : str, optional
        Units for the saved ripple amplitude.

    Returns
    -------
    str
        Path to the saved ``*.events.mat`` file.
    """
    filename = os.path.join(
        basepath,
        os.path.basename(basepath) + f".{event_name}.events.mat",
    )

    intervals = _coerce_interval_array(detection_epochs)

    if events.empty:
        timestamps = np.empty((0, 2), dtype=float)
        peaks = np.empty((0,), dtype=float)
        amplitude = np.empty((0,), dtype=float)
        duration = np.empty((0,), dtype=float)
        center = np.empty((0,), dtype=float)
        frequency = np.empty((0,), dtype=float)
        peak_normed_power = np.empty((0,), dtype=float)
    else:
        timestamps = events[["start", "stop"]].to_numpy(dtype=float)
        peaks = events["peaks"].to_numpy(dtype=float)
        amplitude = events["amplitude"].to_numpy(dtype=float)
        duration = events["duration"].to_numpy(dtype=float)
        center = events["center"].to_numpy(dtype=float)
        frequency = events["frequency"].to_numpy(dtype=float)
        peak_normed_power = events["peakNormedPower"].to_numpy(dtype=float)

    detectorinfo: dict[str, object] = {
        "detectorname": detection_name,
        "detectiondate": datetime.now().strftime("%Y-%m-%d"),
        "detectionintervals": intervals,
        "detectionparms": detection_params if detection_params is not None else {},
    }
    if ripple_channel is not None:
        detectorinfo["detectionchannel"] = int(ripple_channel)
        detectorinfo["detectionchannel1"] = int(ripple_channel) + 1

    data = {
        event_name: {
            "timestamps": timestamps,
            "peaks": peaks,
            "amplitude": amplitude,
            "amplitudeUnits": amplitude_units,
            "eventID": [],
            "eventIDlabels": [],
            "eventIDbinary": [],
            "center": center,
            "duration": duration,
            "frequency": frequency,
            "peakNormedPower": peak_normed_power,
            "detectorinfo": detectorinfo,
        }
    }
    savemat(filename, _sanitize_for_matlab(data), long_field_names=True)
    return filename