braindynamics-starprotocol 0.9.1__tar.gz → 1.0.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.
Files changed (27) hide show
  1. braindynamics_starprotocol-1.0.0/LICENSE +21 -0
  2. braindynamics_starprotocol-1.0.0/MANIFEST.in +7 -0
  3. {braindynamics_starprotocol-0.9.1/src/braindynamics_starprotocol.egg-info → braindynamics_starprotocol-1.0.0}/PKG-INFO +19 -5
  4. braindynamics_starprotocol-1.0.0/README.md +44 -0
  5. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/pyproject.toml +3 -3
  6. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/setup.py +7 -2
  7. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/__init__.py +1 -1
  8. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/network/__init__.py +1 -1
  9. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/network/compare.py +3 -3
  10. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/network/networkdata.py +28 -19
  11. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/network/plot.py +2 -2
  12. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/network/sort.py +3 -3
  13. braindynamics_starprotocol-1.0.0/src/braindynamics_starprotocol/sca/__init__.py +1 -0
  14. braindynamics_starprotocol-0.9.1/src/braindynamics_starprotocol/sca/scaledcrosscorrelogram.py → braindynamics_starprotocol-1.0.0/src/braindynamics_starprotocol/sca/crosscorrelogram.py +77 -37
  15. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/sca/sca_cy.c +590 -390
  16. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/sca/sca_cy.pyx +20 -10
  17. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol/trialbraindata.py +10 -10
  18. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0/src/braindynamics_starprotocol.egg-info}/PKG-INFO +19 -5
  19. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol.egg-info/SOURCES.txt +2 -2
  20. braindynamics_starprotocol-0.9.1/LICENSE +0 -674
  21. braindynamics_starprotocol-0.9.1/MANIFEST.in +0 -7
  22. braindynamics_starprotocol-0.9.1/README.md +0 -30
  23. braindynamics_starprotocol-0.9.1/src/braindynamics_starprotocol/sca/__init__.py +0 -1
  24. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/setup.cfg +0 -0
  25. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol.egg-info/dependency_links.txt +0 -0
  26. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol.egg-info/requires.txt +0 -0
  27. {braindynamics_starprotocol-0.9.1 → braindynamics_starprotocol-1.0.0}/src/braindynamics_starprotocol.egg-info/top_level.txt +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Levente Varga
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,7 @@
1
+ include src/braindynamics_starprotocol/sca/sca_cy.pyx
2
+
3
+ exclude .gitignore
4
+ recursive-exclude **/__pycache__ *
5
+ recursive-exclude docs/ *
6
+ recursive-exclude build/ *
7
+ recursive-exclude example/ *
@@ -1,8 +1,8 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: braindynamics_starprotocol
3
- Version: 0.9.1
3
+ Version: 1.0.0
4
4
  Summary: Functional brain network analysis protocol developed by Varga et al., 2024
5
- Author-email: bpentek <balazs.pentek@ubbcluj.ro>, vlewir <levente.varga@ubbcluj.ro>
5
+ Author-email: vlewir <levente.varga@ubbcluj.ro>, bpentek <balazs.pentek@ubbcluj.ro>
6
6
  Project-URL: Homepage, https://github.com/vlewir/BrainDynamics_STARProtocols
7
7
  Project-URL: Issues, https://github.com/vlewir/BrainDynamics_STARProtocols/issues
8
8
  Classifier: Programming Language :: Python :: 3
@@ -19,9 +19,17 @@ Requires-Dist: cliffs_delta>=1.0.0
19
19
 
20
20
  # BrainDynamics protocol
21
21
 
22
+ This protocol is based on our method: **Varga, L.** et al. Brain dynamics supported by a hierarchy of complex correlation patterns defining a robust functional architecture. *Cell Systems*, Volume **15**, Issue **8**, 770 - 786.e5 (2024). DOI: https://doi.org/10.1016/j.cels.2024.07.003
23
+
22
24
  ## Requirements
23
25
 
24
26
  - Python (tested for 3.12 and later versions)
27
+ - igraph (0.11.6 or later)
28
+ - pandas (2.2.2 or later)
29
+ - scipy (1.14.0 or later)
30
+ - matplotlib (3.9.2 or later)
31
+ - cliffs_delta (1.0.0 or later)
32
+
25
33
  - C/C++ compiler (e.g. gcc on Linux, Xcode Developer Tools for MacOS or Visual C++ Build Tools on Windows)
26
34
 
27
35
  ## Setting up
@@ -37,7 +45,7 @@ python -m venv braindynamics_env
37
45
  OR via Anaconda:
38
46
 
39
47
  ```
40
- conda create --name braindynamics_env python=3.x
48
+ conda create --name braindynamics_env python=3.12
41
49
  ```
42
50
 
43
51
  ### 2) Install package from PyPi
@@ -46,4 +54,10 @@ conda create --name braindynamics_env python=3.x
46
54
  pip install braindynamics-starprotocol
47
55
  ```
48
56
 
49
- Link to the TestPyPi project site for release history: https://pypi.org/project/braindynamics-starprotocol
57
+ ### 3) Usage
58
+
59
+ For an example of the pipeline, check `examples/pipeline_example.ipynb` notebook, or run the `.py` file with the same name.
60
+
61
+ For more details, you can also refer to the [documentation available on ReadTheDocs](https://braindynamics-starprotocols.readthedocs.io)
62
+
63
+ Link to the PyPi project site for release history: https://pypi.org/project/braindynamics-starprotocol
@@ -0,0 +1,44 @@
1
+ # BrainDynamics protocol
2
+
3
+ This protocol is based on our method: **Varga, L.** et al. Brain dynamics supported by a hierarchy of complex correlation patterns defining a robust functional architecture. *Cell Systems*, Volume **15**, Issue **8**, 770 - 786.e5 (2024). DOI: https://doi.org/10.1016/j.cels.2024.07.003
4
+
5
+ ## Requirements
6
+
7
+ - Python (tested for 3.12 and later versions)
8
+ - igraph (0.11.6 or later)
9
+ - pandas (2.2.2 or later)
10
+ - scipy (1.14.0 or later)
11
+ - matplotlib (3.9.2 or later)
12
+ - cliffs_delta (1.0.0 or later)
13
+
14
+ - C/C++ compiler (e.g. gcc on Linux, Xcode Developer Tools for MacOS or Visual C++ Build Tools on Windows)
15
+
16
+ ## Setting up
17
+
18
+ ### 1) Set up virtual python environment using python or conda.
19
+
20
+ For example:
21
+
22
+ ```
23
+ python -m venv braindynamics_env
24
+ ```
25
+
26
+ OR via Anaconda:
27
+
28
+ ```
29
+ conda create --name braindynamics_env python=3.12
30
+ ```
31
+
32
+ ### 2) Install package from PyPi
33
+
34
+ ```
35
+ pip install braindynamics-starprotocol
36
+ ```
37
+
38
+ ### 3) Usage
39
+
40
+ For an example of the pipeline, check `examples/pipeline_example.ipynb` notebook, or run the `.py` file with the same name.
41
+
42
+ For more details, you can also refer to the [documentation available on ReadTheDocs](https://braindynamics-starprotocols.readthedocs.io)
43
+
44
+ Link to the PyPi project site for release history: https://pypi.org/project/braindynamics-starprotocol
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "braindynamics_starprotocol"
7
- version = "0.9.1"
7
+ version = "1.0.0"
8
8
  authors = [
9
- { name="bpentek", email="balazs.pentek@ubbcluj.ro" },
10
9
  { name="vlewir", email="levente.varga@ubbcluj.ro"},
10
+ { name="bpentek", email="balazs.pentek@ubbcluj.ro" },
11
11
  ]
12
12
  description = "Functional brain network analysis protocol developed by Varga et al., 2024"
13
13
  readme = "README.md"
@@ -27,4 +27,4 @@ classifiers = [
27
27
 
28
28
  [project.urls]
29
29
  Homepage = "https://github.com/vlewir/BrainDynamics_STARProtocols"
30
- Issues = "https://github.com/vlewir/BrainDynamics_STARProtocols/issues"
30
+ Issues = "https://github.com/vlewir/BrainDynamics_STARProtocols/issues"
@@ -8,7 +8,12 @@ extensions = [ Extension( name="sca.sca_cy",
8
8
  include_dirs=[np.get_include()]) ]
9
9
 
10
10
  setup( name="braindynamics_starprotocol",
11
- version="0.9.1",
11
+ version="1.0.0",
12
12
  ext_modules=cythonize(extensions),
13
13
  include_dirs=[np.get_include()],
14
- )
14
+ options={
15
+ 'bdist_wheel': {
16
+ 'universal':True,
17
+ },
18
+ },
19
+ )
@@ -1,3 +1,3 @@
1
1
  from .trialbraindata import TrialBrainData
2
2
  from .sca import *
3
- from .network import *
3
+ from .network import *
@@ -1,4 +1,4 @@
1
1
  from .networkdata import NetworkData
2
2
  from .sort import sort_distribution
3
3
  from .plot import plot_distribution, plot_Cliffs_delta
4
- from .compare import compare_ews_Cliffs_delta, compare_nds_Cliffs_delta, compare_news_Cliffs_delta
4
+ from .compare import compare_ews_Cliffs_delta, compare_nds_Cliffs_delta, compare_news_Cliffs_delta
@@ -2,7 +2,7 @@ import numpy as np
2
2
  from cliffs_delta import cliffs_delta
3
3
 
4
4
  def compare_ews_Cliffs_delta(A:np.ndarray, B:np.ndarray)->tuple:
5
- """ Function that computes Cliff's delta metric for two sets of edge weights (EWD samples). Because the EWD is a bimodal distribution, we calculate separately for the negative and for the positive parts of the distribution.
5
+ """Function that computes Cliff's delta metric for two sets of edge weights (EWD samples). Because the EWD is a bimodal distribution, we calculate separately for the negative and for the positive parts of the distribution.
6
6
 
7
7
  Args:
8
8
  A (np.ndarray): First array of edge weights with shape: <number of edges>, <number of trials>
@@ -75,7 +75,7 @@ def compare_nds_Cliffs_delta(A:np.ndarray, B:np.ndarray)->np.ndarray:
75
75
  return deltas
76
76
 
77
77
  def compare_news_Cliffs_delta(A:np.ndarray, B:np.ndarray)->tuple:
78
- """ Function that computes Cliff's delta metric for two sets of node edge weights (N-EWD values). Because the N-EWD is a bimodal distribution, we calculate separately for the negative and for the positive parts of the distribution.
78
+ """Function that computes Cliff's delta metric for two sets of node edge weights (N-EWD values). Because the N-EWD is a bimodal distribution, we calculate separately for the negative and for the positive parts of the distribution.
79
79
 
80
80
  Args:
81
81
  A (np.ndarray): First array of node distances with shape: <number of nodes>, (<number of nodes> - 1)*<total number of trials 1>.
@@ -117,4 +117,4 @@ def compare_news_Cliffs_delta(A:np.ndarray, B:np.ndarray)->tuple:
117
117
  deltas_p = np.asarray(deltas_p)
118
118
  deltas_n = np.asarray(deltas_n)
119
119
 
120
- return deltas_n, deltas_p
120
+ return deltas_n, deltas_p
@@ -1,11 +1,19 @@
1
1
  import numpy as np
2
2
  import os
3
- from ..sca.scaledcrosscorrelogram import ScaledCrossCorrelogram
3
+ from ..sca.crosscorrelogram import CrossCorrelogram
4
4
  import igraph as ig
5
5
 
6
6
 
7
7
  class NetworkData:
8
- """ Datatype used to store functional brain networks (edgelists) extracted from brain activity recordings for multiple experimental trials.
8
+ """
9
+
10
+ Attributes:
11
+ trial_nr (int): Number of experimental trials (2D time series) from which networks will be extracted.
12
+ edge_nr (int): Number of edges in the functional brain network.
13
+ edgelist_arr (np.ndarray): Array of edge lists (in format <source> <target> <weight>) for each trial.
14
+ laglist_arr (np.ndarray): Array of lag lists (in format <source> <target> <lag>) for each trial.
15
+ node_nr (int): Number of nodes in the functional brain network.
16
+ info_dict (dict): Dictionary storing metadata (e.g. node labels).
9
17
  """
10
18
  def __init__(self):
11
19
  self.trial_nr = 0 # total number of trials
@@ -16,7 +24,7 @@ class NetworkData:
16
24
  self.info_dict = {} # dictionary for other information (meta-data)
17
25
 
18
26
  def clear(self):
19
- """ Function that clears NetworkData object.
27
+ """Function that clears NetworkData object.
20
28
  """
21
29
  self.trial_nr = 0
22
30
  self.edge_nr = 0
@@ -26,7 +34,7 @@ class NetworkData:
26
34
  self.info_dict.clear()
27
35
 
28
36
  def load_from_filelist(self, filelist_path:str, load_lags:bool=False)->None:
29
- """ Function that loads edgelists from filelist.
37
+ """Function that loads edgelists from filelist.
30
38
 
31
39
  Args:
32
40
  filelist_path (str): Path to filelist (enumeration of edge list files)
@@ -60,7 +68,7 @@ class NetworkData:
60
68
  self.laglist_arr[i] = laglist
61
69
 
62
70
  def write_to_filelist(self, filelist_path:str, save_lags:bool=False)->None:
63
- """ Function that exports edgelists into separate files and generates the filelist.
71
+ """Function that exports edgelists into separate files and generates the filelist.
64
72
 
65
73
  Args:
66
74
  filelist_path (str): path to filelist
@@ -82,13 +90,14 @@ class NetworkData:
82
90
  file.write(f"{source} {target} {weight}\n")
83
91
  np.savetxt(filelist_path, filelist, fmt="%s")
84
92
 
85
- def extract(self, samp_mat_list:list, corrgram:ScaledCrossCorrelogram, use_fisher:bool=True, sca_method:str="C", export_to_filelists:tuple=None)->None:
86
- """ Function that extracts functional brain networks from experimental trial samples. Functional connectivity (edge weights) is defined as scaled correlation developed by Nikolic et al.
93
+ def extract(self, samp_mat_list:list, corrgram:CrossCorrelogram, use_fisher:bool=True, cc_method:str="C", export_to_filelists:tuple=None)->None:
94
+ """Function that extracts functional brain networks from experimental trial samples. Functional connectivity (edge weights) is defined as cross-correlation (either classical Pearson or SCA developed by Nikolic et al)
87
95
 
88
96
  Args:
89
97
  samp_mat_list (list): list of trial sample matrices of shape (number of trials, number of channels/nodes, length of a trial)
90
- corrgram (ScaledCrossCorrelogram): scaled cross-correlogram object with pre-defined parameters
98
+ corrgram (CrossCorrelogram): cross-correlogram object with pre-defined parameters
91
99
  use_fisher (bool, optional): use Fisher transform or not in scaled correlation computation (see Nikolic et al. 2012). Defaults to True.
100
+ cc_method (str, optional): choose implementation (python or cython). Defaults to C.
92
101
  """
93
102
  self.clear()
94
103
  self.trial_nr = len(samp_mat_list)
@@ -101,7 +110,7 @@ class NetworkData:
101
110
  e = 0
102
111
  for i in range(self.node_nr):
103
112
  for j in range(i + 1, self.node_nr): # NOTE: scaled correlation is symmetric
104
- corrgram.compute(samp_mat_list[t][i], samp_mat_list[t][j], use_fisher=use_fisher, sca_method=sca_method)
113
+ corrgram.compute(samp_mat_list[t][i], samp_mat_list[t][j], use_fisher=use_fisher, cc_method=cc_method)
105
114
  lag, maxabs = corrgram.get_maxabs()
106
115
  self.edgelist_arr[t][e] = [i, j, maxabs]
107
116
  self.laglist_arr[t][e] = [i, j, lag]
@@ -120,7 +129,7 @@ class NetworkData:
120
129
  with open(os.path.join(lag_filelist_root, f"edge_list-{t + 1}.txt"), "w") as lag_file:
121
130
  for i in range(self.node_nr):
122
131
  for j in range(i + 1, self.node_nr): # NOTE: scaled correlation is symmetric
123
- corrgram.compute(samp_mat_list[t][i], samp_mat_list[t][j], use_fisher=use_fisher, sca_method=sca_method)
132
+ corrgram.compute(samp_mat_list[t][i], samp_mat_list[t][j], use_fisher=use_fisher, cc_method=cc_method)
124
133
  lag, maxabs = corrgram.get_maxabs()
125
134
  self.edgelist_arr[t][e] = [i, j, maxabs]
126
135
  self.laglist_arr[t][e] = [i, j, lag]
@@ -133,7 +142,7 @@ class NetworkData:
133
142
  np.savetxt(lag_filelist_path, filelist, fmt="%s")
134
143
 
135
144
  def get_maxabs_weights(self)->float:
136
- """ Function that finds the maximum absolute edge weight across the trials. It can be used to normalize all edge weights.
145
+ """Function that finds the maximum absolute edge weight across the trials. It can be used to normalize all edge weights.
137
146
 
138
147
  Returns:
139
148
  float: value of maximum absolute edge weight (if it's above 1.0, return 1.0 instead)
@@ -144,7 +153,7 @@ class NetworkData:
144
153
  return global_max
145
154
 
146
155
  def get_minmax_distances(self, norm_factor:float=1.0)->tuple:
147
- """ Function that finds the minimum and maximum distance (shortest path length between nodes).
156
+ """Function that finds the minimum and maximum distance (shortest path length between nodes).
148
157
 
149
158
  Args:
150
159
  norm_factor (float, optional): normalizion factor for edge weights (useful when there's a correlation value above 1.0 due to numerical error/interpolation in SCA). Defaults to 1.0.
@@ -173,7 +182,7 @@ class NetworkData:
173
182
  return global_min, global_max
174
183
 
175
184
  def compute_ewd(self, bin_nr:int=30, ewd_vmin:float=-1.0, ewd_vmax:float=1.0)->np.ndarray:
176
- """ Function that computes edge weight distributions from multiple trials, accordingly to Varga et al 2024.
185
+ """Function that computes edge weight distributions from multiple trials, accordingly to Varga et al 2024.
177
186
 
178
187
  Args:
179
188
  bin_nr (int, optional): number of bins for the distribution. Defaults to 30.
@@ -194,7 +203,7 @@ class NetworkData:
194
203
  return ewd
195
204
 
196
205
  def compute_ndd(self, bin_nr:int=30, ndd_vmin:float=None, ndd_vmax:float=None, norm_factor:float=1.0)->np.ndarray:
197
- """ Function that computes the node distance distribution accordingly to Varga et al. 2024
206
+ """Function that computes the node distance distribution accordingly to Varga et al. 2024
198
207
 
199
208
  Args:
200
209
  bin_nr (int, optional): _number of bins for the distribution. Defaults to 30.
@@ -231,7 +240,7 @@ class NetworkData:
231
240
  return ndd
232
241
 
233
242
  def compute_newd(self, bin_nr:int=30, newd_vmin:float=-1.0, newd_vmax:float=1.0)->np.ndarray:
234
- """ Function that computes the node edge weight distribution (aggregated EWD for the nodes), accordingly to Varga et al. 2024
243
+ """Function that computes the node edge weight distribution (aggregated EWD for the nodes), accordingly to Varga et al. 2024
235
244
 
236
245
  Args:
237
246
  bin_nr (int, optional): number of bins for the distribution. Defaults to 30.
@@ -272,7 +281,7 @@ class NetworkData:
272
281
  return newd
273
282
 
274
283
  def compute_ew_for_Cliffs_delta(self)->np.ndarray:
275
- """ Function that prepares the edge weights for Cliff's delta computation, accordingly to Varga et al. 2024
284
+ """Function that prepares the edge weights for Cliff's delta computation, accordingly to Varga et al. 2024
276
285
 
277
286
  Returns:
278
287
  np.ndarray: array of shape (number of edges, number of trials) representing the edge weights for all trials
@@ -289,7 +298,7 @@ class NetworkData:
289
298
 
290
299
 
291
300
  def compute_nd_for_Cliffs_delta(self, norm_factor:float=1.0)->np.ndarray:
292
- """ Function that computes the node distances for Cliff's delta accordingly to Varga et al. 2024
301
+ """Function that computes the node distances for Cliff's delta accordingly to Varga et al. 2024
293
302
 
294
303
  Args:
295
304
  norm_factor (float, optional): normalizion factor for edge weights (useful when there's a correlation value above 1.0 due to numerical error/interpolation in SCA). Defaults to 1.0.
@@ -317,7 +326,7 @@ class NetworkData:
317
326
  return ndd_Cliffs
318
327
 
319
328
  def compute_new_for_Cliffs_delta(self)->np.ndarray:
320
- """ Function that computes the node edge weights for Cliff's delta (aggregated EWD for the nodes), accordingly to Varga et al. 2024
329
+ """Function that computes the node edge weights for Cliff's delta (aggregated EWD for the nodes), accordingly to Varga et al. 2024
321
330
 
322
331
  Args:
323
332
  -
@@ -348,4 +357,4 @@ class NetworkData:
348
357
  else:
349
358
  newd_Cliffs = np.append(newd_Cliffs, res, 1)
350
359
 
351
- return newd_Cliffs
360
+ return newd_Cliffs
@@ -4,7 +4,7 @@ from matplotlib import cm
4
4
  import matplotlib
5
5
 
6
6
  def plot_distribution(data:np.ndarray, sorting:np.ndarray=None, fig:matplotlib.figure.Figure=None, ax:matplotlib.axes._axes.Axes=None, cmap:matplotlib.colors.LinearSegmentedColormap=cm.coolwarm, cmin:float=None, cmax:float=None, clabel:str="", show_cbar:bool=False, xlabel:str=None, ylabel:str=None, title:str=None, vmin:float=None, vmax:float=None, yticks:np.ndarray=None, mirror_yticks:bool=False)->None:
7
- """ Function that plots a heatmap based on a 2D array. It can be used to visualize distributions (EWD, NDD, N-EWD) or to plot the results of their comparison (Cliff's delta values).
7
+ """Function that plots a heatmap based on a 2D array. It can be used to visualize distributions (EWD, NDD, N-EWD) or to plot the results of their comparison (Cliff's delta values).
8
8
 
9
9
  Args:
10
10
  data (np.ndarray): Array of 2D.
@@ -72,7 +72,7 @@ def plot_distribution(data:np.ndarray, sorting:np.ndarray=None, fig:matplotlib.f
72
72
  cbar.set_label(clabel)
73
73
 
74
74
  def plot_Cliffs_delta(deltas:np.ndarray, sorting:np.ndarray=None, fig:matplotlib.figure.Figure=None, axes:list[matplotlib.axes._axes.Axes]=None, clabel:str="", show_cbar:bool=False, titles:list[str]=None)->None:
75
- """ Plot Cliff's delta statistic resulting from the comparison of two 2D distributions. Two separate axes are plotted, one with the delta values and the other showing the absolute thresholds representing significance based on Vargha et al. 2000
75
+ """Plot Cliff's delta statistic resulting from the comparison of two 2D distributions. Two separate axes are plotted, one with the delta values and the other showing the absolute thresholds representing significance based on Vargha et al. 2000
76
76
 
77
77
  Args:
78
78
  deltas (np.ndarray): Array of Cliff deltas
@@ -2,13 +2,13 @@ import numpy as np
2
2
  import operator
3
3
 
4
4
  def sort_distribution(data:np.ndarray)->tuple:
5
- """ Function that performs extensive sort (sorting rows based on column values) of 2D data.
5
+ """Function that performs extensive sort (sorting rows based on column values) of 2D data.
6
6
 
7
7
  Args:
8
- data (np.ndarray): input 2D array
8
+ data (np.ndarray): Input 2D array of shape: <nr_elements>, <nr_bins>.
9
9
 
10
10
  Returns:
11
- tuple: two arrays of sorted indices of rows from first-to-last and last-to first columns
11
+ tuple: Two arrays of sorted indices of rows from first-to-last and last-to first columns.
12
12
  """
13
13
 
14
14
  data_len, bin_nr = data.shape
@@ -0,0 +1 @@
1
+ from .crosscorrelogram import CrossCorrelogram
@@ -2,9 +2,9 @@ import os
2
2
  import numpy as np
3
3
  from scipy.stats import pearsonr
4
4
  try:
5
- from .sca_cy import scaled_cross_correlation, find_extremas
5
+ from .sca_cy import cross_correlation, find_extremas
6
6
  except ModuleNotFoundError:
7
- from sca.sca_cy import scaled_cross_correlation, find_extremas
7
+ from sca.sca_cy import cross_correlation, find_extremas
8
8
  import matplotlib.pyplot as plt
9
9
  from scipy.interpolate import Akima1DInterpolator
10
10
  from scipy.optimize import fmin
@@ -15,26 +15,42 @@ def _fisher_transform(r:float, norm_factor:float=1.12)->float:
15
15
  def _inverse_fisher_transform(z:float, norm_factor:float=1.12)->float:
16
16
  return norm_factor*(exp(2*z) - 1)/(exp(2*z) + 1)
17
17
 
18
- class ScaledCrossCorrelogram():
19
-
20
- def __init__(self, scale_size : int, max_shift_size : int):
21
- self.scale_size = scale_size # SCA scale size
18
+ def _pearson_correlation(self, x:np.ndarray, y:np.ndarray)->float:
19
+ return pearsonr(x, y)[0]
20
+
21
+ class CrossCorrelogram():
22
+ """
23
+ Cross-correlogram object, can be either classical Pearson, or SCA.
24
+
25
+ Attributes:
26
+ max_shift_size (int): Maximum shift (time lag) of time series for which correlation will be computed.
27
+ scale_size (int, optional): Scale size parameter of SCA (length of the average short term window of correlation). Defaults to None.
28
+ corr_coeff_arr (np.ndarray): Array of correlogram values (correlation coefficients) for each shift (time lag).
29
+ _interpolator: Interpolator object used to smoothen correlogram.
30
+ _maxabs_shift (int): Shift (time lag) value of the correlogram's MaxAbs (absolute peak).
31
+ _maxabs_value (float): Correlogram value of MaxAbs (absolute peak).
32
+ _maxabs_is_min (bool): Whether or not MaxAbs (absolute peak) is a minimum or maximum of the correlogram.
33
+ """
34
+ def __init__(self, max_shift_size:int, scale_size:int=None):
22
35
  self.max_shift_size = max_shift_size # size of maximal shift of cross-correlation
36
+ self.scale_size = scale_size # scale parameter of SCA (if None, classical CC will be computed)
23
37
  self.corr_coeff_arr = np.zeros(2*max_shift_size + 1, dtype=np.float32) # array storing values of the correlogram
24
38
  self._interpolator = None # interpolator object
25
39
  self._maxabs_shift, self._maxabs_value = -max_shift_size-1, -max_shift_size-1 # maxabs shift & value
26
40
  self._maxabs_is_min = None # whether or not maxabs is a minimum or a maximum of the correlogram
27
41
 
28
42
  def clear(self)->None:
29
- """ Clear scaled cross-correlogram object.
43
+ """
44
+ Clear the correlogram object.
30
45
  """
31
46
  self.corr_coeff_arr = np.zeros(2*self.max_shift_size + 1, dtype=np.float32)
32
47
  self._interpolator = None
33
48
  self._maxabs_shift, self._maxabs_value = -self.max_shift_size-1, -self.max_shift_size-1
34
49
 
35
50
  def _scaled_correlation(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=False)->float:
36
- """ Compute scaled correlation between two array of samples.
37
-
51
+ """
52
+ 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).
53
+
38
54
  Args:
39
55
  x (np.ndarray): First array of samples
40
56
  y (np.ndarray): Second array
@@ -51,19 +67,20 @@ class ScaledCrossCorrelogram():
51
67
  if not use_fisher:
52
68
  r_s = 0.0 # scaled correlation
53
69
  for i in range(K):
54
- r_s += pearsonr(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s])[0] # NOTE: we don't need the p-value
70
+ r_s += _pearson_correlation(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s])
55
71
  r_s /= K
56
72
  else:
57
73
  z = 0.0 # Fisher transform of scaled correlation
58
74
  for i in range(K):
59
- z += _fisher_transform(pearsonr(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s])[0])
75
+ z += _fisher_transform(_pearson_correlation(x[i*s:(i + 1)*s], y[i*s:(i + 1)*s]))
60
76
  z /= K
61
77
  r_s = _inverse_fisher_transform(z)
62
78
 
63
79
  return r_s
64
80
 
65
81
  def _compute_py(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True)->None:
66
- """ Compute SCA using pure python implementation (slow).
82
+ """
83
+ Compute CC using pure python implementation (slow).
67
84
 
68
85
  Args:
69
86
  x (np.ndarray): first array of data points
@@ -74,17 +91,28 @@ class ScaledCrossCorrelogram():
74
91
 
75
92
  n_x = len(x)
76
93
  n_y = len(y)
77
- # shifting x to the left, relative to y
78
- for shift in range(-self.max_shift_size, 0):
79
- self.corr_coeff_arr[shift + self.max_shift_size] = self._scaled_correlation(x[abs(shift):], y[:n_y - abs(shift)])
80
- # zero shift
81
- self.corr_coeff_arr[self.max_shift_size] = self._scaled_correlation(x, y)
82
- # shifting x to the right, relative to y
83
- for shift in range(1, self.max_shift_size + 1):
84
- self.corr_coeff_arr[shift + self.max_shift_size] = self._scaled_correlation(x[:n_x - shift], y[shift:])
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:])
85
112
 
86
113
  def _compute_cy(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True)->None:
87
- """ Compute SCA using cython implementation (recommended).
114
+ """
115
+ Compute CC using cython implementation (recommended).
88
116
 
89
117
  Args:
90
118
  x (np.ndarray): first array of data points
@@ -92,16 +120,20 @@ class ScaledCrossCorrelogram():
92
120
  use_fisher (bool, optional): Whether or not use Fisher transformation during SCA. Defaults to True.
93
121
  """
94
122
  self.corr_coeff_arr = np.zeros(2*self.max_shift_size + 1, dtype=np.float32)
95
- scaled_cross_correlation(self.corr_coeff_arr, x, y, self.scale_size, self.max_shift_size, use_fisher)
123
+ if self.scale_size is not None:
124
+ cross_correlation(self.corr_coeff_arr, x, y, self.max_shift_size, self.scale_size, use_fisher)
125
+ else:
126
+ cross_correlation(self.corr_coeff_arr, x, y, self.max_shift_size, -1, use_fisher)
96
127
 
97
- def compute(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True, sca_method:str="C")->None:
98
- """ Compute SCA using one of the implementations (cython or python).
128
+ def compute(self, x:np.ndarray, y:np.ndarray, use_fisher:bool=True, cc_method:str="C")->None:
129
+ """
130
+ Compute CC using one of the implementations (cython or python).
99
131
 
100
132
  Args:
101
133
  x (np.ndarray): first array of data points
102
134
  y (np.ndarray): second array of data points
103
135
  use_fisher (bool, optional): Whether or not use Fisher transformation during SCA. Defaults to True.
104
- sca_method (str, optional): Which implementation to use for the computation. Defaults to "C".
136
+ cc_method (str, optional): Which implementation to use for the computation. Defaults to "C".
105
137
 
106
138
  Raises:
107
139
  ValueError: Input arrays are of uneven length
@@ -112,20 +144,21 @@ class ScaledCrossCorrelogram():
112
144
  if len(x) != len(y):
113
145
  raise ValueError(f"Dimension mismatch between x ({len(x)}) and y ({len(y)})")
114
146
 
115
- if len(x) < self.scale_size + self.max_shift_size:
116
- raise ValueError(f"Length of correlation window at max shift ({len(x)} - {self.max_shift_size} = {len(x) - self.max_shift_size}) must be greater or equal than the scale/segment size ({self.scale_size})")
147
+ if self.scale_size is not None and len(x) < self.scale_size + self.max_shift_size:
148
+ raise ValueError(f"SCA: Length of correlation window at max shift ({len(x)} - {self.max_shift_size} = {len(x) - self.max_shift_size}) must be greater or equal than the scale/segment size ({self.scale_size})")
117
149
 
118
150
  x = x.astype(np.float32) # cython code expects float32
119
151
  y = y.astype(np.float32)
120
- if sca_method == "C":
152
+ if cc_method == "C":
121
153
  self._compute_cy(x, y, use_fisher=use_fisher)
122
- elif sca_method == "py":
154
+ elif cc_method == "py":
123
155
  self._compute_py(x, y, use_fisher=use_fisher)
124
156
  else:
125
- raise ValueError("Only two options are supported for `sca_method` parameter: 'py' for pure python implementation, 'C' for cython (recommended)")
157
+ raise ValueError("Only two options are supported for `cc_method` parameter: 'py' for pure python implementation, 'C' for cython (recommended)")
126
158
 
127
159
  def _find_extremas(self)->np.ndarray:
128
- """ Find extremas of the correlogram
160
+ """
161
+ Find extremas of the correlogram
129
162
 
130
163
  Returns:
131
164
  np.ndarray: array of 1 or 0 representing whether the given point of the correlogram is an extrema or not
@@ -135,7 +168,8 @@ class ScaledCrossCorrelogram():
135
168
  return extremas
136
169
 
137
170
  def _interpolate(self, shifts:np.ndarray, values:np.ndarray):
138
- """ Wrapper function for the interpolator object.
171
+ """
172
+ Wrapper function for the interpolator object.
139
173
 
140
174
  Args:
141
175
  shifts (np.ndarray): Time shifts (x axis of the correlogram)
@@ -144,16 +178,21 @@ class ScaledCrossCorrelogram():
144
178
  self._interpolator = Akima1DInterpolator(shifts, values)
145
179
 
146
180
  def get_maxabs(self)->tuple:
147
- """ Function that determines & saves MaxAbs of the interpolated correlogram.
181
+ """
182
+ Function that determines & saves MaxAbs (absolute peak) of the interpolated correlogram.
148
183
 
149
184
  Raises:
150
185
  ValueError: Correlogram is not computed.
151
186
 
152
187
  Returns:
153
- tuple: MaxAbs shift, value
188
+ tuple: MaxAbs shift, correlation value
154
189
  """
155
190
  if (self.corr_coeff_arr == 0.0).all():
156
- raise ValueError("")
191
+ raise ValueError("Correlogram not computed.")
192
+
193
+ if self.max_shift_size == 0: # if no shift was specified, return the only value as MaxAbs
194
+ return self.max_shift_size, self.corr_coeff_arr[0]
195
+
157
196
  # finding maxabs on correlogram
158
197
  is_extrema = (self._find_extremas() == 1)
159
198
  argmax_idx = np.argmax(np.abs(self.corr_coeff_arr[is_extrema]))
@@ -179,7 +218,8 @@ class ScaledCrossCorrelogram():
179
218
  return self._maxabs_shift, self._maxabs_value
180
219
 
181
220
  def plot(self, show_interp:bool=False, show_maxabs:bool=False, interp_shift_res:float=0.1):
182
- """ Plot correlogram.
221
+ """
222
+ Plot correlogram.
183
223
 
184
224
  Args:
185
225
  show_interp (bool, optional): Show interpolated version. Defaults to False.
@@ -200,7 +240,7 @@ class ScaledCrossCorrelogram():
200
240
  plt.plot(hires_shifts, -self._interpolator(hires_shifts), color="tab:blue", label="SmoothCC")
201
241
  if show_maxabs:
202
242
  if self._maxabs_shift == -self.max_shift_size-1 or self._maxabs_value == -self.max_shift_size-1:
203
- raise Warning("Cannot plot maxabs, as it wasn't computed. Calculate it with ScaledCrossCorrelogram.get_maxabs() method")
243
+ raise Warning("Cannot plot maxabs, as it wasn't computed. Calculate it with CrossCorrelogram.get_maxabs() method")
204
244
  plt.scatter([self._maxabs_shift], [self._maxabs_value], color="tab:red", alpha=0.6, s=100, label="MaxAbsVal")
205
245
  plt.xlabel("shifts [S.U.]")
206
246
  plt.grid()