-
-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathtests_complexity.py
701 lines (564 loc) · 22.6 KB
/
tests_complexity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
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
601
602
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
from collections.abc import Iterable
import antropy
import nolds
import numpy as np
import pandas as pd
import sklearn.neighbors
from packaging import version
from pyentrp import entropy as pyentrp
# import EntropyHub
import neurokit2 as nk
# For the testing of complexity, we test our implementations against existing and established ones.
# However, some of these other implementations are not really packaged in a way
# SO THAT we can easily import them. Thus, we directly copied their content in this file
# (below the tests).
# =============================================================================
# Some sanity checks
# =============================================================================
def test_complexity_sanity():
signal = np.cos(np.linspace(start=0, stop=30, num=1000))
mdfa_q = [-5, -3, -1, 1, 3, 5]
# Entropy
assert np.allclose(
nk.entropy_fuzzy(signal)[0],
nk.entropy_sample(signal, fuzzy=True)[0],
atol=0.000001,
)
# Fractal
fractal_dfa, parameters = nk.fractal_dfa(signal, scale=np.array([4, 8, 12, 20]))
assert parameters["Fluctuations"].shape == (4, 1)
assert np.allclose(fractal_dfa, 2.10090484, atol=0.0001)
_, parameters = nk.fractal_dfa(signal, multifractal=True, q=mdfa_q)
# TODO: why this gives 70 or 71 depending on the machine????
# assert parameters["Fluctuations"].shape == (70, len(mdfa_q))
assert np.allclose(
nk.fractal_correlation(signal)[0], 0.7382138350901658, atol=0.000001
)
assert np.allclose(
nk.fractal_correlation(signal, radius="nolds")[0],
nolds.corr_dim(signal, 2),
atol=0.01,
)
# =============================================================================
# Comparison against R
# =============================================================================
# R code:
#
# library(TSEntropies)
# library(pracma)
#
# signal <- read.csv("https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv")$RSP
# r <- 0.2 * sd(signal)
# ApEn --------------------------------------------------------------------
# TSEntropies::ApEn(signal, dim=2, lag=1, r=r)
# 0.04383386
# TSEntropies::ApEn(signal, dim=3, lag=2, r=1)
# 0.0004269369
# pracma::approx_entropy(signal[1:200], edim=2, r=r, elag=1)
# 0.03632554
# SampEn ------------------------------------------------------------------
# TSEntropies::SampEn(signal[1:300], dim=2, lag=1, r=r)
# 0.04777648
# TSEntropies::FastSampEn(signal[1:300], dim=2, lag=1, r=r)
# 0.003490405
# pracma::sample_entropy(signal[1:300], edim=2, tau=1, r=r)
# 0.03784376
# pracma::sample_entropy(signal[1:300], edim=3, tau=2, r=r)
# 0.09185509
def test_complexity_vs_R():
signal = pd.read_csv(
"https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv"
)["RSP"].values
r = 0.2 * np.std(signal, ddof=1)
# ApEn
apen = nk.entropy_approximate(signal, dimension=2, tolerance=r)[0]
assert np.allclose(apen, 0.04383386, atol=0.0001)
apen = nk.entropy_approximate(signal, dimension=3, delay=2, tolerance=1)[0]
assert np.allclose(apen, 0.0004269369, atol=0.0001)
apen = nk.entropy_approximate(signal[0:200], dimension=2, delay=1, tolerance=r)[0]
assert np.allclose(apen, 0.03632554, atol=0.0001)
# SampEn
sampen = nk.entropy_sample(signal[0:300], dimension=2, tolerance=r)[0]
assert np.allclose(
sampen,
nk.entropy_sample(signal[0:300], dimension=2, tolerance=r, distance="infinity")[
0
],
atol=0.001,
)
assert np.allclose(sampen, 0.03784376, atol=0.001)
sampen = nk.entropy_sample(signal[0:300], dimension=3, delay=2, tolerance=r)[0]
assert np.allclose(sampen, 0.09185509, atol=0.01)
# =============================================================================
# Comparison against Python implementations
# =============================================================================
def test_complexity_vs_Python():
signal = np.cos(np.linspace(start=0, stop=30, num=100))
tolerance = 0.2 * np.std(signal, ddof=1)
# Shannon
shannon = nk.entropy_shannon(signal)[0]
# assert scipy.stats.entropy(shannon, pd.Series(signal).value_counts())
assert np.allclose(shannon, pyentrp.shannon_entropy(signal))
# Approximate
assert np.allclose(nk.entropy_approximate(signal)[0], 0.17364897858477146)
# EntropyHub doens't work because of PyEMD
# assert np.allclose(
# nk.entropy_approximate(signal, dimension=2, tolerance=tolerance)[0],
# EntropyHub.ApEn(signal, m=2, tau=1, r=tolerance)[0][2],
# )
assert np.allclose(
nk.entropy_approximate(signal, dimension=2, tolerance=tolerance)[0],
entropy_app_entropy(signal, 2),
)
assert nk.entropy_approximate(signal, dimension=2, tolerance=tolerance)[
0
] != pyeeg_ap_entropy(signal, 2, tolerance)
# Sample
assert np.allclose(
nk.entropy_sample(signal, dimension=2, tolerance=tolerance)[0],
entropy_sample_entropy(signal, 2),
)
assert np.allclose(
nk.entropy_sample(signal, dimension=2, tolerance=0.2)[0],
nolds.sampen(signal, 2, 0.2),
)
assert np.allclose(
nk.entropy_sample(signal, dimension=2, tolerance=0.2)[0],
entro_py_sampen(signal, 2, 0.2, scale=False),
)
assert np.allclose(
nk.entropy_sample(signal, dimension=2, tolerance=0.2)[0],
pyeeg_samp_entropy(signal, 2, 0.2),
)
# assert np.allclose(
# nk.entropy_sample(signal, dimension=2, tolerance=0.2)[0],
# EntropyHub.SampEn(signal, m=2, tau=1, r=0.2)[0][2],
# )
# import sampen
# sampen.sampen2(signal[0:300], mm=2, r=r)
assert (
nk.entropy_sample(signal, dimension=2, tolerance=0.2)[0]
!= pyentrp.sample_entropy(signal, 2, 0.2)[1]
)
assert (
nk.entropy_sample(signal, dimension=2, tolerance=0.2 * np.sqrt(np.var(signal)))[
0
]
!= MultiscaleEntropy_sample_entropy(signal, 2, 0.2)[0.2][2]
)
# MSE
# assert nk.entropy_multiscale(signal, 2, 0.2*np.sqrt(np.var(signal)))
# != np.trapz(MultiscaleEntropy_mse(signal, [i+1 for i in range(10)], 2, 0.2, return_type="list"))
# assert nk.entropy_multiscale(signal, 2, 0.2*np.std(signal, ddof=1))
# != np.trapz(pyentrp.multiscale_entropy(signal, 2, 0.2, 10))
# Fuzzy
assert np.allclose(
nk.entropy_fuzzy(signal, dimension=2, tolerance=0.2, delay=1)[0]
- entro_py_fuzzyen(signal, 2, 0.2, 1, scale=False),
0,
)
# Lempel Ziv Complexity
threshold = np.nanmedian(signal)
binary = np.zeros(len(signal))
binary[signal > threshold] = 1
assert np.allclose(
nk.complexity_lempelziv(signal, symbolize="median", normalize=True)[0]
- antropy.lziv_complexity(binary, normalize=True),
0,
)
# Katz
assert np.allclose(nk.fractal_katz(signal)[0] - antropy.katz_fd(signal), 0)
# # DFA
# assert np.allclose(nk.fractal_dfa(signal, windows=np.array([4, 8, 12, 20]))['slopes'][0], nolds.dfa(
# signal, nvals=[4, 8, 12, 20], fit_exp="poly"), atol=0.01
# )
# =============================================================================
# Wikipedia
# =============================================================================
def wikipedia_sampen(signal, m=2, r=1):
N = len(signal)
B = 0.0
A = 0.0
# Split time series and save all templates of length m
xmi = np.array([signal[i : i + m] for i in range(N - m)])
xmj = np.array([signal[i : i + m] for i in range(N - m + 1)])
# Save all matches minus the self-match, compute B
B = np.sum([np.sum(np.abs(xmii - xmj).max(axis=1) <= r) - 1 for xmii in xmi])
# Similar for computing A
m += 1
xm = np.array([signal[i : i + m] for i in range(N - m + 1)])
A = np.sum([np.sum(np.abs(xmi - xm).max(axis=1) <= r) - 1 for xmi in xm])
# Return SampEn
return -np.log(A / B)
# =============================================================================
# entropy_estimators (https://github.com/paulbrodersen/entropy_estimators)
# =============================================================================
# import numpy as np
# from entropy_estimators import continuous
#
# x = np.random.randn(10000)
#
# # I don't know what this compute though
# continuous.get_h_mvn(x)
# continuous.get_h(x, k=5)
# =============================================================================
# Pyeeg
# =============================================================================
def pyeeg_embed_seq(time_series, tau, embedding_dimension):
if not isinstance(time_series, np.ndarray):
typed_time_series = np.asarray(time_series)
else:
typed_time_series = time_series
shape = (
typed_time_series.size - tau * (embedding_dimension - 1),
embedding_dimension,
)
strides = (typed_time_series.itemsize, tau * typed_time_series.itemsize)
return np.lib.stride_tricks.as_strided(
typed_time_series, shape=shape, strides=strides
)
def pyeeg_bin_power(X, Band, Fs):
C = np.fft.fft(X)
C = abs(C)
Power = np.zeros(len(Band) - 1)
for Freq_Index in range(0, len(Band) - 1):
Freq = float(Band[Freq_Index])
Next_Freq = float(Band[Freq_Index + 1])
Power[Freq_Index] = sum(
C[
int(np.floor(Freq / Fs * len(X))) : int(
np.floor(Next_Freq / Fs * len(X))
)
]
)
Power_Ratio = Power / sum(Power)
return Power, Power_Ratio
def pyeeg_ap_entropy(X, M, R):
N = len(X)
Em = pyeeg_embed_seq(X, 1, M)
A = np.tile(Em, (len(Em), 1, 1))
B = np.transpose(A, [1, 0, 2])
D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = np.max(D, axis=2) <= R
# Probability that random M-sequences are in range
Cm = InRange.mean(axis=0)
# M+1-sequences in range if M-sequences are in range & last values are close
Dp = np.abs(np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T)
Cmp = np.logical_and(Dp <= R, InRange[:-1, :-1]).mean(axis=0)
Phi_m, Phi_mp = np.sum(np.log(Cm)), np.sum(np.log(Cmp))
Ap_En = (Phi_m - Phi_mp) / (N - M)
return Ap_En
def pyeeg_samp_entropy(X, M, R):
N = len(X)
Em = pyeeg_embed_seq(X, 1, M)[:-1]
A = np.tile(Em, (len(Em), 1, 1))
B = np.transpose(A, [1, 0, 2])
D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = np.max(D, axis=2) <= R
np.fill_diagonal(InRange, 0) # Don't count self-matches
# Probability that random M-sequences are in range
Cm = InRange.sum(axis=0)
Dp = np.abs(np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T)
Cmp = np.logical_and(Dp <= R, InRange).sum(axis=0)
# Avoid taking log(0)
Samp_En = np.log(np.sum(Cm + 1e-100) / np.sum(Cmp + 1e-100))
return Samp_En
# =============================================================================
# Entropy
# =============================================================================
def entropy_embed(x, order=3, delay=1):
N = len(x)
if order * delay > N:
raise ValueError("Error: order * delay should be lower than x.size")
if delay < 1:
raise ValueError("Delay has to be at least 1.")
if order < 2:
raise ValueError("Order has to be at least 2.")
Y = np.zeros((order, N - (order - 1) * delay))
for i in range(order):
Y[i] = x[i * delay : i * delay + Y.shape[1]]
return Y.T
def entropy_app_samp_entropy(x, order, metric="chebyshev", approximate=True):
phi = np.zeros(2)
r = 0.2 * np.std(x, axis=-1, ddof=1)
# compute phi(order, r)
_emb_data1 = entropy_embed(x, order, 1)
if approximate:
emb_data1 = _emb_data1
else:
emb_data1 = _emb_data1[:-1]
count1 = (
sklearn.neighbors.KDTree(emb_data1, metric=metric)
.query_radius(emb_data1, r, count_only=True)
.astype(np.float64)
)
# compute phi(order + 1, r)
emb_data2 = entropy_embed(x, order + 1, 1)
count2 = (
sklearn.neighbors.KDTree(emb_data2, metric=metric)
.query_radius(emb_data2, r, count_only=True)
.astype(np.float64)
)
if approximate:
phi[0] = np.mean(np.log(count1 / emb_data1.shape[0]))
phi[1] = np.mean(np.log(count2 / emb_data2.shape[0]))
else:
phi[0] = np.mean((count1 - 1) / (emb_data1.shape[0] - 1))
phi[1] = np.mean((count2 - 1) / (emb_data2.shape[0] - 1))
return phi
def entropy_app_entropy(x, order=2, metric="chebyshev"):
phi = entropy_app_samp_entropy(x, order=order, metric=metric, approximate=True)
return np.subtract(phi[0], phi[1])
def entropy_sample_entropy(x, order=2, metric="chebyshev"):
x = np.asarray(x, dtype=np.float64)
phi = entropy_app_samp_entropy(x, order=order, metric=metric, approximate=False)
return -np.log(np.divide(phi[1], phi[0]))
# =============================================================================
# entro-py
# =============================================================================
def entro_py_sampen(x, dim, r, scale=True):
return entro_py_entropy(x, dim, r, scale=scale)
def entro_py_cross_sampen(x1, x2, dim, r, scale=True):
return entro_py_entropy([x1, x2], dim, r, scale)
def entro_py_fuzzyen(x, dim, r, n, scale=True):
return entro_py_entropy(x, dim, r, n=n, scale=scale, remove_baseline=True)
def entro_py_cross_fuzzyen(x1, x2, dim, r, n, scale=True):
return entro_py_entropy([x1, x2], dim, r, n, scale=scale, remove_baseline=True)
def entro_py_pattern_mat(x, m):
x = np.asarray(x).ravel()
if m == 1:
return x
else:
N = len(x)
patterns = np.zeros((m, N - m + 1))
for i in range(m):
patterns[i, :] = x[i : N - m + i + 1]
return patterns
def entro_py_entropy(x, dim, r, n=1, scale=True, remove_baseline=False):
fuzzy = remove_baseline
cross = isinstance(x, list)
N = len(x[0]) if cross else len(x)
if scale:
if cross:
x = [entro_py_scale(np.copy(x[0])), entro_py_scale(np.copy(x[1]))]
else:
x = entro_py_scale(np.copy(x))
phi = [0, 0] # phi(m), phi(m+1)
for j in [0, 1]:
m = dim + j
npat = N - dim # https://github.com/ixjlyons/entro-py/pull/2/files
if cross:
# patterns = [entro_py_pattern_mat(x[0], m), entro_py_pattern_mat(x[1], m)]
patterns = [
entro_py_pattern_mat(x[0], m)[:, :npat],
entro_py_pattern_mat(x[1], m)[:, :npat],
] # https://github.com/ixjlyons/entro-py/pull/2/files
else:
# patterns = entro_py_pattern_mat(x, m)
patterns = entro_py_pattern_mat(x, m)[:, :npat]
if remove_baseline:
if cross:
patterns[0] = entro_py_remove_baseline(patterns[0], axis=0)
patterns[1] = entro_py_remove_baseline(patterns[1], axis=0)
else:
patterns = entro_py_remove_baseline(patterns, axis=0)
# count = np.zeros(N-m) # https://github.com/ixjlyons/entro-py/pull/2/files
# for i in range(N-m): # https://github.com/ixjlyons/entro-py/pull/2/files
count = np.zeros(npat)
for i in range(npat):
if cross:
if m == 1:
sub = patterns[1][i]
else:
sub = patterns[1][:, [i]]
dist = np.max(np.abs(patterns[0] - sub), axis=0)
else:
if m == 1:
sub = patterns[i]
else:
sub = patterns[:, [i]]
dist = np.max(np.abs(patterns - sub), axis=0)
if fuzzy:
sim = np.exp(-np.power(dist, n) / r)
else:
sim = dist < r
count[i] = np.sum(sim) - 1
# phi[j] = np.mean(count) / (N-m-1)
# https://github.com/ixjlyons/entro-py/pull/2/files
phi[j] = np.mean(count) / (N - dim - 1)
return np.log(phi[0] / phi[1])
def entro_py_scale(x, axis=None):
x = entro_py_remove_baseline(x, axis=axis)
x /= np.std(x, ddof=1, axis=axis, keepdims=True)
return x
def entro_py_remove_baseline(x, axis=None):
x -= np.mean(x, axis=axis, keepdims=True)
return x
# =============================================================================
# MultiscaleEntropy https://github.com/reatank/MultiscaleEntropy/blob/master/MultiscaleEntropy/mse.py
# =============================================================================
def MultiscaleEntropy_init_return_type(return_type):
if return_type == "dict":
return {}
else:
return []
def MultiscaleEntropy_check_type(x, num_type, name):
if isinstance(x, num_type):
tmp = [x]
elif not isinstance(x, Iterable):
raise ValueError(
name
+ " should be a "
+ num_type.__name__
+ " or an iterator of "
+ num_type.__name__
)
else:
tmp = []
for i in x:
tmp.append(i)
if not isinstance(i, num_type):
raise ValueError(
name
+ " should be a "
+ num_type.__name__
+ " or an iterator of "
+ num_type.__name__
)
return tmp
# sum of seperate intervals of x
def MultiscaleEntropy_coarse_grain(x, scale_factor):
x = np.array(x)
x_len = len(x)
if x_len % scale_factor:
padded_len = (1 + int(x_len / scale_factor)) * scale_factor
else:
padded_len = x_len
tmp_x = np.zeros(padded_len)
tmp_x[:x_len] = x
tmp_x = np.reshape(tmp_x, (int(padded_len / scale_factor), scale_factor))
ans = np.reshape(np.sum(tmp_x, axis=1), (-1)) / scale_factor
return ans
def MultiscaleEntropy_sample_entropy(
x, m=[2], r=[0.15], sd=None, return_type="dict", safe_mode=False
):
"""[Sample Entropy, the threshold will be r*sd]
Arguments:
x {[input signal]} -- [an iterator of numbers]
Keyword Arguments:
m {list} -- [m in sample entropy] (default: {[2]})
r {list} -- [r in sample entropy] (default: {[0.15]})
sd {number} -- [standard derivation of x, if None, will be calculated] (default: {None})
return_type {str} -- [can be dict or list] (default: {'dict'})
safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})
Raises:
ValueError -- [some values too big]
Returns:
[dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of m, r;
if list, nest as [i][j] for lengths of m, r]
"""
# type checking
if not safe_mode:
m = MultiscaleEntropy_check_type(m, int, "m")
r = MultiscaleEntropy_check_type(r, float, "r")
if not (sd is None) and not isinstance(sd, (float, int)):
raise ValueError("sd should be a number")
try:
x = np.array(x)
except Exception as exc:
raise ValueError("x should be a sequence of numbers") from exc
# value checking
if len(x) < max(m):
raise ValueError("the max m is bigger than x's length")
# initialization
if sd is None:
sd = np.sqrt(np.var(x))
ans = MultiscaleEntropy_init_return_type(return_type)
# calculation
for i, rr in enumerate(r):
threshold = rr * sd
if return_type == "dict":
ans[rr] = MultiscaleEntropy_init_return_type(return_type)
else:
ans.append(MultiscaleEntropy_init_return_type(return_type))
count = {}
tmp_m = []
for mm in m:
tmp_m.append(mm)
tmp_m.append(mm + 1)
tmp_m = list(set(tmp_m))
for mm in tmp_m:
count[mm] = 0
for j in range(1, len(x) - min(m) + 1):
cont = 0
for inc in range(0, len(x) - j):
if abs(x[inc] - x[j + inc]) < threshold:
cont += 1
elif cont > 0:
for mm in tmp_m:
tmp = cont - mm + 1
count[mm] += tmp if tmp > 0 else 0
cont = 0
if cont > 0:
for mm in tmp_m:
tmp = cont - mm + 1
count[mm] += tmp if tmp > 0 else 0
for mm in m:
if count[mm + 1] == 0 or count[mm] == 0:
t = len(x) - mm + 1
tmp = -np.log(1 / (t * (t - 1)))
else:
tmp = -np.log(count[mm + 1] / count[mm])
if return_type == "dict":
ans[rr][mm] = tmp
else:
ans[i].append(tmp)
return ans
def MultiscaleEntropy_mse(
x,
scale_factor=list(range(1, 21)),
m=[2],
r=[0.15],
return_type="dict",
safe_mode=False,
):
"""[Multiscale Entropy]
Arguments:
x {[input signal]} -- [an iterator of numbers]
Keyword Arguments:
scale_factor {list} -- [scale factors of coarse graining] (default: {[i for i in range(1,21)]})
m {list} -- [m in sample entropy] (default: {[2]})
r {list} -- [r in sample entropy] (default: {[0.15]})
return_type {str} -- [can be dict or list] (default: {'dict'})
safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})
Raises:
ValueError -- [some values too big]
Returns:
[dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of scale_factor, m, r;
if list nest as [i][j][k] for lengths of scale_factor, m, r]
"""
# type checking
if not safe_mode:
m = MultiscaleEntropy_check_type(m, int, "m")
r = MultiscaleEntropy_check_type(r, float, "r")
scale_factor = MultiscaleEntropy_check_type(scale_factor, int, "scale_factor")
try:
x = np.array(x)
except Exception as exc:
raise ValueError("x should be a sequence of numbers") from exc
# value checking
if max(scale_factor) > len(x):
raise ValueError("the max scale_factor is bigger than x's length")
# calculation
sd = np.sqrt(np.var(x))
ms_en = MultiscaleEntropy_init_return_type(return_type)
for s_f in scale_factor:
y = MultiscaleEntropy_coarse_grain(x, s_f)
if return_type == "dict":
ms_en[s_f] = MultiscaleEntropy_sample_entropy(y, m, r, sd, "dict", True)
else:
ms_en.append(MultiscaleEntropy_sample_entropy(y, m, r, sd, "list", True))
if return_type == "list":
ms_en = [i[0] for i in ms_en]
ms_en = [i[0] for i in ms_en]
return ms_en