-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathI2MC_helpers.py
More file actions
1652 lines (1433 loc) · 64.3 KB
/
I2MC_helpers.py
File metadata and controls
1652 lines (1433 loc) · 64.3 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 -*-
"""
Created on Thu Sep 19 10:54:00 2019
@author: Jonathan van Leeuwen, Diederick Niehorster
"""
import copy
import math
import warnings
import numpy as np
import pandas as pd
import scipy
import scipy.interpolate as interp
import scipy.signal
from scipy.cluster.vq import _vq, vq
from scipy.spatial.distance import cdist
# =============================================================================
# Helper functions
# =============================================================================
def is_number(s):
try:
np.array(s, dtype=float)
return True
except ValueError:
return False
def check_numeric(k, v):
if not is_number(v):
raise ValueError(
'The value of "{}" is invalid. Expected input to be a number. Instead its type was {}.'.format(k, type(v)))
def check_scalar(k, v):
if not np.ndim(v) == 0:
raise ValueError(
'The value of "{}" is invalid. Expected input to be a scalar.'.format(k))
def check_vector_2(k, v):
if not np.size(v) == 2:
raise ValueError(
'The value of "{}" is invalid. Expected input to be a 2-element array.'.format(k))
def check_int(k, v):
if np.sum(np.array(v) % 1) != 0:
raise ValueError(
'The value of "{}" is invalid. Expected input to be an integer or list of integers.'.format(k))
def check_fun(k, d, s):
if k not in d.keys():
raise ValueError(
'I2MCfunc: "{}" must be specified using the "{}" option key, but it cannot be found'.format(s, k))
if not is_number(d[k]):
raise ValueError(
'I2MCfunc: "{}" must be set as a number using the "{}" option'.format(s, k))
def angle_to_pixels(angle, screenDist, screenW, screenXY):
"""
Calculate the number of pixels which equals a specified angle in visual
degrees, given parameters. Calculates the pixels based on the width of
the screen. If the pixels are not square, a separate conversion needs
to be done with the height of the screen.\n
"angleToPixelsWH" returns pixels for width and height.
Parameters
----------
angle : float or int
The angle to convert in visual degrees
screenDist : float or int
Viewing distance in cm
screenW : float or int
The width of the screen in cm
screenXY : tuple, ints
The resolution of the screen (width - x, height - y), pixels
Returns
-------
pix : float
The number of pixels which corresponds to the visual degree in angle,
horizontally
Examples
--------
>>> pix = angleToPixels(1, 75, 47.5, (1920,1080))
>>> pix
52.912377341863817
"""
pixSize = screenW / float(screenXY[0])
angle = np.radians(angle / 2.0)
cmOnScreen = np.tan(angle) * float(screenDist)
pix = (cmOnScreen / pixSize) * 2
return pix
def get_missing(L_X, R_X, missing_x, L_Y, R_Y, missing_y):
"""
Gets missing data and returns missing data for left, right and average
Parameters
----------
L_X : np.array
Left eye X gaze position data
R_X : np.array
Right eye X gaze position data
missing_x : scalar
The value reflecting missing values for X coordinates in the dataset
L_Y : np.array
Left eye Y gaze position data
R_Y : np.array
Right eye Y gaze position data
missing_y : scalar
The value reflecting missing values for Y coordinates in the dataset
Returns
-------
qLMiss : np.array - Boolean
Boolean indicating missing samples for the left eye
qRMiss : np.array - Boolean
Boolean indicating missing samples for the right eye
qBMiss : np.array - Boolean
Boolean indicating missing samples for both eyes
"""
# Get where the missing is
# Left eye
qLMissX = np.logical_or(L_X == missing_x, np.isnan(L_X))
qLMissY = np.logical_or(L_Y == missing_y, np.isnan(L_Y))
qLMiss = np.logical_and(qLMissX, qLMissY)
# Right
qRMissX = np.logical_or(R_X == missing_x, np.isnan(R_X))
qRMissY = np.logical_or(R_Y == missing_y, np.isnan(R_Y))
qRMiss = np.logical_and(qRMissX, qRMissY)
# Both eyes
qBMiss = np.logical_and(qLMiss, qRMiss)
return qLMiss, qRMiss, qBMiss
def average_eyes(L_X, R_X, missing_x, L_Y, R_Y, missing_y):
"""
Averages data from two eyes. Take one eye if only one was found.
Parameters
----------
L_X : np.array
Left eye X gaze position data
R_X : np.array
Right eye X gaze position data
missing_x : scalar
The value reflecting missing values for X coordinates in the dataset
L_Y : np.array
Left eye Y gaze position data
R_Y : np.array
Right eye Y gaze position data
missing_y : scalar
The value reflecting missing values for Y coordinates in the dataset
Returns
-------
xpos : np.array
The average Y gaze position
ypos : np.array
The average X gaze position
qBMiss : np.array - Boolean
Boolean indicating missing samples for both eyes
qLMiss : np.array - Boolean
Boolean indicating missing samples for the left eye
qRMiss : np.array - Boolean
Boolean indicating missing samples for the right eye
"""
xpos = np.zeros(len(L_X))
ypos = np.zeros(len(L_Y))
# get missing
qLMiss, qRMiss, qBMiss = get_missing(
L_X, R_X, missing_x, L_Y, R_Y, missing_y)
q = np.logical_and(np.invert(qLMiss), np.invert(qRMiss))
xpos[q] = (L_X[q] + R_X[q]) / 2.
ypos[q] = (L_Y[q] + R_Y[q]) / 2.
q = np.logical_and(qLMiss, np.invert(qRMiss))
xpos[q] = R_X[q]
ypos[q] = R_Y[q]
q = np.logical_and(np.invert(qLMiss), qRMiss)
xpos[q] = L_X[q]
ypos[q] = L_Y[q]
xpos[qBMiss] = np.NAN
ypos[qBMiss] = np.NAN
return xpos, ypos, qBMiss, qLMiss, qRMiss
def bool2bounds(b):
"""
Finds all contiguous sections of true in a boolean
Parameters
----------
data : np.array - Boolean (or convertible to boolean)
A 1D array containing stretches of True and False
Returns
-------
on : np.array
The array contains the indices where each stretch of True starts
off : np.array
The array contains the indices where each stretch of True ends
Example
--------
>>> import numpy as np
>>> b = np.array([1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0])
>>> on, off = bool2bounds(b)
>>> print(on)
[0 4 8]
>>> print(off)
[0 6 9]
"""
b = np.array(np.array(b, dtype=bool), dtype=int)
b = np.pad(b, (1, 1), 'constant', constant_values=(0, 0))
D = np.diff(b)
on = np.array(np.where(D == 1)[0], dtype=int)
off = np.array(np.where(D == -1)[0] - 1, dtype=int)
return on, off
# =============================================================================
# Interpolation functions
# =============================================================================
def find_interp_wins(xpos, ypos, missing, window_time, edge_samples, freq, max_disp):
"""
Description
Parameters
----------
xpos : np.array
X gaze position
ypos : type
Y gaze position
missing : type
Description
window_time : float
Duration of window to interpolate over (ms)
edge_samples : int
Number of samples at window edge used for interpolating
freq : float
Measurement frequency
max_disp : float
maximum dispersion in position signal (i.e. if signal is in pixels, provide maxdisp in pixels)
Returns
-------
miss_start : np.array
Array containing indices where each interval to be interpolated starts
miss_end : np.array
Array containing indices where each interval to be interpolated ends
"""
# get indices of where missing intervals start and end
miss_start, miss_end = bool2bounds(missing)
data_start, data_end = bool2bounds(np.invert(missing))
# Determine windowsamples
window_samples = round(window_time/(1./freq))
# for each candidate, check if have enough valid data at edges to execute
# interpolation. If not, see if merging with adjacent missing is possible
# we don't throw out anything we can't deal with yet, we do that below.
# this is just some preprocessing
k = 0 # was K=1 in matlab
while k < len(miss_start)-1:
# skip if too long
if miss_end[k]-miss_start[k]+1 > window_samples:
k = k+1
continue
# skip if not enough data at left edge
if np.sum(data_end == miss_start[k]-1) > 0:
datk = int(np.argwhere(data_end == miss_start[k]-1))
if data_end[datk]-data_start[datk]+1 < edge_samples:
k = k+1
continue
# if not enough data at right edge, merge with next. Having not enough
# on right edge of this one, means not having enough at left edge of
# next. So both will be excluded always if we don't do anything. So we
# can just merge without further checks. Its ok if it then grows too
# long, as we'll just end up excluding that too below, which is what
# would have happened if we didn't do anything here
datk = np.argwhere(data_start == miss_end[k]+1)
if len(datk) > 0:
datk = int(datk)
if data_end[datk]-data_start[datk]+1 < edge_samples:
miss_end = np.delete(miss_end, k)
miss_start = np.delete(miss_start, k+1)
# don't advance k so we check this one again and grow it further if
# needed
continue
# nothing left to do, continue to next
k = k+1
# mark intervals that are too long to be deleted (only delete later so that
# below checks can use all missing on and offsets)
miss_dur = miss_end - miss_start + 1
qRemove = miss_dur > window_samples
# for each candidate, check if have enough valid data at edges to execute
# interpolation and check displacement during missing wasn't too large.
# Mark for later removal as multiple missing close together may otherwise
# be wrongly allowed
for p in range(len(miss_start)):
# check enough valid data at edges
# missing too close to beginning of data
# previous missing too close
# missing too close to end of data
# next missing too close
if miss_start[p] < edge_samples+1 or \
(p > 0 and miss_end[p-1] > miss_start[p]-edge_samples-1) or \
miss_end[p] > len(xpos)-1-edge_samples or \
(p < len(miss_start)-1 and miss_start[p+1] < miss_end[p]+edge_samples+1):
qRemove[p] = True
continue
# check displacement, per missing interval
# we want to check per bit of missing, even if multiple bits got merged
# this as single data points can still anchor where the interpolation
# goes and we thus need to check distance per bit, not over the whole
# merged bit
idx = np.arange(miss_start[p], miss_end[p]+1, dtype=int)
on, off = bool2bounds(np.isnan(xpos[idx]))
for q in range(len(on)):
lesamps = np.array(
on[q] - np.arange(edge_samples)+miss_start[p]-1, dtype=int)
resamps = np.array(
off[q]+np.arange(edge_samples)+miss_start[p]+1, dtype=int)
displacement = np.hypot(np.nanmedian(xpos[resamps])-np.nanmedian(xpos[lesamps]),
np.nanmedian(ypos[resamps])-np.nanmedian(ypos[lesamps]))
if displacement > max_disp:
qRemove[p] = True
break
if qRemove[p]:
continue
# Remove the missing clusters which cannot be interpolated
qRemove = np.where(qRemove)[0]
miss_start = np.delete(miss_start, qRemove)
miss_end = np.delete(miss_end, qRemove)
return miss_start, miss_end
def windowed_interpolate(xpos, ypos, missing, miss_start, miss_end, edge_samples):
"""
Interpolates the missing data, and removes areas which are not allowed
to be interpolated
Parameters
----------
xpos : np.array
X gaze positions
ypos : type
Y gaze positions
missing : np.array
Boolean vector indicating missing samples
miss_start : np.array
Array containing indices where each interval to be interpolated starts
miss_end : np.array
Array containing indices where each interval to be interpolated ends
edge_samples : int
Number of samples at window edge used for interpolating
Returns
-------
xi : np.array
Interpolated X gaze position
yi : np.array
Interpolated Y gaze position
new_missing : np.array
Updated boolean vector indicating missing samples after interpolation
"""
new_missing = copy.deepcopy(missing)
# Do the interpolating
for p in range(len(miss_start)):
# make vector of all samples in this window
out_win = np.arange(miss_start[p], miss_end[p]+1)
# get edge samples: where no missing data was observed
# also get samples in window where data was observed
out_win_not_missing = np.invert(new_missing[out_win])
valid_samps = np.concatenate((out_win[0]+np.arange(-edge_samples, 0),
out_win[out_win_not_missing],
out_win[-1]+np.arange(1, edge_samples+1)))
# get valid values: where no missing data was observed
valid_x = xpos[valid_samps]
valid_y = ypos[valid_samps]
# do Steffen interpolation, update xpos, ypos
xpos[out_win] = steffen_interp(valid_samps, valid_x, out_win)
ypos[out_win] = steffen_interp(valid_samps, valid_y, out_win)
# update missing: hole is now plugged
new_missing[out_win] = False
return xpos, ypos, new_missing
# =============================================================================
# interpolator
# =============================================================================
def steffen_interp(x, y, xi):
# STEFFEN 1-D Steffen interpolation
# steffenInterp[X,Y,XI] interpolates to find YI, the values of the
# underlying function Y at the points in the array XI, using
# the method of Steffen. X and Y must be vectors of length N.
#
# Steffen's method is based on a third-order polynomial. The
# slope at each grid point is calculated in a way to guarantee
# a monotonic behavior of the interpolating function. The
# curve is smooth up to the first derivative.
# Joe Henning - Summer 2014
# edited DC Niehorster - Summer 2015
# M. Steffen
# A Simple Method for Monotonic Interpolation in One Dimension
# Astron. Astrophys. 239, 443-450 [1990]
n = len(x)
# calculate slopes
yp = np.zeros(n)
# first point
h1 = x[1] - x[0]
h2 = x[2] - x[1]
s1 = (y[1] - y[0])/h1
s2 = (y[2] - y[1])/h2
p1 = s1*(1 + h1/(h1 + h2)) - s2*h1/(h1 + h2)
if p1*s1 <= 0:
yp[0] = 0
elif np.abs(p1) > 2*np.abs(s1):
yp[0] = 2*s1
else:
yp[0] = p1
# inner points
for i in range(1, n-1):
hi = x[i+1] - x[i]
him1 = x[i] - x[i-1]
si = (y[i+1] - y[i])/hi
sim1 = (y[i] - y[i-1])/him1
pi = (sim1*hi + si*him1)/(him1 + hi)
if sim1*si <= 0:
yp[i] = 0
elif (np.abs(pi) > 2*np.abs(sim1)) or (np.abs(pi) > 2*np.abs(si)):
a = np.sign(sim1)
yp[i] = 2*a*np.min([np.abs(sim1), np.abs(si)])
else:
yp[i] = pi
# last point
hnm1 = x[n-1] - x[n-2]
hnm2 = x[n-2] - x[n-3]
snm1 = (y[n-1] - y[n-2])/hnm1
snm2 = (y[n-2] - y[n-3])/hnm2
pn = snm1*(1 + hnm1/(hnm1 + hnm2)) - snm2*hnm1/(hnm1 + hnm2)
if pn*snm1 <= 0:
yp[n-1] = 0
elif np.abs(pn) > 2*np.abs(snm1):
yp[n-1] = 2*snm1
else:
yp[n-1] = pn
yi = np.zeros(xi.size)
for i in range(len(xi)):
# Find the right place in the table by means of a bisection.
# do this instead of search with find as the below now somehow gets
# better optimized by matlab's JIT [runs twice as fast].
klo = 1
khi = n
while khi-klo > 1:
k = int(np.fix((khi+klo)/2.0))
if x[k] > xi[i]:
khi = k
else:
klo = k
# check if requested output is in input, so we can just copy
if xi[i] == x[klo]:
yi[i] = y[klo]
continue
elif xi[i] == x[khi]:
yi[i] = y[khi]
continue
h = x[khi] - x[klo]
s = (y[khi] - y[klo])/h
a = (yp[klo] + yp[khi] - 2*s)/h/h
b = (3*s - 2*yp[klo] - yp[khi])/h
c = yp[klo]
d = y[klo]
t = xi[i] - x[klo]
# Use Horner's scheme for efficient evaluation of polynomials
# y = a*t*t*t + b*t*t + c*t + d
yi[i] = d + t*(c + t*(b + t*a))
return yi
# =============================================================================
# Clustering functions
# =============================================================================
class NotConvergedError(Exception):
pass
def kmeans2(data, first_cluster_fixed_value: int | None, second_cluster_fixed_value: int | None):
# n points in p dimensional space
n = data.shape[0]
max_iterations = 100
# initialize using kmeans++ method.
# code taken and slightly edited from scipy.cluster.vq
dims = data.shape[1] if len(data.shape) > 1 else 1
# cluster centers TODO adapted from original
# should not have any impact
C = np.zeros((2, dims))
# C = np.ndarray((2, dims))
# first cluster TODO adapted from original
if first_cluster_fixed_value is None: # select a first predefined cluster centroid
first_cluster_center_index = np.random.randint(data.shape[0])
else:
first_cluster_center_index = int(
data.shape[0]*first_cluster_fixed_value)
# first predefined cluster centroid
C[0, :] = data[first_cluster_center_index]
# C[0, :] = data[np.random.randint(data.shape[0])]
# second cluster TODO adapted from original
# distance for each point to the first predefined cluster centroid (min only retracts the first dimension (size 1) to create an n-dimensional vector)
D = cdist(C[:1, :], data, metric='sqeuclidean').min(axis=0)
probs = D/D.sum() # portray distances as probability summing up to 1
# portray distances as cumulative probabilities on a linear axis between 0 and 1
cumprobs = probs.cumsum()
if second_cluster_fixed_value is None: # select a probability to choose the second predefined cluster centroid
r = np.random.rand()
else:
r = second_cluster_fixed_value
# r = np.random.rand()
# second predefined cluster centroid
C[1, :] = data[np.searchsorted(cumprobs, r)]
# Compute the distance from every point to each cluster centroid and the
# initial assignment of points to clusters
D = cdist(C, data, metric='sqeuclidean')
# Compute the nearest neighbor for each obs using the current code book
label = vq(data, C)[0]
# Update the code book by computing centroids
C = _vq.update_cluster_means(data, label, 2)[0]
m = np.bincount(label)
# Begin phase one: batch reassignments
# -----------------------------------------------------
# Every point moved, every cluster will need an update
prevtotsumD = math.inf
iter = 0
prev_label = None
while True:
iter += 1
# Calculate the new cluster centroids and counts, and update the
# distance from every point to those new cluster centroids
Clast = C
mlast = m
D = cdist(C, data, metric='sqeuclidean')
# Deal with clusters that have just lost all their members
if np.any(m == 0):
i = np.argwhere(m == 0)
d = D[[label], [range(n)]] # use newly updated distances
# Find the point furthest away from its current cluster.
# Take that point out of its cluster and use it to create
# a new singleton cluster to replace the empty one.
lonely = np.argmax(d)
cFrom = label[lonely] # taking from this cluster
if m[cFrom] < 2:
# In the very unusual event that the cluster had only
# one member, pick any other non-singleton point.
cFrom = np.argwhere(m > 1)[0]
lonely = np.argwhere(label == cFrom)[0]
label[lonely] = i
# Update clusters from which points are taken
C = _vq.update_cluster_means(data, label, 2)[0]
m = np.bincount(label)
D = cdist(C, data, metric='sqeuclidean')
# Compute the total sum of distances for the current configuration.
totsumD = np.sum(D[[label], [range(n)]])
# Test for a cycle: if objective is not decreased, back out
# the last step and move on to the single update phase
if prevtotsumD <= totsumD:
label = prev_label
C = Clast
m = mlast
iter -= 1
break
if iter >= max_iterations:
break
# Determine closest cluster for each point and reassign points to clusters
prev_label = label
prevtotsumD = totsumD
new_label = vq(data, C)[0]
# Determine which points moved
moved = new_label != prev_label
if np.any(moved):
# Resolve ties in favor of not moving
moved[np.bitwise_and(moved, D[0, :] == D[1, :])] = False
if not np.any(moved):
break
label = new_label
# update centers
C = _vq.update_cluster_means(data, label, 2)[0]
m = np.bincount(label)
# ------------------------------------------------------------------
# Begin phase two: single reassignments
# ------------------------------------------------------------------
last_moved = -1
converged = False
while iter < max_iterations:
# Calculate distances to each cluster from each point, and the
# potential change in total sum of errors for adding or removing
# each point from each cluster. Clusters that have not changed
# membership need not be updated.
#
# Singleton clusters are a special case for the sum of dists
# calculation. Removing their only point is never best, so the
# reassignment criterion had better guarantee that a singleton
# point will stay in its own cluster. Happily, we get
# Del(i,idx(i)) == 0 automatically for them.
Del = cdist(C, data, metric='sqeuclidean')
mbrs = label == 0
sgn = 1 - 2*mbrs # -1 for members, 1 for nonmembers
if m[0] == 1:
sgn[mbrs] = 0 # prevent divide-by-zero for singleton mbrs
Del[0, :] = (m[0] / (m[0] + sgn)) * Del[0, :]
# same for cluster 2
sgn = -sgn # -1 for members, 1 for nonmembers
if m[1] == 1:
# prevent divide-by-zero for singleton mbrs
sgn[np.invert(mbrs)] = 0
Del[1, :] = (m[1] / (m[1] + sgn)) * Del[1, :]
# Determine best possible move, if any, for each point. Next we
# will pick one from those that actually did move.
prev_label = label
new_label = (Del[1, :] < Del[0, :]).astype('int')
moved = np.argwhere(prev_label != new_label)
if moved.size > 0:
# Resolve ties in favor of not moving
moved = np.delete(
moved, (Del[0, moved] == Del[1, moved]).flatten(), None)
if moved.size == 0:
converged = True
break
# Pick the next move in cyclic order
moved = (np.min((moved - last_moved % n) + last_moved) % n)
# If we've gone once through all the points, that's an iteration
if moved <= last_moved:
iter = iter + 1
if iter >= max_iterations:
break
last_moved = moved
olbl = label[moved]
nlbl = new_label[moved]
totsumD = totsumD + Del[nlbl, moved] - Del[olbl, moved]
# Update the cluster index vector, and the old and new cluster
# counts and centroids
label[moved] = nlbl
m[nlbl] += 1
m[olbl] -= 1
C[nlbl, :] = C[nlbl, :] + (data[moved, :] - C[nlbl, :]) / m[nlbl]
C[olbl, :] = C[olbl, :] - (data[moved, :] - C[olbl, :]) / m[olbl]
# ------------------------------------------------------------------
if not converged:
raise NotConvergedError(
'Failed to converge after %d iterations.' % iter)
return label, C
def two_cluster_weighting(xpos, ypos, missing, downsamples, downsamp_filter, cheby_order, window_time, step_time, freq, max_errors, logging, logging_offset, first_cluster_fixed_value: int | None, second_cluster_fixed_value: int | None):
"""
Description
Parameters
----------
xpos : type
Description
ypos : type
Description
missing : type
Description
downsamples : type
Description
downsamp_filter : type
Description
cheby_order : type
Description
window_time : type
Description
step_time : type
Description
freq : type
Description
max_errors : type
Description
Returns
-------
finalweights : np.array
Vector of 2-means clustering weights (one weight for each sample), the higher, the more likely a saccade happened
stopped : Boolean
Indicates if stopped because of too many errors encountered (True), or completed successfully (False)
"""
# calculate number of samples of the moving window
num_samples = int(window_time/(1./freq))
step_size = np.max([1, int(step_time/(1./freq))])
# create empty weights vector
total_weights = np.zeros(len(xpos))
total_weights[missing] = np.nan
num_tests = np.zeros(len(xpos))
# stopped is always zero, unless maxiterations is exceeded. this
# indicates that file could not be analyzed after trying for x iterations
stopped = False
num_errors = 0
# Number of downsamples
nd = len(downsamples)
# Downsample
if downsamp_filter:
# filter signal. Follow the lead of decimate(), which first runs a
# Chebychev filter as specified below
rp = .05 # passband ripple in dB
b = [[] for i in range(nd)]
a = [[] for i in range(nd)]
for p in range(nd):
b[p], a[p] = scipy.signal.cheby1(
cheby_order, rp, .8/downsamples[p])
# idx for downsamples
idxs = []
for i in range(nd):
idxs.append(np.arange(num_samples, 0, -
downsamples[i], dtype=int)[::-1] - 1)
# see where are missing in this data, for better running over the data
# below.
on, off = bool2bounds(missing)
if on.size > 0:
# merge intervals smaller than nrsamples long
merge = np.argwhere((on[1:] - off[:-1])-1 < num_samples).flatten()
for p in merge[::-1]:
off[p] = off[p+1]
off = np.delete(off, p+1)
on = np.delete(on, p+1)
# check if intervals at data start and end are large enough
if on[0] < num_samples+1:
# not enough data point before first missing, so exclude them all
on[0] = 0
if off[-1] > (len(xpos)-1-num_samples):
# not enough data points after last missing, so exclude them all
off[-1] = len(xpos)-1
# start at first non-missing sample if trial starts with missing (or
# excluded because too short) data
if on[0] == 0:
i = off[0]+1 # start at first non-missing
else:
i = 0
else:
i = 0
eind = i+num_samples
while eind <= (len(xpos)-1):
# check if max errors is crossed
if num_errors > max_errors:
if logging:
print(logging_offset +
'Too many empty clusters encountered, aborting file. \n')
stopped = True
final_weights = np.nan
return final_weights, stopped
# select data portion of nrsamples
idx = range(i, eind)
ll_d = [[] for p in range(nd+1)]
IDL_d = [[] for p in range(nd+1)]
ll_d[0] = np.vstack([xpos[idx], ypos[idx]])
# Filter the bit of data we're about to downsample. Then we simply need
# to select each nth sample where n is the integer factor by which
# number of samples is reduced. select samples such that they are till
# end of window
for p in range(nd):
if downsamp_filter:
# adjust default padlen to match matlab's filtfilt
ll_d[p+1] = scipy.signal.filtfilt(
b[p], a[p], ll_d[0], padlen=3*(max(len(b[p]), len(a[p]))-1))
ll_d[p+1] = ll_d[p+1][:, idxs[p]]
else:
ll_d[p+1] = ll_d[0][:, idxs[p]]
# do 2-means clustering
try:
for p in range(nd+1):
IDL_d[p] = kmeans2(
ll_d[p].T, first_cluster_fixed_value, second_cluster_fixed_value)[0]
except NotConvergedError as e:
if logging:
print(logging_offset + str(e))
num_errors += 1
except Exception as e:
if logging:
print(logging_offset +
'Unknown error encountered at sample {}.\n'.format(i))
raise e
# detect switches and weight of switch (= 1/number of switches in
# portion)
switches = [[] for p in range(nd+1)]
switchesw = np.empty(nd+1)
for p in range(nd+1):
switches[p] = np.abs(np.diff(IDL_d[p]))
switchesw[p] = 1./np.sum(switches[p])
# get nearest samples of switch and add weight
weighted = np.hstack([switches[0]*switchesw[0], 0])
for p in range(nd):
j = idxs[p][np.argwhere(switches[p+1]).flatten()]
for o in range(int(downsamples[p])):
weighted[j+o] = weighted[j+o] + switchesw[p+1]
# add to total weights
total_weights[idx] = total_weights[idx] + weighted
# record how many times each sample was tested
num_tests[idx] = num_tests[idx] + 1
# update i
i += step_size
eind += step_size
missing_on = np.logical_and(on >= i, on <= eind)
missing_off = np.logical_and(off >= i, off <= eind)
qWhichMiss = np.logical_or(missing_on, missing_off)
if np.sum(qWhichMiss) > 0:
# we have some missing in this window. we don't process windows
# with missing. Move back if we just skipped some samples, or else
# skip whole missing and place start of window and first next
# non-missing.
if on[qWhichMiss][0] == (eind-step_size):
# continue at first non-missing
i = off[qWhichMiss][0]+1
else:
# we skipped some points, move window back so that we analyze
# up to first next missing point
i = on[qWhichMiss][0]-num_samples
eind = i+num_samples
if eind > len(xpos)-1 and eind-step_size < len(xpos)-1:
# we just exceeded data bound, but previous eind was before end of
# data: we have some unprocessed samples. retreat just enough so we
# process those end samples once
d = eind-len(xpos)+1
eind = eind-d
i = i-d
# create final weights
np.seterr(invalid='ignore')
final_weights = total_weights/num_tests
np.seterr(invalid='warn')
return final_weights, stopped
# =============================================================================
# Fixation detection functions
# =============================================================================
def get_fixations(final_weights, timestamp, xpos, ypos, missing, par):
"""
Description
Parameters
----------
finalweights : type
weighting from 2-means clustering procedure
timestamp : np.array
Timestamp from eyetracker (should be in ms!)
xpos : np.array
Horizontal coordinates from Eyetracker
ypos : np.array
Vertical coordinates from Eyetracker
missing : np.array
Vector containing the booleans for missing values
par : Dictionary containing the following keys and values
cutoffstd : float
Number of std above mean clustering-weight to use as fixation cutoff
onoffsetThresh : float
Threshold (x*MAD of fixation) for walking forward/back for saccade off- and onsets
maxMergeDist : float
Maximum Euclidean distance in pixels between fixations for merging
maxMergeTime : float
Maximum time in ms between fixations for merging
minFixDur : Float
Minimum duration allowed for fixation
Returns
-------
fix : Dictionary containing the following keys and values
cutoff : float
Cutoff used for fixation detection
start : np.array
Vector with fixation start indices
end : np.array
Vector with fixation end indices
startT : np.array
Vector with fixation start times
endT : np.array
Vector with fixation end times
dur : type
Vector with fixation durations
xpos : np.array
Vector with fixation median horizontal position (one value for each fixation in trial)
ypos : np.array
Vector with fixation median vertical position (one value for each fixation in trial)
flankdataloss : bool
Boolean with 1 for when fixation is flanked by data loss, 0 if not flanked by data loss
fracinterped : float
Fraction of data loss/interpolated data
Examples
--------
>>> fix = getFixations(finalweights,data['time'],xpos,ypos,missing,par)
>>> fix
{'cutoff': 0.1355980099309374,
'dur': array([366.599, 773.2 , 239.964, 236.608, 299.877, 126.637]),
'end': array([111, 349, 433, 508, 600, 643]),
'endT': array([373.284, 1166.525, 1446.462, 1696.398, 2002.993, 2146.306]),
'flankdataloss': array([1., 0., 0., 0., 0., 0.]),
'fracinterped': array([0.06363636, 0. , 0. , 0. , 0. ,
0. ]),
'start': array([ 2, 118, 362, 438, 511, 606]),
'startT': array([ 6.685, 393.325, 1206.498, 1459.79 , 1703.116, 2019.669]),
'xpos': array([ 945.936, 781.056, 1349.184, 1243.92 , 1290.048, 1522.176]),
'ypos': array([486.216, 404.838, 416.664, 373.005, 383.562, 311.904])}
"""
# Extract the required parameters