| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| function [ET, eegEvents, syncQuality] = synchronize(ET, startEndEvent, eegEvents, eegrate, n_eegsmp, doRegression, filterEyetrack, plotFig, searchRadius) |
|
|
| if nargin < 9 |
| help(mfilename) |
| return; |
| end |
|
|
| |
| startevent = startEndEvent(1); |
| endevent = startEndEvent(2); |
| clear startEndEvent |
|
|
| |
| ix_startevent = find(ET.event(:,2) == startevent,1); |
| ix_endevent = find(ET.event(:,2) == endevent,1,'last'); |
| assert(ix_endevent > ix_startevent,'\n%s(): Synchronization not possible. There is a problem with your chosen synchronization events in the ET data.\nThe last instance of your end-event %i does not occur after the first instance of your start-event %i.\n',mfilename,endevent,startevent); |
| |
| starteventTime = ET.event(ix_startevent,1); |
| endeventTime = ET.event(ix_endevent, 1); |
|
|
| |
| eegEvents = eegEvents(find(eegEvents(:,1) == startevent,1):find(eegEvents(:,1) == endevent,1,'last'),:); |
| eegEvents(:,3) = eegEvents(:,2)-eegEvents(1,2)+1; |
|
|
| |
| n_eegsmp_range = eegEvents(end,2)-eegEvents(1,2)+1; |
| assert(n_eegsmp_range > 0,'\n%s(): Synchronization not possible. There is a problem with your chosen synchronization events in the EEG.\nThe last instance of your end-event %i does not happen after the first instance of your start-event %i.\n',mfilename,endevent,startevent); |
|
|
|
|
| |
| |
| |
| |
| |
| |
| n_eyesmp_range = sum(ET.data(:,1) >= starteventTime & ET.data(:,1) <= endeventTime); |
| ix_starteventSample = find(ET.data(:,1) == starteventTime); |
| ix_endeventSample = find(ET.data(:,1) == endeventTime); |
| |
| |
| |
| |
| |
| |
| |
| if isempty(ix_starteventSample) |
| [ix_starteventSample, dummy] = searchclosest(ET.data(:,1),starteventTime); |
| end |
| if isempty(ix_endeventSample) |
| [ix_endeventSample, dummy] = searchclosest(ET.data(:,1),endeventTime); |
| end |
| n_etsmp_range = length(ix_starteventSample:ix_endeventSample); |
| eyerate = (n_etsmp_range / n_eegsmp_range) * eegrate; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| fprintf('\n\n-- %i EEG samples in synchronization range',n_eegsmp_range); |
| fprintf('\n-- %i ET samples in synchronization range',n_eyesmp_range); |
| fprintf('\n-- %.2f Hz EEG sampling rate',eegrate); |
| fprintf('\n-- %.2f Hz estimated ET sampling rate [*]',eyerate); |
| fprintf('\n ([*] taking EEG as master clock & assuming the ET recording was never paused)'); |
| if eyerate > eegrate |
| fprintf('\n-- Eye track will be downsampled to match the EEG sampling rate\n'); |
| fprintf('\n-- Note: the toolbox does not yet implement a low-pass filter to prevent aliasing.\n'); |
| else |
| fprintf('\n-- Eye track will be upsampled to match the EEG sampling rate\n'); |
| end |
|
|
| |
| |
| |
| |
| |
| |
| ET.newtime = linspace(starteventTime, endeventTime, n_eegsmp_range)'; |
| |
| %% for each existing ET event, search for closest timestamp in new time |
| new_ix = zeros(length(ET.event),1); |
| for k = ix_startevent:ix_endevent |
| new_ix(k) = searchclosest(ET.newtime,ET.event(k,1)); |
| end |
| ET.event(:,3) = new_ix; % assign updated sample index to ET events |
| |
| %% identify "shared" events in ET & EEG |
| % find EEG events that have an ET event of same type no more than |
| % searchRadius samples away |
| eegEventHasPartner = findmatchingevents(eegEvents,ET.event,searchRadius); |
| |
| ix_keepEEG = find(~isnan(eegEventHasPartner(:,1))); % EEG events with partner |
| ix_keepET = eegEventHasPartner(ix_keepEEG,1); % ET events that are partners of EEG events |
| x = eegEvents(ix_keepEEG,2); % sample of EEG events with a partner |
| y = ET.event(ix_keepET,1); % timestamp of ET events with a partner |
| |
| %% optional: linear regression |
| if doRegression |
| % do linear regression based on all shared events to optimize |
| % the recorded latencies of start-event and end-event. Helps to reduce |
| % error if start-event and/or end-event were transmitted with jitter. |
| % Won't help in case of constant transmission delays for all events. |
| |
| |
| b = [ones(length(x),1) x] \ y; |
| yhat = b(1)+b(2).*x; |
| |
| st = sum((y-mean(y)).^2); |
| |
| sr = sum((y-yhat).^2); |
| |
| r2 = (st-sr) / st; |
| |
| |
| |
| |
| ET.event(ix_startevent,1) = round( b(1)+b(2).*eegEvents(1,2) ); |
| ET.event(ix_endevent,1) = round( b(1)+b(2).*eegEvents(end,2) ); |
| starteventTime = ET.event(ix_startevent,1); |
| endeventTime = ET.event(ix_endevent,1); |
| |
| |
| ET.newtime = linspace(starteventTime, endeventTime, n_eegsmp_range)'; |
| end |
| |
| |
| %% linear interpolation |
| if ~isempty(ET.data) |
| |
| %% check for backward jumps in timestamps |
| % Note: with some older eye trackers, ET timestamps can sometimes jump |
| % backwards during the recording. This cannot be repaired since it remains |
| % unknown how much time really passed during such a backward jump. |
| % This problem was observed, in particular, with SMI trackers in combination |
| % with older versions of SMI's "IView X" recording software |
| assert(all(diff(ET.data(:,1)) > 0),'\n%s(): Sample time in the eye tracking data is not monotonically increasing.\nCheck for backward jumps in the timestamp column of your raw data and report this to your ET manufacturer.',mfilename); |
| |
| |
| if filterEyetrack |
| fprintf('\nWarning: Filtering to prevent aliasing is not yet implemented.') |
| fprintf('\nIt is planned for future versions.') |
| end |
| |
| |
| if filterEyetrack |
| |
| |
| |
| |
| |
| end |
| |
| |
| |
| et_new = interp1(ET.data(:,1),ET.data(:,2:end),ET.newtime,'linear','extrap'); |
| |
| |
| if filterEyetrack |
| |
| |
| |
| |
| end |
| |
| |
| ET.syncdata = [ET.newtime et_new]; |
| else |
| ET.syncdata = []; |
| end |
|
|
| |
| |
| new_ix = zeros(length(ET.event),1); |
| for k = ix_startevent:ix_endevent |
| new_ix(k) = searchclosest(ET.newtime,ET.event(k,1)); |
| end |
| ET.event(:,3) = new_ix; |
|
|
| |
| if isfield(ET,'eyeevent') |
| |
| eventTypes = fieldnames(ET.eyeevent)'; |
| |
| % go tru eye movement event types in Eyelink data (e.g., 'L_fixation', 'R_saccade',...) |
| for t = 1:length(eventTypes) |
| eventType = eventTypes{t}; |
| |
| % delete events not within synchronized time range |
| inRange = (ET.eyeevent.(eventType).data(:,1) > starteventTime) & (ET.eyeevent.(eventType).data(:,2) < endeventTime) ; |
| ET.eyeevent.(eventType).data = ET.eyeevent.(eventType).data(inRange,:); |
| ET.eyeevent.(eventType).eye = ET.eyeevent.(eventType).eye(inRange,:); |
| n_events = size(ET.eyeevent.(eventType).data,1); |
| |
| % find corresponding sample in new ('rescaled') ET time |
| new_ix = zeros(n_events,3); |
| new_time = zeros(n_events,3); |
| for e = 1:2*n_events |
| [new_ix(e) new_time(e)] = searchclosest(ET.newtime,ET.eyeevent.(eventType).data(e)); |
| end |
| |
| % update event "duration" |
| new_ix(:,3) = new_ix(:,2)-new_ix(:,1)+1; |
| |
| % translate to event indices in continuous EEG (add offset) |
| new_ix(:,1:2) = new_ix(:,1:2)-1 + eegEvents(1,2); |
| |
| % store event |
| ET.eyeevent.(eventType).data(:,1:3) = new_ix; |
| end |
| |
| clear new_* n_events inRange |
| end |
| |
| %% update timestamp of 'other' ET messages (new in Jan-2017, OD) |
| % = all messages starting with 'MSG', which are *not* keyword messages |
| % (used for synchronization) and *not* eyeevents (e.g. saccades). |
| if isfield(ET,'othermessages') |
| |
| % delete messages with timestamps not within synchronizeable time range |
| NotInRange = [ET.othermessages(:).timestamp] < starteventTime | [ET.othermessages(:).timestamp] > endeventTime; |
| ET.othermessages(NotInRange) = []; |
| % go tru 'other' messages |
| for m = 1:length(ET.othermessages) |
| % find corresponding sample in new ('rescaled') ET time |
| [new_ix, new_time] = searchclosest(ET.newtime,ET.othermessages(m).timestamp); |
| new_ix = new_ix-1 + eegEvents(1,2); |
| % add the corresponding EEG time (= sample of EEG corresponding to |
| % time that the message was send) to ET.othermessages |
| ET.othermessages(m).EEGsample = new_ix; |
| end |
| end |
| |
| %% find matching events again to update estimate of synchronization error |
| eegEventHasPartner = findmatchingevents(eegEvents,ET.event,searchRadius); |
| |
| %% feedback: estimate sync error based on all "shared" events |
| n_total = size(eegEventHasPartner,1); |
| n_nopartner = sum(isnan(eegEventHasPartner(:,2))); |
| [count, bin] = hist(eegEventHasPartner(:,end),-searchRadius:searchRadius); |
| syncQuality = [bin;count]'; |
|
|
| |
| fprintf('\nShared events of same type less than +/- %i samples apart: %i',searchRadius,n_total-n_nopartner); |
| fprintf('\n\nSynchronization quality:') |
| if n_nopartner == 0 |
| fprintf('\nFor all events in the EEG, an ET event of the same type was found within plusminus %i samples.',searchRadius); |
| fprintf('\nSynch. error is the latency difference between matching ET/EEG events after synchronization.'); |
| fprintf('\nIt is distributed as follows:\n'); |
| else |
| fprintf('\nWarning: For %i of %i EEG events (%.1f%%), no ET event of same name was found within plusminus %i samples',n_nopartner,n_total,100*n_nopartner/n_total,searchRadius); |
| fprintf('\nThis can occur, for example if some events were not transmitted to the ET (or EEG)'); |
| fprintf('\nIf only a few events do not have a \"partner\" event, and sync quality for the remaining events is good, you are probably safe.'); |
| fprintf('\nSynch. error is the latency difference between matching ET/EEG events after synchronization.'); |
| fprintf('\nFor the remaining %i events, it is distributed as follows:\n',n_total-n_nopartner); |
| end |
| fprintf('\n%s\t%s','Error [smp]','Events'); |
| fprintf('\n-------------------------\n'); |
| disp(syncQuality); |
| fprintf('-------------------------\n'); |
| avg_abs_error = sum(abs(syncQuality(:,1)).*syncQuality(:,2)) ./ sum(syncQuality(:,2)); |
| fprintf('Mean abs. sync. error (estimated from \"shared\" events): %.3f ms',avg_abs_error.*1000/eegrate); |
| fprintf('\n-------------------------\n\n'); |
|
|
| |
| |
| |
| |
| |
| if plotFig |
| figure('Name','synchronize(): Synchronization results'); |
| |
| |
| subplot(2,2,1:2); hold on; box on; |
| title('Overview: Event latencies in synchronized dataset','fontweight','bold') |
| |
| |
| colors_rgb = colormap('hsv'); |
| colors_rgb = [colors_rgb rand(size(colors_rgb,1),1)]; |
| colors_rgb = sortrows(colors_rgb,4); |
| |
| |
| eeg_type = eegEvents(:,1); |
| et_type = ET.event(ix_startevent:ix_endevent,2); |
| types_unique = unique([eeg_type; et_type]); |
| |
| |
| |
| |
| eeg_abssmp = eegEvents(:,2); |
| offset = eeg_abssmp(1)-1; |
| et_abssmp = ET.event(ix_startevent:ix_endevent,3)+offset; |
| |
| |
| rgb_type = colors_rgb( mod( (1:size(types_unique,1))-1, size(colors_rgb,1)) +1, :); |
| |
| h_bgGr = hggroup; |
| |
| fill([0 eeg_abssmp(1) eeg_abssmp(1) 0],[0 0 1 1],[.5 .5 .5], 'Parent',h_bgGr); |
| fill([eeg_abssmp(end) n_eegsmp n_eegsmp eeg_abssmp(end)],[0 0 1 1],[.5 .5 .5], 'Parent',h_bgGr); |
| |
| plot([0 n_eegsmp],[0.5 0.5],'linestyle','-','color',[0 0 0],'linewidth',1.0, 'Parent',h_bgGr) |
| |
| hleg = zeros(size(types_unique)); |
| |
| for loop = 1 : length(types_unique); |
| |
| ix1 = find(types_unique(loop) == eeg_type); |
| if ix1 |
| plot(eeg_abssmp(ix1),0.499,'linestyle','none','marker','.','color',rgb_type(loop,1:3),'handleVisibility','off'); |
| hline = plot(eeg_abssmp([ix1 ix1])', [0 0.499],'linestyle','-','color',rgb_type(loop,1:3),'linewidth',1,'handleVisibility','off'); |
| hleg(loop) = hline(1); |
| end |
| % 2. plot latencies of ET triggers between start-event & end-event |
| ix2 = find(types_unique(loop) == et_type); |
| if ix2 |
| plot(et_abssmp(ix2),0.501,'linestyle','none','marker','.','color',rgb_type(loop,1:3),'handleVisibility','off'); |
| hline = plot(et_abssmp([ix2 ix2])', [0.501 1],'linestyle','-','color',rgb_type(loop,1:3),'linewidth',1,'handleVisibility','off'); |
| if isempty(ix1) |
| hleg(loop) = hline(1); |
| end |
| end |
| end |
| ylim([0 1]) |
| xlim([0 n_eegsmp]) |
| xlabel('Time after start of EEG recording [samples]') |
| set(gca,'yTick',[0.25 0.75]); |
| set(gca,'yTickLabel',{'EEG events','ET events'}); |
| |
| try |
| get(hleg,{'DisplayName'}); |
| set(hleg,'handleVisibility','on'); |
| set(hleg,{'DisplayName'}, cellstr(num2str(types_unique)) ); |
| legend('show') |
| catch |
| fprintf('\nSubplot legend not shown.') |
| end |
| |
| |
| subplot(2,2,3); hold on; box on; |
| title('Comparison: Event latencies','fontweight','bold') |
| if doRegression |
| plot(x,yhat,'r-'); |
| plot(x,y,'k.'); |
| plot(x(1),yhat(1),'bo'); |
| plot(x(end),yhat(end),'bo'); |
| l = legend('regression line (ET on EEG)','shared events','start-/endEvent','Location','NorthWest'); |
| |
| xl = xlim; yl = ylim; |
| text(xl(2)-0.4*(xl(2)-xl(1)),yl(2)-0.6*(yl(2)-yl(1)),sprintf('R^2 = %.3f',r2),'fontsize',10); |
| else |
| plot(x,y,'k.'); |
| l = legend('shared events','Location','NorthWest'); |
| end |
| set(l,'box','off','fontsize',8); |
| xlabel('EEG latency (in samples)') |
| ylabel('Original ET latency (timestamp)') |
| |
| |
| |
| subplot(2,2,4); hold on; box on; |
| title('Quality of synchronization','fontweight','bold') |
| bar(bin,count,'k') |
| set(gca,'xTick',-searchRadius:1:searchRadius); |
| xlim([-searchRadius-0.5 searchRadius+0.5]) |
| xlabel('Time diff. between shared events (in samples)') |
| ylabel('Number of events') |
| end |