Skip to content

Analysis

LongRecordingAnalyzer

Source code in pythoneeg/core/analysis.py
 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
class LongRecordingAnalyzer:
    def __init__(self, longrecording: core.LongRecordingOrganizer, fragment_len_s=10, notch_freq=60) -> None:
        assert isinstance(longrecording, core.LongRecordingOrganizer)

        self.LongRecording = longrecording
        self.fragment_len_s = fragment_len_s
        self.n_fragments = longrecording.get_num_fragments(fragment_len_s)
        self.channel_names = longrecording.channel_names
        self.n_channels = longrecording.meta.n_channels
        self.mult_to_uV = longrecording.meta.mult_to_uV
        self.f_s = int(longrecording.LongRecording.get_sampling_frequency())
        self.notch_freq = notch_freq

    def get_fragment_rec(self, index) -> "si.BaseRecording":
        """Get window at index as a spikeinterface recording object

        Args:
            index (int): Index of time window

        Returns:
            si.BaseRecording: spikeinterface recording object
        """
        if si is None:
            raise ImportError("spikeinterface is required for get_fragment_rec")
        return self.LongRecording.get_fragment(self.fragment_len_s, index)

    def get_fragment_np(self, index, recobj=None) -> np.ndarray:
        """Get window at index as a numpy array object

        Args:
            index (int): Index of time window
            recobj (si.BaseRecording, optional): If not None, uses this recording object to get the numpy array. Defaults to None.

        Returns:
            np.ndarray: Numpy array with dimensions (N, M), N = number of samples, M = number of channels. Values in uV
        """
        if si is not None:
            assert isinstance(recobj, si.BaseRecording) or recobj is None
        if recobj is None:
            return self.get_fragment_rec(index).get_traces(
                return_scaled=True
            )  # (num_samples, num_channels), in units uV
        else:
            return recobj.get_traces(return_scaled=True)

    def get_fragment_mne(self, index, recobj=None) -> np.ndarray:
        """Get window at index as a numpy array object, formatted for ease of use with MNE functions

        Args:
            index (int): Index of time window
            recobj (si.BaseRecording, optional): If not None, uses this recording object to get the numpy array. Defaults to None.

        Returns:
            np.ndarray: Numpy array with dimensions (1, M, N), M = number of channels, N = number of samples. 1st dimension corresponds
             to number of epochs, which there is only 1 in a window. Values in uV
        """
        rec = self.get_fragment_np(index, recobj=recobj)[..., np.newaxis]
        return np.transpose(rec, (2, 1, 0))  # (1 epoch, num_channels, num_samples)

    def get_file_end(self, index, **kwargs):
        tstart, tend = self.convert_idx_to_timebound(index)
        for tfile in self.LongRecording.cumulative_file_durations:
            if tstart <= tfile < tend:
                return tfile - tstart
        return None

    def compute_rms(self, index, **kwargs):
        """Compute average root mean square amplitude

        Args:
            index (int): Index of time window

        Returns:
            result: np.ndarray with shape (1, M), M = number of channels
        """
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_rms(rec=rec, **kwargs)

    def compute_logrms(self, index, **kwargs):
        """Compute the log of the root mean square amplitude"""
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_logrms(rec=rec, **kwargs)

    def compute_ampvar(self, index, **kwargs):
        """Compute average amplitude variance

        Args:
            index (int): Index of time window

        Returns:
            result: np.ndarray with shape (1, M), M = number of channels
        """
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_ampvar(rec=rec, **kwargs)

    def compute_logampvar(self, index, **kwargs):
        """Compute the log of the amplitude variance"""
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_logampvar(rec=rec, **kwargs)

    def compute_psd(self, index, welch_bin_t=1, notch_filter=True, multitaper=False, **kwargs):
        """Compute PSD (power spectral density)

        Args:
            index (int): Index of time window
            welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
            notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
            multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

        Returns:
            f (np.ndarray): Array of sample frequencies
            psd (np.ndarray): Array of PSD values at sample frequencies. (X, M), X = number of sample frequencies, M = number of channels.
            If sample window length is too short, PSD is interpolated
        """
        rec = self.get_fragment_np(index)

        f, psd = FragmentAnalyzer.compute_psd(
            rec=rec, f_s=self.f_s, welch_bin_t=welch_bin_t, notch_filter=notch_filter, multitaper=multitaper, **kwargs
        )

        if index == self.n_fragments - 1 and self.n_fragments > 1:
            f_prev, _ = self.compute_psd(index - 1, welch_bin_t, notch_filter, multitaper)
            psd = Akima1DInterpolator(f, psd, axis=0, extrapolate=True)(f_prev)
            f = f_prev

        return f, psd

    def compute_psdband(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        bands: list[tuple[float, float]] = constants.FREQ_BANDS,
        multitaper=False,
        **kwargs,
    ):
        """Compute power spectral density of the signal for each frequency band.

        Args:
            index (int): Index of time window
            welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
            notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
            bands (list[tuple[float, float]], optional): List of frequency bands to compute PSD for. Defaults to constants.FREQ_BANDS.
            multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

        Returns:
            dict: Dictionary mapping band names to PSD values for each channel
        """

        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_psdband(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            bands=bands,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_logpsdband(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        bands: list[tuple[float, float]] = constants.FREQ_BANDS,
        multitaper=False,
        **kwargs,
    ):
        """Compute the log of the power spectral density of the signal for each frequency band."""
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_logpsdband(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            bands=bands,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_psdtotal(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
        multitaper=False,
        **kwargs,
    ):
        """Compute total power over PSD (power spectral density) plot within a specified frequency band

        Args:
            index (int): Index of time window
            welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
            notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
            band (tuple[float, float], optional): Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.
            multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

        Returns:
            psdtotal (np.ndarray): (M,) long array, M = number of channels. Each value corresponds to sum total of PSD in that band at that channel
        """
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_psdtotal(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            band=band,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_logpsdtotal(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
        multitaper=False,
        **kwargs,
    ):
        """Compute the log of the total power over PSD (power spectral density) plot within a specified frequency band"""
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_logpsdtotal(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            band=band,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_psdfrac(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        bands: list[tuple[float, float]] = constants.FREQ_BANDS,
        total_band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
        multitaper=False,
        **kwargs,
    ):
        """Compute the power spectral density in each band as a fraction of the total power."""
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_psdfrac(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            bands=bands,
            total_band=total_band,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_logpsdfrac(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        bands: list[tuple[float, float]] = constants.FREQ_BANDS,
        total_band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
        multitaper=False,
        **kwargs,
    ):
        """Compute the log of the power spectral density in each band as a fraction of the total power."""
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_logpsdfrac(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            bands=bands,
            total_band=total_band,
            multitaper=multitaper,
            **kwargs,
        )

    def compute_psdslope(
        self,
        index,
        welch_bin_t=1,
        notch_filter=True,
        band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
        multitaper=False,
        **kwargs,
    ):
        """Compute the slope of the power spectral density of the signal.

        Args:
            index (int): Index of time window
            welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
            notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
            band (tuple[float, float], optional): Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.
            multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

        Returns:
            np.ndarray: Array of shape (M,2) where M is number of channels. Each row contains [slope, intercept] of log-log fit.
        """
        rec = self.get_fragment_np(index)

        return FragmentAnalyzer.compute_psdslope(
            rec=rec,
            f_s=self.f_s,
            welch_bin_t=welch_bin_t,
            notch_filter=notch_filter,
            band=band,
            multitaper=multitaper,
            **kwargs,
        )

    def convert_idx_to_timebound(self, index: int) -> tuple[float, float]:
        """Convert fragment index to timebound (start time, end time)

        Args:
            index (int): Fragment index

        Returns:
            tuple[float, float]: Timebound in seconds
        """
        frag_len_idx = round(self.fragment_len_s * self.f_s)
        startidx = frag_len_idx * index
        endidx = min(frag_len_idx * (index + 1), self.LongRecording.LongRecording.get_num_frames())
        return (startidx / self.f_s, endidx / self.f_s)

    def compute_cohere(
        self,
        index,
        freq_res: float = 1,
        mode: Literal["cwt_morlet", "multitaper"] = "multitaper",
        geomspace: bool = False,
        cwt_n_cycles_max: float = 7.0,
        mt_bandwidth: float = 4.0,
        downsamp_q: int = 4,
        epsilon: float = 1e-2,
        **kwargs,
    ) -> np.ndarray:
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_cohere(
            rec=rec,
            f_s=self.f_s,
            freq_res=freq_res,
            mode=mode,
            geomspace=geomspace,
            cwt_n_cycles_max=cwt_n_cycles_max,
            mt_bandwidth=mt_bandwidth,
            downsamp_q=downsamp_q,
            epsilon=epsilon,
            **kwargs,
        )

    def compute_zcohere(self, index, z_epsilon: float = 1e-6, **kwargs) -> np.ndarray:
        """Compute the Fisher z-transformed coherence of the signal.

        Args:
            index (int): Index of time window
            z_epsilon (float): Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]
            **kwargs: Additional arguments passed to compute_zcohere
        """
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_zcohere(rec=rec, f_s=self.f_s, z_epsilon=z_epsilon, **kwargs)

    def compute_imcoh(self, index, **kwargs) -> np.ndarray:
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_imcoh(rec=rec, f_s=self.f_s, **kwargs)

    def compute_zimcoh(self, index, z_epsilon: float = 1e-6, **kwargs) -> np.ndarray:
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_zimcoh(rec=rec, f_s=self.f_s, z_epsilon=z_epsilon, **kwargs)

    def compute_pcorr(self, index, lower_triag=False, **kwargs) -> np.ndarray:
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_pcorr(rec=rec, f_s=self.f_s, lower_triag=lower_triag, **kwargs)

    def compute_zpcorr(self, index, z_epsilon: float = 1e-6, **kwargs) -> np.ndarray:
        """Compute the Fisher z-transformed Pearson correlation coefficient of the signal.

        Args:
            index (int): Index of time window
            z_epsilon (float): Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]
            **kwargs: Additional arguments passed to compute_zpcorr
        """
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_zpcorr(rec=rec, f_s=self.f_s, z_epsilon=z_epsilon, **kwargs)

    def compute_nspike(self, index, **kwargs):
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_nspike(rec=rec, f_s=self.f_s, **kwargs)

    def compute_lognspike(self, index, **kwargs):
        rec = self.get_fragment_np(index)
        return FragmentAnalyzer.compute_lognspike(rec=rec, f_s=self.f_s, **kwargs)

compute_ampvar(index, **kwargs)

Compute average amplitude variance

Parameters:

Name Type Description Default
index int

Index of time window

required

Returns:

Name Type Description
result

np.ndarray with shape (1, M), M = number of channels

Source code in pythoneeg/core/analysis.py
107
108
109
110
111
112
113
114
115
116
117
def compute_ampvar(self, index, **kwargs):
    """Compute average amplitude variance

    Args:
        index (int): Index of time window

    Returns:
        result: np.ndarray with shape (1, M), M = number of channels
    """
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_ampvar(rec=rec, **kwargs)

compute_logampvar(index, **kwargs)

Compute the log of the amplitude variance

Source code in pythoneeg/core/analysis.py
119
120
121
122
def compute_logampvar(self, index, **kwargs):
    """Compute the log of the amplitude variance"""
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_logampvar(rec=rec, **kwargs)

compute_logpsdband(index, welch_bin_t=1, notch_filter=True, bands=constants.FREQ_BANDS, multitaper=False, **kwargs)

Compute the log of the power spectral density of the signal for each frequency band.

Source code in pythoneeg/core/analysis.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def compute_logpsdband(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    bands: list[tuple[float, float]] = constants.FREQ_BANDS,
    multitaper=False,
    **kwargs,
):
    """Compute the log of the power spectral density of the signal for each frequency band."""
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_logpsdband(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        bands=bands,
        multitaper=multitaper,
        **kwargs,
    )

compute_logpsdfrac(index, welch_bin_t=1, notch_filter=True, bands=constants.FREQ_BANDS, total_band=constants.FREQ_BAND_TOTAL, multitaper=False, **kwargs)

Compute the log of the power spectral density in each band as a fraction of the total power.

Source code in pythoneeg/core/analysis.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def compute_logpsdfrac(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    bands: list[tuple[float, float]] = constants.FREQ_BANDS,
    total_band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
    multitaper=False,
    **kwargs,
):
    """Compute the log of the power spectral density in each band as a fraction of the total power."""
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_logpsdfrac(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        bands=bands,
        total_band=total_band,
        multitaper=multitaper,
        **kwargs,
    )

compute_logpsdtotal(index, welch_bin_t=1, notch_filter=True, band=constants.FREQ_BAND_TOTAL, multitaper=False, **kwargs)

Compute the log of the total power over PSD (power spectral density) plot within a specified frequency band

Source code in pythoneeg/core/analysis.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def compute_logpsdtotal(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
    multitaper=False,
    **kwargs,
):
    """Compute the log of the total power over PSD (power spectral density) plot within a specified frequency band"""
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_logpsdtotal(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        band=band,
        multitaper=multitaper,
        **kwargs,
    )

compute_logrms(index, **kwargs)

Compute the log of the root mean square amplitude

Source code in pythoneeg/core/analysis.py
102
103
104
105
def compute_logrms(self, index, **kwargs):
    """Compute the log of the root mean square amplitude"""
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_logrms(rec=rec, **kwargs)

compute_psd(index, welch_bin_t=1, notch_filter=True, multitaper=False, **kwargs)

Compute PSD (power spectral density)

Parameters:

Name Type Description Default
index int

Index of time window

required
welch_bin_t float

Length of time bins to use in Welch's method, in seconds. Defaults to 1.

1
notch_filter bool

If True, applies notch filter at line frequency. Defaults to True.

True
multitaper bool

If True, uses multitaper method instead of Welch's method. Defaults to False.

False

Returns:

Name Type Description
f ndarray

Array of sample frequencies

psd ndarray

Array of PSD values at sample frequencies. (X, M), X = number of sample frequencies, M = number of channels.

If sample window length is too short, PSD is interpolated

Source code in pythoneeg/core/analysis.py
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
def compute_psd(self, index, welch_bin_t=1, notch_filter=True, multitaper=False, **kwargs):
    """Compute PSD (power spectral density)

    Args:
        index (int): Index of time window
        welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
        notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
        multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

    Returns:
        f (np.ndarray): Array of sample frequencies
        psd (np.ndarray): Array of PSD values at sample frequencies. (X, M), X = number of sample frequencies, M = number of channels.
        If sample window length is too short, PSD is interpolated
    """
    rec = self.get_fragment_np(index)

    f, psd = FragmentAnalyzer.compute_psd(
        rec=rec, f_s=self.f_s, welch_bin_t=welch_bin_t, notch_filter=notch_filter, multitaper=multitaper, **kwargs
    )

    if index == self.n_fragments - 1 and self.n_fragments > 1:
        f_prev, _ = self.compute_psd(index - 1, welch_bin_t, notch_filter, multitaper)
        psd = Akima1DInterpolator(f, psd, axis=0, extrapolate=True)(f_prev)
        f = f_prev

    return f, psd

compute_psdband(index, welch_bin_t=1, notch_filter=True, bands=constants.FREQ_BANDS, multitaper=False, **kwargs)

Compute power spectral density of the signal for each frequency band.

Parameters:

Name Type Description Default
index int

Index of time window

required
welch_bin_t float

Length of time bins to use in Welch's method, in seconds. Defaults to 1.

1
notch_filter bool

If True, applies notch filter at line frequency. Defaults to True.

True
bands list[tuple[float, float]]

List of frequency bands to compute PSD for. Defaults to constants.FREQ_BANDS.

FREQ_BANDS
multitaper bool

If True, uses multitaper method instead of Welch's method. Defaults to False.

False

Returns:

Name Type Description
dict

Dictionary mapping band names to PSD values for each channel

Source code in pythoneeg/core/analysis.py
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
def compute_psdband(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    bands: list[tuple[float, float]] = constants.FREQ_BANDS,
    multitaper=False,
    **kwargs,
):
    """Compute power spectral density of the signal for each frequency band.

    Args:
        index (int): Index of time window
        welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
        notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
        bands (list[tuple[float, float]], optional): List of frequency bands to compute PSD for. Defaults to constants.FREQ_BANDS.
        multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

    Returns:
        dict: Dictionary mapping band names to PSD values for each channel
    """

    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_psdband(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        bands=bands,
        multitaper=multitaper,
        **kwargs,
    )

compute_psdfrac(index, welch_bin_t=1, notch_filter=True, bands=constants.FREQ_BANDS, total_band=constants.FREQ_BAND_TOTAL, multitaper=False, **kwargs)

Compute the power spectral density in each band as a fraction of the total power.

Source code in pythoneeg/core/analysis.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def compute_psdfrac(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    bands: list[tuple[float, float]] = constants.FREQ_BANDS,
    total_band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
    multitaper=False,
    **kwargs,
):
    """Compute the power spectral density in each band as a fraction of the total power."""
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_psdfrac(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        bands=bands,
        total_band=total_band,
        multitaper=multitaper,
        **kwargs,
    )

compute_psdslope(index, welch_bin_t=1, notch_filter=True, band=constants.FREQ_BAND_TOTAL, multitaper=False, **kwargs)

Compute the slope of the power spectral density of the signal.

Parameters:

Name Type Description Default
index int

Index of time window

required
welch_bin_t float

Length of time bins to use in Welch's method, in seconds. Defaults to 1.

1
notch_filter bool

If True, applies notch filter at line frequency. Defaults to True.

True
band tuple[float, float]

Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.

FREQ_BAND_TOTAL
multitaper bool

If True, uses multitaper method instead of Welch's method. Defaults to False.

False

Returns:

Type Description

np.ndarray: Array of shape (M,2) where M is number of channels. Each row contains [slope, intercept] of log-log fit.

Source code in pythoneeg/core/analysis.py
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
def compute_psdslope(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
    multitaper=False,
    **kwargs,
):
    """Compute the slope of the power spectral density of the signal.

    Args:
        index (int): Index of time window
        welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
        notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
        band (tuple[float, float], optional): Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.
        multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

    Returns:
        np.ndarray: Array of shape (M,2) where M is number of channels. Each row contains [slope, intercept] of log-log fit.
    """
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_psdslope(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        band=band,
        multitaper=multitaper,
        **kwargs,
    )

compute_psdtotal(index, welch_bin_t=1, notch_filter=True, band=constants.FREQ_BAND_TOTAL, multitaper=False, **kwargs)

Compute total power over PSD (power spectral density) plot within a specified frequency band

Parameters:

Name Type Description Default
index int

Index of time window

required
welch_bin_t float

Length of time bins to use in Welch's method, in seconds. Defaults to 1.

1
notch_filter bool

If True, applies notch filter at line frequency. Defaults to True.

True
band tuple[float, float]

Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.

FREQ_BAND_TOTAL
multitaper bool

If True, uses multitaper method instead of Welch's method. Defaults to False.

False

Returns:

Name Type Description
psdtotal ndarray

(M,) long array, M = number of channels. Each value corresponds to sum total of PSD in that band at that channel

Source code in pythoneeg/core/analysis.py
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
def compute_psdtotal(
    self,
    index,
    welch_bin_t=1,
    notch_filter=True,
    band: tuple[float, float] = constants.FREQ_BAND_TOTAL,
    multitaper=False,
    **kwargs,
):
    """Compute total power over PSD (power spectral density) plot within a specified frequency band

    Args:
        index (int): Index of time window
        welch_bin_t (float, optional): Length of time bins to use in Welch's method, in seconds. Defaults to 1.
        notch_filter (bool, optional): If True, applies notch filter at line frequency. Defaults to True.
        band (tuple[float, float], optional): Frequency band to calculate over. Defaults to constants.FREQ_BAND_TOTAL.
        multitaper (bool, optional): If True, uses multitaper method instead of Welch's method. Defaults to False.

    Returns:
        psdtotal (np.ndarray): (M,) long array, M = number of channels. Each value corresponds to sum total of PSD in that band at that channel
    """
    rec = self.get_fragment_np(index)

    return FragmentAnalyzer.compute_psdtotal(
        rec=rec,
        f_s=self.f_s,
        welch_bin_t=welch_bin_t,
        notch_filter=notch_filter,
        band=band,
        multitaper=multitaper,
        **kwargs,
    )

compute_rms(index, **kwargs)

Compute average root mean square amplitude

Parameters:

Name Type Description Default
index int

Index of time window

required

Returns:

Name Type Description
result

np.ndarray with shape (1, M), M = number of channels

Source code in pythoneeg/core/analysis.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def compute_rms(self, index, **kwargs):
    """Compute average root mean square amplitude

    Args:
        index (int): Index of time window

    Returns:
        result: np.ndarray with shape (1, M), M = number of channels
    """
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_rms(rec=rec, **kwargs)

compute_zcohere(index, z_epsilon=1e-06, **kwargs)

Compute the Fisher z-transformed coherence of the signal.

Parameters:

Name Type Description Default
index int

Index of time window

required
z_epsilon float

Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]

1e-06
**kwargs

Additional arguments passed to compute_zcohere

{}
Source code in pythoneeg/core/analysis.py
383
384
385
386
387
388
389
390
391
392
def compute_zcohere(self, index, z_epsilon: float = 1e-6, **kwargs) -> np.ndarray:
    """Compute the Fisher z-transformed coherence of the signal.

    Args:
        index (int): Index of time window
        z_epsilon (float): Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]
        **kwargs: Additional arguments passed to compute_zcohere
    """
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_zcohere(rec=rec, f_s=self.f_s, z_epsilon=z_epsilon, **kwargs)

compute_zpcorr(index, z_epsilon=1e-06, **kwargs)

Compute the Fisher z-transformed Pearson correlation coefficient of the signal.

Parameters:

Name Type Description Default
index int

Index of time window

required
z_epsilon float

Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]

1e-06
**kwargs

Additional arguments passed to compute_zpcorr

{}
Source code in pythoneeg/core/analysis.py
406
407
408
409
410
411
412
413
414
415
def compute_zpcorr(self, index, z_epsilon: float = 1e-6, **kwargs) -> np.ndarray:
    """Compute the Fisher z-transformed Pearson correlation coefficient of the signal.

    Args:
        index (int): Index of time window
        z_epsilon (float): Small value to prevent arctanh(1) = inf. Values are clipped to [-1+z_epsilon, 1-z_epsilon]
        **kwargs: Additional arguments passed to compute_zpcorr
    """
    rec = self.get_fragment_np(index)
    return FragmentAnalyzer.compute_zpcorr(rec=rec, f_s=self.f_s, z_epsilon=z_epsilon, **kwargs)

convert_idx_to_timebound(index)

Convert fragment index to timebound (start time, end time)

Parameters:

Name Type Description Default
index int

Fragment index

required

Returns:

Type Description
tuple[float, float]

tuple[float, float]: Timebound in seconds

Source code in pythoneeg/core/analysis.py
343
344
345
346
347
348
349
350
351
352
353
354
355
def convert_idx_to_timebound(self, index: int) -> tuple[float, float]:
    """Convert fragment index to timebound (start time, end time)

    Args:
        index (int): Fragment index

    Returns:
        tuple[float, float]: Timebound in seconds
    """
    frag_len_idx = round(self.fragment_len_s * self.f_s)
    startidx = frag_len_idx * index
    endidx = min(frag_len_idx * (index + 1), self.LongRecording.LongRecording.get_num_frames())
    return (startidx / self.f_s, endidx / self.f_s)

get_fragment_mne(index, recobj=None)

Get window at index as a numpy array object, formatted for ease of use with MNE functions

Parameters:

Name Type Description Default
index int

Index of time window

required
recobj BaseRecording

If not None, uses this recording object to get the numpy array. Defaults to None.

None

Returns:

Type Description
ndarray

np.ndarray: Numpy array with dimensions (1, M, N), M = number of channels, N = number of samples. 1st dimension corresponds to number of epochs, which there is only 1 in a window. Values in uV

Source code in pythoneeg/core/analysis.py
69
70
71
72
73
74
75
76
77
78
79
80
81
def get_fragment_mne(self, index, recobj=None) -> np.ndarray:
    """Get window at index as a numpy array object, formatted for ease of use with MNE functions

    Args:
        index (int): Index of time window
        recobj (si.BaseRecording, optional): If not None, uses this recording object to get the numpy array. Defaults to None.

    Returns:
        np.ndarray: Numpy array with dimensions (1, M, N), M = number of channels, N = number of samples. 1st dimension corresponds
         to number of epochs, which there is only 1 in a window. Values in uV
    """
    rec = self.get_fragment_np(index, recobj=recobj)[..., np.newaxis]
    return np.transpose(rec, (2, 1, 0))  # (1 epoch, num_channels, num_samples)

get_fragment_np(index, recobj=None)

Get window at index as a numpy array object

Parameters:

Name Type Description Default
index int

Index of time window

required
recobj BaseRecording

If not None, uses this recording object to get the numpy array. Defaults to None.

None

Returns:

Type Description
ndarray

np.ndarray: Numpy array with dimensions (N, M), N = number of samples, M = number of channels. Values in uV

Source code in pythoneeg/core/analysis.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def get_fragment_np(self, index, recobj=None) -> np.ndarray:
    """Get window at index as a numpy array object

    Args:
        index (int): Index of time window
        recobj (si.BaseRecording, optional): If not None, uses this recording object to get the numpy array. Defaults to None.

    Returns:
        np.ndarray: Numpy array with dimensions (N, M), N = number of samples, M = number of channels. Values in uV
    """
    if si is not None:
        assert isinstance(recobj, si.BaseRecording) or recobj is None
    if recobj is None:
        return self.get_fragment_rec(index).get_traces(
            return_scaled=True
        )  # (num_samples, num_channels), in units uV
    else:
        return recobj.get_traces(return_scaled=True)

get_fragment_rec(index)

Get window at index as a spikeinterface recording object

Parameters:

Name Type Description Default
index int

Index of time window

required

Returns:

Type Description
BaseRecording

si.BaseRecording: spikeinterface recording object

Source code in pythoneeg/core/analysis.py
37
38
39
40
41
42
43
44
45
46
47
48
def get_fragment_rec(self, index) -> "si.BaseRecording":
    """Get window at index as a spikeinterface recording object

    Args:
        index (int): Index of time window

    Returns:
        si.BaseRecording: spikeinterface recording object
    """
    if si is None:
        raise ImportError("spikeinterface is required for get_fragment_rec")
    return self.LongRecording.get_fragment(self.fragment_len_s, index)