-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract.R
1077 lines (899 loc) · 40.2 KB
/
abstract.R
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
# 20200630WF
# TODO:
# * trial 40 blink is weird
# * compare trial score to origianl for each
# * run interpolation and derv (est, fst) over whole?
# * better plotting
# 20200503WF - attempt to extract from complex mess I've made
# using parquet/arrow format for quick reads (maybe)
# library(arrow)
# ds <- read_parquet("./anti.parquet")
# encase return value with success/failure structure
# helpful when we need to bail out of a function because something broke
# 20200629 - is this better than `stop` and tryCatch?
r <- function(value=NULL, reason=NULL)
list(value=value,success=!is.null(value), reason=reason)
f <- function(reason) r(reason=reason)
#
# data pipeline:
# opts <- studysettings(): task and algo settings/options. passed everwhere.
# eyedf <- {read,clean}_data(): all raw data
# b.approx, interp_df/b.nona <- interp_samples(): blink exended and sike removed, nan's removed
# -- trial <- trial_sacs() --
# blinks <- find_blinks(): blink index info
# sac_df <- find_saccades(): where eye movement velocity excites expected
# <- sac_pos(): use expected position to "score" saccades
# make a list of variables and carry over those names
namedList <-function(...) { X_<-list(...); names(X_) <- unlist(substitute(...())); return(X_)}
studysettings <- function(...){
defaults <- list(
##LIKELY TO CHANGE (task)
# number of trials
expectedTrialLengths=c(48),
startcodes=c(32,34,35,36),
targetcodes=c(131,132,133,134),
stopcodes=c(250,254,255),
sac.time=1.45, # how long is the target up before we see the fixation cross again?
sac.majorRegionEnd=.75, # the useful saccades probably already occur
## XDAT functions -> trial info
# use xdat to get trial info
# what is the threshold for left/right position
# xdatCode is index for thesholds (1 -> right short, 2-> right long, 3->left short, 4->left long)
getExpPos=function(xdat) return(c(258, 172, 87, 2)[ xdat - 130 ] ),
# is this xdat an antisaccde xdat?
xdatIsAS=function(xdat) return(TRUE),
trialIsType=function(xdat) return('AS'),
## equipment - ASL eyetracker circa ~2000
# where is the middle of screen (fix location)
xmax=274,
ymax=250,
screen.x.mid=261/2, # ASL coordinate positions
sampleHz = 60,
## algo parameters
lat.fastest=67/1000, # seconds, fastests possible saccade
#minium distance to be considered a saccade
sac.minmag=10, # min abs of x position change -- set very low, inc to 20 at LR request :)
maxsamples=200, # more than this means we took more than we should have
# acceleration -- needs to be this many pixels per sample before considering saccade
lat.minvel=4, # ASLcoordx/60Hz
sac.slowvel=1, # ASLXcord/60Hz
# if there are spikes in fixation, bad tracking, drop
# 99 means don't worry about it
maxSamplesFromBaseline=99,
sac.padding=30, # padding to give to expected positions
xposStdDevMax = 40, # how unsmooth can interopolation be?
blink.mintimedrop=100/1000,
sac.minlen=42/1000, # saccades less than 50ms are merged/ignored
sac.held=100/1000, # if a sac is held -- it is accurate
sac.trackingtresh=0, # what percent of a sac has to have actual samples (tacked) to be counted, set to 0 to ignore
blink.trim.samples=2,
### Score settings
soipercent=F, # samples of interest percent missing (30%)
ignorexpossd=F, # poor tracking: sd of xpos Δ= 40
highvelstartok=F, # uses maxBeforeOnset
ignoreblinks=F,
blinkbeforeok=F,
dontcutspikes=F,
useextremefilter=F # any kill sammple if any dil, xpos, ypos are bad
)
changes <- list(...)
if(length(changes)>0L) return(modifyList(defaults, changes))
return(defaults)
}
drop_interp <- function(interp_xpos, base.val, opts) {
# okay fixation position?
if(is.nan(base.val) || abs(base.val - opts$screen.x.mid)>50) {
return(sprintf('average fixpos(%f) is off from baseline(%f)!', base.val, opts$screen.x.mid ))
}
xtime <- 1:length(interp_xpos)
# check tracking coverage for "samples of interest"
SOI.expect <- with(opts, (sac.majorRegionEnd - lat.fastest)*sampleHz)
SOI.actual <- length(which(xtime/opts$sampleHz < opts$sac.majorRegionEnd &
xtime/opts$sampleHz > opts$lat.fastest) )
if(SOI.actual < SOI.expect*.30 && !opts$soipercent) return('< 30% tracking for samples of interest')
# is there big movement before the start?
# don't do this for fix or anti (maxSamp... = 99, bars scanbars=2)
# 20200506 - previously used on uninterpoltaed data
onset_samples <- interp_xpos[1:(opts$lat.fastest*opts$sampleHz)]
averageChangeBeforePhysOnset <- abs(na.omit(onset_samples- base.val))
numtoofarfrombaseline <- length(which(averageChangeBeforePhysOnset > opts$sac.minmag ) )
if(numtoofarfrombaseline> maxSamplesFromBaseline) {
return(sprintf('%.0f samples > %.0f px (%.2f max) from %.2f (base)',
numtoofarfrombaseline,
max(averageChangeBeforePhysOnset),
sac.minmag,base.val))
}
# is tracking smooth?
# 20200506 - previously used on uninterpoltaed data
averageChange <- sd(abs(diff(na.omit(interp_xpos[3:max(opts$sac.majorRegionEnd*opts$sampleHz, length(interp_xpos))]))))
if(is.na(averageChange) || (averageChange > opts$xposStdDevMax && !opts$ignorexpossd) ) {
return(sprintf('poor tracking: sd of xpos Δ=%f',averageChange))
}
# target codes didn't match, we ate the whole file
# or way too many
# 200 might be too low of a threshold
if (length(interp_xpos ) > opts$maxsamples ) {
return(paste('too many samples in trial', dim(interp_xpos)[1]))
}
return(NA)
}
no_early_move <- function(ts, opts){
# opts$lat.fastest*opts$sampleHz
if(length(ts) > opts$lat.fastest*opts$sampleHz+1) stop('no_early_move given too long a timesies!')
if(any(is.na(ts))) return("blink at onset")
fst <- KernSmooth::locpoly(1:length(ts), ts, bandwidth=1, drv=1)
# catch movement before actual onset
# fst$x is in samples, we want the y value before the sample capturing closest time a sac can be made
# avoid points up to the first sample to all things to settle
# fst$x starts at 1, 1.9 is enough time to settle down from initial
maxBeforeOnset <- max(abs(fst$y[fst$x< opts$lat.fastest*opts$sampleHz & fst$x> 1.9]),na.rm=T)
# sac.slowvel is probably 1px/60Hz
# lat.minvel is probably 4px/60Hz
if(!opts$highvelstartok &&
(is.nan(maxBeforeOnset) ||
abs(maxBeforeOnset) == Inf ||
maxBeforeOnset > opts$lat.minvel)){
return(sprintf('moving (%.3f px/60Hz) before target onset', maxBeforeOnset))
}
return(NA)
}
find_blinks <- function(x, opts){
# find blink indexes (in actual sample space)
# x from b.approx$x
NArle <- rle(is.na(x))
NArlecs <- cumsum(NArle$lengths)/opts$sampleHz
actualblinkidx <- NArle$values==T & NArle$lengths/opts$sampleHz > opts$blink.mintimedrop
eyeidx.blinkstart <- NArlecs[which(actualblinkidx)-1]*opts$sampleHz
blinkends <- NArlecs[actualblinkidx]
if(length(blinkends)==0) blinkends <- Inf
# all the things we'll use later
namedList(NArlecs, actualblinkidx, eyeidx.blinkstart, blinkends)
}
# trial 40 error:
# onsets <- c(0.432125, 0.6263, 0.78120833, 0.97295833)
# blinks <- list(NArlecs = c(0.4, 0.65, 0.667, 1), actualblinkidx = c(TRUE, FALSE, FALSE, FALSE), eyeidx.blinkstart = numeric(0), blinkends = 0.4)
onset_blink <-function(onsets, blinks, opts) {
# if a sac starts with a blink, add that blink to the start
# NB!!! onsetidx, min and max are now incorrect!!!
if(opts$ignoreblinks) return(onsets)
sapply(onsets,
function(x){
a=x-blinks$blinkends
bidx=which(a<2/opts$sampleHz & a>0)
blink_offset <- blinks$NArlecs[which(blinks$actualblinkidx)-1]
newstart=blink_offset[bidx]
#TODO: newstart should be null if this change doesn't change x position
if(length(newstart)>0 && x-newstart < .5 )
return(newstart + opts$blink.trim.samples/opts$sampleHz )
# not in a blink, no reason to change
return(x)
})
}
# get accelration info from interopolated xposition
find_accels <- function(interp_xpos, opts, xtime=1:length(interp_xpos)){
# fit to local polynomial (with guassain kernel)
# 20200706 NB! gridsize defaults to 401. we want to get a consistant resolution.
# 60 is likely length of target area (orig input). 401/60 ~= 6.66
gs <- round(6.66*length(xtime)) +1
est <- KernSmooth::locpoly(xtime, interp_xpos, bandwidth=1, drv=0, gridsize=gs)
fst <- KernSmooth::locpoly(xtime, interp_xpos, bandwidth=1, drv=1, gridsize=gs)
# run length encode when the change in sacad postion is faster
# than the min velocity for a saccade
# ** First sacade attribute
rlePastDrv <- rle(abs(fst$y)>opts$lat.minvel & !is.na(fst$y))
delt.x <- cumsum(rlePastDrv$lengths)
# when does the direction change?
#nsamp <- length(fst$x)
#idxDirChange <- which( c(F, sign(fst$y[1:(nsamp-1)]) != sign(fst$y[2:nsamp]) ) )
# where they are moving, but less than requried for a saccade
slowpoints <-rle(abs(fst$y)< opts$sac.slowvel)
slowpntIdx <-cumsum(slowpoints$lengths)
# stages of motion
# where has the subject started to move, made an actual saccade, slowed down, and stopped moving
startUp <- slowpntIdx[slowpoints$values==T]
speedingUp <- delt.x[rlePastDrv$values==F]
slowingDown <- delt.x[rlePastDrv$values==T]
slowedDown <- slowpntIdx[slowpoints$values==F]
namedList(est, fst, startUp, speedingUp, slowingDown,slowedDown)
}
find_saccades <- function(accel, blinks, opts){
# 20200503 - init - copy of ScoreRun.R:getSacs
# how do those match up
sac.df <- data.frame(
# saccade started
onsetIdx = accel$speedingUp,
# find matching slowDowns
slowedIdx = sapply(accel$speedingUp, function(x) accel$slowingDown[which(x<accel$slowingDown)[1]]),
# find the first place they slow down after speeding up
endIdx = sapply(accel$speedingUp, function(x) accel$slowedDown[which(x<accel$slowedDown)[1]] ))
# remove saccades that haven't finished (end usually doesn't matter)
# could probably do the same thing by which(df$onset < sac.time)
noEndIdx <- which(is.na(sac.df$endIdx+sac.df$slowedIdx))
if(length(noEndIdx)>0) { sac.df <- sac.df[ -noEndIdx, ] }
nsacs <- dim(sac.df)[1]
if(nsacs==0L) stop("no saccades found!")
# actual time from target cue
# est$x is in 60Hz samples, but est indexes are not!
sac.df$onset = accel$est$x[sac.df$onsetIdx]/opts$sampleHz
sac.df$slowed = accel$est$x[sac.df$slowedIdx]/opts$sampleHz
sac.df$end = accel$est$x[sac.df$endIdx]/opts$sampleHz
# onsets start at start of blink if saccade over a blink
sac.df$onset_withblink <- sac.df$onset
sac.df$onset <- onset_blink(sac.df$onset, blinks, opts)
# fix overlapping saccades
sac.df <- fix_overlap(sac.df)
# position
sac.df$startpos = accel$est$y[sac.df$onsetIdx]
sac.df$endpos = accel$est$y[sac.df$endIdx]
sac.df <- cbind( sac.df,
plyr::ddply(sac.df,c('onsetIdx', 'endIdx'),function(x){
a=accel$est$y[x$onsetIdx:x$endIdx];
c(maxpos=max(a),minpos=min(a))}
)[,c('maxpos','minpos')]
)
# T/F saccade attributes
# direction, position, length(time), and before next fixation
if(nsacs>1){
sac.df$held = c(sac.df$onset[2:nsacs] - sac.df$end[1:(nsacs-1)] >= opts$sac.held, T)
} else {
sac.df$held = 1
}
sac.df$gtMinLen = sac.df$end - sac.df$onset > opts$sac.minlen
sac.df$intime = sac.df$onset < opts$sac.time & sac.df$end > opts$lat.fastest
# first clause of intime (within xdat, isn't needed)
sac.df$distance = sac.df$endpos - sac.df$startpos
slowcnt <- length(which(slowpntIdx<opts$sac.majorRegionEnd*opts$sampleHz))
# normal seems to be around 7
# 2 would be perfect (e.g. start going up, slow once at top)
if(slowcnt > 8) { cat("WARNING: unusual number of velc. changes",slowcnt ," poor tracking?\n") }
# 20200508 - reset onsetIdx and endIdx to be relative to actual samplerate
sac.df$onsetIdx <- round(accel$est$x[sac.df$onsetIdx])
sac.df$slowedIdx <- round(accel$est$x[sac.df$slowedIdx])
sac.df$endIdx <- round(accel$est$x[sac.df$endIdx])
return(sac.df)
}
fix_overlap <- function(sac.df) {
#####
##### OVERLAPS
#####
# for blink then overlap, see
# scannerbars.10128.20080925.3
# merge sacs that are too close together
## look for overlap, set end info of overlapping to first
## remove overlap
## may have trouble with many overlapping
overlapSac <- c(F, sac.df$onset[2:nsacs] - sac.df$end[1:(nsacs-1)] < 0)
if(nsacs<2) { overlapSac <- F}
# TODO: don't merge saccades that go opposite ways?
# ... & sign($endpos-$startpos) == sign($endpos-$startpos)
# ... end[2:nsacs] = start[1:(nsacs-1)]
#sac.df$combined <- overlapSac
if(any(overlapSac) ) {
overlapSac <- which(overlapSac)
# merge into one
#needReplaced <-c('slowedIdx','endIdx','slowed','end','combined')
#sac.df[overlapSac-1,needReplaced] <- sac.df[overlapSac, needReplaced]
#sac.df<-sac.df[-overlapSac,]
#nsacs<-dim(sac.df)[1]
# move end of first to beginning of second
endAttr <- c('endIdx','end')
startAttr <- c('onsetIdx','onset')
mid <- sac.df[overlapSac,startAttr]
sac.df[overlapSac-1, endAttr ] <- mid
sac.df$slowed[overlapSac-1] <- NA
sac.df[overlapSac, startAttr] <- mid
}
return(sac.df)
}
# quick way to see if blink is held
# if xpos is more than 5 px from any other
# return true or false for each blink onset idx
find_unheld_blinks <- function(blink_idx, blinks, opts) {
# before and after blink ( with a two samples give for blink junk)
samples <- round(opts$sac.held*opts$sampleHz)
if(blink_idx<samples) {
origIdxesBeforeBlink <- c()
} else {
origIdxesBeforeBlink <- blinks$eyeidx.blinkstart[blink_idx]+c(-samples:-1)
}
origIdxesAfterBlink <- blinks$blinkends[blink_idx]*opts$sampleHz+c(1:samples)
# 20200506 change from real data to interoplated
#position <- b.orig[c(origIdxesBeforeBlink,origIdxesAfterBlink) ,'blink_idx']
posittion <- ts[c(origIdxesBeforeBlink,origIdxesAfterBlink)]
cat(blinks$blinkends[blink_idx] - blinks$eyeidx.blinkstart[blink_idx]/opts$sampleHz,"\n")
max(position)-min(position) > opts$sac.minmag | # positions of start and stop are far away
blinks$blinkends[blink_idx] - blinks$eyeidx.blinkstart[blink_idx]/opts$sampleHz > .5 # sac is too long
# should let scannerbars 10701.20110323.2.30 pass, doesn't
}
drop_blink <- function(ts, sac.df, blinks, opts) {
###### DROP TRIAL CONDITIONS
# no saccades, also will trap no enough data
if(nrow(sac.df)<1L){return('no saccades (drop_blink)')}
# BLINK DROP
# drop if there is a long blink that ends before any good sacade begins
# TODO: rename variables to someting saine
firstgoodsacidx <- sac.df$intime & sac.df$gtMinLen & sac.df$gtMinMag & sac.df$p.tracked>opts$sac.trackingtresh
firstsacstart <- sac.df[firstgoodsacidx, ]$onset[1]
if(is.na(firstsacstart)){firstsacstart <- -Inf}
if(any(blinks$blinkends < firstsacstart ) & !opts$ignoreblinks){
unheldblinks <- sapply(which(blinks$blinkends<firstsacstart),
FUN=find_unheld_blinks, blinks=blinks, opts=opts)
# this checks that there isn't an immediate acceleration after the blink
if(is.na(unheldblinks) || any(unheldblinks)) {
return('blink ends before any saccades')
}
## after the blink (or loss of tracking) the blink is held
## move back the onset of a sac to the start of the closest blink onset
#firstsacstart[firstsacstart<]
# if actualbinkidx has a 1, this will fail, but hopefully that is a preblink and is cut anyway
}
## unheld blink before first saccade
## added 20131217 - WF
# * we'll check that a blink doesn't start some threshold before the first saccade
# * see bars getSacDot('10872.20131129.1.55') and .54
# - these are correct saccades, but cant be distinquished from a blink
if(length(blinks$eyeidx.blinkstart)>0
&& nrow(sac.df) > 0
&& length(blinks$eyeidx.blinkstart)>0
&& !opts$blinkbeforeok
&& !opts$ignoreblinks){
firstsacstart <- sac.df$onset[1]
firstblinkbeforesac <- firstsacstart - blinks$eyeidx.blinkstart[1]/opts$sampleHz
if( firstblinkbeforesac > maxBlinkLengthBeforeFirstSac){
return('blink starts %.3f before any saccade', firstblinkbeforesac)
}
}
return(NA)
}
# remove spikes at single time points
# see rmspikes(b.approx$x, opts$sac.padding)
# 20200629 thres was hardcoded at 30 (sac.padding)
# was:
# which(zoo::rollapply(c(0,diff(ts)),2,function(x){sign(prod(x,na.rm=T))==-1 & abs(min(x,na.rm=T))>30}))
rmspikes <- function(ts, thres) {
delta <- c(0, diff(ts))
# change is different on both sides (spike) and is greater than threshold
spikypointsIdx <- which(zoo::rollapply(delta, 2, function(x){
# remove warnings about no comparison in min
if(all(is.na(x))) return(F)
# return diff on each side, gt thres
sign(prod(x, na.rm=T)) == -1 &
abs( min(x, na.rm=T)) > thres
}))
ts[spikypointsIdx ] <- NA
return(ts)
}
interp_samples <- function(ts, opts){
## get eye tracking for relevant portion
b.orig <- data.frame(time=1:length(ts),x=ts)
###### BLINK
# scary blink fliter -- remove 2 samples on each side of an NA seq that is longer than 10 samples (1/6 sec)
naSeq <- rle(is.na(b.orig$x))
SeqStartIdx <- cumsum(naSeq$lengths) - naSeq$lengths + 1
naStartIdx <- which( naSeq$values == T & naSeq$lengths > 10 )
nastarts <- SeqStartIdx[naStartIdx]-opts$blink.trim.samples
nastarts[nastarts<1] <- 1
nastops <- SeqStartIdx[naStartIdx]+ naSeq$lengths[naStartIdx]+opts$blink.trim.samples
nastops[nastops>length(b.orig$x)] <- length(b.orig$x)
start10nas <- unname(unlist(plyr::alply(cbind(nastarts,nastops),1, function(x) { x[1]:x[2]} )))
b.cutblink <- b.orig
b.cutblink$x[start10nas] <- NA
#b.cuttblink$used[start10nas] <- F
b.approx <- b.cutblink
###### Remove crazy points that can be nothing other than tracking errors
# eg, xpos like: 10 10 *200* 10 10; see behbars: 10827.20100617.1.34
if(!opts$dontcutspikes){
b.approx$x <- rmspikes(b.approx$x, opts$sac.padding)
}
###### TRIM
# drop all NAs at the end (b/c they can't be estimtated)
naX <- which(is.na(b.cutblink$x))
lastNA <- ifelse(length(naX)==0, 0 , lastNA <- naX[length(naX)] )
# trim last
while(length(b.approx$x) == lastNA && length(b.approx$x)>0) {
# find all the NAs at the end
NAreps <- tail(rle(diff(naX))$lengths,n=1)
if( length(NAreps)>=1 & !is.na(NAreps[1])) {
dropidxs <- seq( lastNA - NAreps,lastNA)
} else {
dropidxs <- lastNA
}
b.approx <- b.approx[-dropidxs,]
naX <- which(is.na(b.approx$x))
lastNA<-ifelse(length(naX)==0, 0, naX[length(naX)] )
}
naX <- which(is.na(b.approx$x))
firstNA <-ifelse(length(naX)==0, 0, naX[1] )
# trim first
while(firstNA == 1) {
# find all the NAs at the end
NAreps <- rle(diff(naX))$lengths[1]
if(length(NAreps)>=1 & !is.na(NAreps[1]) ) {
dropidxs <- seq( firstNA , NAreps+1)
} else {
dropidxs <- firstNA
}
b.approx <- b.approx[-dropidxs,]
naX <- which(is.na(b.approx$x))
firstNA <-ifelse(length(naX)==0, 0, naX[1] )
}
###### CHECKS
# if we take out the NAs and there is nothing left!
if(length(b.approx$x)<=1) stop('no data left after removing blinks')
####### Estimate away NAs
# replace NAs so we can do polyfit
names(b.approx) <- c('time','xpos')
b.nona <- b.approx
b.nona$xpos <- zoo::na.approx(b.approx$xpos,x=b.approx$time)
return(namedList(b.approx, b.nona))
}
sac_pos <- function(sac.df) {
# use position to inform extracted saccades
# used soley by trail_pos
# here to make it "easier" to read through code (maybe)
# quick check. need to have gotten a few extra columns
stopifnot(c("onset", "base.val", "sac.thres") %in%names(sac.df))
# previously not stored in df. so extract here
base.val <- sac.df$base.val[1]
sac.thres <- sac.df$sac.thres[1]
#expected mag and direction of saccade
sac.expdir <- sign(sac.df$sac.expmag)
sac.df$crossFix = as.numeric(sac.df$startpos < base.val) - as.numeric(sac.df$endpos < base.val)
# want to test against both the base.val (where we think center is) and screen.x.mid (where center fix should be)
#sac.df$MaxMinX = as.numeric(sac.df$minpos < min(base.val,screen.x.mid)) - as.numeric(sac.df$maxpos < max(base.val,screen.x.mid))
sac.df$MaxMinX = sign(sac.df$minpos - base.val) != sign(sac.df$maxpos - base.val)
sac.df$gtMinMag = abs(sac.df$distance) > opts$sac.minmag
sac.df$startatFix= sac.df$startpos > base.val -10 & sac.df$startpos < base.val + 10
# 0 if sac did not cross sides
# -1 moved to the left
# 1 moved to the right
# SCORE
sac.df$cordir = sign(sac.df$endpos - sac.df$startpos) == sac.expdir
sac.df$corpos = abs(sac.df$endpos - sac.thres) <= opts$sac.padding
sac.df$corside = sign(sac.df$endpos - base.val ) == sign(sac.thres - base.val)
return(sac.df)
}
tracked_withinsac <- function(sac_df, rawts) {
mapply(function(a,b) length(which(!is.na(rawts[a:b])))/(b-a+1), sac_df$onsetIdx, sac_df$endIdx)
}
plot_data <- function(eyedf, interp_df, sac.df, base.val, sac.exp, opts, tmin=1, tmax=nrow(eyedf)) {
require(ggplot2)
d <- eyedf
d$time <- 1:nrow(eyedf)
d <- merge(d, interp_df, by="time", suffixes = c("",".interp"))
d <- d[tmin:tmax, ]
d$type <- xdat_to_type(d$xdat, opts)
print(head(d$type))
ggplot(d) + aes(x=time, y=xpos) +
geom_point(aes(y=xpos.interp), color="black") +
geom_point(aes(size=dil, color=type)) +
geom_hline(yintercept=base.val, color="green") +
cowplot::theme_cowplot()
}
#' add_trials
#' add trial info to all saccades
#' @param all_sacs - find_saccades()
#' @param tidxdf - trial_indexs() + get_baseline()
#' @param ntrials - opts$expectedTrialLengths
#' @return all_sacs with trl{Start,End,Trg}Idx + trial, base.val, xdat
add_trials <- function(all_sacs, tidxdf, ntrials) {
# find a trial for each saccade
# put saccade in the trial where the saccade ends
# (maybe IRanges is a better way to do this)
l <- apply(tidxdf,1,function(x)
data.frame(
# will match against saccade dataframe column
endIdx=x[['start']]:x[['stop']],
# same dataframe as before
trial=x[['trial']],
xdat=x[['xdat']],
trlStartIdx=x[['start']],
trlEndIdx=x[['stop']],
trlTrgIdx=x[['target']],
base.val=x[['baseline']]
)) %>% dplyr::bind_rows()
all_sacs <- merge(l, all_sacs, by='endIdx', all.y=T)
# add all trials
all_sacs <- merge(data.frame(trial=1:ntrials), all_sacs, by='trial',all=T)
# saccades should be short. so no risk of being in target of previous?
if(with(all_sacs,
any(!is.na(trlStartIdx) &
onsetIdx < trlStartIdx &
endIdx >= trlTrgIdx)))
stop('saccades starts in one trial and end in/after target of another')
return(all_sacs)
}
#' segment_file
#' pull out target segements of eye tracking
#' @param data_file file to read from
#' @param opts options for this study
#' @return list(eyedf=raw w/xdats fixed, interps=interp_samples(), tinfo=partition_trials())
segment_file <- function(data_file, opts=studysettings()){
# data_file <- './10997.20200221.1.data.tsv'
eyedf <- read_eye(data_file) # this maybe replaced by arrow?
eyedf <- clean_xdat(eyedf, opts) # bad data samples to NA
tidxdf <- trial_indexs(eyedf, opts) # trial, start, target, stop, xdat
tidxdf$baseline <- get_baselines(tidxdf, eyedf$xpos)
interps <- interp_samples(eyedf$xpos, opts) # remove samples around blinks, smooth
all_blinks <- find_blinks(interps$b.approx$xpos, opts)
all_accel <- find_accels(interps$b.nona$xpos, opts)
all_sacs <- find_saccades(all_accel, all_blinks, opts)
# add aditional columns
all_sacs <- add_trials(all_sacs, tidxdf, opts$expectedTrialLengths)
all_sacs <- sac_thres(all_sacs, opts)
all_sacs$p.tracked <- tracked_withinsac(all_sacs, eyedf$xpos)
all_sacs <- sac_pos(all_sacs)
# TODO: drop per trial
#dropreasons <- lapply(
# rawdf=segs$eyedf[ti,],
# t_interp_xpos=segs$interps$b.nona$xpos[ti],
# t_approx=segs$interps$b.approx$xpos[ti],
# opts=opts),
#dropreason <- should_drop(eye_xpos, t_interp_xpos, sac_df, blinks, opts)
#sac_df$Desc <- dropreason
#sac_df$Drop <- !is.na(dropreason)
#plot_trial(eyedf, all_accel, all_blinks, all_sacs)
# return list of all things
tinfo <- partition_trials(tidxdf, eyedf$xpos)
namedList(eyedf, interps, tinfo)
}
# TODO: maybe part of partition_trials?
relative_times <- function(sac_df, blinks, interp){
}
score_visit <- function(data_file, opts=studysettings(), onlyon=NA){
# data_file <- './10997.20200221.1.data.tsv'
segs <- segment_file(data_file, opts)
# restict to indexes provided by onlyon if we have any
if(!is.na(onlyon)) segs$tinfo <- segs$tinfo[onlyon]
lapply(segs$tinfo, function(trl) {
ti<-trl$trgidxs
failure <- NA
sac_df <- data.frame(xdat=trl$xdat,trial=trl$trial)
tryCatch(
sac_df <- trial_sacs(trl,
rawdf=segs$eyedf[ti,],
t_interp_xpos=segs$interps$b.nona$xpos[ti],
t_approx=segs$interps$b.approx$xpos[ti],
opts=opts),
error=function(e){
# set the parent failure variable
failure<<-e$message
cat(sprintf("WARNING: trial %d failure %s\n", trl$trial, failure))
})
score_trial(sac_df, opts, failreason=failure)
})
}
#' get baseline for a number of samples before target onset
#' @param tidxdf from trial_indexs()
#' @param xpos timeseries of all x positions to get pre target baseline
#' @param nbefore timepoints before onset
#' @param nafter timepoints after onset
#' @return baselines for each trial
get_baselines <- function(tidxdf, xpos, nbefore=5, nafter=2) {
sapply(tidxdf$target,
FUN=function(i) mean(xpos[c((-1*nbefore):nafter) + i],na.rm=T))
}
#' parition_trials
#' parition trials into target info lists
#' @param tidxdf from trial_indexs()
#' @param xpos timeseries of all x positions to get pre target baseline
#' @return list(baseline, trgidxs, xdat, trial)
partition_trials <- function(tidxdf, xpos) {
stopifnot(c("target", "stop", "xdat", "trial") %in% names(tidxdf))
# how to partition trials - need baseline (from raw ts) and range of where to work
# take raw input and target/stop indexs
baselines <- get_baselines(tidxdf, xpos)
trgrange <- mapply(FUN=function(a,b) c(a:(b-1)),
tidxdf$target, tidxdf$stop,
SIMPLIFY=F)
# put these together
lapply(1:length(baselines), function(i)
list(baseline=baselines[i], trgidxs=trgrange[[i]],
xdat=tidxdf$xdat[i], trial=tidxdf$trial[i]))
}
#' @title plot trial info
#' @description freq from opts$sampleHz
#' @param orig xpos time series of target segment
#' @param a from find_accels()
#' @param blinks from find_blinks()
#' @param sacs TODO
#' @param freq from opts$sampleHz
plot_trial <- function(origdf, a=NULL, blinks=NULL, sacs=NULL,
freq=60, ylim=c(0,270), maxdil=50) {
# make 30 = size 1, range 0-50 to .1 - 2
dil <- origdf$dil * (2-.1)/50 + .1
p <- plot(origdf$xpos, ylim=ylim, cex=dil)
if(!is.null(sacs)){
# colored blocks for each saccade
# green if good, red if bad
rec_col <- ifelse(sacs$cordir,"green","red")
rect(xleft=sacs$onset*freq,
xright=sacs$end*freq,
ybottom=ylim[1]-100, ytop=ylim[2]*100, # out of bounds, no margin
col=alpha(rec_col, .4),
border=NA)
# show baseline
abline(h=sacs$baseline[1], col="darkgreen", lty=2)
}
# interpolated and first derivative
if(!is.null(a)){
lines(a$est$x, a$est$y, col="green")
lines(a$fst$x, a$fst$y+mean(a$est$y), col="blue")
}
# if we have blinks
# NArcels in ornage
# start and stop (dashed) in red
if(!is.null(blinks)) {
lapply(blinks$NArlecs, function(x)
abline(v=x*freq, col="orange"))
lapply(blinks$eyeindx.blinkstart, function(x)
abline(v=x*freq, col="red", lty=2))
lapply(blinks$blinkends, function(x)
abline(v=x*freq, col="red", lty=2))
}
return(p)
}
trial_sacs <- function(trl, rawdf, t_interp_xpos, t_approx, opts, plot=F){
# get blinks, saccades, tracking
# check for resaons to drop
# trl is a list. should have this info
stopifnot(c("xdat","trial", "baseline") %in% names(trl))
eye_xpos <- rawdf$xpos
# parse data
blinks <- find_blinks(t_approx, opts)
accel_info <- find_accels(t_interp_xpos, opts)
sac_df <- find_saccades(accel_info, blinks, opts)
sac_df$trial <- trl$trial
sac_df$xdat <- trl$xdat
sac_df$base.val <- trl$baseline
sac_df$p.tracked <- tracked_withinsac(sac_df, eye_xpos)
# sac.thres for anti like reverse of 2, 87, 172 or 258 (left to right)
sac_df <- sac_thres(sac_df, opts)
# drop?
dropreason <- should_drop(eye_xpos, t_interp_xpos, sac_df, blinks, opts)
sac_df$Desc <- dropreason
sac_df$Drop <- !is.na(dropreason)
# use columns to setup useful info from positions
sac_df <- sac_pos(sac_df)
if(plot) plot_trial(origdf, accel_info, blinks, sac_df)
return(sac_df)
}
#' sac_thres
#' adds xposition threshold info based on xdat
#' @param sac_df df with xdat
#' @param opts list with getExpPos function and screen.x.mid
#' @return sac_df with additonal columns: sac.thres, sac.expmag
sac_thres <- function(sac_df, opts){
sac.thres <- opts$getExpPos(sac_df$xdat)
sac_df$sac.expmag <- sac.thres - opts$screen.x.mid
sac_df$sac.thres <- sac.thres
return(sac_df)
}
should_drop <- function(eye_xpos, t_interp_xpos, sac_df, blinks, opts) {
# should we drop?
dropreason <- drop_interp(t_interp_xpos, sac_df$base.val[1], opts)
if(!is.na(dropreason)) return(dropreason)
dropreason <- no_early_move(eye_xpos[1:(opts$lat.fastest*opts$sampleHz)], opts)
if(!is.na(dropreason)) return(dropreason)
dropreason <- drop_blink(ts, sac_df, blinks, opts)
if(!is.na(dropreason)) return(dropreason)
if(dim(sac_df)[1]<1 || is.na(sac_df$onset)) return('no saccades')
# if the first sacc is too soon
# is something the scoring function should do!? -- dropTrialSacs is easier to run from here
if(sac_df$onset[1]<lat.fastest && !opts$nothingistoofast ) return('1st good sac too soon')
if(abs(sac_df$startpos[1] - opts$screen.x.mid) > 50 && !opts$ignorefirstsacstart)
return('start pos too far from center fix')
goodsacsIdx <- with(sac_df,{intime & gtMinLen & p.tracked > sac.trackingtresh})
if(length(goodsacsIdx)<1) return('no good saccades')
if(!any(sac_df$onset < opts$sac.time))
return(sprintf('no saccades within sac.time(%.3f)', opts$sac.time))
return(NA)
}
read_eye <- function(data_file, verbose=T){
# read tsv file created by dataFromAnyEyd.pl
# empty but with correct columns
default <- data.frame(xdat=NA,dil=NA,xpos=NA,ypos=NA)
if(verbose) cat('using ', data_file ,'\n')
### load data
#load xdat, eye position and dialation data for parsed data_file
d <- tryCatch(read.table(data_file, sep="\t",header=T),
error=function(e){
cat(sprintf("# error! cant read input '%s': %s\n", data_file, e))
return(default)})
if(dim(d)[2] != 4) return(default)
names(d) <- c("xdat","dil","xpos","ypos")
return(d)
}
clean_xdat <- function(d, opts) {
# replace strings of zeros with prevous xdat
# zero out values that are too hight (blinks)
# input is dataframe with xdat xpos ypos dil
# see read_eye
# opts for xmax, ymax, and useextremefilter
## fix bars zero'ed xdats
zeroxdat <- rle(d$xdat==0)
if(zeroxdat$values[1] == T) {
minzeroxdatlen <-2
} else {
minzeroxdatlen <-1
}
if(length(zeroxdat$lengths)>minzeroxdatlen) {
xdatswitchidx <- cumsum(zeroxdat$lengths)
zeroxdatidx <- which(zeroxdat$values==TRUE)
#if the very first xdat is 0, we're in trouble, so ingore that one
if(zeroxdatidx[1] == 1) {
zeroxdatidx <- zeroxdatidx[-1]
}
#replacementXdat <- d$xdat[xdatswitchidx[zeroxdatidx-1]]
#needReplaced <- d$xdat[xdatswitchidx[zeroxdatidx]:(xdatswitchidx[zeroxdatidx]+zeroxdat$lengths[zeroxdatidx])]
zerostartend <- cbind( end=xdatswitchidx[zeroxdatidx],
start=(xdatswitchidx[zeroxdatidx]-zeroxdat$lengths[zeroxdatidx]+1)
)
zeroIdxinD <- apply(zerostartend,1,function(x){x['start']:x['end']})
shouldbeXdat <- d$xdat[xdatswitchidx[zeroxdatidx-1]]
if(length(shouldbeXdat) != length(zeroIdxinD) )
warning('zero xdats and replacement not the same length!! something very funny is going on')
for( i in 1:length(shouldbeXdat)){ d$xdat[zeroIdxinD[[i]]] <- shouldbeXdat[i]}
}
##### Remove bad data #####
# both x and y are out of range, or there is no dilation measure
# TODO!!
# if there is x and ypos and dil != 0
# maybe we should keep?
# see scannerbars 10711.20121108.1.17 -- good xpos, no good dil or ypos
if(opts$useextremefilter){
badidxs=d$xpos>opts$xmax|d$ypos>opts$ymax|d$dil==0
}else{
# allow for some over/under shooting (xmax+50->xmax, -50 -> 0)
allowedovershoot <- 0
d$xpos[d$xpos>opts$xmax&d$xpos<opts$xmax+allowedovershoot] <- opts$xmax
d$xpos[d$xpos<0&d$xpos>-allowedovershoot] <- 0
badidxs=d$xpos>opts$xmax|(d$xpos==0&d$ypos==0&d$dil==0)
}
d[which(badidxs),c('dil','xpos','ypos')] <- c(NA,NA,NA)
if(any(na.omit(d$dil)<1)) { d$dil[which(d$dil<1)]<-1 }# so we can see something!
# which is need to not die on scanbars 10656.20090410.2
return(d)
}
get_targets <- function(d, opts) {
# deperacatd?
# remove repeats
xdats <- rle(d$xdat) # run length encode
xdats$cs <- cumsum(xdats$lengths) # index in d where xdat happends
#### Split eye positions by target code
# use only targetcodes that are preceded by startcodes and followed by end codes
# this should let us ingore catch trials (no target)
tarCodePos <- which(xdats$values %in% opts$targetcodes)
goodTargPos.start <- tarCodePos[ xdats$values[tarCodePos - 1] %in% opts$startcodes ]
goodTargPos <- goodTargPos.start[ xdats$values[goodTargPos.start + 1] %in% opts$stopcodes ]
# x by 2 matrix of target onset and offset indicies
targetIdxs <- cbind(xdats$cs[goodTargPos-1],xdats$cs[goodTargPos])
if(length(goodTargPos) <= 0) {
#allsacs <- dropTrialSacs(subj,runtype,runontrials,0,'no understandable start/stop xdats!',allsacs,showplot=F,run=run,rundate=rundate)
#return()
stop('no understandable start/stop xdats!')
}
if(! length(goodTargPos) %in% opts$expectedTrialLengths ) {
cat('WARNING: unexpected num of trials: ',
length(goodTargPos), '!%in% ',
paste(collaspe=" or ", opts$expectedTrialLengths),
'\n')
}
return(targetIdxs)
}
xdat_to_type <- function(xdat, opts) {
type <- 2*(xdat %in% opts$startcodes) +
4*(xdat %in% opts$targetcodes) +
8*(xdat %in% opts$stopcodes)
#0=unknown, 2=start, 4=target, 8=stop
type <- factor(type, c(0,2,4,8), c('unknown','start','target','stop'))
}
trial_indexs <- function(d, opts) {
# return: index xdat type trial xdat(target)
#
# 20200629 - replaces get_targets ?
xdats <- rle(d$xdat) # run length encode
xdats$cs <- cumsum(xdats$lengths) # index in d where xdat happends
# remove repeats
trials <- rle(d$xdat)
if(!any(trials$values %in% opts$targetcodes)) stop('no targetcodes in data!')
# make dataframe
trials <- data.frame(index=trials$lengths,
xdat=trials$values)
# get index of change. start at 1st.
trials$index<- c(1, head(cumsum(trials$index), -1)) + 1
# set types
trials$type <- xdat_to_type(trials$xdat, opts)
# on recording stop
# if last xdat is 254 and there is a stop before it
# remove last
if(trials$xdat[nrow(trials)]==254 & trials$type[nrow(trials)-1]=='stop')
trials <- trials[-nrow(trials),]
trials$trial<- cumsum(trials$type == 'start')
# remove any unknown
trials <- trials[!is.na(trials$type), ]
trials <- trials[trials$type!='unknown',]
# transform to wide
# merge with target xdat
# or return an error message
tryCatch({
wide <- tidyr::spread(trials[,c("index","type","trial")], type, index)
merge(wide, trials[trials$type=='target',c('trial','xdat')], by='trial')
}, error=function(e)
stop("cannot create start,target,stop pairing: %s", e$message))
}
score_trial <- function(sac_df, opts, failreason=NA, subj=NA) {
# should get these from trial_sacs()
stopifnot(c("xdat", "trial") %in% names(sac_df))
# should have fail reason set if no rows. will be missing xdat and trial info
stopifnot(nrow(sac_df)>0L)
# dataframe has saccades but is dropped for some reason
if(any(sac_df$Drop)) failreason <- sac_df$Desc[1]