edgeofpy 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: edgeofpy
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Tools for brain criticality estimation, especially for M/EEG
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -41,8 +41,22 @@ Description-Content-Type: text/x-rst
41
41
  EDGE OF PY
42
42
  ==========
43
43
 
44
+ .. image:: https://img.shields.io/pypi/v/edgeofpy.svg
45
+ :target: https://pypi.org/project/edgeofpy/
46
+ :alt: PyPI version
47
+
48
+ .. image:: https://readthedocs.org/projects/edgeofpy/badge/?version=latest
49
+ :target: https://edgeofpy.readthedocs.io/en/latest/
50
+ :alt: Documentation status
51
+
52
+ .. image:: https://github.com/jnobyrne/edgeofpy/actions/workflows/tests.yml/badge.svg
53
+ :target: https://github.com/jnobyrne/edgeofpy/actions/workflows/tests.yml
54
+ :alt: Tests
55
+
44
56
  Package for assessing the distance to criticality in brain dynamics.
45
57
 
58
+ **Documentation:** https://edgeofpy.readthedocs.io
59
+
46
60
  Features
47
61
  --------
48
62
  - Avalanche criticality measures
@@ -85,7 +99,8 @@ Install edgeofpy by running:
85
99
 
86
100
  Documentation
87
101
  -------------
88
- Coming soon.
102
+ The documentation, at https://edgeofpy.readthedocs.io, includes a quick
103
+ start, a user guide, worked examples and the API reference.
89
104
 
90
105
  Requirements
91
106
  ------------
@@ -4,8 +4,22 @@
4
4
  EDGE OF PY
5
5
  ==========
6
6
 
7
+ .. image:: https://img.shields.io/pypi/v/edgeofpy.svg
8
+ :target: https://pypi.org/project/edgeofpy/
9
+ :alt: PyPI version
10
+
11
+ .. image:: https://readthedocs.org/projects/edgeofpy/badge/?version=latest
12
+ :target: https://edgeofpy.readthedocs.io/en/latest/
13
+ :alt: Documentation status
14
+
15
+ .. image:: https://github.com/jnobyrne/edgeofpy/actions/workflows/tests.yml/badge.svg
16
+ :target: https://github.com/jnobyrne/edgeofpy/actions/workflows/tests.yml
17
+ :alt: Tests
18
+
7
19
  Package for assessing the distance to criticality in brain dynamics.
8
20
 
21
+ **Documentation:** https://edgeofpy.readthedocs.io
22
+
9
23
  Features
10
24
  --------
11
25
  - Avalanche criticality measures
@@ -48,7 +62,8 @@ Install edgeofpy by running:
48
62
 
49
63
  Documentation
50
64
  -------------
51
- Coming soon.
65
+ The documentation, at https://edgeofpy.readthedocs.io, includes a quick
66
+ start, a user guide, worked examples and the API reference.
52
67
 
53
68
  Requirements
54
69
  ------------
@@ -61,6 +61,13 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
61
61
  Number of channels containing events.
62
62
  profile : 1d array
63
63
  Number of events (active channels) in each successive time bin.
64
+ pattern : 1d array of int
65
+ 1 for each channel containing events, 0 otherwise (see
66
+ `avl_repertoire`).
67
+
68
+ .. versionchanged:: 0.2.1
69
+ With single-channel input, `pattern` is ``[1]`` and `n_chan` is 1;
70
+ both were the string 'N/A'.
64
71
  events_all_chan : 2d array of same shape as data, dtype=int
65
72
  Time series of zeros with ones at the event peaks.
66
73
  events_one_chan : 1d array
@@ -1093,13 +1100,26 @@ def avl_repertoire(avalanches):
1093
1100
  The repertoire of unique avalanche patterns, where axis=0 is the
1094
1101
  individual patterns and axis=1 is the spatial nodes (channels). The
1095
1102
  matrix is binary, with 1 indicating that the node was involved in the
1096
- avalanche, and 0 indicating that it was not.
1103
+ avalanche, and 0 indicating that it was not. With single-channel
1104
+ data, it is ``[[1]]``.
1097
1105
 
1098
1106
  References
1099
1107
  ----------
1100
1108
  Sorrentino et al. (2021) Sci Rep 11(1), 1-12.
1101
1109
  """
1102
- repertoire = np.vstack([x['pattern'] for x in avalanches])
1110
+ if len(avalanches) == 0:
1111
+ raise ValueError('No avalanches.')
1112
+ patterns = [np.asarray(x['pattern']) for x in avalanches]
1113
+ if not all(np.issubdtype(x.dtype, np.number) and x.ndim == 1
1114
+ for x in patterns):
1115
+ raise ValueError("Avalanche patterns must be 1d arrays of 0 and 1. "
1116
+ "Avalanches detected on single-channel data with "
1117
+ "edgeofpy < 0.2.1 have the pattern 'N/A': detect "
1118
+ "them again.")
1119
+ if len({x.size for x in patterns}) > 1:
1120
+ raise ValueError('All avalanche patterns must have the same number '
1121
+ 'of channels.')
1122
+ repertoire = np.vstack(patterns)
1103
1123
 
1104
1124
  return np.unique(repertoire, axis=0)
1105
1125
 
@@ -1350,7 +1370,9 @@ def _det_avls(events, s_freq, time, max_iei):
1350
1370
  pattern = np.sign(np.sum(events[:, avl_start:avl_end], axis=1))
1351
1371
  n_chan = int(np.sum(pattern))
1352
1372
  else:
1353
- pattern = n_chan = 'N/A'
1373
+ # a single channel, necessarily involved in every avalanche
1374
+ pattern = np.ones(1, dtype=int)
1375
+ n_chan = 1
1354
1376
  profile = time_bin_events(profile_raw, max_iei_len)
1355
1377
  avl = {'start_time': start_time,
1356
1378
  'end_time': end_time,
@@ -259,8 +259,9 @@ def schreiber_denoise(x, r=None, chunk_size=256):
259
259
  x : 1d array
260
260
  The time series.
261
261
  r : float or None
262
- Neighbourhood radius. If None, the standard deviation of `x` is used.
263
- Schreiber (1993) suggests a radius of a few times the noise amplitude.
262
+ Neighbourhood radius. If None, the standard deviation of `x` is used,
263
+ as in the chaos decision tree of Toker et al. (2020), which calls the
264
+ Matlab implementation with its default radius. See Notes.
264
265
  chunk_size : int
265
266
  Number of delay vectors processed at once. Lower values reduce memory
266
267
  use (about 8 * chunk_size * len(x) bytes) without changing the result.
@@ -272,11 +273,24 @@ def schreiber_denoise(x, r=None, chunk_size=256):
272
273
 
273
274
  Notes
274
275
  -----
275
- This code was adapted from Matlab code by Alexandros Leontitsis.
276
+ The default radius suits the 0-1 test for chaos (`chaos_pipeline`),
277
+ for which Toker et al. (2020) validated it with measurement noise of up
278
+ to 40% of the standard deviation of the signal. It is, however, large
279
+ for recovering the signal itself when the noise is weak: on the Henon
280
+ and logistic maps, it increases the error when the noise is below about
281
+ 15% of the standard deviation of the signal (e.g. 3 times the error of
282
+ the noisy signal at 5%). A radius of about twice the standard deviation
283
+ of the noise (Schreiber, 1993) reduced the error by about a third at all
284
+ noise levels tested (5-40%).
285
+
286
+ This code was adapted from Matlab code by Alexandros Leontitsis. Unlike
287
+ that code, it keeps the first and last samples instead of setting them
288
+ to zero.
276
289
 
277
290
  References
278
291
  ----------
279
- Schreiber T (1993) Phys Rev E 47, 2401-2404.
292
+ - Schreiber T (1993) Phys Rev E 47, 2401-2404.
293
+ - Toker et al. (2020) Commun Biol 3, 11.
280
294
  """
281
295
  x = np.asarray(x, dtype=float).ravel()
282
296
  if r is None:
@@ -2,6 +2,8 @@
2
2
  Edge-of-synchrony measures
3
3
  """
4
4
 
5
+ import warnings
6
+
5
7
  import numpy as np
6
8
  import scipy.signal
7
9
 
@@ -204,86 +206,102 @@ def _binary_pattern_entropy(x, m, tau):
204
206
  return -np.sum(p * np.log(p)) / (m * np.log(2))
205
207
 
206
208
  def complex_phase_relationship(data, s_freq=None, win_dur=None):
207
- """Compute all pairwise complex-valued phase relationships for a set of
209
+ r"""Compute all pairwise complex-valued phase relationships for a set of
208
210
  oscillators, time-resolved.
209
211
 
212
+ For signals i and j with analytic signals :math:`W_i` and :math:`W_j`
213
+ (Hilbert transform), the phase relationship is
214
+
215
+ .. math:: C_{ij}(t) = \frac{\langle W_i^* W_j \rangle}
216
+ {\sqrt{\langle |W_i|^2 \rangle \langle |W_j|^2 \rangle}},
217
+
218
+ where :math:`\langle \cdot \rangle` is a moving average over `win_dur`
219
+ (Kitzbichler et al., 2009, Eq. 2). Its argument is the local mean phase
220
+ difference :math:`\phi_j - \phi_i`, and its squared modulus, between 0
221
+ and 1, measures the consistency of that difference within the window.
222
+ Without averaging (``win_dur=None``), :math:`C_{ij}(t)` is the
223
+ instantaneous phase difference as a unit complex number, i.e. Eq. 1 of
224
+ Kitzbichler et al.
225
+
210
226
  Parameters
211
227
  ----------
212
228
  data : 2d array
213
- The filtered input data, where the first dimension is the different
214
- oscillators, and the second dimension is time.
215
- s_freq : int or None
216
- Sampling frequency, only required if using local time-averaging.
229
+ Band-pass filtered signals, oscillators x time.
230
+ s_freq : float or None
231
+ Sampling frequency. Required if `win_dur` is given.
217
232
  win_dur : float or None
218
- If not None, a local time average will be applied to the signal, with
219
- a window of length win_dur, in seconds.
233
+ Duration, in seconds, of the moving average. Kitzbichler et al.
234
+ average over 8 cycles of the highest frequency of the band, e.g.
235
+ about 0.67 s for 8-12 Hz. If None (default), no averaging is
236
+ applied, and the modulus of every entry is 1.
220
237
 
221
238
  Returns
222
239
  -------
223
240
  c_ij_t : 3d array, dtype=complex128
224
- N x N x T array of complex-valued pairwise phase relationships, where N
225
- is the number of oscillators and T is time. Will return NaN for entries
226
- where at least one of the signals in the pair has modulus zero at time
227
- t.
241
+ N x N x T array of complex-valued pairwise phase relationships, where
242
+ N is the number of oscillators and T is time. ``np.angle(c_ij_t[i, j])``
243
+ is the phase of j minus the phase of i, in (-pi, pi]. NaN where at
244
+ least one of the signals in the pair has modulus zero.
228
245
 
229
246
  Notes
230
247
  -----
231
- Time averaging (using win_dur) introduces spurious phase locking when there
232
- is a large pos-to-neg or neg-to-pos jump in the relative phase. This can
233
- often occur when the relative phase crosses between 0 and 2π.
248
+ The moving average is centred on each time point; Kitzbichler et al.
249
+ average over [t, t + win_dur], which only shifts the result in time.
250
+ Within half a window of the edges, the average is taken over fewer
251
+ samples.
252
+
253
+ Because complex values are averaged, a phase difference that fluctuates
254
+ around +-pi is not mistaken for phase locking.
234
255
 
235
256
  The output holds N * N * T complex values (16 bytes each), e.g. about
236
257
  6.5 GB for 64 channels and 100,000 samples.
237
258
 
259
+ .. versionchanged:: 0.2.1
260
+ The conjugate is now taken on signal i, as in Kitzbichler et al., so
261
+ that the phase difference is phi_j - phi_i. It was phi_i - phi_j,
262
+ i.e. ``c_ij_t`` was the complex conjugate of the current output.
263
+
238
264
  References
239
265
  ----------
240
266
  - Kitzbichler et al. (2009) PLoS Comp Biol 5(3), e1000314.
241
267
  - Shriki et al. (2013) J Neurosci 33(16), 7079–90.
242
268
  """
243
- # TODO: something is wrong with the phases: they are all coming out 0 or 2pi
244
269
  if win_dur is not None and s_freq is None:
245
270
  raise ValueError('Time averaging requires that s_freq be specified.')
246
271
 
247
- N, T = data.shape
248
272
  analytic = scipy.signal.hilbert(data, axis=1)
249
- c_ij_t = np.zeros((N, N, T), dtype=complex)
250
-
251
- for t in range(T):
252
- i = analytic[:, t]
253
- j = analytic[:, t].conj().T
254
- c_ij_t[:, :, t] = np.outer(i, j)
255
-
256
- if win_dur is None:
257
- norm = np.outer(np.abs(i), np.abs(j))
258
- c_ij_t[:, :, t] = c_ij_t[:, :, t] / norm
273
+ # conj(W_i) W_j for all pairs: N x N x T
274
+ c_ij_t = np.conj(analytic)[:, np.newaxis, :] * analytic[np.newaxis, :, :]
275
+ power = np.abs(analytic) ** 2
259
276
 
260
277
  if win_dur is not None:
261
- mod_sq = np.square(np.abs(analytic))
262
- flat = np.ones(int(win_dur * s_freq))
263
- H = flat / flat.sum()
264
- c_ij_t = scipy.signal.fftconvolve(c_ij_t, H[np.newaxis, np.newaxis, :],
265
- mode='same', axes=-1)
266
- mod_sq_smooth = scipy.signal.fftconvolve(mod_sq, H[np.newaxis, :],
267
- mode='same', axes=-1)
268
- norm = np.zeros((N, N, T))
269
-
270
- for t in range(T):
271
- i = mod_sq_smooth[:, t]
272
- j = mod_sq_smooth[:, t].conj().T
273
- norm[:, :, t] = np.sqrt(np.outer(i, j))
274
-
275
- c_ij_t = c_ij_t / norm
278
+ n_win = _sec_to_samples(win_dur, s_freq, name='win_dur')
279
+ kernel = np.ones(n_win) / n_win
280
+ c_ij_t = scipy.signal.fftconvolve(
281
+ c_ij_t, kernel[np.newaxis, np.newaxis, :], mode='same', axes=-1)
282
+ power = scipy.signal.fftconvolve(power, kernel[np.newaxis, :],
283
+ mode='same', axes=-1)
284
+
285
+ with np.errstate(divide='ignore', invalid='ignore'):
286
+ c_ij_t = c_ij_t / np.sqrt(power[:, np.newaxis, :]
287
+ * power[np.newaxis, :, :])
276
288
 
277
289
  return c_ij_t
278
290
 
291
+
279
292
  def phase_locking(c_ij_t, phase_thresh=np.pi/4, mod_sq_thresh=0.5):
280
293
  """Find time points where signals i and j are phase-locked.
281
294
 
295
+ Signals i and j are phase-locked when their phase difference is within
296
+ +-`phase_thresh` and the squared modulus of their phase relationship
297
+ exceeds `mod_sq_thresh` (Kitzbichler et al., 2009).
298
+
282
299
  Parameters
283
300
  ----------
284
301
  c_ij_t : 3d array, dtype=complex128
285
302
  N x N x T array of complex-valued pairwise phase relationships, where N
286
- is the number of oscillators and T is time.
303
+ is the number of oscillators and T is time, from
304
+ `complex_phase_relationship`.
287
305
  phase_thresh : float, optional
288
306
  Maximum absolute phase difference, in radians, for i and j to be
289
307
  considered in phase. The default is pi/4.
@@ -296,16 +314,27 @@ def phase_locking(c_ij_t, phase_thresh=np.pi/4, mod_sq_thresh=0.5):
296
314
  phase_locked : 3d array, dtype='bool'
297
315
  Locations where i and j are phase-locked at time t.
298
316
 
317
+ Warns
318
+ -----
319
+ UserWarning
320
+ If all moduli are 1, as when `c_ij_t` was computed without time
321
+ averaging: the significance criterion then has no effect.
322
+
299
323
  References
300
324
  ----------
301
325
  Kitzbichler et al. (2009) PLoS Comp Biol 5(3), e1000314.
302
326
  """
303
327
  phase_diff = np.angle(c_ij_t)
304
328
  in_phase = np.logical_and(-phase_thresh < phase_diff,
305
- phase_diff < phase_thresh)
306
- # The significance threshold only varies away from 1 if a moving average
307
- # was taken in computing c_ij_t
308
- significance = np.square(np.abs(c_ij_t)) > mod_sq_thresh
329
+ phase_diff < phase_thresh)
330
+ mod_sq = np.square(np.abs(c_ij_t))
331
+ if np.nanmax(np.abs(mod_sq - 1), initial=0) < 1e-9:
332
+ warnings.warn('All phase relationships have modulus 1, so the '
333
+ 'significance criterion (mod_sq_thresh) has no effect. '
334
+ 'This is the case without time averaging: use win_dur '
335
+ 'in complex_phase_relationship, as in Kitzbichler et '
336
+ 'al. (2009).', stacklevel=2)
337
+ significance = mod_sq > mod_sq_thresh
309
338
  phase_locked = np.logical_and(in_phase, significance)
310
339
 
311
340
  return phase_locked
@@ -346,7 +375,7 @@ def phase_lock_interval(phase_locked):
346
375
  return all_durations
347
376
 
348
377
  def global_lability(phase_locked, s_freq, delta_t_sec, norm=True):
349
- """Compute the global lability of synchronization (GLS), a time-resolved
378
+ r"""Compute the global lability of synchronization (GLS), a time-resolved
350
379
  measure of the change in the extent of global synchronization in the
351
380
  system.
352
381
 
@@ -360,10 +389,16 @@ def global_lability(phase_locked, s_freq, delta_t_sec, norm=True):
360
389
  delta_t_sec : float
361
390
  Time delay parameter, in seconds. GLS will be calculated as the
362
391
  difference in the number of pairs of coupled oscillators between t and
363
- t + delta_t_sec, for every t.
392
+ t + delta_t_sec, for every t. Kitzbichler et al. (2009) choose it
393
+ longer than the averaging window (`win_dur` in
394
+ `complex_phase_relationship`), so that the two counts come from
395
+ different windows.
364
396
  norm : bool
365
- If True, the GLS will be normalized with respect to the maximum
366
- possible number of synchronized pairs.
397
+ If True, the difference in the number of phase-locked pairs is
398
+ divided by the number of pairs, N (N - 1) / 2, before squaring. If
399
+ False, the GLS is :math:`|n(t + \Delta t) - n(t)|^2`, with
400
+ :math:`n(t)` the number of phase-locked pairs at time t, as in
401
+ Kitzbichler et al. (2009, Eq. 5).
367
402
 
368
403
  Returns
369
404
  -------
@@ -500,6 +535,8 @@ def detect_phase_avls(data, s_freq, phase_range, time=None, max_iei=0.024,
500
535
  Number of channels containing events.
501
536
  profile : 1d array
502
537
  Number of events (active channels) in each successive time bin.
538
+ pattern : 1d array of int
539
+ 1 for each channel containing events, 0 otherwise.
503
540
  events_one_chan : 1d array
504
541
  Collapsed time series of phase-locking events.
505
542
  """
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [project]
6
6
  name = "edgeofpy"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "Tools for brain criticality estimation, especially for M/EEG"
9
9
  readme = "README.rst"
10
10
  license = "Apache-2.0"
File without changes
File without changes
File without changes
File without changes
File without changes