-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
1241 lines (1054 loc) · 55.8 KB
/
data.py
File metadata and controls
1241 lines (1054 loc) · 55.8 KB
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
# -*- coding: utf-8 -*-
"""
This module allows for the importing of participant data for use in fitting
:Author: Dominic Hunt
"""
import pickle
import scipy.io as io
import numpy as np
import pandas as pd
import os
import re
import collections
import utils
class LengthError(Exception):
pass
class IDError(Exception):
pass
class DimentionError(Exception):
pass
class FileTypeError(Exception):
pass
class FileError(Exception):
pass
class FoldersError(Exception):
pass
class ProcessingError(Exception):
pass
class FileFilterError(Exception):
pass
DATA_KEYWORDS = {"filename": "filename",
"ID": "participant_ID",
"folder": "folder"}
class Data(list):
@classmethod
def load_data(cls,
file_type='csv',
folders='./',
file_name_filter=None,
terminal_ID=True,
split_by=None,
participantID=None,
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
group_by=None,
extra_processing=None,
data_read_options=None):
"""
Import data from a folder. This is a wrapper function for the other import methods
Parameters
----------
file_type : string, optional
The file type of the data, from ``mat``, ``csv``, ``xlsx`` and ``pkl``. Default is ``csv``
folders : string or list of strings, optional
The folder or folders where the data can be found. Default is the current folder.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
split_by : string or list of strings, optional
If multiple participant datasets are in one file sheet, this specifies the column or columns that can
distinguish and identify the rows for each participant. Default ``None``
participantID : string, optional
The dict key where the participant ID can be found. Default ``None``, which results in the file name being
used.
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or None or one element list with a list, optional
If a string or list of strings these are treated as dict keys where the valid actions for each trial can
be found. If None then all trials will use all available actions. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
group_by : list of strings, optional
A list of parts of filenames that are repeated across participants, identifying all the files that should
be grouped together to form one participants data. The rest of the filename is assumed to identify the
participant. Default is ``None``
extra_processing : callable, optional
A function that modifies the dictionary of data read for each participant in such that it is appropriate
for fitting. Default is ``None``
data_read_options : dict, optional
The keyword arguments for the data importing method chosen
Returns
-------
Data : Data class instance
"""
if isinstance(folders, str):
folder_list = [folders]
elif isinstance(folders, list):
folder_list = folders
else:
raise FoldersError('``folders`` must be a string or a list of strings. Found {}'.format(type(folders)))
dat = None
for folder in folder_list:
if file_type == 'mat':
subdat = cls.from_mat(folder=folder,
file_name_filter=file_name_filter,
terminal_ID=terminal_ID,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options,
group_by=group_by,
extra_processing=extra_processing)
elif file_type == 'csv':
subdat = cls.from_csv(folder=folder,
file_name_filter=file_name_filter,
terminal_ID=terminal_ID,
split_by=split_by,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options,
group_by=group_by,
extra_processing=extra_processing,
csv_read_options=data_read_options)
elif file_type == 'xlsx':
subdat = cls.from_xlsx(folder=folder,
file_name_filter=file_name_filter,
terminal_ID=terminal_ID,
split_by=split_by,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options,
group_by=group_by,
extra_processing=extra_processing,
xlsx_read_options=data_read_options)
elif file_type == 'pkl':
subdat = cls.from_pkl(folder=folder,
file_name_filter=file_name_filter,
terminal_ID=terminal_ID,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options,
group_by=group_by,
extra_processing=extra_processing)
else:
raise FileTypeError('{} is not a supported file type. Please use ``mat``, ``csv``, ``xlsx`` or ``pkl``'.format(file_type))
if dat is None:
dat = subdat
else:
dat.extend(subdat)
return dat
@classmethod
def from_mat(cls,
folder='./',
file_name_filter=None,
terminal_ID=True,
participantID=None,
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
group_by=None,
extra_processing=None):
"""
Import data from a folder full of .mat files, where each file contains the information of one participant
Parameters
----------
folder : string, optional
The folder where the data can be found. Default is the current folder.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
participantID : string, optional
The dict key where the participant ID can be found. Default ``None``, which results in the file name being
used.
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or None or one element list with a list, optional
If a string or list of strings these are treated as dict keys where the valid actions for each trial can
be found. If None then all trials will use all available actions. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
group_by : list of strings, optional
A list of parts of filenames that are repeated across participants, identifying all the files that should
be grouped together to form one participants data. The rest of the filename is assumed to identify the
participant. Default is ``None``
extra_processing : callable, optional
A function that modifies the dictionary of data read for each participant in such that it is appropriate
for fitting. Default is ``None``
Returns
-------
Data : Data class instance
See Also
--------
scipy.io.loadmat
"""
folder_path = cls.__folder_path_cleaning(folder)
files, file_IDs = cls.__locate_files(folder_path, "mat", file_name_filter=file_name_filter, terminal_ID=terminal_ID)
participant_data = []
for f, i in zip(files, file_IDs):
file_data = {DATA_KEYWORDS['filename']: f,
DATA_KEYWORDS['folder']: folder_path}
if participantID is None:
file_data[DATA_KEYWORDS['ID']] = i
mat = io.loadmat(folder_path + f, struct_as_record=False, squeeze_me=True)
for key, value in mat.items():
if key[0:2] == "__":
continue
elif type(value) == io.matlab.mio5_params.mat_struct:
data_structure = {s: getattr(value, s) for s in value._fieldnames}
file_data.update(data_structure)
else:
file_data[key] = value
participant_data.append(file_data)
if participantID is None:
participantID = DATA_KEYWORDS['ID']
participant_processed_data = cls.__clean_data(participant_data,
extra_processing=extra_processing,
group_by=group_by)
return cls(participant_processed_data,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options)
@classmethod
def from_csv(cls,
folder='./',
file_name_filter=None,
terminal_ID=True,
split_by=None,
participantID=None,
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
group_by=None,
extra_processing=None,
csv_read_options=None):
"""
Import data from a folder full of .csv files, where each file contains the information of one participant
Parameters
----------
folder : string, optional
The folder where the data can be found. Default is the current folder.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
split_by : string or list of strings, optional
If multiple participants datasets are in one file sheet, this specifies the column or columns that can
distinguish and identify the rows for each participant. Default ``None``
participantID : string, optional
The dict key where the participant ID can be found. Default ``None``, which results in the file name being
used.
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or None or one element list with a list, optional
If a string or list of strings these are treated as dict keys where the valid actions for each trial can
be found. If None then all trials will use all available actions. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
group_by : list of strings, optional
A list of parts of filenames that are repeated across participants, identifying all the files that should
be grouped together to form one participants data. The rest of the filename is assumed to identify the
participant. Default is ``None``
extra_processing : callable, optional
A function that modifies the dictionary of data read for each participant in such that it is appropriate
for fitting. Default is ``None``
csv_read_options : dict, optional
The keyword arguments for pandas.read_csv. Default ``{}``
Returns
-------
Data : Data class instance
See Also
--------
pandas.read_csv
"""
folder_path = cls.__folder_path_cleaning(folder)
files, file_IDs = cls.__locate_files(folder_path, "csv", file_name_filter=file_name_filter,
terminal_ID=terminal_ID)
if split_by is None:
split_by = []
elif isinstance(split_by, str):
split_by = [split_by]
elif isinstance(split_by, (list, np.ndarray)):
for s in split_by:
if not isinstance(s, str):
raise TypeError('A split_by list should only contain strings. Found {}'.format(type(s)))
else:
raise TypeError('split_by should be a string or a list of strings. Found {}'.format(type(split_by)))
if csv_read_options is None:
csv_read_options = {}
participant_data = []
participantID_changed = False
for filename, fileID in zip(files, file_IDs):
dat = pd.read_csv(folder_path + filename, **csv_read_options)
if split_by:
classifier_list = []
for s in split_by:
try:
dat[s].fillna(method='ffill', inplace=True)
except KeyError as err:
raise KeyError('Data split by contains a column that does not exist: ``{}``'.format(s))
if dat[s].dtype in [np.dtype('int64'), np.dtype('float64')]:
sSorted = sorted(list(set(dat[s])))
classifier_list.append(sSorted)
else:
classifier_list.append(cls.__sort_strings(list(set(dat[s])), ''))
participants = utils.listMerge(*classifier_list)
for p in participants:
sub_dat = dat[(dat[split_by] == p).all(axis=1)]
sub_dat_dict = sub_dat.to_dict(orient='list')
sub_dat_dict[DATA_KEYWORDS['filename']] = filename
sub_dat_dict[DATA_KEYWORDS['folder']] = folder_path
if participantID is None or participantID == split_by[0]:
participantID_changed = True
if len(p) > 1:
sub_dat_dict[DATA_KEYWORDS['ID']] = "-".join([str(pi) for pi in p])
else:
sub_dat_dict[DATA_KEYWORDS['ID']] = p[0]
participant_data.append(sub_dat_dict)
else:
dat_dict = dat.to_dict(orient='list')
dat_dict[DATA_KEYWORDS['filename']] = filename
dat_dict[DATA_KEYWORDS['folder']] = folder_path
if participantID is None:
dat_dict[DATA_KEYWORDS['ID']] = fileID
participantID_changed = True
elif participantID in dat_dict and isinstance(dat_dict[participantID], (list, np.ndarray)):
if utils.list_all_equal(dat_dict[participantID]):
dat_dict[DATA_KEYWORDS['ID']] = dat_dict[participantID][0]
participantID_changed = True
else:
raise TypeError("participantID's column, {}, had more than one value".format(participantID))
participant_data.append(dat_dict)
if participantID_changed:
participantID = DATA_KEYWORDS['ID']
participant_processed_data = cls.__clean_data(participant_data,
extra_processing=extra_processing,
group_by=group_by)
return cls(participant_processed_data,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options)
@classmethod
def from_xlsx(cls,
folder='./',
file_name_filter=None,
terminal_ID=True,
split_by=None,
participantID=None,
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
group_by=None,
extra_processing=None,
xlsx_read_options=None):
"""
Import data from a folder full of .xlsx files, where each file contains the information of one participant
Parameters
----------
folder : string, optional
The folder where the data can be found. Default is the current folder.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
split_by : string or list of strings, optional
If multiple participants datasets are in one file sheet, this specifies the column or columns that can
distinguish and identify the rows for each participant. Default ``None``
participantID : string, optional
The dict key where the participant ID can be found. Default ``None``, which results in the file name being
used.
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or None or one element list with a list, optional
If a string or list of strings these are treated as dict keys where the valid actions for each trial can
be found. If None then all trials will use all available actions. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
group_by : list of strings, optional
A list of parts of filenames that are repeated across participants, identifying all the files that should
be grouped together to form one participants data. The rest of the filename is assumed to identify the
participant. Default is ``None``
extra_processing : callable, optional
A function that modifies the dictionary of data read for each participant in such that it is appropriate
for fitting. Default is ``None``
xlsx_read_options : dict, optional
The keyword arguments for pandas.read_excel
Returns
-------
Data : Data class instance
See Also
--------
pandas.read_excel
"""
folder_path = cls.__folder_path_cleaning(folder)
files, file_IDs = cls.__locate_files(folder_path, "xlsx", file_name_filter=file_name_filter,
terminal_ID=terminal_ID)
if split_by is None:
split_by = []
elif isinstance(split_by, str):
split_by = [split_by]
elif isinstance(split_by, (list, np.ndarray)):
for s in split_by:
if not isinstance(s, str):
raise TypeError('A split_by list should only contain strings. Found {}'.format(type(s)))
else:
raise TypeError('split_by should be a string or a list of strings. Found {}'.format(type(split_by)))
if xlsx_read_options is None:
xlsx_read_options = {}
participant_data = []
participantID_changed = False
for filename, fileID in zip(files, file_IDs):
# In case the file is open, this will in fact be a temporary file and not a valid file.
if filename.startswith('~$'):
continue
dat = pd.read_excel(folder_path + filename, **xlsx_read_options)
if split_by:
classifier_list = []
for s in split_by:
try:
dat[s].fillna(method='ffill', inplace=True)
except KeyError as err:
raise KeyError('Data split by contains a column that does not exist: ``{}``'.format(s))
if dat[s].dtype in [np.dtype('int64'), np.dtype('float64')]:
sSorted = sorted(list(set(dat[s])))
classifier_list.append(sSorted)
else:
classifier_list.append(cls.__sort_strings(list(set(dat[s])), ''))
participants = utils.listMerge(*classifier_list)
for p in participants:
sub_dat = dat[(dat[split_by] == p).all(axis=1)]
sub_dat_dict = sub_dat.to_dict(orient='list')
sub_dat_dict[DATA_KEYWORDS['filename']] = filename
sub_dat_dict[DATA_KEYWORDS['folder']] = folder_path
if participantID is None or participantID == split_by[0]:
participantID_changed = True
if len(p) > 1:
sub_dat_dict[DATA_KEYWORDS['ID']] = "-".join([str(pi) for pi in p])
else:
sub_dat_dict[DATA_KEYWORDS['ID']] = p[0]
participant_data.append(sub_dat_dict)
else:
dat_dict = dat.to_dict(orient='list')
dat_dict[DATA_KEYWORDS['filename']] = filename
dat_dict[DATA_KEYWORDS['folder']] = folder_path
if participantID is None:
dat_dict[DATA_KEYWORDS['ID']] = fileID
participantID_changed = True
elif participantID in dat_dict and isinstance(dat_dict[participantID], (list, np.ndarray)):
if utils.list_all_equal(dat_dict[participantID]):
dat_dict[DATA_KEYWORDS['ID']] = dat_dict[participantID][0]
participantID_changed = True
else:
raise TypeError("participantID's column, {}, had more than one value".format(participantID))
participant_data.append(dat_dict)
if participantID_changed:
participantID = DATA_KEYWORDS['ID']
participant_processed_data = cls.__clean_data(participant_data,
extra_processing=extra_processing,
group_by=group_by)
return cls(participant_processed_data,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options)
@classmethod
def from_pkl(cls,
folder='./',
file_name_filter=None,
terminal_ID=True,
participantID=None,
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
group_by=None,
extra_processing=None):
"""
Import data from a folder full of .pkl files, where each file contains the information of one participant.
This will principally be used to import data stored by task simulations
Parameters
----------
folder : string, optional
The folder where the data can be found. Default is the current folder.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
participantID : string, optional
The dict key where the participant ID can be found. Default ``None``, which results in the file name being
used.
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or None or one element list with a list, optional
If a string or list of strings these are treated as dict keys where the valid actions for each trial can
be found. If None then all trials will use all available actions. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
group_by : list of strings, optional
A list of parts of filenames that are repeated across participants, identifying all the files that should
be grouped together to form one participants data. The rest of the filename is assumed to identify the
participant. Default is ``None``
extra_processing : callable, optional
A function that modifies the dictionary of data read for each participant in such that it is appropriate
for fitting. Default is ``None``
Returns
-------
Data : Data class instance
"""
folder_path = cls.__folder_path_cleaning(folder)
files, file_IDs = cls.__locate_files(folder_path, "pkl", file_name_filter=file_name_filter,
terminal_ID=terminal_ID)
participant_data = []
for filename, fileID in zip(files, file_IDs):
with open(folder_path + filename, 'rb') as o:
dat = pickle.load(o)
if not isinstance(dat, dict):
raise TypeError("Data coming from ``.pkl`` files expected to be dictionaries. Found {}".format(type(dat)))
dat[DATA_KEYWORDS['filename']] = filename
dat[DATA_KEYWORDS['folder']] = folder_path
file_data = {k: v for k, v in dat.items()}
if participantID is None:
file_data[DATA_KEYWORDS['ID']] = fileID
participant_data.append(file_data)
if participantID is None:
participantID = DATA_KEYWORDS['ID']
participant_processed_data = cls.__clean_data(participant_data,
extra_processing=extra_processing,
group_by=group_by)
return cls(participant_processed_data,
participantID=participantID,
choices=choices,
feedbacks=feedbacks,
stimuli=stimuli,
action_options=action_options)
def __init__(self,
participants,
participantID='ID',
choices='actions',
feedbacks='feedbacks',
stimuli=None,
action_options=None,
process_data_function=None):
"""
Parameters
----------
participants : list of dict
Each dictionary contains the information for one participant
participantID : string, optional
The dict key where the participant ID can be found. Default ``ID``
choices : string, optional
The dict key where the participant choices can be found. Default ``'actions'``
feedbacks : string, optional
The dict key where the feedbacks the participant received can be found. Default ``'feedbacks'``
stimuli : string or list of strings, optional
The dict keys where the stimulus cues for each trial can be found. Default ``'None'``
action_options : string or list of strings or one element list with a list, optional
The dict keys where the valid actions for each trial can be found as a single key or list of keys.
If ``None`` then the action list is considered to stay constant. If the list contains one list then it will
be treated as a list of valid actions for each trialstep. Default ``'None'``
"""
self.process_function = process_data_function
if callable(process_data_function):
participant_data = process_data_function(participants)
elif isinstance(process_data_function, str):
pass
else:
participant_data = participants
if not isinstance(participantID, str):
raise TypeError('participantID should be a string not a {}'.format(type(participantID)))
if not isinstance(choices, str):
raise TypeError('choices should be a string not a {}'.format(type(choices)))
if not isinstance(feedbacks, str):
raise TypeError('feedbacks should be a string not a {}'.format(type(feedbacks)))
if stimuli is None or isinstance(stimuli, str):
combining_stimuli = False
elif isinstance(stimuli, list):
combining_stimuli = True
if not all(isinstance(s, str) for s in stimuli):
raise TypeError('stimuli in the list should be strings: {}'.format(stimuli))
else:
raise TypeError('stimuli should be a string or list of strings not a {}'.format(type(stimuli)))
if action_options is None or isinstance(action_options, str):
combining_action_options = False
elif isinstance(action_options, (list, np.ndarray)):
if all(isinstance(s, str) for s in action_options):
combining_action_options = True
elif len(action_options) == 1:
combining_action_options = False
else:
raise TypeError('The list of action_options should contain strings or one example of trial valid action choices: {}'.format(action_options))
else:
raise TypeError('action_options should be a string, a list of strings or a list containing one example of trial valid action choices, not a {}'.format(type(action_options)))
self.IDs = {}
for loc, p in enumerate(participant_data):
if not isinstance(p, dict):
raise TypeError("participants must be in the form of a dict, not {}".format(type(p)))
keys = list(p.keys())
if participantID not in keys:
raise KeyError("participantID key not found in participant data: `{}`".format(participantID))
elif not isinstance(p[participantID], str):
raise TypeError("participantID value must be a string. Found {}".format(type(p[participantID])))
elif p[participantID] in self.IDs:
raise IDError("participantID must be unique. Found more than one instance of `{}`".format(p[participantID]))
else:
self.participantID = participantID
self.IDs[p[participantID]] = loc
if choices not in keys:
raise KeyError("choices key not found in participant {} data: `{}`".format(p[participantID], choices))
elif not isinstance(p[choices], (list, np.ndarray)):
raise TypeError("choices value must be a list or numpy array. Found {} in {}".format(type(p[choices]), p[participantID]))
else:
self.choices = choices
if feedbacks not in keys:
raise KeyError("feedbacks key not found in participant {} data: `{}`".format(p[participantID], feedbacks))
elif not isinstance(p[feedbacks], (list, np.ndarray)):
raise TypeError("feedbacks value must be a list or numpy array. Found {} in {}".format(type(p[feedbacks]), p[participantID]))
else:
self.feedbacks = feedbacks
if len(p[choices]) != len(p[feedbacks]):
raise LengthError('The number of values for choices and feedbacks must be the same: {} choices and {} feedbacks for participant `{}`'.format(len(p[choices]), len(p[feedbacks]), p[participantID]))
if not combining_stimuli:
if stimuli is None:
self.stimuli = None
elif stimuli not in keys:
raise KeyError("stimuli key not found in participant {} data: `{}`".format(p[participantID], stimuli))
elif not isinstance(p[stimuli], (list, np.ndarray)):
raise TypeError("stimuli value must be a list or numpy array. Found {} in {}".format(type(p[stimuli]), p[participantID]))
else:
self.stimuli = stimuli
else:
if not set(stimuli).issubset(set(keys)):
raise KeyError("stimuli keys not found in participant {} data: `{}`".format(p[participantID], stimuli))
cues_list = [np.array(p[s])[:, np.newaxis] for s in stimuli]
try:
cues_array = np.hstack(cues_list)
except ValueError as error:
if all([True if len(a.shape) == 2 else False for a in cues_list]):
# I did not expect this
raise error
else:
raise DimentionError("If you are using separate keys for each stimulus cue, they must all be 1D lists")
stimuli_combined_name = "cues_combined"
if stimuli_combined_name in keys:
raise KeyError("Unexpected use of key `{}`. Use other name".format(stimuli_combined_name))
p[stimuli_combined_name] = cues_array
self.stimuli = stimuli_combined_name
if stimuli and len(p[choices]) != len(p[self.stimuli]):
raise LengthError('The number of values for choices and stimuli must be the same: {} choices and {} stimuli for participant `{}`'.format(len(p[choices]), len(p[self.stimuli]), p[participantID]))
if not combining_action_options:
if action_options is None:
self.action_options = None
elif isinstance(action_options, (list, np.ndarray)) and len(action_options) == 1:
action_options_constant_name = 'constant_valid_actions'
participant_data[loc][action_options_constant_name] = [action_options[0]] * len(p[choices])
self.action_options = action_options_constant_name
elif action_options not in keys:
raise KeyError("action_options key not found in participant {} data: `{}`".format(p[participantID], action_options))
elif not isinstance(p[action_options], (list, np.ndarray)):
raise TypeError("action_options value must be a list or numpy array. Found {} in {}".format(type(p[action_options]), p[participantID]))
else:
self.action_options = action_options
else:
if not set(action_options).issubset(set(keys)):
raise KeyError("action_options keys not found in participant {} data: {}".format(p[participantID], action_options))
options_list = [np.array(p[a])[:, np.newaxis] for a in action_options]
try:
options_array = np.hstack(options_list)
except ValueError as error:
if all([True if len(a.shape) == 2 else False for a in options_list]):
# I did not expect this
raise error
else:
raise DimentionError(
"If you are using separate keys for each action option, they must all be 1D lists")
action_options_combined_name = "valid_actions_combined"
if action_options_combined_name in keys:
raise KeyError("Unexpected use of key `{}`. Use other name".format(action_options_combined_name))
participant_data[loc][action_options_combined_name] = options_array
self.action_options = action_options_combined_name
if action_options and len(p[choices]) != len(p[self.action_options]) and len(action_options) > 1:
raise LengthError('The number of values for choices and valid actions must be the same: {} choices and {} action_options for participant `{}`'.format(len(p[choices]), len(p[self.action_options]), p[participantID]))
super(Data, self).__init__(participant_data)
def extend(self, iterable):
"""Combines two Data instances into one
Parameters
----------
iterable : Data instance or list of participant dicts
"""
if isinstance(iterable, Data):
if self.participantID != iterable.participantID:
raise AttributeError('participantID ``{}`` cannot be extended with ``{}``'.format(self.participantID, iterable.participantID))
if self.choices != iterable.choices:
raise AttributeError('choices ``{}`` cannot be extended with ``{}``'.format(self.choices, iterable.choices))
if self.feedbacks != iterable.feedbacks:
raise AttributeError('feedbacks ``{}`` cannot be extended with ``{}``'.format(self.feedbacks, iterable.feedbacks))
if self.stimuli != iterable.stimuli:
raise AttributeError('stimuli ``{}`` cannot be extended with ``{}``'.format(self.stimuli, iterable.stimuli))
if self.action_options != iterable.action_options:
raise AttributeError('action_options ``{}`` cannot be extended with ``{}``'.format(self.action_options, iterable.action_options))
if self.process_function != iterable.process_function:
raise AttributeError('process_function ``{}`` cannot be extended with ``{}``'.format(self.process_function, iterable.process_function))
IDs = self.IDs.copy()
number_IDs = len(IDs)
for i, (id_key, id_val) in enumerate(iterable.IDs.items()):
if id_key in IDs:
raise IDError("participantID must be unique. Found more than one instance of `{}`".format(id_key))
else:
self.IDs[id_key] = number_IDs + id_val
super(Data, self).extend(iterable)
else:
dat = Data(iterable,
participantID=self.participantID,
choices=self.choices,
feedbacks=self.feedbacks,
stimuli=self.stimuli,
action_options=self.action_options,
process_data_function=self.process_function
)
self.extend(dat)
def __add__(self, y):
self.extend(y)
def __eq__(self, other):
if not isinstance(other, Data):
return False
eq_list = []
for item1, item2 in zip(self, other):
if any(item1.keys() != item2.keys()):
eq_list.append(False)
elif any(item1.values() != item2.values()):
eq_list.append(False)
else:
eq_list.append(True)
if len(eq_list) == 0:
return True
else:
return eq_list
def __ne__(self, other):
return not self.__eq__(other)
@staticmethod
def __folder_path_cleaning(folder):
folder_path = os.path.abspath(folder).replace('\\', '/')
if folder_path[-1] != '/':
folder_path += '/'
return folder_path
@classmethod
def __locate_files(cls, folder, file_type, file_name_filter=None, terminal_ID=True):
"""
Produces the list of valid input files
Parameters
----------
folder : string
The folder string should end in a ``/``
file_type : string
The file extension found after the ``.``.
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
terminal_ID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed.
Default ``True``
Returns
-------
dataFiles : list
A sorted list of the the files
fileIDs : list of strings
A list of unique parts of the filenames, in the order of dataFiles
See Also
--------
sortStrings : sorts the files found
"""
files = os.listdir(folder)
data_files = [f for f in files if f.endswith(file_type)]
valid_file_names = cls.__valid_files(data_files, file_name_filter=file_name_filter)
if not valid_file_names:
raise FileError('No data files found')
sorted_files, file_IDs = cls.__sort_strings(valid_file_names,
"." + file_type,
terminalID=terminal_ID,
return_IDs=True)
return sorted_files, file_IDs
@classmethod
def __valid_files(cls, data_files, file_name_filter=None):
"""
Take a list of file names in the folder and a filter function and returns the filtered list
Parameters
----------
data_files : list of strings
The list of file names without paths
file_name_filter : callable, string, list of strings or None, optional
A function to process the file names or a list of possible prefixes as strings or a single string.
Default ``None``, no file names removed
Returns
-------
valid_file_list : list of strings
A subset of the data_files
"""
if file_name_filter is None:
valid_file_list = data_files
elif callable(file_name_filter):
valid_file_list = file_name_filter(data_files)
elif isinstance(file_name_filter, str):
valid_file_list = cls.__file_prefix_filter(data_files, [file_name_filter])
elif isinstance(file_name_filter, (list, np.ndarray)):
valid_file_list = cls.__file_prefix_filter(data_files, file_name_filter)
else:
raise FileFilterError('Unrecognised data file filter {}', file_name_filter)
return valid_file_list
@classmethod
def __sort_strings(cls, unordered_list, suffix, terminalID=True, return_IDs=False):
"""
Takes an unordered list of strings and sorts them if possible and necessary
Parameters
----------
unordered_list : list of strings
A list of valid strings
suffix : string
A known suffix for the string
terminalID : bool, optional
Is there an ID number at the end of the filename? If not then a more general search will be performed. Default ``True``
return_IDs : bool, optional
Specify if the fileIDs should be returned. Default ``False``
Returns
-------
sortedList : list of strings
A sorted list of the the strings
fileIDs : list of strings
A list of unique parts of the filenames, in the order of dataFiles. Only returned if ``return_IDs=True``