Skip to content

Commit 8bfea7f

Browse files
first
0 parents  commit 8bfea7f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+3830
-0
lines changed

.idea/inspectionProfiles/profiles_settings.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/modules.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/workspace.xml

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

LICENSE

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2018 The Python Packaging Authority
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
SOFTWARE.

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Example Package
2+
3+
This is a simple example package. You can use
4+
[Github-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
5+
to write your content.

examples/example_decay_conv.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# import standard libraries
2+
import os, sys
3+
import numpy as np
4+
import matplotlib.pyplot as plt
5+
6+
# import mesostat
7+
from mesostat.utils.signals import approx_decay_conv
8+
9+
# Create signal
10+
DT = 0.001 # s
11+
TAU = 0.1 # s
12+
t = np.arange(0, 10, DT)
13+
y = (np.sin(1 * t)**2 > 0.7).astype(float)
14+
15+
yc = approx_decay_conv(y, TAU, DT)
16+
17+
plt.figure()
18+
plt.plot(t, y)
19+
plt.plot(t, yc)
20+
plt.show()

examples/example_decorator_lib.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from mesostat.utils.decorators import time_mem_1starg
2+
3+
@time_mem_1starg
4+
def myfunc(x):
5+
return x**2
6+
7+
print(myfunc(10))

examples/example_downsample.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
'''
2+
VERY IMPORTANT:
3+
DO NOT USE SAME PROCEDURE FOR UPSAMPLING AND DOWNSAMPLING
4+
5+
* When we upsample, we want to interpolate data
6+
* When we downsample, we want to sample the trendline, not individual fluctuations
7+
8+
[] Maybe impl FFT-based resampling, that joins both
9+
'''
10+
11+
# import standard libraries
12+
import os, sys
13+
import numpy as np
14+
import matplotlib.pyplot as plt
15+
16+
# import special libraries
17+
from mesostat.utils.signals import resample
18+
19+
##########################
20+
# Downsampling
21+
##########################
22+
23+
# Create data
24+
T = 10 # s
25+
DT = 0.001 # s
26+
t1 = np.arange(0, T, DT)
27+
y1 = np.random.normal(0, 1, t1.size)
28+
for i in range(1, t1.size):
29+
y1[i] += y1[i-1]
30+
31+
# Resample
32+
DT2 = 0.1 # s
33+
t2 = np.arange(0, t1[-1], DT2)
34+
y2 = resample(t1, y1, t2, {"method" : "smooth", "kind" : "window"})
35+
y3 = resample(t1, y1, t2, {"method" : "smooth", "kind" : "kernel", "ker_sig2" : DT2**2})
36+
y4 = resample(t1, y1, t2, {"method" : "smooth", "kind" : "kernel", "ker_sig2" : (DT2/2)**2})
37+
y5 = resample(t1, y1, t2, {"method" : "smooth", "kind" : "kernel", "ker_sig2" : (DT2/4)**2})
38+
39+
# Plot
40+
plt.figure()
41+
plt.title('Downsampling using window and kernel estimators')
42+
plt.plot(t1, y1, '.-', label='orig')
43+
plt.plot(t2, y2, '.-', label='window')
44+
plt.plot(t2, y3, '.-', label="ker, s2=d2^2")
45+
plt.plot(t2, y4, '.-', label="ker, s2=(d2/2)^2")
46+
plt.plot(t2, y5, '.-', label="ker, s2=(d2/4)^2")
47+
plt.legend()
48+
49+
##########################
50+
# Upsampling
51+
##########################
52+
53+
# Create Data
54+
T = 10 # s
55+
DT = 0.1 # s
56+
t1 = np.arange(0, T, DT)
57+
y1 = np.sin(10*t1) * np.sin(2*t1)
58+
59+
# Resample
60+
DT2 = 0.01 # s
61+
t2 = np.arange(0, t1[-1], DT2)
62+
y2 = resample(t1, y1, t2, {"method" : "interpolative", "kind" : "linear"})
63+
y3 = resample(t1, y1, t2, {"method" : "interpolative", "kind" : "quadratic"})
64+
y4 = resample(t1, y1, t2, {"method" : "interpolative", "kind" : "cubic"})
65+
66+
# Plot
67+
plt.figure()
68+
plt.title('Upsampling using interpolation')
69+
plt.plot(t1, y1, 'o', label='orig')
70+
plt.plot(t2, y2, '.-', label='linear')
71+
plt.plot(t2, y3, '.-', label="quadratic")
72+
plt.plot(t2, y4, '.-', label="cubic")
73+
plt.legend()
74+
75+
plt.show()

examples/example_map_memory_use.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import sys
2+
import numpy as np
3+
4+
from mesostat.utils.system import mem_now_as_str, bytes2str
5+
6+
def heavyFunc(i):
7+
x = np.random.normal(0,1, 10**8)
8+
print(i, mem_now_as_str(), bytes2str(sys.getsizeof(x)))
9+
return i
10+
11+
12+
print(list(map(heavyFunc, np.arange(10))))

examples/example_stat.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
import mesostat.stat.stat as stat
5+
6+
plt.ion()
7+
8+
############################
9+
# Random bool permutation
10+
############################
11+
N_TEST1 = 1000
12+
nTot = 100
13+
freqArr = np.zeros(nTot)
14+
nTrueArr = np.random.randint(0, 100, N_TEST1)
15+
16+
for nTrue in zip(nTrueArr):
17+
perm = stat.rand_bool_perm(nTrue, nTot).astype(int)
18+
assert np.sum(perm) == nTrue
19+
freqArr += perm
20+
21+
plt.figure()
22+
plt.title("Testing array permutation for bias")
23+
plt.xlabel("array element")
24+
plt.ylabel("number of occurences")
25+
plt.plot(freqArr, '.')
26+
plt.show()
27+
28+
############################
29+
# Discrete PDF and CDF
30+
############################
31+
N_VAL_TEST2 = 20
32+
keys = np.random.randint(0, 1000, N_VAL_TEST2)
33+
vals = np.random.uniform(0, 1, N_VAL_TEST2)
34+
vals /= np.sum(vals)
35+
36+
pdf = dict(zip(keys, vals))
37+
cdf = stat.discrete_distr_to_cdf(pdf)
38+
39+
plt.figure()
40+
plt.title("Discrete PDF and CDF")
41+
plt.semilogy(pdf.keys(), pdf.values(), '.')
42+
plt.semilogy(cdf.keys(), cdf.values())
43+
plt.show()
44+
45+
############################
46+
# Sampling distributions
47+
############################
48+
N_TEST3 = 1000
49+
N_VAL_TEST3 = 20
50+
keys = np.arange(N_VAL_TEST3)
51+
vals = np.random.uniform(0,1,N_VAL_TEST3)
52+
vals /= np.sum(vals)
53+
pdf = dict(zip(keys,vals))
54+
cdf = stat.discrete_distr_to_cdf(pdf)
55+
56+
resample = stat.discrete_cdf_sample(cdf, N_TEST3)
57+
emp_pdf = stat.discrete_empirical_pdf_from_sample(resample)
58+
59+
assert emp_pdf.keys() == pdf.keys()
60+
61+
plt.figure()
62+
plt.title("Resamling random distribution using " + str(N_TEST3) + " trials")
63+
plt.bar(pdf.keys(), pdf.values(), alpha=0.5, label="true")
64+
plt.bar(emp_pdf.keys(), emp_pdf.values(), alpha=0.5, label="resampled")
65+
plt.legend()
66+
plt.ioff()
67+
plt.show()

examples/example_stat_cranksum.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
import numpy as np
3+
import matplotlib.pyplot as plt
4+
5+
from mesostat.stat.htests import difference_test
6+
from mesostat.stat.hteststatistics import cranksum
7+
8+
A = np.random.uniform(0.5,2,100)#np.abs(np.random.normal(0,1,100))
9+
B = np.random.uniform(0,1,100)#np.abs(np.random.normal(0,1,100))
10+
11+
def CDF(x):
12+
return np.sort(x), np.linspace(0,1,len(x))
13+
14+
def permutation_test_distinct(f, x, y, nResample=2000):
15+
M, N = len(x), len(y)
16+
fTrue = f(x, y)
17+
xy = np.hstack([x, y])
18+
fTest = []
19+
for iTest in range(nResample):
20+
xyShuffle = xy[np.random.permutation(M + N)]
21+
xTest, yTest = xyShuffle[:M], xyShuffle[M:]
22+
fTest += [f(xTest, yTest)]
23+
24+
plt.figure()
25+
plt.hist(fTest, bins='auto')
26+
plt.axvline(x=fTrue, color='r')
27+
28+
29+
xa, ca = CDF(A)
30+
xb, cb = CDF(B)
31+
32+
fig, ax = plt.subplots()
33+
ax.plot(xa, ca)
34+
ax.plot(xb, cb)
35+
36+
permutation_test_distinct(cranksum, A, B)
37+
plt.show()
38+

examples/fc/example_crosscorr.py

+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# import standard libraries
2+
import os, sys
3+
import numpy as np
4+
import matplotlib.pyplot as plt
5+
6+
# import mesostat
7+
from mesostat.metric.corr import cross_corr_3D
8+
from mesostat.utils.plotting import plot_matrix
9+
10+
'''
11+
Test 1:
12+
Generate random data, and shift it by fixed steps for each channel
13+
Expected outcomes:
14+
* If shift <= max_delay, corr ~ 1, delay = shift
15+
* If shift > max_delay, corr ~ 0, delay = rand
16+
* Delay is the same for all diagonals, because we compare essentially the same data, both cycled by the same amount
17+
'''
18+
19+
nNode = 5
20+
nData = 1000
21+
settings = {
22+
'min_lag_sources' : 1,
23+
'max_lag_sources' : 2,
24+
'dim_order' : 'ps'
25+
}
26+
27+
#data = np.random.uniform(0, 1, nNode*nData).reshape((nNode, nData))
28+
# Generate progressively more random data
29+
data = np.zeros((nNode, nData))
30+
data[0] = np.random.normal(0, 1, nData)
31+
for i in range(1, nNode):
32+
data[i] = np.hstack((data[i-1][1:], data[i-1][0]))
33+
34+
rezCorr = cross_corr_3D(data, settings, est='corr')
35+
rezSpr = cross_corr_3D(data, settings, est='spr')
36+
37+
compose = lambda lst1, lst2: [a + "_" + b for a in lst1 for b in lst2]
38+
39+
plot_matrix(
40+
"Test 1: Channels are shifts of the same data",
41+
(2, 3),
42+
[*rezCorr, *rezSpr],
43+
np.array(compose(["corr", "spr"], ["val", "lag", "p"])),
44+
lims = [[-1, 1], [0, settings['max_lag_sources']], [0, 1]]*2,
45+
draw = True
46+
)
47+
48+
49+
'''
50+
Test 2:
51+
Generate random data, all copies of each other, each following one a bit more noisy than prev
52+
Expected outcomes:
53+
* Correlation decreases with distance between nodes, as they are separated by more noise
54+
* Correlation should be approx the same for any two nodes given fixed distance between them
55+
'''
56+
57+
nNode = 5
58+
nData = 1000
59+
settings = {
60+
'min_lag_sources' : 0,
61+
'max_lag_sources' : 0,
62+
'dim_order' : 'ps'
63+
}
64+
alpha = 0.5
65+
66+
data = np.random.normal(0, 1, (nNode, nData))
67+
for i in range(1, nNode):
68+
data[i] = data[i-1] * np.sqrt(1 - alpha) + np.random.normal(0, 1, nData) * np.sqrt(alpha)
69+
70+
rezCorr = cross_corr_3D(data, settings, est='corr')
71+
rezSpr = cross_corr_3D(data, settings, est='spr')
72+
73+
plot_matrix(
74+
"Test 2: Channels are same, but progressively more noisy",
75+
(2, 3),
76+
[*rezCorr, *rezSpr],
77+
np.array(compose(["corr", "spr"], ["val", "lag", "p"])),
78+
lims = [[-1, 1], [0, settings['max_lag_sources']], [0, 1]]*2,
79+
draw = True
80+
)
81+
82+
83+
'''
84+
Test 3:
85+
Random data structured by trials. Two channels (0 -> 3) connected with lag 6, others unrelated
86+
Expected outcomes:
87+
* No structure, except for (0 -> 3) connection
88+
'''
89+
90+
nNode = 5
91+
lagTrue = 6
92+
settings = {
93+
'min_lag_sources' : 1,
94+
'max_lag_sources' : 6,
95+
'dim_order' : 'rsp'
96+
}
97+
nData = settings['max_lag_sources']+1
98+
nTrial = 200
99+
100+
data = np.random.normal(0, 1, (nTrial,nData,nNode))
101+
data[0, lagTrue:, :] = data[3, :-lagTrue, :]
102+
103+
rezCorr = cross_corr_3D(data, settings, est='corr')
104+
rezSpr = cross_corr_3D(data, settings, est='spr')
105+
106+
plot_matrix(
107+
"Test 3: Random trial-based cross-correlation",
108+
(2, 3),
109+
[*rezCorr, *rezSpr],
110+
np.array(compose(["corr", "spr"], ["val", "lag", "p"])),
111+
lims = [[-1, 1], [0, settings['max_lag_sources']], [0, 1]]*2,
112+
draw = True
113+
)
114+
115+
plt.show()

0 commit comments

Comments
 (0)