-
Notifications
You must be signed in to change notification settings - Fork 73
/
test_active_information_storage.py
287 lines (260 loc) · 10.6 KB
/
test_active_information_storage.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
"""Test AIS analysis class.
This module provides unit tests for the AIS analysis class.
"""
import pytest
import random as rn
import numpy as np
from idtxl.data import Data
from idtxl.active_information_storage import ActiveInformationStorage
from idtxl.estimators_jidt import JidtDiscreteCMI
from test_estimators_jidt import jpype_missing
package_missing = False
try:
import pyopencl
except ImportError as err:
package_missing = True
opencl_missing = pytest.mark.skipif(
package_missing,
reason="Jpype is missing, JIDT estimators are not available")
@jpype_missing
def test_return_local_values():
"""Test estimation of local values."""
max_lag = 5
settings = {
'cmi_estimator': 'JidtKraskovCMI',
'local_values': True, # request calculation of local values
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': max_lag,
'tau': 1}
data = Data()
data.generate_mute_data(100, 3)
ais = ActiveInformationStorage()
processes = [1, 2]
results = ais.analyse_network(settings, data, processes)
for p in processes:
lais = results.get_single_process(p, fdr=False)['ais']
if lais is np.nan:
continue
assert type(lais) is np.ndarray, (
'LAIS estimation did not return an array of values: {0}'.format(
lais))
assert lais.shape[0] == data.n_replications, (
'Wrong dim (no. replications) in LAIS estimate: {0}'.format(
lais.shape))
assert lais.shape[1] == data.n_realisations_samples((0, max_lag)), (
'Wrong dim (no. samples) in LAIS estimate: {0}'.format(lais.shape))
@jpype_missing
def test_ActiveInformationStorage_init():
"""Test instance creation for ActiveInformationStorage class."""
# Test error on missing estimator
settings = {'max_lag': 5}
data = Data()
data.generate_mute_data(10, 3)
ais = ActiveInformationStorage()
with pytest.raises(RuntimeError):
ais.analyse_single_process(settings, data, process=0)
# Test tau larger than maximum lag
settings['cmi_estimator'] = 'JidtKraskovCMI'
settings['tau'] = 10
with pytest.raises(RuntimeError):
ais.analyse_single_process(settings, data, process=0)
# Test negative tau and maximum lag
settings['tau'] = -10
with pytest.raises(RuntimeError):
ais.analyse_single_process(settings, data, process=0)
settings['tau'] = 1
settings['max_lag'] = -5
with pytest.raises(RuntimeError):
ais.analyse_single_process(settings, data, process=0)
# Invalid: process is not an int
settings['max_lag'] = 5
with pytest.raises(RuntimeError): # no int
ais.analyse_single_process(settings, data, process=1.5)
with pytest.raises(RuntimeError): # negative
ais.analyse_single_process(settings, data, process=-1)
with pytest.raises(RuntimeError): # not in data
ais.analyse_single_process(settings, data, process=10)
with pytest.raises(RuntimeError): # wrong type
ais.analyse_single_process(settings, data, process={})
@jpype_missing
def test_add_conditional_manually():
"""Enforce the conditioning on additional variables."""
settings = {'cmi_estimator': 'JidtKraskovCMI',
'max_lag': 5,
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21}
data = Data()
data.generate_mute_data(10, 3)
ais = ActiveInformationStorage()
# Add a conditional with a lag bigger than the max_lag requested above
settings['add_conditionals'] = (8, 0)
with pytest.raises(IndexError):
ais.analyse_single_process(settings=settings, data=data, process=0)
# Add valid conditionals and test if they were added
settings['add_conditionals'] = [(0, 1), (1, 3)]
ais._initialise(settings, data, 0)
# Get list of conditionals after intialisation and convert absolute samples
# back to lags for comparison.
cond_list = ais._idx_to_lag(ais.selected_vars_full)
assert settings['add_conditionals'][0] in cond_list, (
'First enforced conditional is missing from results.')
assert settings['add_conditionals'][1] in cond_list, (
'Second enforced conditional is missing from results.')
def test_analyse_network():
"""Test AIS estimation for the whole network."""
settings = {
'cmi_estimator': 'JidtKraskovCMI',
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': 5,
'tau': 1}
data = Data()
data.generate_mute_data(10, 3)
ais = ActiveInformationStorage()
# Test analysis of 'all' processes
results = ais.analyse_network(settings, data)
k = results.processes_analysed
assert all(np.array(k) == np.arange(data.n_processes)), (
'Network analysis did not run on all targets.')
# Test check for correct definition of processes
with pytest.raises(ValueError): # no list
ais.analyse_network(settings, data=data, processes={})
with pytest.raises(ValueError): # no list of ints
ais.analyse_network(settings, data=data, processes=[1.5, 0.7])
@jpype_missing
def test_single_source_storage_gaussian():
n = 1000
proc_1 = [rn.normalvariate(0, 1) for r in range(n)] # correlated src
proc_2 = [rn.normalvariate(0, 1) for r in range(n)] # correlated src
# Cast everything to numpy so the idtxl estimator understands it.
data = Data(np.array([proc_1, proc_2]), dim_order='ps')
settings = {
'cmi_estimator': 'JidtKraskovCMI',
'alpha_mi': 0.05,
'tail_mi': 'one_bigger',
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': 5,
'tau': 1
}
processes = [1]
network_analysis = ActiveInformationStorage()
results = network_analysis.analyse_network(settings, data, processes)
print('AIS for random normal data without memory (expected is NaN): '
'{0}'.format(results._single_process[1].ais))
assert results._single_process[1].ais is np.nan, (
'Estimator did not return nan for memoryless data.')
@jpype_missing
@opencl_missing
def test_compare_jidt_open_cl_estimator():
"""Compare results from OpenCl and JIDT estimators for AIS calculation."""
data = Data()
data.generate_mute_data(1000, 2)
settings = {
'cmi_estimator': 'OpenCLKraskovCMI',
'alpha_mi': 0.05,
'tail_mi': 'one_bigger',
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': 5,
'tau': 1
}
processes = [2, 3]
network_analysis = ActiveInformationStorage()
res_opencl = network_analysis.analyse_network(settings, data, processes)
settings['cmi_estimator'] = 'JidtKraskovCMI'
res_jidt = network_analysis.analyse_network(settings, data, processes)
# Note that I require equality up to three digits. Results become more
# exact for bigger data sizes, but this takes too long for a unit test.
ais_opencl_2 = res_opencl._single_process[2].ais
ais_jidt_2 = res_jidt._single_process[2].ais
ais_opencl_3 = res_opencl._single_process[3].ais
ais_jidt_3 = res_jidt._single_process[3].ais
print('AIS for MUTE data proc 2 - opencl: {0} and jidt: {1}'.format(
ais_opencl_2, ais_jidt_2))
print('AIS for MUTE data proc 3 - opencl: {0} and jidt: {1}'.format(
ais_opencl_3, ais_jidt_3))
if not (ais_opencl_2 is np.nan or ais_jidt_2 is np.nan):
assert (ais_opencl_2 - ais_jidt_2) < 0.05, (
'AIS results differ between OpenCl and JIDT estimator.')
else:
assert ais_opencl_2 is ais_jidt_2, (
'AIS results differ between OpenCl and JIDT estimator.')
if not (ais_opencl_3 is np.nan or ais_jidt_3 is np.nan):
assert (ais_opencl_3 - ais_jidt_3) < 0.05, (
'AIS results differ between OpenCl and JIDT estimator.')
else:
assert ais_opencl_3 is ais_jidt_3, (
'AIS results differ between OpenCl and JIDT estimator.')
def test_discrete_input():
"""Test AIS estimation from discrete data."""
# Generate AR data
order = 1
n = 10000 - order
self_coupling = 0.5
process = np.zeros(n + order)
process[0:order] = np.random.normal(size=(order))
for n in range(order, n + order):
process[n] = self_coupling * process[n - 1] + np.random.normal()
# Discretise data
settings = {'discretise_method': 'equal',
'n_discrete_bins': 5}
est = JidtDiscreteCMI(settings)
process_dis, temp = est._discretise_vars(var1=process, var2=process)
data = Data(process_dis, dim_order='s', normalise=False)
settings = {
'cmi_estimator': 'JidtDiscreteCMI',
'discretise_method': 'none',
'n_discrete_bins': 5, # alphabet size of the variables
'n_perm_max_stat': 21,
'n_perm_min_stat': 21,
'n_perm_mi': 21,
'max_lag': 2}
nw = ActiveInformationStorage()
nw.analyse_single_process(settings=settings, data=data, process=0)
@jpype_missing
def test_define_candidates():
"""Test candidate definition from a list of procs and a list of samples."""
target = 1
tau_target = 3
max_lag_target = 10
current_val = (target, 10)
procs = [target]
samples = np.arange(current_val[1] - 1, current_val[1] - max_lag_target,
-tau_target)
# Test if candidates that are added manually to the conditioning set are
# removed from the candidate set.
nw = ActiveInformationStorage()
settings = [
{'add_conditionals': None},
{'add_conditionals': (2, 3)},
{'add_conditionals': [(2, 3), (4, 1)]}]
for s in settings:
nw.settings = s
candidates = nw._define_candidates(procs, samples)
assert (1, 9) in candidates, 'Sample missing from candidates: (1, 9).'
assert (1, 6) in candidates, 'Sample missing from candidates: (1, 6).'
assert (1, 3) in candidates, 'Sample missing from candidates: (1, 3).'
settings = [
{'add_conditionals': [(1, 9)]},
{'add_conditionals': [(1, 9), (2, 3), (4, 1)]}]
for s in settings:
nw.settings = s
candidates = nw._define_candidates(procs, samples)
assert (1, 9) not in candidates, 'Sample missing from candidates: (1, 9).'
assert (1, 6) in candidates, 'Sample missing from candidates: (1, 6).'
assert (1, 3) in candidates, 'Sample missing from candidates: (1, 3).'
if __name__ == '__main__':
test_define_candidates()
test_return_local_values()
test_discrete_input()
test_analyse_network()
test_ActiveInformationStorage_init()
test_single_source_storage_gaussian()
test_compare_jidt_open_cl_estimator()