rsatoolbox 0.3.2.dev8__cp313-cp313-win_amd64.whl

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 (74) hide show
  1. rsatoolbox/__init__.py +13 -0
  2. rsatoolbox/cengine/__init__.pxd +1 -0
  3. rsatoolbox/cengine/__init__.py +1 -0
  4. rsatoolbox/cengine/similarity.cp313-win_amd64.pyd +0 -0
  5. rsatoolbox/cengine/similarity.pyx +333 -0
  6. rsatoolbox/data/__init__.py +12 -0
  7. rsatoolbox/data/base.py +204 -0
  8. rsatoolbox/data/computations.py +43 -0
  9. rsatoolbox/data/dataset.py +892 -0
  10. rsatoolbox/data/noise.py +436 -0
  11. rsatoolbox/data/ops.py +97 -0
  12. rsatoolbox/inference/__init__.py +25 -0
  13. rsatoolbox/inference/boot_testset.py +160 -0
  14. rsatoolbox/inference/bootstrap.py +119 -0
  15. rsatoolbox/inference/crossvalsets.py +386 -0
  16. rsatoolbox/inference/evaluate.py +800 -0
  17. rsatoolbox/inference/noise_ceiling.py +78 -0
  18. rsatoolbox/inference/result.py +337 -0
  19. rsatoolbox/io/__init__.py +0 -0
  20. rsatoolbox/io/bids.py +226 -0
  21. rsatoolbox/io/fmriprep.py +209 -0
  22. rsatoolbox/io/hdf5.py +118 -0
  23. rsatoolbox/io/hrf.py +103 -0
  24. rsatoolbox/io/meadows.py +221 -0
  25. rsatoolbox/io/mne.py +62 -0
  26. rsatoolbox/io/optional.py +65 -0
  27. rsatoolbox/io/pandas.py +42 -0
  28. rsatoolbox/io/petnames.py +460 -0
  29. rsatoolbox/io/pkl.py +43 -0
  30. rsatoolbox/io/spm.py +154 -0
  31. rsatoolbox/model/__init__.py +10 -0
  32. rsatoolbox/model/fitter.py +513 -0
  33. rsatoolbox/model/model.py +367 -0
  34. rsatoolbox/model/model_family.py +119 -0
  35. rsatoolbox/py.typed +0 -0
  36. rsatoolbox/rdm/__init__.py +28 -0
  37. rsatoolbox/rdm/calc.py +536 -0
  38. rsatoolbox/rdm/calc_unbalanced.py +203 -0
  39. rsatoolbox/rdm/combine.py +231 -0
  40. rsatoolbox/rdm/compare.py +739 -0
  41. rsatoolbox/rdm/pairs.py +40 -0
  42. rsatoolbox/rdm/rdms.py +715 -0
  43. rsatoolbox/rdm/transform.py +218 -0
  44. rsatoolbox/resources.py +18 -0
  45. rsatoolbox/simulation/__init__.py +4 -0
  46. rsatoolbox/simulation/sim.py +204 -0
  47. rsatoolbox/test.py +102 -0
  48. rsatoolbox/util/__init__.py +1 -0
  49. rsatoolbox/util/build_rdm.py +65 -0
  50. rsatoolbox/util/data_utils.py +43 -0
  51. rsatoolbox/util/descriptor_utils.py +203 -0
  52. rsatoolbox/util/file_io.py +20 -0
  53. rsatoolbox/util/inference_util.py +751 -0
  54. rsatoolbox/util/matrix.py +313 -0
  55. rsatoolbox/util/pooling.py +121 -0
  56. rsatoolbox/util/rdm_utils.py +236 -0
  57. rsatoolbox/util/searchlight.py +232 -0
  58. rsatoolbox/util/weighted_mds.py +499 -0
  59. rsatoolbox/vis/__init__.py +8 -0
  60. rsatoolbox/vis/colors.py +108 -0
  61. rsatoolbox/vis/icon.py +621 -0
  62. rsatoolbox/vis/model_map.py +836 -0
  63. rsatoolbox/vis/model_plot.py +1002 -0
  64. rsatoolbox/vis/modelfamily_graph.py +156 -0
  65. rsatoolbox/vis/rdm.mplstyle +12 -0
  66. rsatoolbox/vis/rdm_comparison.py +577 -0
  67. rsatoolbox/vis/rdm_plot.py +879 -0
  68. rsatoolbox/vis/scatter_plot.py +242 -0
  69. rsatoolbox/vis/timecourse.py +172 -0
  70. rsatoolbox-0.3.2.dev8.dist-info/METADATA +75 -0
  71. rsatoolbox-0.3.2.dev8.dist-info/RECORD +74 -0
  72. rsatoolbox-0.3.2.dev8.dist-info/WHEEL +5 -0
  73. rsatoolbox-0.3.2.dev8.dist-info/licenses/LICENSE +21 -0
  74. rsatoolbox-0.3.2.dev8.dist-info/top_level.txt +1 -0
rsatoolbox/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ Top level package: Only imports and organisation
4
+ """
5
+
6
+ from . import cengine
7
+ from . import data
8
+ from . import inference
9
+ from . import model
10
+ from . import rdm
11
+ from . import simulation
12
+ from . import util
13
+ from . import vis
@@ -0,0 +1 @@
1
+ from .similarity cimport similarity
@@ -0,0 +1 @@
1
+ from .similarity import similarity, calc_one
@@ -0,0 +1,333 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import cython
5
+ from cython.view cimport array as cvarray
6
+ from libc.math cimport log, sqrt, isnan, NAN
7
+ from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
8
+ cimport scipy.linalg.cython_blas as blas
9
+ cimport numpy as cnp
10
+
11
+ cnp.import_array()
12
+
13
+ ctypedef cnp.int64_t int_t
14
+ ctypedef cnp.float64_t float_t
15
+
16
+ @cython.boundscheck(False)
17
+ @cython.cdivision(True)
18
+ cpdef float_t [:] calc(
19
+ float_t [:, :] data, int_t [:] desc,
20
+ int_t [:] cv_desc, int n,
21
+ int method_idx, float_t [:, :] noise=None,
22
+ float_t prior_lambda=1, float_t prior_weight=0.1,
23
+ int weighting=1, int crossval=0):
24
+ # calculates an RDM from a double array of data with integer descriptors
25
+ # There are no checks or saveguards in this function!
26
+ # All entries in desc should be in [0, n-1]. They will be used for indexing
27
+ # into the RDM running into segfaults if they are outside the range.
28
+ # Inputs:
29
+ # double [:, :] data : the data
30
+ # long [:] desc : defines the patterns
31
+ # long [:] cv_desc : rows with equal values are excluded from the computation
32
+ # int n : defines the RDM size, all desc should be < n
33
+ # int method_idx: which method to use:
34
+ # 1: method == 'euclidean'
35
+ # 2: method == 'correlation'
36
+ # 3: method in ['mahalanobis', 'crossnobis']
37
+ # 4: method in ['poisson', 'poisson_cv']
38
+ # double [:, :] noise = None: noise for Mahalanobis/Crossnobis
39
+ # double prior_lambda=1 : for poisson KL
40
+ # double prior_weight=0.1 : for poisson KL
41
+ # int weighting=1 : controls weighting of rows:
42
+ # 0: each row has equal weight
43
+ # 1: rows weighted by number of valid measurements
44
+ cdef:
45
+ float_t [:] vec_i
46
+ float_t [:] vec_j
47
+ float_t weight, sim
48
+ float_t [:] weights
49
+ float_t [:] values
50
+ int i, j, idx
51
+ int n_rdm = (n * (n-1)) / 2
52
+ int n_dim = data.shape[1]
53
+ float_t prior_lambda_l = prior_lambda * prior_weight
54
+ float_t prior_weight_l = 1 + prior_weight
55
+ float_t [:, :] log_data
56
+ if (method_idx > 4) or (method_idx < 1):
57
+ raise ValueError('dissimilarity method not recognized!')
58
+ # precompute stuff for poisson KL
59
+ if method_idx == 4:
60
+ data = data.copy()
61
+ log_data = data.copy()
62
+ for i in range(data.shape[0]):
63
+ for j in range(n_dim):
64
+ data[i, j] = (data[i, j] + prior_lambda_l) / prior_weight_l
65
+ log_data[i, j] = log(data[i, j])
66
+ weights = <float_t [:(n_rdm+n)]> PyMem_Malloc((n_rdm+n) * sizeof(float_t))
67
+ values = <float_t [:(n_rdm+n)]> PyMem_Malloc((n_rdm+n) * sizeof(float_t))
68
+ for idx in range(n_rdm + n):
69
+ weights[idx] = 0
70
+ values[idx] = 0
71
+ for i in range(data.shape[0]):
72
+ if not crossval:
73
+ if method_idx == 1: # method == 'euclidean':
74
+ sim, weight = euclid(data[i], data[i], n_dim)
75
+ elif method_idx == 2: # method == 'correlation':
76
+ sim, weight = correlation(data[i], data[i], n_dim)
77
+ elif method_idx == 3: # method in ['mahalanobis', 'crossnobis']:
78
+ if noise is None:
79
+ sim, weight = euclid(data[i], data[i], n_dim)
80
+ else:
81
+ sim = mahalanobis(data[i], data[i], n_dim, noise)
82
+ weight = <float_t> n_dim
83
+ elif method_idx == 4: # method in ['poisson', 'poisson_cv']:
84
+ sim, weight = poisson_cv(data[i], data[i], log_data[i], log_data[i], n_dim)
85
+ idx = desc[i]
86
+ if weighting == 1: #'number':
87
+ values[idx] += sim / 2
88
+ weights[idx] += weight / 2
89
+ elif weighting == 0: #'equal':
90
+ values[idx] += sim / weight / 2
91
+ weights[idx] += 1 / 2
92
+ for j in range(i + 1, data.shape[0]):
93
+ if not crossval or not cv_desc[i] == cv_desc[j]:
94
+ #vec_i = data[i]
95
+ #vec_j = data[j]
96
+ if method_idx == 1: # method == 'euclidean':
97
+ sim, weight = euclid(data[i], data[j], n_dim)
98
+ elif method_idx == 2: # method == 'correlation':
99
+ sim, weight = correlation(data[i], data[j], n_dim)
100
+ elif method_idx == 3: # method in ['mahalanobis', 'crossnobis']:
101
+ if noise is None:
102
+ sim, weight = euclid(data[i], data[j], n_dim)
103
+ else:
104
+ sim = mahalanobis(data[i], data[j], n_dim, noise)
105
+ weight = <float_t> n_dim
106
+ elif method_idx == 4: # method in ['poisson', 'poisson_cv']:
107
+ sim, weight = poisson_cv(data[i], data[j], log_data[i], log_data[j], n_dim)
108
+ if weight > 0:
109
+ if desc[i] == desc[j]:
110
+ idx = desc[i]
111
+ else:
112
+ if desc[j] > desc[i]:
113
+ idx = (n - 1) * desc[i] - (((desc[i] + 1) * desc[i]) / 2) + desc[j] - 1 + n
114
+ else:
115
+ idx = (n - 1) * desc[j] - (((desc[j] + 1) * desc[j]) / 2) + desc[i] - 1 + n
116
+ if weighting == 1: #'number':
117
+ values[idx] += sim
118
+ weights[idx] += weight
119
+ elif weighting == 0: #'equal':
120
+ values[idx] += sim / weight
121
+ weights[idx] += 1
122
+ for idx in range(n_rdm + n):
123
+ if weights[idx] > 0:
124
+ values[idx] = values[idx] / weights[idx]
125
+ else:
126
+ values[idx] = NAN
127
+ return values
128
+
129
+
130
+ @cython.boundscheck(False)
131
+ @cython.cdivision(True)
132
+ cpdef (float_t, float_t) calc_one(
133
+ float_t [:, :] data_i, float_t [:, :] data_j,
134
+ int_t [:] cv_desc_i, int_t [:] cv_desc_j,
135
+ int n_i, int n_j,
136
+ int method_idx, float_t [:, :] noise=None,
137
+ float_t prior_lambda=1, float_t prior_weight=0.1,
138
+ int weighting=1):
139
+ cdef:
140
+ #double [:] values = np.zeros(n_i * n_j)
141
+ #double [:] weights = np.zeros(n_i * n_j)
142
+ float_t [:] vec_i
143
+ float_t [:] vec_j
144
+ float_t weight, sim, weight_sum, value
145
+ int i, j
146
+ int n_dim = data_i.shape[1]
147
+ float_t prior_lambda_l = prior_lambda * prior_weight
148
+ float_t prior_weight_l = 1 + prior_weight
149
+ float_t [:, :] log_data_i
150
+ float_t [:, :] log_data_j
151
+ if (method_idx > 4) or (method_idx < 1):
152
+ raise ValueError('dissimilarity method not recognized!')
153
+ # precompute stuff for poisson KL
154
+ if method_idx == 4:
155
+ data_i = data_i.copy()
156
+ log_data_i = data_i.copy()
157
+ for i in range(data_i.shape[0]):
158
+ for j in range(n_dim):
159
+ data_i[i, j] = (data_i[i, j] + prior_lambda_l) / prior_weight_l
160
+ log_data_i[i, j] = log(data_i[i, j])
161
+ data_j = data_j.copy()
162
+ log_data_j = data_j.copy()
163
+ for i in range(data_j.shape[0]):
164
+ for j in range(n_dim):
165
+ data_j[i, j] = (data_j[i, j] + prior_lambda_l) / prior_weight_l
166
+ log_data_j[i, j] = log(data_j[i, j])
167
+ weight_sum = 0
168
+ value = 0
169
+ for i in range(n_i):
170
+ for j in range(n_j):
171
+ if not (cv_desc_i[i] == cv_desc_j[j]):
172
+ if method_idx == 1: # method == 'euclidean':
173
+ sim, weight = euclid(data_i[i], data_j[j], n_dim)
174
+ elif method_idx == 2: # method == 'correlation':
175
+ sim, weight = correlation(data_i[i], data_j[j], n_dim)
176
+ elif method_idx == 3: # method in ['mahalanobis', 'crossnobis']:
177
+ if noise is None:
178
+ sim, weight = euclid(data_i[i], data_j[j], n_dim)
179
+ else:
180
+ sim = mahalanobis(data_i[i], data_j[j], n_dim, noise)
181
+ weight = <float_t> n_dim
182
+ elif method_idx == 4: # method in ['poisson', 'poisson_cv']:
183
+ sim, weight = poisson_cv(data_i[i], data_j[j], log_data_i[i], log_data_j[j], n_dim)
184
+ if weight > 0:
185
+ if weighting == 1: #'number':
186
+ value += sim
187
+ weight_sum += weight
188
+ elif weighting == 0: #'equal':
189
+ value += sim / weight
190
+ weight_sum += 1
191
+ if weight_sum > 0:
192
+ value = value / weight_sum
193
+ else:
194
+ value = NAN
195
+ return value, weight_sum
196
+
197
+
198
+ @cython.boundscheck(False)
199
+ cpdef (float_t, float_t) similarity(float_t [:] vec_i, float_t [:] vec_j, int method_idx,
200
+ int n_dim, float_t [:, :] noise):
201
+ """
202
+ double similarity(double [:] vec_i, double [:] vec_j, int method_idx,
203
+ int n_dim, double [:, :] noise=None)
204
+
205
+ This is a single similarity computation in cython.
206
+ remember to call everything with continuous numpy arrays.
207
+ In particular, noise must be such an array for Mahalanobis distances!
208
+
209
+ Mahalanobis distances require full measurement vectors at the moment!
210
+ """
211
+ cdef float_t sim
212
+ cdef float_t weight
213
+ if method_idx == 1: # method == 'euclidean':
214
+ sim, weight = euclid(vec_i, vec_j, n_dim)
215
+ elif method_idx == 2: # method == 'correlation':
216
+ sim, weight = correlation(vec_i, vec_j, n_dim)
217
+ elif method_idx == 3: # method in ['mahalanobis', 'crossnobis']:
218
+ if noise is None:
219
+ sim, weight = euclid(vec_i, vec_j, n_dim)
220
+ else:
221
+ sim = mahalanobis(vec_i, vec_j, n_dim, noise)
222
+ weight = <float_t> n_dim
223
+ return sim, weight
224
+
225
+
226
+ @cython.boundscheck(False)
227
+ cdef (float_t, float_t) euclid(float_t [:] vec_i, float_t [:] vec_j, int n_dim):
228
+ cdef:
229
+ float_t sim = 0
230
+ float_t weight = 0
231
+ int i
232
+ for i in range(n_dim):
233
+ if not isnan(vec_i[i]) and not isnan(vec_j[i]):
234
+ sim += vec_i[i] * vec_j[i]
235
+ weight += 1
236
+ return sim, weight
237
+
238
+
239
+ @cython.boundscheck(False)
240
+ @cython.cdivision(True)
241
+ cdef (float_t, float_t) poisson_cv(float_t [:] vec_i, float_t [:] vec_j,
242
+ float_t [:] log_vec_i, float_t [:] log_vec_j,
243
+ int n_dim):
244
+ cdef:
245
+ float_t sim = 0
246
+ float_t weight = 0
247
+ int i
248
+ for i in range(n_dim):
249
+ if not isnan(vec_i[i]) and not isnan(vec_j[i]):
250
+ sim += (vec_j[i] - vec_i[i]) * (log_vec_i[i] - log_vec_j[i])
251
+ weight += 1
252
+ sim = sim / 2.0
253
+ return (sim, weight)
254
+
255
+
256
+ @cython.boundscheck(False)
257
+ cdef float_t mahalanobis(float_t [:] vec_i, float_t [:] vec_j, int n_dim,
258
+ float_t [:, :] noise):
259
+ cdef:
260
+ float_t *vec1
261
+ float_t *vec2
262
+ int *finite
263
+ int zero = 0
264
+ int one = 1
265
+ float_t onef = 1.0
266
+ float_t zerof = 0.0
267
+ char trans = b'n'
268
+ float_t sim = 0.0
269
+ int i, j, k, l, n_finite
270
+ float_t [:, :] noise_small
271
+ finite = <int*> PyMem_Malloc(n_dim * sizeof(int))
272
+ # use finite as a bool to choose the non-nan values
273
+ n_finite = 0
274
+ for i in range(n_dim):
275
+ if not isnan(vec_i[i]) and not isnan(vec_j[i]):
276
+ finite[i] = 1
277
+ n_finite += 1
278
+ else:
279
+ finite[i] = 0
280
+ vec1 = <float_t*> PyMem_Malloc(n_finite * sizeof(float_t))
281
+ vec2 = <float_t*> PyMem_Malloc(n_finite * sizeof(float_t))
282
+ vec3 = <float_t*> PyMem_Malloc(n_finite * sizeof(float_t))
283
+ noise_small = cvarray(shape=(n_finite, n_finite), itemsize=sizeof(float_t), format="d")
284
+ k = 0
285
+ for i in range(n_dim):
286
+ if finite[i]:
287
+ vec1[k] = vec_i[i]
288
+ vec2[k] = vec_j[i]
289
+ l = 0
290
+ for j in range(n_dim):
291
+ if finite[j]:
292
+ noise_small[k, l] = noise[i, j]
293
+ l += 1
294
+ k += 1
295
+ blas.dgemv(&trans, &n_finite, &n_finite, &onef, &noise_small[0, 0], &n_finite, vec2, &one, &zerof, vec3, &one)
296
+ for i in range(n_dim):
297
+ sim += vec1[i] * vec3[i]
298
+ PyMem_Free(vec1)
299
+ PyMem_Free(vec2)
300
+ PyMem_Free(vec3)
301
+ PyMem_Free(finite)
302
+ return sim
303
+
304
+
305
+ @cython.boundscheck(False)
306
+ @cython.cdivision(True)
307
+ cdef (float_t, float_t) correlation(float_t [:] vec_i, float_t [:] vec_j, int n_dim):
308
+ cdef:
309
+ float_t si = 0.0
310
+ float_t sj = 0.0
311
+ float_t si2 = 0.0
312
+ float_t sj2 = 0.0
313
+ float_t sij = 0.0
314
+ float_t sim
315
+ float_t weight = 0
316
+ int i
317
+ for i in range(n_dim):
318
+ if not isnan(vec_i[i]) and not isnan(vec_j[i]):
319
+ si += vec_i[i]
320
+ sj += vec_j[i]
321
+ si2 += vec_i[i] * vec_i[i]
322
+ sj2 += vec_j[i] * vec_j[i]
323
+ sij += vec_i[i] * vec_j[i]
324
+ weight += 1
325
+ if si2 > 0 and sj2 > 0:
326
+ # sim = (np.sum(vec_i * vec_j) / np.sqrt(norm_i) / np.sqrt(norm_j))
327
+ sim = sij - (si * sj / n_dim)
328
+ sim /= sqrt(si2 - (si * si / n_dim))
329
+ sim /= sqrt(sj2 - (sj * sj / n_dim))
330
+ else:
331
+ sim = 1
332
+ sim = sim * n_dim / 2
333
+ return sim, weight
@@ -0,0 +1,12 @@
1
+ from .dataset import Dataset
2
+ from .dataset import TemporalDataset
3
+ from .dataset import load_dataset
4
+ from .dataset import dataset_from_dict
5
+ from .computations import average_dataset
6
+ from .computations import average_dataset_by
7
+ from .noise import cov_from_residuals
8
+ from .noise import prec_from_residuals
9
+ from .noise import cov_from_measurements
10
+ from .noise import prec_from_measurements
11
+ from .noise import cov_from_unbalanced
12
+ from .noise import prec_from_unbalanced
@@ -0,0 +1,204 @@
1
+ """Base class for Dataset
2
+ """
3
+ from __future__ import annotations
4
+ from rsatoolbox.util.descriptor_utils import check_descriptor_length_error
5
+ from rsatoolbox.util.descriptor_utils import format_descriptor
6
+ from rsatoolbox.util.descriptor_utils import parse_input_descriptor
7
+ from rsatoolbox.io.hdf5 import write_dict_hdf5
8
+ from rsatoolbox.io.pkl import write_dict_pkl
9
+ from rsatoolbox.util.file_io import remove_file
10
+
11
+
12
+ class DatasetBase:
13
+ """
14
+ Abstract dataset class.
15
+ Defines members that every class needs to have, but does not
16
+ implement any interesting behavior. Inherit from this class
17
+ to define specific dataset types
18
+
19
+ Args:
20
+ measurements (numpy.ndarray): n_obs x n_channel 2d-array,
21
+ descriptors (dict): descriptors (metadata)
22
+ obs_descriptors (dict): observation descriptors (all
23
+ are array-like with shape = (n_obs,...))
24
+ channel_descriptors (dict): channel descriptors (all are
25
+ array-like with shape = (n_channel,...))
26
+
27
+ Returns:
28
+ dataset object
29
+ """
30
+
31
+ def __init__(self, measurements, descriptors=None,
32
+ obs_descriptors=None, channel_descriptors=None,
33
+ check_dims=True):
34
+ if measurements.ndim != 2:
35
+ raise AttributeError(
36
+ "measurements must be in dimension n_obs x n_channel")
37
+ self.measurements = measurements
38
+ self.n_obs, self.n_channel = self.measurements.shape
39
+ if check_dims:
40
+ check_descriptor_length_error(obs_descriptors,
41
+ "obs_descriptors",
42
+ self.n_obs
43
+ )
44
+ check_descriptor_length_error(channel_descriptors,
45
+ "channel_descriptors",
46
+ self.n_channel
47
+ )
48
+ self.descriptors = parse_input_descriptor(descriptors)
49
+ self.obs_descriptors = parse_input_descriptor(obs_descriptors)
50
+ self.channel_descriptors = parse_input_descriptor(channel_descriptors)
51
+
52
+ def __repr__(self):
53
+ """
54
+ defines string which is printed for the object
55
+ """
56
+ return (f'rsatoolbox.data.{self.__class__.__name__}(\n'
57
+ f'measurements = \n{self.measurements}\n'
58
+ f'descriptors = \n{self.descriptors}\n'
59
+ f'obs_descriptors = \n{self.obs_descriptors}\n'
60
+ f'channel_descriptors = \n{self.channel_descriptors}\n'
61
+ )
62
+
63
+ def __str__(self):
64
+ """
65
+ defines the output of print
66
+ """
67
+ string_desc = format_descriptor(self.descriptors)
68
+ string_obs_desc = format_descriptor(self.obs_descriptors)
69
+ string_channel_desc = format_descriptor(self.channel_descriptors)
70
+ if self.measurements.shape[0] > 5:
71
+ measurements = self.measurements[:5, :]
72
+ else:
73
+ measurements = self.measurements
74
+ return (f'rsatoolbox.data.{self.__class__.__name__}\n'
75
+ f'measurements = \n{measurements}\n...\n\n'
76
+ f'descriptors: \n{string_desc}\n\n'
77
+ f'obs_descriptors: \n{string_obs_desc}\n\n'
78
+ f'channel_descriptors: \n{string_channel_desc}\n'
79
+ )
80
+
81
+ def __eq__(self, other: object) -> bool:
82
+ """Equality check, to be implemented in the specific
83
+ Dataset class
84
+
85
+ Args:
86
+ other (DatasetBase): The object to compare to.
87
+
88
+ Raises:
89
+ NotImplementedError: This is not valid if not implemented
90
+ by the specific Dataset class
91
+
92
+ Returns:
93
+ bool: Never returns
94
+ """
95
+ if isinstance(other, DatasetBase):
96
+ raise NotImplementedError()
97
+ else:
98
+ return False
99
+
100
+ def copy(self) -> DatasetBase:
101
+ """Copy Dataset
102
+ To be implemented in child class
103
+
104
+ Raises:
105
+ NotImplementedError: raised if not implemented
106
+
107
+ Returns:
108
+ DatasetBase: Never returns
109
+ """
110
+ raise NotImplementedError
111
+
112
+ def split_obs(self, by):
113
+ """ Returns a list Datasets split by obs
114
+
115
+ Args:
116
+ by(String): the descriptor by which the splitting is made
117
+
118
+ Returns:
119
+ list of Datasets, splitted by the selected obs_descriptor
120
+
121
+ """
122
+ raise NotImplementedError(
123
+ "split_obs function not implemented in used Dataset class!")
124
+
125
+ def split_channel(self, by):
126
+ """ Returns a list Datasets split by channels
127
+
128
+ Args:
129
+ by(String): the descriptor by which the splitting is made
130
+
131
+ Returns:
132
+ list of Datasets, splitted by the selected channel_descriptor
133
+
134
+ """
135
+ raise NotImplementedError(
136
+ "split_channel function not implemented in used Dataset class!")
137
+
138
+ def subset_obs(self, by, value):
139
+ """ Returns a subsetted Dataset defined by certain obs value
140
+
141
+ Args:
142
+ by(String): the descriptor by which the subset selection is made
143
+ from obs dimension
144
+ value: the value by which the subset selection is made
145
+ from obs dimension
146
+
147
+ Returns:
148
+ Dataset, with subset defined by the selected obs_descriptor
149
+
150
+ """
151
+ raise NotImplementedError(
152
+ "subset_obs function not implemented in used Dataset class!")
153
+
154
+ def subset_channel(self, by, value):
155
+ """ Returns a subsetted Dataset defined by certain channel value
156
+
157
+ Args:
158
+ by(String): the descriptor by which the subset selection is made
159
+ from channel dimension
160
+ value: the value by which the subset selection is made
161
+ from channel dimension
162
+
163
+ Returns:
164
+ Dataset, with subset defined by the selected channel_descriptor
165
+
166
+ """
167
+ raise NotImplementedError(
168
+ "subset_channel function not implemented in used Dataset class!")
169
+
170
+ def save(self, filename, file_type='hdf5', overwrite=False):
171
+ """ Saves the dataset object to a file
172
+
173
+ Args:
174
+ filename(String): path to the file
175
+ [or opened file]
176
+ file_type(String): Type of file to create:
177
+ hdf5: hdf5 file
178
+ pkl: pickle file
179
+ overwrite(Boolean): overwrites file if it already exists
180
+
181
+ """
182
+ data_dict = self.to_dict()
183
+ if overwrite:
184
+ remove_file(filename)
185
+ if file_type == 'hdf5':
186
+ write_dict_hdf5(filename, data_dict)
187
+ elif file_type == 'pkl':
188
+ write_dict_pkl(filename, data_dict)
189
+
190
+ def to_dict(self):
191
+ """ Generates a dictionary which contains the information to
192
+ recreate the dataset object. Used for saving to disc
193
+
194
+ Returns:
195
+ data_dict(dict): dictionary with dataset information
196
+
197
+ """
198
+ data_dict = {}
199
+ data_dict['measurements'] = self.measurements
200
+ data_dict['descriptors'] = self.descriptors
201
+ data_dict['obs_descriptors'] = self.obs_descriptors
202
+ data_dict['channel_descriptors'] = self.channel_descriptors
203
+ data_dict['type'] = type(self).__name__
204
+ return data_dict
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Dataset computations
5
+ """
6
+
7
+ import numpy as np
8
+ from rsatoolbox.util.data_utils import get_unique_inverse
9
+
10
+
11
+ def average_dataset(dataset):
12
+ """
13
+ computes the average of a dataset
14
+
15
+ Args:
16
+ dataset(rsatoolbox.data.Dataset): the dataset to operate on
17
+
18
+ Returns:
19
+ numpy.ndarray: average: average activation vector
20
+ """
21
+ return np.mean(dataset.measurements, axis=0)
22
+
23
+
24
+ def average_dataset_by(dataset, by):
25
+ """
26
+ computes the average of a dataset per value of a descriptor
27
+
28
+ Args:
29
+ dataset(rsatoolbox.data.Dataset): the dataset to operate on
30
+ by(String): which obs_descriptor to split by
31
+
32
+ Returns:
33
+ numpy.ndarray: average: average activation vector
34
+ """
35
+ unique_values, inverse = get_unique_inverse(dataset.obs_descriptors[by])
36
+ average = np.nan * np.empty(
37
+ (len(unique_values), dataset.measurements.shape[1]))
38
+ n_obs = np.nan * np.empty(len(unique_values))
39
+ for i_v, _ in enumerate(unique_values):
40
+ measurements = dataset.measurements[inverse == i_v, :]
41
+ average[i_v] = np.mean(measurements, axis=0)
42
+ n_obs[i_v] = measurements.shape[0]
43
+ return average, unique_values, n_obs