forked from poldrack/pytest_tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtanalysis.py
77 lines (61 loc) · 2.11 KB
/
rtanalysis.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
"""example function to analyze reaction times
- given a data frame with RT and accuracy,
compute mean RT for correct trials and mean accuracy
"""
# %%
import pandas as pd
# %%
class RTAnalysis:
"""[summary]
"""
def __init__(self, outlier_cutoff_sd=None):
"""
RT analysis
Parameters:
-----------
outlier_cutoff_sd: standard deviation cutoff for long RT outliers (default: no cutoff)
"""
self.outlier_cutoff_sd = outlier_cutoff_sd
self.meanrt_ = None
self.meanacc_ = None
def fit(self, rt, accuracy, verbose=True):
"""[summary]
Args:
rt (Series of floats): response times for each trial
accuracy (Series of booleans): accuracy for each trial
"""
rt = self._ensure_series_type(rt)
accuracy = self._ensure_series_type(accuracy)
try:
assert rt.shape[0] == accuracy.shape[0]
except AssertionError:
raise ValueError('rt and accuracy must be the same length!')
# ensure that accuracy values are boolean
assert len(set(accuracy.unique()).difference([True, False])) == 0
if self.outlier_cutoff_sd is not None:
cutoff = rt.std() * self.outlier_cutoff_sd
if verbose:
print(f'outlier rejection excluded {(rt > cutoff).sum()} trials')
rt = rt.mask(rt > cutoff)
self.meanacc_ = accuracy.mean()
try:
assert self.meanacc_ > 0
except:
raise ValueError('accuracy is zero')
rt = rt.mask(~accuracy)
self.meanrt_ = rt.mean()
if verbose:
print(f'mean RT: {self.meanrt_}')
print(f'mean accuracy: {self.meanacc_}')
@staticmethod
def _ensure_series_type(var):
"""return variable as a pandas Series or raise exception if
not possible
Args:
var (array-like): variable to convert
Returns:
series (pandas Series): converted variable
"""
if type(var) is not pd.core.series.Series:
var = pd.Series(var)
return(var)