%% EXERCISES for TUTORIAL 1

%% EXERCISE 1

load Parkinson_Demo_Data.mat
whos

MEG=data.trial{1}(1,:);
EMG=data.trial{1}(2,:);
sf=data.fsample;

tmpTime=data.time;

Nsamples=size(EMG,2);% if all dimentions but one are 1 then Nsamples=length(EMG,2);



figure;
plot(tmpTime,EMG);

tmpInd=find(tmpTime>=35&tmpTime<=37);
figure;
plot(tmpTime(tmpInd),EMG(tmpInd));


%sptool;


% Segment with tremor i.e. 80 to 82 seconds
tmpInd=find(tmpTime>=80&tmpTime<=82);
figure;
plot(tmpTime(tmpInd),EMG(tmpInd));

%============================
%baseline 25-35 secs
tmpInd=find(tmpTime>=25&tmpTime<=35);
tmpData=EMG-mean(EMG(tmpInd));

%detrend
tmpData=detrend(tmpData);

figure;
plot(tmpTime,EMG,tmpTime,tmpData);
%----------------------------


%==================================
tmpInd=find(tmpTime>=140&tmpTime<=141);

% mean smothing - single forward
tmpSmoothed=filter(ones(1,30)/30,1,tmpData);
figure;
plot(tmpTime(tmpInd),tmpData(tmpInd),tmpTime(tmpInd),tmpSmoothed(tmpInd))

% mean smothing - forward and reverse 
tmpSmoothed=filtfilt(ones(1,15)/15,1,tmpData);
figure;
plot(tmpTime(tmpInd),tmpData(tmpInd),tmpTime(tmpInd),tmpSmoothed(tmpInd))

% median smoothing
tmpSmoothed=medfilt1(tmpData,30);
figure;
plot(tmpTime(tmpInd),tmpData(tmpInd),tmpTime(tmpInd),tmpSmoothed(tmpInd))

% smoothing with Savitzky-Golay filter
tmpSmoothed=sgolayfilt(tmpData,3,41);
figure;
plot(tmpTime(tmpInd),tmpData(tmpInd),tmpTime(tmpInd),tmpSmoothed(tmpInd))

%----------------------------------------

ylabel('mV');


%=========================================
%========================================
%=========================================
%=========================================
%=========================================



%% EXERCISE 2
%fdatool;



%% EXERCISE 3
tmpData=EMG;
Fc=10;
Fniq=sf/2;

[b,a]=butter(4,Fc/Fniq);
tmpFilt=filtfilt(b,a,tmpData);
figure;
plot(tmpTime,tmpData,tmpTime,tmpFilt);



[b,a]=butter(4,[1 30]./Fniq);
tmpFilt=filtfilt(b,a,tmpData);
figure;
plot(tmpTime,tmpData,tmpTime,tmpFilt);



[b,a]=butter(4,[0.1 30]./Fniq);
tmpFilt=filtfilt(b,a,tmpData);
figure;
plot(tmpTime,tmpData,tmpTime,tmpFilt);



%% EXERCISE 4

tmpDecim=decimate(tmpData,5);
tmpDecimTime=tmpTime(1:5:end);
figure;
plot(tmpTime,tmpData,tmpDecimTime,tmpDecim);
