edgeofpy 0.2.1__tar.gz → 0.3.0__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.1
3
+ Version: 0.3.0
4
4
  Summary: Tools for brain criticality estimation, especially for M/EEG
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -60,7 +60,8 @@ Package for assessing the distance to criticality in brain dynamics.
60
60
  Features
61
61
  --------
62
62
  - Avalanche criticality measures
63
- - Avalanche detection
63
+ - Avalanche detection, from M/EEG signals or spike times, with a
64
+ data-driven (Gaussian-fit) event threshold
64
65
  - Avalanche distribution plotting
65
66
  - Power-law fitting (via `powerlaw <https://github.com/jeffalstott/powerlaw>`_)
66
67
  - Deviation from criticality coefficient (DCC)
@@ -69,9 +70,12 @@ Features
69
70
  - Branching ratios
70
71
  - Susceptibility
71
72
  - Fano factor
73
+ - Phase-randomized surrogates
72
74
 
73
75
  - Edge of chaos measures
74
76
  - 0-1 chaos test
77
+
78
+ - Distance to instability
75
79
  - Lambda max (Dahmen et al., 2019)
76
80
 
77
81
  - Edge of synchrony measures
@@ -23,7 +23,8 @@ Package for assessing the distance to criticality in brain dynamics.
23
23
  Features
24
24
  --------
25
25
  - Avalanche criticality measures
26
- - Avalanche detection
26
+ - Avalanche detection, from M/EEG signals or spike times, with a
27
+ data-driven (Gaussian-fit) event threshold
27
28
  - Avalanche distribution plotting
28
29
  - Power-law fitting (via `powerlaw <https://github.com/jeffalstott/powerlaw>`_)
29
30
  - Deviation from criticality coefficient (DCC)
@@ -32,9 +33,12 @@ Features
32
33
  - Branching ratios
33
34
  - Susceptibility
34
35
  - Fano factor
36
+ - Phase-randomized surrogates
35
37
 
36
38
  - Edge of chaos measures
37
39
  - 0-1 chaos test
40
+
41
+ - Distance to instability
38
42
  - Lambda max (Dahmen et al., 2019)
39
43
 
40
44
  - Edge of synchrony measures
@@ -4,6 +4,7 @@ dynamics."""
4
4
  from importlib.metadata import version, PackageNotFoundError
5
5
 
6
6
  from edgeofpy.avalanche import (detect_avalanches,
7
+ plot_gaussian_threshold,
7
8
  plot_pdf,
8
9
  plot_cdf,
9
10
  fit_powerlaw,
@@ -12,7 +13,6 @@ from edgeofpy.avalanche import (detect_avalanches,
12
13
  estimate_dcc,
13
14
  shape_collapse_error,
14
15
  dcc_collapse,
15
- dcc_collapse_2,
16
16
  fit_shape_collapse,
17
17
  plot_shape_collapse,
18
18
  avl_repertoire,
@@ -24,10 +24,10 @@ from edgeofpy.avalanche import (detect_avalanches,
24
24
  )
25
25
  from edgeofpy.chaos import (z1_chaos_test,
26
26
  chaos_pipeline,
27
- lambda_max,
28
27
  minmaxsig,
29
28
  schreiber_denoise,
30
29
  )
30
+ from edgeofpy.stability import lambda_max
31
31
  from edgeofpy.synchrony import (pcf,
32
32
  pli,
33
33
  ple,
@@ -50,7 +50,10 @@ from edgeofpy.ising import (fit_pmem,
50
50
  )
51
51
  from edgeofpy import models # noqa: F401 (submodule: eop.models.<name>)
52
52
  from edgeofpy.utils import (binarized_events,
53
+ gaussian_threshold,
54
+ phase_randomize,
53
55
  time_bin_events,
56
+ bin_spikes,
54
57
  lattice_search,
55
58
  )
56
59
 
@@ -61,15 +64,16 @@ except PackageNotFoundError: # not installed, e.g. run from a source checkout
61
64
 
62
65
  __all__ = [
63
66
  # avalanche
64
- 'detect_avalanches', 'plot_pdf', 'plot_cdf', 'fit_powerlaw',
67
+ 'detect_avalanches', 'plot_gaussian_threshold', 'plot_pdf', 'plot_cdf', 'fit_powerlaw',
65
68
  'fit_third_exponent', 'dcc', 'estimate_dcc', 'shape_collapse_error',
66
- 'dcc_collapse', 'dcc_collapse_2', 'fit_shape_collapse',
69
+ 'dcc_collapse', 'fit_shape_collapse',
67
70
  'plot_shape_collapse', 'avl_repertoire',
68
71
  'avl_pattern_dissimilarity', 'avl_branching_ratio', 'branching_ratio',
69
72
  'susceptibility', 'fano_factor',
70
73
  # chaos
71
- 'z1_chaos_test', 'chaos_pipeline', 'lambda_max', 'minmaxsig',
72
- 'schreiber_denoise',
74
+ 'z1_chaos_test', 'chaos_pipeline', 'minmaxsig', 'schreiber_denoise',
75
+ # stability
76
+ 'lambda_max',
73
77
  # synchrony
74
78
  'pcf', 'pli', 'ple', 'complex_phase_relationship', 'phase_locking',
75
79
  'phase_lock_interval', 'global_lability', 'detect_phase_avls',
@@ -78,5 +82,6 @@ __all__ = [
78
82
  'fit_pmem', 'fit_beta', 'sk_diagram', 'metropolis', 'plot_sk',
79
83
  'ht_diagram', 'ising_energy', 'heat_capacity', 'energy_landscape_2d',
80
84
  # utils
81
- 'binarized_events', 'time_bin_events', 'lattice_search',
85
+ 'binarized_events', 'gaussian_threshold', 'phase_randomize',
86
+ 'time_bin_events', 'bin_spikes', 'lattice_search',
82
87
  ]
@@ -12,8 +12,9 @@ import powerlaw
12
12
  from edgeofpy.utils import (binarized_events, time_bin_events,
13
13
  lattice_search, _sec_to_samples)
14
14
 
15
- def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
16
- thresh_type='both'):
15
+ def detect_avalanches(data, s_freq, time=None, max_iei=.004,
16
+ threshold='gaussian', thresh_type='both',
17
+ pop_threshold=None):
17
18
  """Detect avalanches in coarse-grained electrophysiological
18
19
  recordings. Takes either raw or binarized data.
19
20
 
@@ -32,14 +33,29 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
32
33
  max_iei : float, : .004
33
34
  Duration, in seconds, of the maximum inter-event interval within which
34
35
  successive events are counted as belonging to the same avalanche.
35
- threshold : float
36
+ threshold : float or 'gaussian'
36
37
  Number of standard deviations. Only signal excursions exceeding
37
- this threshold are considered events.
38
+ this threshold are considered events. 'gaussian' (default) finds
39
+ the amplitude at which the signal departs from a Gaussian, with
40
+ `gaussian_threshold` and its default settings. To compare
41
+ recordings, compute one threshold for all of them with
42
+ `gaussian_threshold` and pass it here.
38
43
  thresh_type : str
39
44
  If 'above', an event is detected when signal is greater than thresh.
40
45
  If 'below', an event is detected when signal is less than -thresh.
41
46
  If 'both', the signal above thresh and below -thresh is detected as an
42
47
  event.
48
+ pop_threshold : int or 'median', optional
49
+ Threshold on the number of events per sample, summed over channels.
50
+ If None (default), an avalanche is a run of samples with at least one
51
+ event, separated from the next by more than `max_iei`. If given,
52
+ only the events above the threshold count: each sample keeps
53
+ ``max(count - pop_threshold, 0)`` events. Use it for large
54
+ populations, e.g. spikes of hundreds of neurons, where samples
55
+ without any event are too rare to separate avalanches. 'median'
56
+ uses the median count per sample, rounded down to an integer.
57
+
58
+ .. versionadded:: 0.3.0
43
59
 
44
60
  Returns
45
61
  -------
@@ -51,7 +67,8 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
51
67
  end_time : float
52
68
  End time in seconds since recording start.
53
69
  size : int
54
- Number of events (over all channels).
70
+ Number of events (over all channels); with `pop_threshold`,
71
+ the number of events above the threshold.
55
72
  dur_sec : float
56
73
  Duration, in seconds, from first to last event in the
57
74
  avalanche.
@@ -71,7 +88,7 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
71
88
  events_all_chan : 2d array of same shape as data, dtype=int
72
89
  Time series of zeros with ones at the event peaks.
73
90
  events_one_chan : 1d array
74
- Collapsed event time series.
91
+ Collapsed event time series (after `pop_threshold`, if given).
75
92
  mean_iei : float
76
93
  Mean inter-event interval, in seconds. NaN if fewer than two events
77
94
  were found.
@@ -86,6 +103,9 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
86
103
  .. versionchanged:: 0.2.0
87
104
  The default `threshold` is 2 standard deviations (previously 3).
88
105
 
106
+ .. versionchanged:: 0.3.0
107
+ The default `threshold` is 'gaussian' (previously 2).
108
+
89
109
  References
90
110
  ----------
91
111
  - Benayoun et al. (2010) J Clin Neurophysiol 27(6) 458-64.
@@ -102,13 +122,52 @@ def detect_avalanches(data, s_freq, time=None, max_iei=.004, threshold=2,
102
122
  thresh_type=thresh_type, null_value=0)
103
123
 
104
124
  avalanches, events_one_chan = _det_avls(data, s_freq=s_freq, time=time,
105
- max_iei=max_iei)
125
+ max_iei=max_iei,
126
+ pop_threshold=pop_threshold)
106
127
  idx_events = np.flatnonzero(events_one_chan)
107
128
  mean_iei = (np.mean(np.diff(idx_events)) / s_freq if len(idx_events) > 1
108
129
  else np.nan)
109
130
 
110
131
  return avalanches, data, events_one_chan, mean_iei
111
132
 
133
+ def plot_gaussian_threshold(details, ax=None):
134
+ """Plot the amplitude distribution, the fitted Gaussian and the
135
+ threshold found by `gaussian_threshold`.
136
+
137
+ Parameters
138
+ ----------
139
+ details : dict
140
+ Second output of ``gaussian_threshold(..., return_details=True)``.
141
+ ax : matplotlib Axes, optional
142
+ Axes to draw on; a new figure is created if None.
143
+
144
+ Returns
145
+ -------
146
+ ax : matplotlib Axes
147
+
148
+ Notes
149
+ -----
150
+ .. versionadded:: 0.3.0
151
+ """
152
+ if ax is None:
153
+ _, ax = plt.subplots()
154
+ x, p = details['bin_centers'], details['density']
155
+ ax.semilogy(x[p > 0], p[p > 0], color='k', lw=1.5, label='data')
156
+ ax.semilogy(x, details['gaussian'], color='tab:red', lw=1,
157
+ label='fitted Gaussian')
158
+ ax.set_ylim(max(p[p > 0].min(), details['gaussian'].max() * 1e-12),
159
+ p.max() * 3)
160
+ thr = details['threshold']
161
+ if np.isfinite(thr):
162
+ lines = {'both': (-thr, thr), 'above': (thr,),
163
+ 'below': (-thr,)}[details['thresh_type']]
164
+ for i, t in enumerate(lines):
165
+ ax.axvline(t, color='tab:blue', ls='--', lw=1,
166
+ label=f'threshold ({thr:g} SD)' if i == 0 else None)
167
+ ax.set(xlabel='amplitude (SD)', ylabel='probability density')
168
+ ax.legend(frameon=False)
169
+ return ax
170
+
112
171
  def plot_pdf(data, binning='d_lin', n_bins=100, xlabel=None, ylabel=None,
113
172
  ax=None):
114
173
  """Plot the probability density function of the data in double logarithmic
@@ -231,7 +290,9 @@ def fit_powerlaw(data, xmin=None, xmax=None, discrete=True):
231
290
  Kolmogorov-Smirnov distance between the data and the fitted power law
232
291
  (Clauset et al., 2009). If 'min', the minimum value of `data` is used;
233
292
  this biases the exponent if the distribution only follows a power law
234
- above some value, as is typical for avalanches.
293
+ above some value, as for avalanches in many models. For avalanche
294
+ sizes from sensor arrays (M/EEG), use 1 with `xmax` about 1.5 times
295
+ the number of channels instead (see Notes).
235
296
  xmax : int or float or str or None
236
297
  The maximum value below which to fit the data. If None, there is no
237
298
  upper limit. If 'max', the maximum value of `data` will be used.
@@ -289,11 +350,28 @@ def fit_powerlaw(data, xmin=None, xmax=None, discrete=True):
289
350
  The summary loglikelihood values for each fit function (power law,
290
351
  truncated power law, exponential, lognormal).
291
352
 
353
+ Warns
354
+ -----
355
+ UserWarning
356
+ If the fitted exponent is at 1 or 3, the limits of the range searched
357
+ by powerlaw: the estimate is then clipped and the true exponent may
358
+ lie beyond the limit.
359
+
360
+ .. versionadded:: 0.3.0
361
+
292
362
  Notes
293
363
  -----
294
364
  .. versionchanged:: 0.1.0
295
365
  The default `xmin` is None (automatic selection) instead of 'min'.
296
366
 
367
+ The automatic choice of `xmin` assumes that the data follow a power law
368
+ from `xmin` upward. With a cutoff, as for avalanches recorded with a
369
+ finite array of sensors, whose sizes bend down near the number of
370
+ channels N, it tends to place `xmin` on the cutoff, and the fit then
371
+ describes the cutoff (with exponents near 3) rather than the scale-free
372
+ range. For such data, fit sizes from 1 to about 1.5 N (Shriki et al.,
373
+ 2013).
374
+
297
375
  Automatic selection of `xmin` fits a power law above every candidate
298
376
  value, which takes a few times longer than a fixed `xmin`, e.g. about a
299
377
  minute for 50,000 continuous values.
@@ -310,6 +388,7 @@ def fit_powerlaw(data, xmin=None, xmax=None, discrete=True):
310
388
  ----------
311
389
  - Alstott et al. (2014) PLoS ONE 9(1), e85777.
312
390
  - Clauset et al. (2009) SIAM review 51(4), 661-703.
391
+ - Shriki et al. (2013) J Neurosci 33(16), 7079-90.
313
392
  """
314
393
  if xmin == 'min':
315
394
  xmin = min(data)
@@ -341,6 +420,7 @@ def fit_powerlaw(data, xmin=None, xmax=None, discrete=True):
341
420
  L = -PvL[0] - TvL[0] - EvL[0]
342
421
  best_fit = 'PTEL'[np.argmax([P, T, E, L])]
343
422
  best_fit_R_sum = np.max([P, T, E, L])
423
+ _check_exponent_bounds(fit.power_law.alpha)
344
424
 
345
425
  return {'fit': fit,
346
426
  'power_law_exp': fit.power_law.alpha,
@@ -363,6 +443,32 @@ def fit_powerlaw(data, xmin=None, xmax=None, discrete=True):
363
443
  'E_R_sum': E,
364
444
  'L_R_sum': L,}
365
445
 
446
+
447
+ # Range of exponents searched by powerlaw.Fit for the power law: it does not
448
+ # return values below 1 or above 3 (DEFAULT_PARAMETER_RANGES and its fitting
449
+ # with an upper bound xmax).
450
+ _PL_EXP_LIMITS = (1.0, 3.0)
451
+
452
+
453
+ def _check_exponent_bounds(exponent, name='power-law exponent', stacklevel=3):
454
+ """Warn if a fitted exponent sits at a limit of powerlaw's range."""
455
+ low, high = _PL_EXP_LIMITS
456
+ if not np.isfinite(exponent):
457
+ return
458
+ if exponent <= low + 5e-3:
459
+ warnings.warn(f'The fitted {name} ({exponent:.3f}) is at {low:g}, the '
460
+ f'lower limit of the range searched by powerlaw: the '
461
+ f'true exponent may be smaller, and the estimate should '
462
+ f'not be interpreted.', stacklevel=stacklevel)
463
+ elif exponent >= high - 5e-3:
464
+ warnings.warn(f'The fitted {name} ({exponent:.3f}) is at {high:g}, '
465
+ f'the upper limit of the range searched by powerlaw: '
466
+ f'the true exponent may be larger. Exponents this '
467
+ f'steep often mean that the fit covers a cutoff rather '
468
+ f'than a scale-free range (e.g. above the number of '
469
+ f'channels of a sensor array).', stacklevel=stacklevel)
470
+
471
+
366
472
  def fit_third_exponent(sizes, durations, discrete=True, method='mean',
367
473
  dur_range=None):
368
474
  """Estimate the third exponent, i.e. the exponent of the scaling relation
@@ -553,7 +659,13 @@ def estimate_dcc(sizes, durations, size_range=(None, None),
553
659
  -----
554
660
  UserWarning
555
661
  If fewer than 100 avalanches fall within a fitted range, or a fitted
556
- range spans less than one decade.
662
+ range spans less than one decade; if tau or alpha is at a limit of
663
+ the range searched by powerlaw (see `fit_powerlaw`); or if tau is
664
+ below 1.1, where ``(alpha - 1) / (tau - 1)``, and so the DCC, is very
665
+ sensitive to small errors in tau.
666
+
667
+ .. versionchanged:: 0.3.0
668
+ The last two warnings were added.
557
669
 
558
670
  Notes
559
671
  -----
@@ -582,12 +694,17 @@ def estimate_dcc(sizes, durations, size_range=(None, None),
582
694
  exponents and the DCC even though the underlying dynamics are the same.
583
695
  When comparing conditions or subjects, fixed fitting ranges are
584
696
  therefore preferable; `xmin_sensitivity` shows how much the DCC depends
585
- on them.
697
+ on them. For avalanches recorded with a sensor array (M/EEG), sizes are
698
+ limited by the number of channels N, and the automatic choice tends to
699
+ fall on this cutoff; use ``size_range=(1, about 1.5 N)`` instead
700
+ (Shriki et al., 2013). Durations are then short; check that their
701
+ fitted range spans at least a decade before interpreting the DCC.
586
702
 
587
703
  References
588
704
  ----------
589
705
  - Ma et al. (2019) Neuron 104(4), 655-64.
590
706
  - Clauset et al. (2009) SIAM Rev 51(4), 661-703.
707
+ - Shriki et al. (2013) J Neurosci 33(16), 7079-90.
591
708
  """
592
709
  sizes = np.asarray(sizes, dtype=float)
593
710
  durations = np.asarray(durations, dtype=float)
@@ -602,11 +719,15 @@ def estimate_dcc(sizes, durations, size_range=(None, None),
602
719
  f'avalanches ({n_total}).')
603
720
  rng = np.random.default_rng(rand_seed)
604
721
 
605
- # fitting ranges, from all avalanches
606
- size_fit = fit_powerlaw(sizes, xmin=size_range[0], xmax=size_range[1],
607
- discrete=discrete)
608
- dur_fit = fit_powerlaw(durations, xmin=dur_range[0], xmax=dur_range[1],
609
- discrete=discrete)
722
+ # fitting ranges, from all avalanches; the bound check is done below,
723
+ # once, on the reported exponents
724
+ with warnings.catch_warnings():
725
+ warnings.filterwarnings('ignore', message='The fitted power-law '
726
+ 'exponent', category=UserWarning)
727
+ size_fit = fit_powerlaw(sizes, xmin=size_range[0],
728
+ xmax=size_range[1], discrete=discrete)
729
+ dur_fit = fit_powerlaw(durations, xmin=dur_range[0],
730
+ xmax=dur_range[1], discrete=discrete)
610
731
  s_range = (size_fit['xmin'], size_fit['xmax'])
611
732
  d_range = (dur_fit['xmin'], dur_fit['xmax'])
612
733
 
@@ -676,6 +797,16 @@ def estimate_dcc(sizes, durations, size_range=(None, None),
676
797
  discrete, third_method)['dcc']
677
798
  grid_range = (np.nanmin(grid), np.nanmax(grid))
678
799
 
800
+ _check_exponent_bounds(point['tau'], 'size exponent tau')
801
+ _check_exponent_bounds(point['alpha'], 'duration exponent alpha')
802
+ if (np.isfinite(point['tau']) and point['tau'] < 1.1
803
+ and point['tau'] > _PL_EXP_LIMITS[0] + 5e-3):
804
+ warnings.warn(f"tau = {point['tau']:.3f} is close to 1, where "
805
+ f"(alpha - 1) / (tau - 1) is very sensitive to tau: an "
806
+ f"error of 0.01 in tau changes it by about "
807
+ f"{0.01 * abs(point['alpha'] - 1) / (point['tau'] - 1) ** 2:.2g}. "
808
+ f"The DCC is unreliable.", stacklevel=2)
809
+
679
810
  return {'dcc': point['dcc'],
680
811
  'dcc_signed': point['dcc_signed'],
681
812
  'tau': point['tau'],
@@ -807,34 +938,11 @@ def _collapse_error(T_set, profiles, gamma):
807
938
  squared_span = np.square(np.ptp(rescaled_profiles))
808
939
  return np.mean(variance) / squared_span
809
940
 
810
- def dcc_collapse(gamma, third):
811
- """The deviation from criticality coefficient for the scaling relation
812
- between the shape collapse exponent and the so-called "third" avalanche
813
- exponent.
814
-
815
- Parameters
816
- ----------
817
- gamma : float
818
- The empirical power law exponent for the shape collapse.
819
- third : float
820
- The empirical power law exponent of the relation between avalanche
821
- size and duration.
822
-
823
- Returns
824
- -------
825
- dcc_collapse : float
826
- The deviation from criticality coefficient for shape collapse.
827
-
828
- References
829
- ----------
830
- Friedman et al. (2012) PRL 108, 208102.
831
- """
832
- return np.abs( (third - 1) - gamma )
833
-
834
- def dcc_collapse_2(tau, alpha, gamma):
835
- """The deviation from criticality coefficient for the scaling relation
836
- between the avalanche size and duration exponents and the shape collapse
837
- exponent, (alpha - 1) / (tau - 1) = gamma + 1.
941
+ def dcc_collapse(tau, alpha, gamma):
942
+ """The deviation from criticality coefficient for the shape collapse:
943
+ the deviation from the scaling relation between the avalanche size and
944
+ duration exponents and the shape collapse exponent,
945
+ (alpha - 1) / (tau - 1) = gamma + 1.
838
946
 
839
947
  Parameters
840
948
  ----------
@@ -851,6 +959,23 @@ def dcc_collapse_2(tau, alpha, gamma):
851
959
  float
852
960
  The deviation from criticality coefficient.
853
961
 
962
+ Notes
963
+ -----
964
+ Gamma is compared with the size and duration distributions, not with
965
+ the third exponent (the slope of mean size against duration). Gamma and
966
+ the third exponent both describe how the mean avalanche size grows with
967
+ duration: if the mean profiles collapse with gamma, the mean size of
968
+ avalanches of duration T grows as T**(1 + gamma). Fitted on the same
969
+ avalanches, they agree for any process whose mean profiles keep their
970
+ shape across durations, critical or not, so their deviation is not a
971
+ test of criticality (`fit_shape_collapse` still returns the third
972
+ exponent, as a check of the collapse).
973
+
974
+ .. versionchanged:: 0.3.0
975
+ Formerly ``dcc_collapse_2``. The previous
976
+ ``dcc_collapse(gamma, third)``, ``|third - 1 - gamma|``, was
977
+ removed.
978
+
854
979
  References
855
980
  ----------
856
981
  Friedman et al. (2012) PRL 108, 208102.
@@ -860,18 +985,22 @@ def dcc_collapse_2(tau, alpha, gamma):
860
985
  def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
861
986
  n_levels=2, min_dur=3, min_avl=10, interp_n=1000,
862
987
  min_dur_check=(3, 5, 8, 12), n_boot=0, ci=0.95,
863
- rand_seed=0):
864
- """Fit the shape collapse exponent gamma, and compare it with the third
865
- exponent fitted over the same durations.
988
+ rand_seed=0, tau=None, alpha=None):
989
+ """Fit the shape collapse exponent gamma and, given the size and
990
+ duration exponents, its deviation from criticality.
866
991
 
867
992
  At criticality, the mean temporal profiles of avalanches of different
868
993
  durations T collapse onto a single curve when time is rescaled by T and
869
- the profiles by T**gamma, with gamma = third - 1. Gamma is found by
870
- minimizing `shape_collapse_error` with `lattice_search`. The third
871
- exponent is fitted (with `fit_third_exponent`) over exactly the
872
- durations used for the collapse: with finite data, both exponents depend
873
- on the range of durations, and fitting them over different ranges biases
874
- their comparison.
994
+ the profiles by T**gamma, with gamma + 1 = (alpha - 1) / (tau - 1).
995
+ Gamma is found by minimizing `shape_collapse_error` with
996
+ `lattice_search`. If `tau` and `alpha` are given (e.g. from
997
+ `estimate_dcc`), the deviation from that relation is returned as
998
+ `dcc_collapse`.
999
+
1000
+ The third exponent is also fitted (with `fit_third_exponent`) over the
1001
+ durations used for the collapse, as a check: if the profiles collapse,
1002
+ third = gamma + 1 whether or not the system is critical, so a large
1003
+ difference means that the profiles change shape with duration.
875
1004
 
876
1005
  Parameters
877
1006
  ----------
@@ -902,6 +1031,11 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
902
1031
  Coverage of the confidence intervals, e.g. 0.95.
903
1032
  rand_seed : int or numpy.random.Generator or None
904
1033
  Seed or random number generator for bootstrapping.
1034
+ tau, alpha : float, optional
1035
+ Exponents of the size and duration distributions. If both are
1036
+ given, `dcc_collapse` is computed.
1037
+
1038
+ .. versionadded:: 0.3.0
905
1039
 
906
1040
  Returns
907
1041
  -------
@@ -913,9 +1047,14 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
913
1047
  collapse_error : float
914
1048
  `shape_collapse_error` at `gamma`.
915
1049
  third : float
916
- Third exponent, over the durations used for the collapse.
917
- dcc_collapse : float
918
- ``|third - 1 - gamma|`` (see `dcc_collapse`).
1050
+ Third exponent, over the durations used for the collapse (a
1051
+ check of the collapse; see above).
1052
+ dcc_collapse : float or None
1053
+ ``|(alpha - 1) / (tau - 1) - (gamma + 1)|`` (see
1054
+ `dcc_collapse`); None unless `tau` and `alpha` are given.
1055
+
1056
+ .. versionchanged:: 0.3.0
1057
+ Previously ``|third - 1 - gamma|``.
919
1058
  durations : 1d array
920
1059
  Durations used for the collapse.
921
1060
  n_avalanches_used : int
@@ -924,9 +1063,13 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
924
1063
  Gamma for each value of `min_dur_check` (NaN where too few
925
1064
  durations qualify).
926
1065
  gamma_ci, dcc_collapse_ci : tuple or None
927
- Bootstrap confidence intervals (None if `n_boot` is 0).
1066
+ Bootstrap confidence intervals (None if `n_boot` is 0;
1067
+ `dcc_collapse_ci` also None unless `tau` and `alpha` are given).
1068
+ `dcc_collapse_ci` reflects the uncertainty of gamma only, with
1069
+ `tau` and `alpha` held fixed.
928
1070
  boot : dict or None
929
- Bootstrap values of 'gamma', 'third' and 'dcc_collapse'.
1071
+ Bootstrap values of 'gamma' and 'third' (and 'dcc_collapse' if
1072
+ `tau` and `alpha` are given).
930
1073
  x : 1d array
931
1074
  Rescaled time t/T of the profiles.
932
1075
  profiles : dict
@@ -936,6 +1079,16 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
936
1079
  Mean profile of each duration T (T values, one per time bin),
937
1080
  neither rescaled nor interpolated.
938
1081
 
1082
+ Warns
1083
+ -----
1084
+ UserWarning
1085
+ If gamma is at an edge of `gamma_range`, where the best collapse may
1086
+ lie outside the range searched. With the default range, a gamma of 0
1087
+ means that the mean profiles do not grow with duration (flat
1088
+ profiles), as for bursts of roughly constant activity.
1089
+
1090
+ .. versionadded:: 0.3.0
1091
+
939
1092
  Notes
940
1093
  -----
941
1094
  Bootstrap resamples draw avalanches with replacement and give percentile
@@ -949,6 +1102,9 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
949
1102
  """
950
1103
  if not 0 < ci < 1:
951
1104
  raise ValueError('ci must be between 0 and 1.')
1105
+ if (tau is None) != (alpha is None):
1106
+ raise ValueError('Give both tau and alpha, or neither.')
1107
+ with_dcc = tau is not None
952
1108
  rng = np.random.default_rng(rand_seed)
953
1109
  avalanches = list(avalanches)
954
1110
 
@@ -962,10 +1118,19 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
962
1118
  third = fit_third_exponent([a['size'] for a in in_set],
963
1119
  [a['dur_bin'] for a in in_set])
964
1120
  return {'gamma': gamma, 'collapse_error': error, 'third': third,
965
- 'dcc_collapse': dcc_collapse(gamma, third), 'T_set': T_set,
966
- 'n_used': len(in_set), 'x': x, 'profiles': profiles}
1121
+ 'dcc_collapse': (dcc_collapse(tau, alpha, gamma) if with_dcc
1122
+ else None),
1123
+ 'T_set': T_set, 'n_used': len(in_set), 'x': x,
1124
+ 'profiles': profiles}
967
1125
 
968
1126
  res = fit(avalanches, gamma_range, min_dur)
1127
+ for edge, side in ((gamma_range[0], 'lower'), (gamma_range[1], 'upper')):
1128
+ if abs(res['gamma'] - edge) < 1e-6:
1129
+ hint = (' A gamma of 0 means that the mean profiles do not grow '
1130
+ 'with duration (flat profiles).' if edge == 0 else '')
1131
+ warnings.warn(f"gamma ({res['gamma']:g}) is at the {side} edge of "
1132
+ f"gamma_range {tuple(gamma_range)}: the best "
1133
+ f"collapse may lie outside it.{hint}", stacklevel=2)
969
1134
 
970
1135
  gamma_by_min_dur = {}
971
1136
  for md in (min_dur_check or ()):
@@ -978,7 +1143,7 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
978
1143
  if n_boot:
979
1144
  g_range = (max(gamma_range[0], res['gamma'] - 0.5),
980
1145
  min(gamma_range[1], res['gamma'] + 0.5))
981
- keys = ('gamma', 'third', 'dcc_collapse')
1146
+ keys = ('gamma', 'third') + (('dcc_collapse',) if with_dcc else ())
982
1147
  boot = {k: np.full(n_boot, np.nan) for k in keys}
983
1148
  for b in range(n_boot):
984
1149
  idx = rng.integers(len(avalanches), size=len(avalanches))
@@ -990,7 +1155,8 @@ def fit_shape_collapse(avalanches, gamma_range=(0., 3.), step=0.1,
990
1155
  boot[k][b] = rep[k]
991
1156
  q = 100 * np.array([(1 - ci) / 2, (1 + ci) / 2])
992
1157
  gamma_ci = tuple(np.nanpercentile(boot['gamma'], q))
993
- dcc_ci = tuple(np.nanpercentile(boot['dcc_collapse'], q))
1158
+ if with_dcc:
1159
+ dcc_ci = tuple(np.nanpercentile(boot['dcc_collapse'], q))
994
1160
 
995
1161
  scaled = _rescale_profiles(res['T_set'], res['profiles'], res['gamma'])
996
1162
  raw = {T: np.mean([a['profile'] for a in avalanches if a['dur_bin'] == T],
@@ -1320,7 +1486,7 @@ def fano_factor(data):
1320
1486
  F = np.var(data) / np.mean(data)
1321
1487
  return F
1322
1488
 
1323
- def _det_avls(events, s_freq, time, max_iei):
1489
+ def _det_avls(events, s_freq, time, max_iei, pop_threshold=None):
1324
1490
  """Utility function for detecting avalanches from event time series."""
1325
1491
  # Maximum inter-event interval, in samples
1326
1492
  max_iei_len = _sec_to_samples(max_iei, s_freq, name='max_iei')
@@ -1333,6 +1499,19 @@ def _det_avls(events, s_freq, time, max_iei):
1333
1499
  else:
1334
1500
  events_one_chan = events.squeeze()
1335
1501
 
1502
+ # Keep only the events above a threshold on the summed count
1503
+ if pop_threshold is not None:
1504
+ if isinstance(pop_threshold, str):
1505
+ if pop_threshold != 'median':
1506
+ raise ValueError("pop_threshold must be an integer, "
1507
+ "'median' or None.")
1508
+ pop_threshold = int(np.floor(np.median(events_one_chan)))
1509
+ elif pop_threshold != int(pop_threshold) or pop_threshold < 0:
1510
+ raise ValueError('pop_threshold must be a non-negative '
1511
+ 'integer.')
1512
+ events_one_chan = np.maximum(events_one_chan - int(pop_threshold),
1513
+ 0)
1514
+
1336
1515
  # Obtain inter-event intervals
1337
1516
  idx_events = np.flatnonzero(events_one_chan)
1338
1517
  if len(idx_events) < 2: