braindynamics-starprotocol 1.0.2__tar.gz → 1.1.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.
- braindynamics_starprotocol-1.1.0/MANIFEST.in +7 -0
- {braindynamics_starprotocol-1.0.2/src/braindynamics_starprotocol.egg-info → braindynamics_starprotocol-1.1.0}/PKG-INFO +1 -1
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/pyproject.toml +1 -1
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/setup.py +2 -7
- braindynamics_starprotocol-1.1.0/src/braindynamics_starprotocol/network/compare.py +89 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/sca/crosscorrelogram.py +121 -71
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/sca/sca_cy.c +16641 -17119
- braindynamics_starprotocol-1.1.0/src/braindynamics_starprotocol/sca/sca_cy.pyx +132 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0/src/braindynamics_starprotocol.egg-info}/PKG-INFO +1 -1
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol.egg-info/top_level.txt +0 -1
- braindynamics_starprotocol-1.0.2/MANIFEST.in +0 -6
- braindynamics_starprotocol-1.0.2/src/braindynamics_starprotocol/network/compare.py +0 -120
- braindynamics_starprotocol-1.0.2/src/braindynamics_starprotocol/sca/sca_cy.pyx +0 -89
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/LICENSE +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/README.md +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/setup.cfg +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/__init__.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/network/__init__.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/network/networkdata.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/network/plot.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/network/sort.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/sca/__init__.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol/trialbraindata.py +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol.egg-info/SOURCES.txt +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol.egg-info/dependency_links.txt +0 -0
- {braindynamics_starprotocol-1.0.2 → braindynamics_starprotocol-1.1.0}/src/braindynamics_starprotocol.egg-info/requires.txt +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
include src/braindynamics_starprotocol/sca/sca_cy.pyx
|
|
2
|
+
|
|
3
|
+
exclude src/braindynamics_starprotocol/rawbraindata.py
|
|
4
|
+
exclude src/braindynamics_starprotocol/trialdata.py
|
|
5
|
+
recursive-exclude src/braindynamics_starprotocol/build/ *
|
|
6
|
+
recursive-exclude src/braindynamics_starprotocol/io/ *
|
|
7
|
+
recursive-exclude **/__pycache__ *
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: braindynamics_starprotocol
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 1.1.0
|
|
4
4
|
Summary: Functional brain network analysis protocol developed by Varga et al., 2024
|
|
5
5
|
Author-email: vlewir <levente.varga@ubbcluj.ro>, bpentek <balazs.pentek@ubbcluj.ro>
|
|
6
6
|
Project-URL: Homepage, https://github.com/vlewir/BrainDynamics_STARProtocols
|
|
@@ -3,17 +3,12 @@ import os
|
|
|
3
3
|
from Cython.Build import cythonize
|
|
4
4
|
import numpy as np
|
|
5
5
|
|
|
6
|
-
extensions = [ Extension( name="sca.sca_cy",
|
|
6
|
+
extensions = [ Extension( name="braindynamics_starprotocol.sca.sca_cy",
|
|
7
7
|
sources=[os.path.join("src", "braindynamics_starprotocol", "sca", "sca_cy.pyx")],
|
|
8
8
|
include_dirs=[np.get_include()]) ]
|
|
9
9
|
|
|
10
10
|
setup( name="braindynamics_starprotocol",
|
|
11
|
-
version="1.0
|
|
11
|
+
version="1.1.0",
|
|
12
12
|
ext_modules=cythonize(extensions),
|
|
13
13
|
include_dirs=[np.get_include()],
|
|
14
|
-
options={
|
|
15
|
-
'bdist_wheel': {
|
|
16
|
-
'universal':True,
|
|
17
|
-
},
|
|
18
|
-
},
|
|
19
14
|
)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from cliffs_delta import cliffs_delta
|
|
3
|
+
|
|
4
|
+
def _safe_cliffs_delta(a:np.ndarray, b:np.ndarray)->float:
|
|
5
|
+
"""Cliff's delta of two samples, or NaN if either sample is empty."""
|
|
6
|
+
if a.size == 0 or b.size == 0:
|
|
7
|
+
return np.nan
|
|
8
|
+
d, _ = cliffs_delta(a, b)
|
|
9
|
+
return d
|
|
10
|
+
|
|
11
|
+
def _check_rows(A:np.ndarray, B:np.ndarray)->tuple:
|
|
12
|
+
"""Returns (number of rows, True if either array has no samples).
|
|
13
|
+
An array with no samples (e.g. loaded from an empty filelist, shape (0, 0)) is allowed to have a different number of rows."""
|
|
14
|
+
if A.size == 0 or B.size == 0:
|
|
15
|
+
return max(A.shape[0], B.shape[0]), True
|
|
16
|
+
if A.shape[0] != B.shape[0]:
|
|
17
|
+
raise ValueError(f"Uneven number of rows in the input arrays: {A.shape[0]} != {B.shape[0]}")
|
|
18
|
+
return A.shape[0], False
|
|
19
|
+
|
|
20
|
+
def compare_ews_Cliffs_delta(A:np.ndarray, B:np.ndarray, split_by:float|None=0)->tuple|np.ndarray:
|
|
21
|
+
"""Function that computes Cliff's delta metric for two sets of edge weights (EWD samples), for each edge.
|
|
22
|
+
Because the EWD is a bimodal distribution, by the samples are split around 0 and the metric is computed separately for the lower (negative) and upper (positive) parts of the distribution.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
A (np.ndarray): First array of edge weights with shape: <number of edges>, <number of trials>
|
|
26
|
+
B (np.ndarray): Second array of edge weights with shape: <number of edges>, <number of trials>
|
|
27
|
+
split_by (float|None, optional): value around which the samples are split. None -> no split, a single delta per edge. Defaults to 0.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
ValueError: Length of the first dimension (number of edges) don't match in the two arrays.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
tuple : a tuple (deltas_n, deltas_p) of two arrays holding Cliff's delta of the lower (negative) and upper (positive) parts, for each edge.
|
|
34
|
+
Entries are NaN where a part is empty in either array (all NaN if either array has no trials).
|
|
35
|
+
If split_by is None, a single array of deltas (one per edge) is returned instead.
|
|
36
|
+
"""
|
|
37
|
+
edge_nr, any_empty = _check_rows(A, B)
|
|
38
|
+
|
|
39
|
+
if split_by is None:
|
|
40
|
+
return compare_nds_Cliffs_delta(A, B)
|
|
41
|
+
if any_empty:
|
|
42
|
+
return np.full(edge_nr, np.nan), np.full(edge_nr, np.nan)
|
|
43
|
+
|
|
44
|
+
# Cliff's delta values for the lower (negative) and upper (positive) parts of the bimodal EWD
|
|
45
|
+
deltas_n = []
|
|
46
|
+
deltas_p = []
|
|
47
|
+
|
|
48
|
+
for i in range(edge_nr):
|
|
49
|
+
deltas_n += [_safe_cliffs_delta(A[i][A[i] < split_by], B[i][B[i] < split_by])]
|
|
50
|
+
deltas_p += [_safe_cliffs_delta(A[i][A[i] >= split_by], B[i][B[i] >= split_by])]
|
|
51
|
+
|
|
52
|
+
return np.asarray(deltas_n), np.asarray(deltas_p)
|
|
53
|
+
|
|
54
|
+
def compare_nds_Cliffs_delta(A:np.ndarray, B:np.ndarray)->np.ndarray:
|
|
55
|
+
"""Function that computes Cliff's delta metric for two sets of node distances (NDD values).
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
A (np.ndarray): First array of node distances with shape: <number of nodes>, (<number of nodes> - 1)*<total number of trials 1>.
|
|
59
|
+
B (np.ndarray): Second array of node distances with shape: <number of nodes>, (<number of nodes> - 1)*<total number of trials 2>.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ValueError: Length of first dimension (number of nodes) don't match in the two arrays.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
np.ndarray: Array representing Cliff's delta metric for each node (NaN where a node's sample is empty in either array).
|
|
66
|
+
"""
|
|
67
|
+
node_nr, any_empty = _check_rows(A, B)
|
|
68
|
+
if any_empty:
|
|
69
|
+
return np.full(node_nr, np.nan)
|
|
70
|
+
|
|
71
|
+
return np.asarray([_safe_cliffs_delta(A[i], B[i]) for i in range(node_nr)])
|
|
72
|
+
|
|
73
|
+
def compare_news_Cliffs_delta(A:np.ndarray, B:np.ndarray, split_by:float|None=0)->tuple|np.ndarray:
|
|
74
|
+
"""Function that computes Cliff's delta metric for two sets of node edge weights (N-EWD values), for each node.
|
|
75
|
+
Because the N-EWD is a bimodal distribution, by the samples are split around 0 and the metric is computed separately for the lower (negative) and upper (positive) parts of the distribution.
|
|
76
|
+
Same computation as `compare_ews_Cliffs_delta`, applied per node.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
A (np.ndarray): First array of node edge weights with shape: <number of nodes>, (<number of nodes> - 1)*<total number of trials 1>.
|
|
80
|
+
B (np.ndarray): Second array of node edge weights with shape: <number of nodes>, (<number of nodes> - 1)*<total number of trials 2>.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ValueError: Length of first dimension (number of nodes) don't match in the two arrays.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
tuple: a tuple (deltas_n, deltas_p) of two arrays holding Cliff's delta of the lower (negative) and upper (positive) parts, for each node.
|
|
87
|
+
Entries are NaN where a part is empty in either array.
|
|
88
|
+
"""
|
|
89
|
+
return compare_ews_Cliffs_delta(A, B, split_by=split_by)
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import
|
|
1
|
+
import warnings
|
|
2
2
|
import numpy as np
|
|
3
3
|
from scipy.stats import pearsonr
|
|
4
4
|
try:
|
|
5
|
-
from .sca_cy import cross_correlation
|
|
5
|
+
from .sca_cy import cross_correlation
|
|
6
6
|
except ModuleNotFoundError:
|
|
7
|
-
|
|
7
|
+
cross_correlation = None # cython extension not compiled: only the python implementation is available
|
|
8
8
|
import matplotlib.pyplot as plt
|
|
9
9
|
from scipy.interpolate import Akima1DInterpolator
|
|
10
|
-
from scipy.optimize import
|
|
10
|
+
from scipy.optimize import minimize_scalar
|
|
11
11
|
|
|
12
12
|
def _fisher_transform(r:float, norm_factor:float=1.12)->float:
|
|
13
|
-
return 0.5*log((1 + r/norm_factor)/(1 - r/norm_factor))
|
|
13
|
+
return 0.5*np.log((1 + r/norm_factor)/(1 - r/norm_factor))
|
|
14
14
|
|
|
15
15
|
def _inverse_fisher_transform(z:float, norm_factor:float=1.12)->float:
|
|
16
|
-
return norm_factor*(exp(2*z) - 1)/(exp(2*z) + 1)
|
|
16
|
+
return norm_factor*(np.exp(2*z) - 1)/(np.exp(2*z) + 1)
|
|
17
17
|
|
|
18
|
-
def _pearson_correlation(
|
|
18
|
+
def _pearson_correlation(x:np.ndarray, y:np.ndarray)->float:
|
|
19
19
|
return pearsonr(x, y)[0]
|
|
20
20
|
|
|
21
21
|
class CrossCorrelogram():
|
|
@@ -46,37 +46,43 @@ class CrossCorrelogram():
|
|
|
46
46
|
self.corr_coeff_arr = np.zeros(2*self.max_shift_size + 1, dtype=np.float32)
|
|
47
47
|
self._interpolator = None
|
|
48
48
|
self._maxabs_shift, self._maxabs_value = -self.max_shift_size-1, -self.max_shift_size-1
|
|
49
|
+
self._maxabs_is_min = None
|
|
49
50
|
|
|
50
51
|
def _scaled_correlation(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=False)->float:
|
|
51
52
|
"""
|
|
52
53
|
Python implementation of scaled correlation analysis (SCA) between two array of samples. For reference, see Nikolic et al. "Scaled correlation analysis: a better way to compute a cross-correlogram" (2012).
|
|
54
|
+
The scale/segment size is `self.scale_size`; if it is None, classical Pearson correlation is computed (SCA with a single segment spanning the window, K = 1).
|
|
53
55
|
|
|
54
56
|
Args:
|
|
55
57
|
x (np.ndarray): First array of samples
|
|
56
58
|
y (np.ndarray): Second array
|
|
57
|
-
s (int): Scale/segment size
|
|
58
59
|
use_fisher (bool, optional): Whether or not use Fisher transformation during SCA. Defaults to False.
|
|
59
60
|
|
|
60
61
|
Returns:
|
|
61
62
|
float: scaled correlation value
|
|
62
63
|
"""
|
|
63
64
|
|
|
64
|
-
s = self.scale_size
|
|
65
65
|
T = len(x) # window size
|
|
66
|
+
s = self.scale_size if self.scale_size is not None else T # classical CC = single segment
|
|
66
67
|
K = T//s # number of scale segments that fit into window
|
|
67
|
-
if not use_fisher:
|
|
68
|
-
r_s = 0.0 # scaled correlation
|
|
69
|
-
for i in range(K):
|
|
70
|
-
r_s += _pearson_correlation(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s])
|
|
71
|
-
r_s /= K
|
|
72
|
-
else:
|
|
73
|
-
z = 0.0 # Fisher transform of scaled correlation
|
|
74
|
-
for i in range(K):
|
|
75
|
-
z += _fisher_transform(_pearson_correlation(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s]))
|
|
76
|
-
z /= K
|
|
77
|
-
r_s = _inverse_fisher_transform(z)
|
|
78
68
|
|
|
79
|
-
|
|
69
|
+
# segments as rows of a (K, s) matrix (samples beyond K*s are not used), in double precision
|
|
70
|
+
X = x[:K*s].reshape(K, s).astype(np.float64)
|
|
71
|
+
Y = y[:K*s].reshape(K, s).astype(np.float64)
|
|
72
|
+
# Pearson's r of every segment at once
|
|
73
|
+
Xc = X - X.mean(axis=1, keepdims=True)
|
|
74
|
+
Yc = Y - Y.mean(axis=1, keepdims=True)
|
|
75
|
+
xx = np.einsum('ks,ks->k', Xc, Xc)
|
|
76
|
+
yy = np.einsum('ks,ks->k', Yc, Yc)
|
|
77
|
+
if (xx == 0).any() or (yy == 0).any(): # constant segment: Pearson's r is undefined
|
|
78
|
+
return np.nan
|
|
79
|
+
r = np.einsum('ks,ks->k', Xc, Yc)/np.sqrt(xx*yy)
|
|
80
|
+
|
|
81
|
+
if K == 1: # single segment: plain Pearson's r (no need for the Fisher round-trip)
|
|
82
|
+
return r[0]
|
|
83
|
+
if not use_fisher:
|
|
84
|
+
return r.mean() # scaled correlation
|
|
85
|
+
return _inverse_fisher_transform(_fisher_transform(r).mean()) # average in Fisher z space
|
|
80
86
|
|
|
81
87
|
def _compute_py(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True)->None:
|
|
82
88
|
"""
|
|
@@ -91,25 +97,21 @@ class CrossCorrelogram():
|
|
|
91
97
|
|
|
92
98
|
n_x = len(x)
|
|
93
99
|
n_y = len(y)
|
|
94
|
-
if self.scale_size is not None: # SCA
|
|
95
|
-
# shifting x to the left, relative to y
|
|
96
|
-
for shift in range(-self.max_shift_size, 0):
|
|
97
|
-
self.corr_coeff_arr[shift + self.max_shift_size] = self._scaled_correlation(x[abs(shift):], y[:n_y - abs(shift)], use_fisher=use_fisher)
|
|
98
|
-
# zero shift
|
|
99
|
-
self.corr_coeff_arr[self.max_shift_size] = self._scaled_correlation(x, y, use_fisher=use_fisher)
|
|
100
|
-
# shifting x to the right, relative to y
|
|
101
|
-
for shift in range(1, self.max_shift_size + 1):
|
|
102
|
-
self.corr_coeff_arr[shift + self.max_shift_size] = self._scaled_correlation(x[:n_x - shift], y[shift:], use_fisher=use_fisher)
|
|
103
|
-
else: # CC
|
|
104
|
-
# shifting x to the left, relative to y
|
|
105
|
-
for shift in range(-self.max_shift_size, 0):
|
|
106
|
-
self.corr_coeff_arr[shift + self.max_shift_size] = _pearson_correlation(x[abs(shift):], y[:n_y - abs(shift)])
|
|
107
|
-
# zero shift
|
|
108
|
-
self.corr_coeff_arr[self.max_shift_size] = _pearson_correlation(x, y)
|
|
109
|
-
# shifting x to the right, relative to y
|
|
110
|
-
for shift in range(1, self.max_shift_size + 1):
|
|
111
|
-
self.corr_coeff_arr[shift + self.max_shift_size] = _pearson_correlation(x[:n_x - shift], y[shift:])
|
|
112
100
|
|
|
101
|
+
# Common interval
|
|
102
|
+
## To have ensure equal correlation window sizes for all shifts
|
|
103
|
+
## we must take first & last max shift no. of samples as "padding"
|
|
104
|
+
start = self.max_shift_size
|
|
105
|
+
end = min(n_x, n_y) - self.max_shift_size
|
|
106
|
+
|
|
107
|
+
# shifting y relative to x (classical CC is SCA with a single segment, handled in _scaled_correlation)
|
|
108
|
+
for shift in range(-self.max_shift_size, self.max_shift_size + 1):
|
|
109
|
+
self.corr_coeff_arr[shift + self.max_shift_size] = self._scaled_correlation(
|
|
110
|
+
x[start:end],
|
|
111
|
+
y[start + shift:end + shift],
|
|
112
|
+
use_fisher=use_fisher
|
|
113
|
+
)
|
|
114
|
+
|
|
113
115
|
def _compute_cy(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True)->None:
|
|
114
116
|
"""
|
|
115
117
|
Compute CC using cython implementation (recommended).
|
|
@@ -135,20 +137,37 @@ class CrossCorrelogram():
|
|
|
135
137
|
use_fisher (bool, optional): Whether or not use Fisher transformation during SCA. Defaults to True.
|
|
136
138
|
cc_method (str, optional): Which implementation to use for the computation. Defaults to "C".
|
|
137
139
|
|
|
140
|
+
If a correlation segment (scale segment for SCA, the whole correlation window for classical CC) is constant,
|
|
141
|
+
Pearson's r is undefined there and the correlogram is NaN at the affected shifts (at all shifts if the segment is in `x`),
|
|
142
|
+
which is reported with a RuntimeWarning.
|
|
143
|
+
|
|
138
144
|
Raises:
|
|
139
145
|
ValueError: Input arrays are of uneven length
|
|
140
|
-
ValueError:
|
|
146
|
+
ValueError: Correlation window (input length - 2*max_shift_size) is shorter than 2 samples, or than the scale size during SCA
|
|
147
|
+
ValueError: Scale size is less than 2 during SCA
|
|
141
148
|
ValueError: Wrong implementation method is given
|
|
142
149
|
"""
|
|
143
|
-
|
|
150
|
+
|
|
144
151
|
if len(x) != len(y):
|
|
145
152
|
raise ValueError(f"Dimension mismatch between x ({len(x)}) and y ({len(y)})")
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
153
|
+
|
|
154
|
+
# correlation window: first & last max_shift_size samples are padding, so the window size is the same at every shift
|
|
155
|
+
T = len(x) - 2*self.max_shift_size
|
|
156
|
+
if T < 2:
|
|
157
|
+
raise ValueError(f"Length of correlation window ({len(x)} - 2*{self.max_shift_size} = {T}) must be at least 2 samples")
|
|
158
|
+
if self.scale_size is not None:
|
|
159
|
+
if self.scale_size < 2:
|
|
160
|
+
raise ValueError(f"SCA: Scale/segment size ({self.scale_size}) must be at least 2 samples")
|
|
161
|
+
if T < self.scale_size:
|
|
162
|
+
raise ValueError(f"SCA: Length of correlation window ({len(x)} - 2*{self.max_shift_size} = {T}) must be greater or equal than the scale/segment size ({self.scale_size})")
|
|
163
|
+
|
|
164
|
+
self.clear() # drop results (maxabs, interpolator) of any previous computation
|
|
165
|
+
|
|
150
166
|
x = x.astype(np.float32) # cython code expects float32
|
|
151
167
|
y = y.astype(np.float32)
|
|
168
|
+
if cc_method == "C" and cross_correlation is None:
|
|
169
|
+
warnings.warn("Cython extension (sca_cy) is not compiled, falling back to the python implementation (cc_method='py'), which is ~3-4x slower. Build it e.g. with `pip install -e .`", RuntimeWarning, stacklevel=2)
|
|
170
|
+
cc_method = "py"
|
|
152
171
|
if cc_method == "C":
|
|
153
172
|
self._compute_cy(x, y, use_fisher=use_fisher)
|
|
154
173
|
elif cc_method == "py":
|
|
@@ -156,18 +175,27 @@ class CrossCorrelogram():
|
|
|
156
175
|
else:
|
|
157
176
|
raise ValueError("Only two options are supported for `cc_method` parameter: 'py' for pure python implementation, 'C' for cython (recommended)")
|
|
158
177
|
|
|
178
|
+
nan_count = np.isnan(self.corr_coeff_arr).sum()
|
|
179
|
+
if nan_count > 0:
|
|
180
|
+
warnings.warn(f"Correlogram is NaN at {nan_count} of {len(self.corr_coeff_arr)} shifts: constant correlation segment(s) in x and/or y (Pearson's r is undefined), or NaN in the input.", RuntimeWarning, stacklevel=2)
|
|
181
|
+
|
|
159
182
|
def _find_extremas(self)->np.ndarray:
|
|
160
183
|
"""
|
|
161
|
-
Find extremas of the correlogram
|
|
184
|
+
Find extremas (peaks) of the correlogram. Flat peaks (plateaus of equal values) are marked at their middle point.
|
|
162
185
|
|
|
163
186
|
Returns:
|
|
164
|
-
np.ndarray: array of
|
|
187
|
+
np.ndarray: array of booleans representing whether the given point of the correlogram is an extrema or not
|
|
165
188
|
"""
|
|
166
|
-
extremas = np.
|
|
167
|
-
|
|
189
|
+
extremas = np.full(len(self.corr_coeff_arr), False, dtype=bool)
|
|
190
|
+
diffs = np.diff(self.corr_coeff_arr)
|
|
191
|
+
steps = np.flatnonzero(diffs != 0) # non-flat steps (flat steps of plateaus are skipped)
|
|
192
|
+
turns = diffs[steps[:-1]]*diffs[steps[1:]] < 0 # slope changes sign between consecutive non-flat steps
|
|
193
|
+
# points between such steps a & b (a + 1, ..., b) are equal: mark the middle one (a + 1 if there is no plateau)
|
|
194
|
+
a, b = steps[:-1][turns], steps[1:][turns]
|
|
195
|
+
extremas[(a + 1 + b)//2] = True
|
|
168
196
|
return extremas
|
|
169
197
|
|
|
170
|
-
def
|
|
198
|
+
def _set_interpolator(self, shifts:np.ndarray, values:np.ndarray):
|
|
171
199
|
"""
|
|
172
200
|
Wrapper function for the interpolator object.
|
|
173
201
|
|
|
@@ -177,6 +205,11 @@ class CrossCorrelogram():
|
|
|
177
205
|
"""
|
|
178
206
|
self._interpolator = Akima1DInterpolator(shifts, values)
|
|
179
207
|
|
|
208
|
+
def _interpolate(self, shift:float):
|
|
209
|
+
if self._interpolator is None:
|
|
210
|
+
raise ValueError('Akima interpolator object not set')
|
|
211
|
+
return self._interpolator(shift)
|
|
212
|
+
|
|
180
213
|
def get_maxabs(self)->tuple:
|
|
181
214
|
"""
|
|
182
215
|
Function that determines & saves MaxAbs (absolute peak) of the interpolated correlogram.
|
|
@@ -190,33 +223,49 @@ class CrossCorrelogram():
|
|
|
190
223
|
if (self.corr_coeff_arr == 0.0).all():
|
|
191
224
|
raise ValueError("Correlogram not computed.")
|
|
192
225
|
|
|
226
|
+
if np.isnan(self.corr_coeff_arr).any(): # e.g. constant segments during computation
|
|
227
|
+
warnings.warn("Correlogram contains NaN values, MaxAbs is undefined: returning (nan, nan).", RuntimeWarning, stacklevel=2)
|
|
228
|
+
self._maxabs_shift, self._maxabs_value = np.nan, np.nan
|
|
229
|
+
return self._maxabs_shift, self._maxabs_value
|
|
230
|
+
|
|
193
231
|
if self.max_shift_size == 0: # if no shift was specified, return the only value as MaxAbs
|
|
194
|
-
|
|
232
|
+
self._maxabs_shift = 0
|
|
233
|
+
self._maxabs_value = self.corr_coeff_arr[0]
|
|
234
|
+
return self._maxabs_shift, self._maxabs_value
|
|
195
235
|
|
|
196
236
|
# finding maxabs on correlogram
|
|
197
|
-
is_extrema =
|
|
237
|
+
is_extrema = self._find_extremas()
|
|
238
|
+
|
|
239
|
+
# check if no peaks were detected on correlogram
|
|
240
|
+
if (is_extrema == False).all():
|
|
241
|
+
maxabs_idx = np.argmax(np.abs(self.corr_coeff_arr)) # in that case, maxabs will be its maximal absolute value (either first or last point, because it's monotonic)
|
|
242
|
+
self._maxabs_shift = maxabs_idx - self.max_shift_size
|
|
243
|
+
self._maxabs_value = self.corr_coeff_arr[maxabs_idx]
|
|
244
|
+
print(f'\tNOTE: No peaks found on the correlogram (it is monotonic function). Returning the maximal absolute value of the correlogram ({self._maxabs_value}) located at the maximal shift ({self._maxabs_shift}).')
|
|
245
|
+
return self._maxabs_shift, self._maxabs_value
|
|
246
|
+
|
|
198
247
|
argmax_idx = np.argmax(np.abs(self.corr_coeff_arr[is_extrema]))
|
|
199
248
|
maxabs_idx = np.where(is_extrema == 1)[0][argmax_idx] # index of extrema with max abs in the correlogram
|
|
249
|
+
# nearest neighbours with a different value (further than +-1 if the peak is a plateau)
|
|
250
|
+
left, right = maxabs_idx - 1, maxabs_idx + 1
|
|
251
|
+
while self.corr_coeff_arr[left] == self.corr_coeff_arr[maxabs_idx]:
|
|
252
|
+
left -= 1
|
|
253
|
+
while self.corr_coeff_arr[right] == self.corr_coeff_arr[maxabs_idx]:
|
|
254
|
+
right += 1
|
|
200
255
|
# preparing data for interpolation
|
|
201
256
|
shifts = np.arange(-self.max_shift_size, self.max_shift_size + 1, 1)
|
|
202
257
|
values = self.corr_coeff_arr
|
|
203
|
-
|
|
204
|
-
if self.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
maxabs_hires_value = self._interpolator(maxabs_hires_shift)
|
|
209
|
-
elif self.corr_coeff_arr[maxabs_idx] > self.corr_coeff_arr[maxabs_idx - 1] and self.corr_coeff_arr[maxabs_idx] > self.corr_coeff_arr[maxabs_idx + 1]:
|
|
210
|
-
self._maxabs_is_min = False
|
|
211
|
-
self._interpolate(shifts, -values) # if extrema is maxima, flip the function & find the minimas
|
|
212
|
-
maxabs_hires_shift = fmin(self._interpolator, shifts[maxabs_idx], disp=0)
|
|
213
|
-
maxabs_hires_value = -self._interpolator(maxabs_hires_shift)
|
|
214
|
-
|
|
215
|
-
self._maxabs_shift = maxabs_hires_shift[0]
|
|
216
|
-
self._maxabs_value = maxabs_hires_value[0]
|
|
258
|
+
self._maxabs_is_min = bool(self.corr_coeff_arr[maxabs_idx] < self.corr_coeff_arr[left])
|
|
259
|
+
sign = 1 if self._maxabs_is_min else -1 # if extrema is maxima, flip the function & find the minima
|
|
260
|
+
# interpolate & find minimum near the detected peak (maxabs)
|
|
261
|
+
self._set_interpolator(shifts, sign*values)
|
|
262
|
+
res = minimize_scalar(self._interpolate, bounds=(shifts[left], shifts[right]), method='bounded')
|
|
217
263
|
|
|
218
|
-
|
|
264
|
+
self._maxabs_shift = res.x
|
|
265
|
+
self._maxabs_value = sign*res.fun # flipping back to get maxima value
|
|
219
266
|
|
|
267
|
+
return self._maxabs_shift, self._maxabs_value
|
|
268
|
+
|
|
220
269
|
def plot(self, show_interp:bool=False, show_maxabs:bool=False, interp_shift_res:float=0.1):
|
|
221
270
|
"""
|
|
222
271
|
Plot correlogram.
|
|
@@ -233,11 +282,12 @@ class CrossCorrelogram():
|
|
|
233
282
|
plt.scatter(shifts, self.corr_coeff_arr, color="tab:blue", label="CC")
|
|
234
283
|
plt.plot(shifts, np.abs(self.corr_coeff_arr), color="tab:orange", alpha=0.6, label="Abs(CC)")
|
|
235
284
|
if show_interp:
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
plt.plot(hires_shifts, self._interpolator(hires_shifts), color="tab:blue", label="SmoothCC")
|
|
285
|
+
if self.max_shift_size == 0:
|
|
286
|
+
warnings.warn("Cannot interpolate a correlogram with a single point (max_shift_size = 0); skipping SmoothCC.", RuntimeWarning, stacklevel=2)
|
|
239
287
|
else:
|
|
240
|
-
|
|
288
|
+
# own interpolator on the correlogram: independent of get_maxabs() (works for monotonic correlograms too)
|
|
289
|
+
hires_shifts = np.linspace(-self.max_shift_size, self.max_shift_size, int(round(2*self.max_shift_size/interp_shift_res)) + 1)
|
|
290
|
+
plt.plot(hires_shifts, Akima1DInterpolator(shifts, self.corr_coeff_arr)(hires_shifts), color="tab:blue", label="SmoothCC")
|
|
241
291
|
if show_maxabs:
|
|
242
292
|
if self._maxabs_shift == -self.max_shift_size-1 or self._maxabs_value == -self.max_shift_size-1:
|
|
243
293
|
raise Warning("Cannot plot maxabs, as it wasn't computed. Calculate it with CrossCorrelogram.get_maxabs() method")
|