-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
130 lines (97 loc) · 2.89 KB
/
functions.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
# -*- coding: utf-8 -*-
import scipy.linalg as linalg
import scipy.io as io
import numpy as np
from glob import glob
import re
# -----------------------------------------------------------------------------
# The following is to sort files in numerical order
numbers = re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
# -----------------------------------------------------------------------------
def matlab_to_python(file):
"""
Convert MATLAB arrays into Python arrays.
The original dataset is composed of BOLD fMRI time series as MATLAB
arrays, that is, files with the .m extension. This function is thus
necessary for the Pythonic analysis of the time series.
Parameters
----------
file : MATLAB array
Files with .m extension.
Returns
-------
py_arr : ndarray
The converted MATLAB array.
"""
m_arr = io.loadmat(file)['X_3']
n = len(m_arr)
py_arr = m_arr.reshape(1, n)[0]
return py_arr
def array_of_time_series(PATH):
"""
Amalgamate the time series in a given folder (of a subject in a
particular condition, "before" or "after"). Returns an array
containing a set of vectors of observations (time series).
Again, since this analysis requires Python arrays, we invoke the
function matlab_to_python to convert MATLAB arrays into Python
ones.
Parameters
----------
PATH: str
The path to the dataset.
Returns
-------
X : ndarray
A 1-D containing multiple variables.
"""
X = np.array(
[
matlab_to_python(file) for file in sorted(
glob(PATH, recursive=True),
key=numericalSort
)
]
)
return X
def density_matrix(X):
"""
Calculate the density matrix from a set of vectors.
Parameters
----------
X : array_like
A 1-D or 2-D array containing multiple variables.
Returns
-------
A : ndarray
The scaled correlation matrix (density matrix) of X.
"""
N = len(X)
R = np.corrcoef(X)
A = R / N
return A
def von_neumann_entropy(A, norm=False):
"""
Calculate the von Neumann entropy of a density matrix.
Parameters
----------
A : array_like
Density matrix whose von Neumann entropy to evaluate.
norm : bool, optional
Evaluates the normalized von Neumann entropy of A. (Default: False)
Returns
-------
S : ndarray
The von Neumann entropy of A.
"""
logA = linalg.logm(A)
AlogA = np.matmul(A, logA)
N = len(A)
S = -np.trace(AlogA)
if norm == True:
return S / np.log(N)
else:
return S