-
Notifications
You must be signed in to change notification settings - Fork 0
/
coh_process_results.py
4167 lines (3550 loc) · 149 KB
/
coh_process_results.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Classes and methods for applying post-processing to results.
CLASSES
-------
PostProcess
- Class for the post-processing of results derived from raw signals.
METHODS
-------
load_results_of_types
- Loads results of a multiple types of data and merges them into a single
PostProcess object.
load_results_of_type
- Loads results of a single type of data and appends them into a single
PostProcess object
"""
import os
from copy import deepcopy
from typing import Any, Callable, Optional, Union
import numpy as np
import pandas as pd
from scipy import stats
from scipy.interpolate import RBFInterpolator
import mne
import trimesh
from coh_exceptions import (
DuplicateEntryError,
EntryLengthError,
UnavailableProcessingError,
UnidenticalEntryError,
)
from coh_handle_entries import (
combine_col_vals_df,
check_non_repeated_vals_lists,
check_vals_identical_df,
dict_to_df,
get_eligible_idcs_list,
get_group_idcs,
sort_inputs_results,
unique,
)
from coh_handle_files import generate_sessionwise_fpath, load_file
from coh_normalisation import gaussian_transform
from coh_saving import save_dict, save_object
from coh_track_fibres import TrackFibres
class PostProcess:
"""Class for the post-processing of results derived from raw signals.
PARAMETERS
----------
results : dict
- A dictionary containing results to process.
- The entries in the dictionary should be either lists, numpy arrays, or
dictionaries.
- Entries which are dictionaries will have their values treated as being
identical for all values in the 'results' dictionary, given they are
extracted from these dictionaries into the results.
- A key with the name "dimensions" is treated as containing information
about the dimensions of other attributes in the results, e.g. with value
["windows", "channels", "frequencies"].
extract_from_dicts : dict[list[str]] | None; default None
- The entries of dictionaries within 'results' to include in the
processing.
- Entries which are extracted are treated as being identical for all
values in the 'results' dictionary.
identical_keys : list[str] | None; default None
- The keys in 'results' which are identical across channels and for
which only one copy is present.
- If any dimension attributes are present, these should be included as an
identical entry, as they will be added automatically.
discard_keys : list[str] | None; default None
- The keys which should be discarded immediately without processing.
METHODS
-------
average
- Averages results.
subtract
- Subtracts results.
log
- Log transforms results with base 10.
isolate_bands
- Isolates data from bands (i.e. portions) of the results (e.g frequency
bands) into a new DataFrame.
append
- Appends other dictionaries of results to the list of result dictionaries
stored in the PostProcess object.
merge
- Merge dictionaries of results containing different keys into the
results.
"""
def __init__(
self,
results: dict,
extract_from_dicts: Optional[dict[list[str]]] = None,
identical_keys: Optional[list[str]] = None,
discard_keys: Optional[list[str]] = None,
verbose: bool = True,
) -> None:
# Initialises inputs of the object.
results = sort_inputs_results(
results=results,
extract_from_dicts=extract_from_dicts,
identical_keys=identical_keys,
discard_keys=discard_keys,
verbose=verbose,
)
self._results = dict_to_df(obj=results)
self._verbose = verbose
# Initialises aspects of the object that will be filled with information
# as the data is processed.
self._process_measures = []
self._var_measures = []
self._var_columns = []
self._desc_measures = []
self._desc_process_measures = []
self._desc_var_measures = ["std", "sem"]
self._band_results = None
def append_from_dict(
self,
new_results: dict,
extract_from_dicts: Optional[dict[list[str]]] = None,
identical_keys: Optional[list[str]] = None,
discard_keys: Optional[list[str]] = None,
) -> None:
"""Appends a dictionary of results to the results stored in the
PostProcess object.
- Cannot be called after frequency band results have been computed.
PARAMETERS
----------
new_results : dict
- A dictionary containing results to add.
- The entries in the dictionary should be either lists, numpy arrays,
or dictionaries.
- Entries which are dictionaries will have their values treated as
being identical for all values in the 'results' dictionary, given
they are extracted from these dictionaries into the results.
extract_from_dicts : dict[list[str]] | None; default None
- The entries of dictionaries within 'results' to include in the
processing.
- Entries which are extracted are treated as being identical for all
values in the 'results' dictionary.
identical_keys : list[str] | None; default None
- The keys in 'results' which are identical across channels and for
which only one copy is present.
discard_keys : list[str] | None; default None
- The keys which should be discarded immediately without
processing.
"""
new_results = sort_inputs_results(
results=new_results,
extract_from_dicts=extract_from_dicts,
identical_keys=identical_keys,
discard_keys=discard_keys,
verbose=self._verbose,
)
check_non_repeated_vals_lists(
lists=[list(self._results.keys()), list(new_results.keys())],
allow_non_repeated=False,
)
new_results = dict_to_df(obj=new_results)
self._results = pd.concat(
objs=[self._results, new_results], ignore_index=True
)
def append_from_df(
self,
new_results: pd.DataFrame,
) -> None:
"""Appends a DataFrame of results to the results stored in the
PostProcess object.
- Cannot be called after frequency band results have been computed.
PARAMETERS
----------
new_results : pandas DataFrame
- The new results to append.
"""
check_non_repeated_vals_lists(
lists=[self._results.keys().tolist(), new_results.keys().tolist()],
allow_non_repeated=False,
)
self._results = pd.concat(
objs=[self._results, new_results], ignore_index=True
)
def _make_results_mergeable(
self, results_1: pd.DataFrame, results_2: pd.DataFrame
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Converts results DataFrames into a format that can be handled by the
pandas function 'merge' by converting any lists into tuples.
PARAMETERS
----------
results_1: pandas DataFrame
- The first DataFrame to make mergeable.
results_2: pandas DataFrame
- The second DataFrame to make mergeable.
RETURNS
-------
pandas DataFrame
- The first DataFrame made mergeable.
pandas DataFrame
- The second DataFrame made mergeable.
"""
dataframes = [results_1, results_2]
for df_i, dataframe in enumerate(dataframes):
for row_i in dataframe.index:
for key in dataframe.keys():
if isinstance(dataframe[key][row_i], list):
dataframe.at[row_i, key] = tuple(dataframe[key][row_i])
dataframes[df_i] = dataframe
return dataframes[0], dataframes[1]
def _restore_results_after_merge(
self, results: pd.DataFrame
) -> pd.DataFrame:
"""Converts a results DataFrame into its original format after merging
by converting any tuples back to lists.
PARAMETERS
----------
results : pandas DataFrame
- The DataFrame with lists to restore from tuples.
RETURNS
-------
results : pandas DataFrame
- The restored DataFrame.
"""
for row_i in results.index:
for key in results.keys():
if isinstance(results[key][row_i], tuple):
results.at[row_i, key] = list(results[key][row_i])
return results
def _check_missing_before_merge(
self, results_1: pd.DataFrame, results_2: pd.DataFrame
) -> None:
"""Checks that merging pandas DataFrames with the 'merge' method and
the 'how' parameter set to 'outer' will not introduce new rows into the
merged results DataFrame, resulting in some rows having NaN values for
columns not present in their original DataFrame, but present in the
other DataFrames being merged.
- This can occur if the column names which are shared between the
DataFrames do not have all the same entries between the DataFrames,
leading to new rows being added to the merged DataFrame.
PARAMETERS
----------
results_1 : pandas DataFrame
- The first DataFrame to check.
results_2 : pandas DataFrame
- The second DataFrame to check.
RAISES
------
MissingEntryError
- Raised if the DataFrames' shared columns do not have values that are
identical in the other DataFrame, leading to rows being excluded
from the merged DataFrame.
"""
if len(results_1.index) == len(results_2.index):
test_merge = pd.merge(results_1, results_2, how="inner")
if len(test_merge.index) != len(results_1.index):
raise EntryLengthError(
"Error when trying to merge two sets of results with "
"'allow_missing' set to 'False':\nThe shared columns of "
"the DataFrames being merged do not have identical values "
"in the other DataFrame, leading to "
f"{len(test_merge.index)-len(results_1.index)} new row(s) "
"being included in the merged DataFrame.\nIf you still "
"want to merge these results, set 'allow_missing' to "
"'True'."
)
else:
raise EntryLengthError(
"Error when trying to merge two sets of results with "
"'allow_missing' set to 'False':\nThere is an unequal number "
"of channels present in the two sets of results being merged "
f"({len(results_1.index)} and {len(results_2.index)}). Merging "
"these results will lead to some attributes of the results "
"having NaN values.\nIf you still want to merge these results, "
"set 'allow_missing' to 'True'."
)
def _check_keys_before_merge(self, new_results: pd.DataFrame) -> None:
"""Checks that the column names in the DataFrames being merged are not
identical.
PARAMETERS
----------
new_results : pandas DataFrame
- The new results being added.
RAISES
------
DuplicateEntryError
- Raised if there are no columns that are unique to the DataFrames
being merged.
"""
all_repeated = check_non_repeated_vals_lists(
lists=[self._results.keys().tolist(), new_results.keys().tolist()],
allow_non_repeated=True,
)
if all_repeated:
raise DuplicateEntryError(
"Error when trying to merge results:\nThere are no new columns "
"in the results being added. If you still want to add the "
"results, use the append methods."
)
def merge_from_dict(
self,
new_results: dict,
extract_from_dicts: Optional[dict[list[str]]] = None,
identical_keys: Optional[list[str]] = None,
discard_keys: Optional[list[str]] = None,
allow_missing: bool = False,
) -> None:
"""Merges a dictionary of results to the results stored in the
PostProcess object.
- Cannot be called after frequency band results have been computed.
PARAMETERS
----------
new_results : dict
- A dictionary containing results to add.
- The entries in the dictionary should be either lists, numpy arrays,
or dictionaries.
- Entries which are dictionaries will have their values treated as
being identical for all values in the 'results' dictionary, given
they are extracted from these dictionaries into the results.
extract_from_dicts : dict[list[str]] | None; default None
- The entries of dictionaries within 'results' to include in the
processing.
- Entries which are extracted are treated as being identical for all
values in the 'results' dictionary.
identical_keys : list[str] | None; default None
- The keys in 'results' which are identical across channels and for
which only one copy is present.
discard_keys : list[str] | None; default None
- The keys which should be discarded immediately without
processing.
allow_missing : bool; default False
- Whether or not to allow new rows to be present in the merged results
with NaN values for columns not shared between the results being
merged if the shared columns do not have matching values.
- I.e. if you want to make sure you are merging results from the same
channels, set this to False, otherwise results from different
channels will be merged and any missing information will be set to
NaN.
"""
new_results = sort_inputs_results(
results=new_results,
extract_from_dicts=extract_from_dicts,
identical_keys=identical_keys,
discard_keys=discard_keys,
verbose=self._verbose,
)
new_results = dict_to_df(obj=new_results)
self._check_keys_before_merge(new_results=new_results)
current_results, new_results = self._make_results_mergeable(
results_1=self._results, results_2=new_results
)
if not allow_missing:
self._check_missing_before_merge(
results_1=current_results, results_2=new_results
)
merged_results = pd.merge(current_results, new_results, how="outer")
self._results = self._restore_results_after_merge(
results=merged_results
)
def merge_from_df(
self,
new_results: pd.DataFrame,
allow_missing: bool = False,
) -> None:
"""Merges a dictionary of results to the results stored in the
PostProcess object.
- Cannot be called after frequency band results have been computed.
PARAMETERS
----------
new_results : pandas DataFrame
- A DataFrame containing results to add.
allow_missing : bool; default False
- Whether or not to allow new rows to be present in the merged results
with NaN values for columns not shared between the results being
merged if the shared columns do not have matching values.
- I.e. if you want to make sure you are merging results from the same
channels, set this to False, otherwise results from different
channels will be merged and any missing information will be set to
NaN.
"""
self._check_keys_before_merge(new_results=new_results)
current_results, new_results = self._make_results_mergeable(
results_1=self._results, results_2=new_results
)
if not allow_missing:
self._check_missing_before_merge(
results_1=current_results, results_2=new_results
)
merged_results = pd.merge(current_results, new_results, how="outer")
self._results = self._restore_results_after_merge(
results=merged_results
)
def _populate_columns(
self,
attributes: list[str],
fill: Optional[Any] = None,
) -> None:
"""Creates placeholder columns to add to the results DataFrame.
PARAMETERS
----------
attributes : list[str]
- Names of the columns to add.
fill : Any; default None
- Placeholder values in the columns.
"""
for attribute in attributes:
self._results[attribute] = [deepcopy(fill)] * len(
self._results.index
)
def _refresh_desc_measures(self, keys: list[str]) -> None:
"""Refreshes a list of the descriptive measures (e.g. variability
measures such as standard error of the mean) that need to be
re-calculated after any processing steps (e.g. averaging) are applied.
PARAMETERS
----------
keys : list of str
- Attributes of the data which are being processed and which will
have the number of events the values are derived from added to the
results.
"""
present_desc_measures = []
all_measures = [
*self._process_measures,
*self._var_measures,
]
all_desc_measures = [
*self._desc_process_measures,
*self._desc_var_measures,
]
for measure in all_measures:
if measure in all_desc_measures:
present_desc_measures.append(measure)
for key in keys:
present_desc_measures.append(f"{key}_n")
self._desc_measures = np.unique(present_desc_measures).tolist()
def _prepare_var_measures(
self,
measures: list[str],
idcs: list[list[int]],
keys: list[str],
) -> None:
"""Prepares for the calculation of variabikity measures, checking that
the required attributes are present in the data (adding them if not)
and checking that the requested measure is supported.
PARAMETERS
----------
measures : list[str]
- Types of measures to compute.
- Supported types are: 'std' for standard deviation; and 'sem' for
standard error of the mean.
idcs : list[list[int]]
- List containing sublists of indices for the data that has been
grouped and processed together.
keys : list[str]
- Attributes of the results to calculate variability measures for.
RAISES
------
UnavailableProcessingError
- Raised if a requested variability measure is not supported.
"""
supported_measures = ["std", "sem", "ci_"]
for measure in measures:
if measure[:3] == "ci_":
ci_percent = int(measure[3:])
if ci_percent <= 0 or ci_percent > 100:
raise ValueError(
"Confidence interval percentages must be > 0 and "
"<= 100."
)
elif measure not in supported_measures:
raise UnavailableProcessingError(
"Error when calculating variability measures of the "
f"averaged data:\nComputing the measure '{measure}' is "
"not supported. Supported measures are: "
f"{supported_measures}"
)
current_measures = np.unique([*self._var_measures, *measures]).tolist()
for measure in current_measures:
if measure[:3] == "ci_":
suffixes = ["_low", "_high"]
else:
suffixes = [""]
for key in keys:
for suffix in suffixes:
attribute_name = f"{key}_{measure}{suffix}"
if attribute_name not in self._results.keys():
self._populate_columns(attributes=[attribute_name])
else:
for group_idcs in idcs:
self._results.at[group_idcs[0], attribute_name] = (
None
)
def _reset_var_measures(
self,
idcs: list[list[int]],
keys: list[str],
) -> None:
"""Resets the values of variability measures for data that has been
processed to 'None'.
PARAMETERS
----------
idcs : list[list[int]]
- List containing sublists of indices for the data that has been
grouped and processed together.
keys : list[str]
- Attributes of the results to calculate variability measures for.
"""
for measure in self._var_measures:
if measure[:3] == "ci_":
suffixes = ["_low", "_high"]
else:
suffixes = [""]
for key in keys:
for suffix in suffixes:
for group_idcs in idcs:
self._results.at[
group_idcs[0], f"{key}_{measure}{suffix}"
] = None
def _compute_var_measures_over_nodes(
self,
measures: list[str],
idcs: list[list[int]],
keys: list[str],
) -> None:
"""Computes the variability measures over nodes in the results.
PARAMETERS
----------
measures : list[str]
- Types of variabilty measures to compute.
- Supported types are: 'std' for standard deviation; and 'sem' for
standard error of the mean.
idcs: list[list[int]]
- Unique indices of nodes in the results that should be processed.
keys : list[str]
- Attributes of the results to calculate variability measures for.
"""
self._prepare_var_measures(
measures=measures,
idcs=idcs,
keys=keys,
)
for measure in measures:
for key in keys:
results_name = f"{key}_{measure}"
for group_idcs in idcs:
if len(group_idcs) > 1:
entries = self._results.loc[group_idcs, key].tonumpy()
if measure == "std":
value = np.std(entries, axis=0).tolist()
elif measure == "sem":
value = stats.sem(entries, axis=0).tolist()
self._results.at[idcs[0], results_name] = value
self._var_measures = np.unique(
[*self._var_measures, *measures]
).tolist()
self._refresh_desc_measures(keys)
if self._verbose:
print(
"Computing the following variability measures on attributes "
"for the processed data over nodes:\n- Variability measure(s): "
f"{measures}\n- On attribute(s): {keys}\n"
)
def _compute_var_measures_within_nodes(
self,
measures: list[str],
idcs: list[int],
keys: list[str],
dimension: str,
axis_of_dimension: np.ndarray,
) -> None:
"""Computes the variability measures over dimensions within in each
node of the results.
PARAMETERS
----------
measures : list[str]
- Types of variabilty measures to compute.
- Supported types are: 'std' for standard deviation; and 'sem' for
standard error of the mean.
idcs : list[int]
- Unique indices of nodes in the results that should be processed.
keys : list[str]
- Attributes of the results to calculate variability measures for.
dimension : str
- The dimension which variability is being computed over.
axis_of_dimension: numpy ndarray
- The axis of the data to compute variability over with shape
[len('process_entry_idcs') x len('process_keys')], giving an axis
to compute variability over for each entry being processed.
"""
self._prepare_var_measures(
measures=measures,
idcs=[[idx] for idx in idcs],
keys=keys,
)
append_measures = []
for measure in measures:
if measure[:3] == "ci_":
append_measures.append(f"{measure}_low")
append_measures.append(f"{measure}_high")
else:
append_measures.append(measure)
for key_i, key in enumerate(keys):
results_name = f"{key}_{measure}"
for idx_i, idx in enumerate(idcs):
axis = axis_of_dimension[idx_i, key_i]
entries = np.array(self._results.loc[idx, key])
already_added = False
if entries.shape[axis] > 1:
if measure == "std":
value = np.std(entries, axis=axis).tolist()
elif measure == "sem":
value = stats.sem(entries, axis=axis).tolist()
elif measure[:3] == "ci_":
value = self._compute_cis(
entries,
alpha=int(measure[3:]) / 100,
axis=axis,
)
self._results.at[idx, f"{results_name}_low"] = (
value[0]
)
self._results.at[idx, f"{results_name}_high"] = (
value[1]
)
already_added = True
if not already_added:
self._results.at[idx, results_name] = value
self._var_measures = np.unique(
[*self._var_measures, *append_measures]
).tolist()
self._refresh_desc_measures(keys)
if self._verbose:
print(
"Computing the following variability measures on attributes "
f"for the processed data within node dimension {dimension}:\n- "
f"Variability measure(s): {measures}\n- On attribute(s): "
f"{keys}\n"
)
def _compute_cis(
self, data: np.ndarray, alpha: int, axis: int
) -> np.ndarray:
"""Compute confidence intervals
Parameters
----------
data : numpy ndarray
- The data to compute the confidence intervals for.
alpha : int
- The confidence level to compute the intervals for (between 0 and
1).
axis : int
- The axis of the data to compute the confidence intervals over.
Returns
-------
confidence_intervals : tuple
- Lower and upper confidence intervals, respectively.
"""
return stats.t.interval(
alpha=alpha,
df=np.shape(data)[axis] - 1,
loc=np.mean(data, axis=axis),
scale=stats.sem(data, axis=axis),
)
def _get_eligible_idcs(self, eligible_entries: dict) -> list[int]:
"""Finds the entries with eligible values for processing.
PARAMETERS
----------
eligible_entries : dict | None
- Dictionary where the keys are attributes in the data and the values
are the values of the attributes which are considered eligible for
processing. If None, all entries are processed.
RETURNS
-------
eligible_idcs : list of int
- The rows of the results with values eligible for processing.
RAISES
------
TypeError
- Raised if 'eligible_entries' is not a dict and is not None.
"""
if eligible_entries is None:
eligible_idcs = np.arange(len(self._results)).tolist()
else:
if not isinstance(eligible_entries, dict):
raise TypeError(
"'eligible_entries' must be of type dict, not "
f"{type(eligible_entries)}."
)
eligible_idcs = []
for key, values in eligible_entries.items():
eligible_idcs.append(
get_eligible_idcs_list(
vals=self._results[key], eligible_vals=values
)
)
eligible_idcs = list(
set(eligible_idcs[0]).intersection(*eligible_idcs[1:])
)
return eligible_idcs
def _prepare_for_nongroup_method(
self, eligible_entries: Union[dict, None]
) -> list[int]:
"""Finds what data should be processed, and, if applicable, how that
data should be grouped in preparation for applying a processing method.
PARAMETERS
----------
eligible_entries : dict | None
- Dictionary where the keys are attributes in the data and the values
are the values of the attributes which are considered eligible for
processing. If None, all entries are processed.
RETURNS
-------
process_idcs : list[int]
- Indices of the data that should be processed.
"""
return self._get_eligible_idcs(eligible_entries)
def _prepare_for_group_method(
self,
method: str,
over_key: str,
data_keys: list[str],
group_keys: list[str],
eligible_entries: Union[dict, None],
identical_keys: list[str],
var_measures: list[str],
) -> list[list[int]]:
"""Finds the indices of results that should be grouped and processed
together.
PARAMETERS
----------
method : str
- Type of processing to apply, e.g. 'average', 'subtract'.
over_key : str
- Name of the attribute in the results to process over.
data_keys : list[str]
- Names of the attributes in the results containing data that should
be processed, and any variability measures computed on.
group_keys : [list[str]]
- Names of the attributes in the results to use to group results that
will be processed.
eligible_entries : dict | None
- Dictionary where the keys are attributes in the data and the values
are the values of the attributes which are considered eligible for
processing. If None, all entries are processed.
identical_keys : list[str]
- The names of the attributes in the results that will be checked if
they are identical across the results being processed. If they are
not identical, an error will be raised.
var_measures : list[str]
- Names of measures of variability to be computed alongside the
processing of the results.
- Supported measures are: 'std' for standard deviation; and 'sem' for
standard error of the mean.
RETURNS
-------
group_idcs : list[list[int]]
- A list of sublists corresponding to each group containing the
indices of results to process together.
RAISES
------
ValueError
- Raised if the 'over_key' attribute is present in the 'group_keys' or
'identical_keys'.
"""
if group_keys is not None and over_key in group_keys:
raise ValueError(
"The attribute being processed over cannot be a member of the "
"attributes used for grouping results."
)
if identical_keys is not None and over_key in identical_keys:
raise ValueError(
"The attribute being processed over cannot be a member of the "
"attributes marked as identical."
)
if self._verbose:
if eligible_entries is None:
eligible_entries_msg = "all entries"
else:
eligible_entries_msg = eligible_entries
print(
f"Applying the method {method} for groups of results:\n"
f"{method}-over attribute: {over_key}\n{method}-over attribute "
f"with value(s): {eligible_entries_msg}.\nData attribute(s): "
f"{data_keys}\nGrouping attribute(s): {group_keys}\nCheck "
f"identical across results attribute(s): {identical_keys}\n"
f"Variability measure(s): {var_measures}\n"
)
self._refresh_desc_measures(data_keys)
eligible_idcs = self._get_eligible_idcs(eligible_entries)
combined_vals = combine_col_vals_df(
dataframe=self._results,
keys=group_keys,
idcs=eligible_idcs,
special_vals={"avg[": "avg_"},
)
group_idcs, _ = get_group_idcs(
vals=combined_vals, replacement_idcs=eligible_idcs
)
if identical_keys is not None:
check_vals_identical_df(
dataframe=self._results,
keys=identical_keys,
idcs=group_idcs,
)
return group_idcs
def average_over_nodes(
self,
over_key: str,
data_keys: list[str],
group_keys: list[str],
eligible_entries: Union[dict, None] = None,
identical_keys: Union[list[str], None] = None,
ignore_nan: bool = True,
var_measures: Union[list[str], None] = None,
) -> None:
"""Averages results over nodes in the data.
PARAMETERS
----------
over_key : str
- Name of the attribute in the results to average over.
data_keys : list[str]
- Names of the attributes in the results containing data that should
be averaged, and any variability measures computed on.
group_keys : [list[str]]
- Names of the attributes in the results to use to group results that
will be averaged over.
eligible_entries : dict | None; default None
- Dictionary where the keys are attributes in the data and the values
are the values of the attributes which are considered eligible for
processing. If None, all entries are processed.
identical_keys : list[str] | None; default None
- The names of the attributes in the results that will be checked if
they are identical across the results being averaged. If they are
not identical, an error will be raised.
ignore_nan : bool; default True
- Whether or not to ignore NaN values when averaging. If True, numpy's
nanmean method is used to compute the average, else numpy's mean
method is used.
var_measures : list[str] | None; default None
- Names of measures of variability to be computed alongside the
averaging of the results.
- Supported measures are: 'std' for standard deviation; and 'sem' for
standard error of the mean.
"""
group_idcs = self._prepare_for_group_method(
method="average_over_nodes",
over_key=over_key,
data_keys=data_keys,
eligible_entries=eligible_entries,
group_keys=group_keys,
identical_keys=identical_keys,
var_measures=var_measures,
)
if self._var_measures:
self._reset_var_measures(idcs=group_idcs, keys=data_keys)
if var_measures:
self._compute_var_measures_over_nodes(
measures=var_measures,
idcs=group_idcs,