Skip to content

Commit

Permalink
Debugged constant issue
Browse files Browse the repository at this point in the history
  • Loading branch information
mickcrosse committed Mar 22, 2019
1 parent 462da49 commit 80c26d5
Show file tree
Hide file tree
Showing 10 changed files with 117 additions and 140 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
14 changes: 7 additions & 7 deletions LICENSE
@@ -1,17 +1,17 @@
BSD 2-Clause License

Copyright (c) 2014, Edmund Lalor, Mick Crosse, Giovanni Di Liberto & Adam Bednar
Copyright (c) 2019, Mick Crosse
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Expand All @@ -22,4 +22,4 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19 changes: 1 addition & 18 deletions README.md
@@ -1,18 +1 @@
# mTRF Toolbox
The mTRF Toolbox is a MATLAB repository that permits the fast computation of the linear stimulus-response mapping of any sensory system in the forward or backward direction. It is suitable for analysing multi-channel EEG, MEG, ECoG and EMG data. The forward encoding model, or temporal response function (TRF) as it is commonly known, can be used to investigate information processing in neuronal populations using conventional time-frequency and source analysis techniques. In addition, TRFs can be used to predict the spectrotemporal dynamics of future neural responses to unseen stimulus sequences. Stimulus reconstruction can also be performed using backward decoding models that project the multi-channel population responses back to the dynamics of the causal stimulus signal. The mTRF Toolbox facilitates the use of extended continuous stimuli in electrophysiological studies compared to conventional time-locked averaging approaches which require the use of discrete, isolated stimulus events. This allows researchers to investigate of how neural systems process dynamic environmental signals such as speech, music and motion.

Supporting documentation can be found in the accompanying open access paper:<br/>
1. Crosse MJ, Di Liberto GM, Bednar A, Lalor EC (2016) [The Multivariate Temporal Response Function (mTRF) Toolbox: A MATLAB Toolbox for Relating Neural Signals to Continuous Stimuli](http://dx.doi.org/10.3389/fnhum.2016.00604). *Frontiers in Human Neuroscience* 10:604.

## Functions
- mTRFtrain.m
- mTRFpredict.m
- mTRFtransform.m
- mTRFcrossval.m
- mTRFmulticrossval.m
- lagGen.m

## Datasets
- speech_data.mat
- contrast_data.mat
- coherentmotion_data.mat
# mTRF-Toolbox
72 changes: 36 additions & 36 deletions README.txt
@@ -1,20 +1,19 @@
mTRF Toolbox is a MATLAB TOOLBOX that permits the fast computation of the
linear stimulus-response mapping of any sensory system in the forward or
backward direction. It is suitable for analysing EEG, MEG, ECoG and EMG
data.

The forward model, or temporal response function (TRF), can be interpreted
using conventional analysis techniques such as time-frequency and source
analysis. The TRF can also be used to predict future responses of the
system given a new stimulus signal. Similarly, the backward model can be
used to reconstruct spectrotemporal stimulus information given new response
data.

mTRF Toolbox facilitates the use of continuous stimuli in
electrophysiological studies as opposed to time-locked averaging
techniques which require discrete stimuli. This enables examination of
how neural systems process more natural and ecologically valid stimuli
such as speech, music, motion and contrast.
The mTRF Toolbox is a MATLAB repository that permits the fast computation
of the linear stimulus-response mapping of any sensory system in the
forward or backward direction. It is suitable for analysing multi-channel
EEG, MEG, ECoG and EMG data. The forward encoding model, or temporal
response function (TRF) as it is commonly known, can be used to investigate
information processing in neuronal populations using conventional time-
frequency and source analysis techniques. In addition, TRFs can be used to
predict the spectrotemporal dynamics of future neural responses to unseen
stimulus sequences. Stimulus reconstruction can also be performed using
backward decoding models that project the multi-channel population
responses back to the dynamics of the causal stimulus signal. The mTRF
Toolbox facilitates the use of extended continuous stimuli in
electrophysiological studies compared to conventional time-locked averaging
approaches which require the use of discrete, isolated stimulus events.
This allows researchers to investigate of how neural systems process
dynamic environmental signals such as speech, music and motion.

Table of Contents
=================
Expand Down Expand Up @@ -257,9 +256,9 @@ Tips on Practical Use
and number of samples.
* Downsample the data when conducting large-scale multivariate analyses
to reduce running time, e.g., 128 Hz or 64 Hz.
* Normalise all data, e.g., between [-1,1] or [0,1] or z-score. This will
stabalise regularisation across trials and enable a smaller parameter
search.
* Normalise or standardise the data beforehand. We recommend normalising
by the standard deviation. This will stabalise regularisation across
trials/subjects/groups and facilitate a smaller parameter search.
* Enter the start and finish time lags in milliseconds. Enter positive
lags for post-stimulus mapping and negative lags for pre-stimulus
mapping. This is the same for both forward and backward mapping - the
Expand All @@ -268,71 +267,72 @@ Tips on Practical Use
3-dimensional form, i.e., do not remove any singleton dimensions.
* When using MTRFCROSSVAL, the trials do not have to be the same length,
but using trials of the same length will optimise performance.
* When using mTRFmulticrossval, the trials in each of the three sensory
* When using MTRFMULTICROSSVAL, the trials in each of the three sensory
conditions should correspond to the stimuli in STIM.

Examples
========

Contrast: Forward model (TRF/VESPA)
>> load('contrast_data.mat');
>> [w,t] = mTRFtrain(contrastLevel,EEG,128,0,-150,450,1);
>> [w,t] = mTRFtrain(contrastLevel,EEG,128,1,-150,450,1);
>> figure; plot(t,squeeze(w(1,:,23))); xlim([-100,400]);
>> xlabel('Time lag (ms)'); ylabel('Amplitude (a.u.)')

Motion: Forward model (TRF/VESPA)
>> load('coherentmotion_data.mat');
>> [w,t] = mTRFtrain(coherentMotionLevel,EEG,128,0,-150,450,1);
>> [w,t] = mTRFtrain(coherentMotionLevel,EEG,128,1,-150,450,1);
>> figure; plot(t,squeeze(w(1,:,21))); xlim([-100,400]);
>> xlabel('Time lag (ms)'); ylabel('Amplitude (a.u.)')

Speech: Forward model (TRF/AESPA)
>> load('speech_data.mat');
>> [w,t] = mTRFtrain(envelope,EEG,128,0,-150,450,0.1);
>> [w,t] = mTRFtrain(envelope,EEG,128,1,-150,450,0.1);
>> figure; plot(t,squeeze(w(1,:,85))); xlim([-100,400]);
>> xlabel('Time lag (ms)'); ylabel('Amplitude (a.u.)')

Speech: Spectrotemporal forward model (STRF)
>> load('speech_data.mat');
>> [w,t] = mTRFtrain(spectrogram,EEG,128,0,-150,450,100);
>> [w,t] = mTRFtrain(spectrogram,EEG,128,1,-150,450,100);
>> figure; imagesc(t,1:16,squeeze(w(:,:,85))); xlim([-100,400]);
>> xlabel('Time lag (ms)'); ylabel('Frequency band')

Speech: Backward model (stimulus reconstruction)
>> load('speech_data.mat');
>> envelope = resample(envelope,64,128); EEG = resample(EEG,64,128);
>> stimTrain = envelope(1:64*60,1); respTrain = EEG(1:64*60,:);
>> [g,t,con] = mTRFtrain(stimTrain,respTrain,64,1,0,500,1e5);
>> [g,t,con] = mTRFtrain(stimTrain,respTrain,64,-1,0,500,1e5);
>> stimTest = envelope(64*60+1:end,1); respTest = EEG(64*60+1:end,:);
>> [recon,r,p,MSE] = mTRFpredict(stimTest,respTest,g,64,1,0,500,con);
>> [recon,r,p,MSE] = mTRFpredict(stimTest,respTest,g,64,-1,0,500,con);

Additional Information
======================

mTRF Toolbox is available for download at:
http://sourceforge.net/projects/aespa
SourceForge: http://sourceforge.net/projects/aespa
GitHub: https://github.com/mickcrosse/mTRF_Toolbox

mTRF Toolbox support documentation is available at:
http://dx.doi.org/10.3389/fnhum.2016.00604

For any questions and comments, please email Dr. Edmund Lalor at:
edmundlalor@gmail.com
For any questions and comments, please email:
mickcrosse@gmail.com (Mick Crosse) or edmundlalor@gmail.com (Ed Lalor)

Acknowledgments:
This work was supported in part by Science Foundation Ireland (SFI), the
Irish Higher Education Authority (HEA) and the Irish Research Council
(IRC).

References:
* Crosse MC, Di Liberto GM, Bednar A, Lalor EC (2015) The multivariate
temporal response function (mTRF) toolbox: a MATLAB toolbox for relating
neural signals to continuous stimuli. Front Hum Neurosci 10:604.
* Lalor EC, Pearlmutter BA, Reilly RB, McDarby G, Foxe JJ (2006) The
VESPA: a method for the rapid estimation of a visual evoked potential.
NeuroImage 32:1549-1561.
* Gon�alves NR, Whelan R, Foxe JJ, Lalor EC (2014) Towards obtaining
spatiotemporally precise responses to continuous sensory stimuli in
humans: a general linear modeling approach to EEG. NeuroImage 97(2014):196-205.
* Lalor, EC, & Foxe, JJ (2010) Neural responses to uninterrupted natural
speech can be extracted with precise temporal resolution. Eur J Neurosci
31(1):189-193.
* Crosse MC, Di Liberto GM, Bednar A, Lalor EC (2015) The multivariate
temporal response function (mTRF) toolbox: a MATLAB toolbox for relating
neural signals to continuous stimuli. Front Hum Neurosci 10:604.
* Gon�alves NR, Whelan R, Foxe JJ, Lalor EC (2014) Towards obtaining
spatiotemporally precise responses to continuous sensory stimuli in
humans: a general linear modeling approach to EEG. NeuroImage 97(2014):196-205.
8 changes: 4 additions & 4 deletions lagGen.m
Expand Up @@ -16,11 +16,11 @@
%
% See also MTRFTRAIN MTRFPREDICT MTRFCROSSVAL MTRFMULTICROSSVAL.

% Author: Michael Crosse
% Author: Mick Crosse
% Email: mickcrosse@gmail.com, edmundlalor@gmail.com
% Website: www.lalorlab.net
% Lalor Lab, Trinity College Dublin, IRELAND
% Email: edmundlalor@gmail.com
% Website: http://lalorlab.net/
% April 2014; Last revision: 18 August 2015
% April 2014; Last revision: 18-Aug-2015

xLag = zeros(size(x,1),size(x,2)*length(lags));

Expand Down
41 changes: 20 additions & 21 deletions mTRFcrossval.m
@@ -1,14 +1,14 @@
function [r,p,mse,pred,model] = mTRFcrossval(stim,resp,fs,map,tmin,tmax,lambda)
function [r,p,rmse,pred,model] = mTRFcrossval(stim,resp,fs,map,tmin,tmax,lambda)
%mTRFcrossval mTRF Toolbox cross-validation function.
% [R,P,MSE] = MTRFCROSSVAL(STIM,RESP,FS,MAP,TMIN,TMAX,LAMBDA) performs
% [R,P,RMSE] = MTRFCROSSVAL(STIM,RESP,FS,MAP,TMIN,TMAX,LAMBDA) performs
% leave-one-out cross-validation on the set of stimuli STIM and the
% neural responses RESP for the range of ridge parameter values LAMBDA.
% As a measure of performance, it returns the correlation coefficients R
% between the predicted and original signals, the corresponding p-values
% P and the mean squared errors MSE. Pass in MAP==1 to map in the forward
% direction or MAP==-1 to map backwards. The sampling frequency FS should
% be defined in Hertz and the time lags should be set in milliseconds
% between TMIN and TMAX.
% P and the root-mean-square errors RMSE. Pass in MAP==1 to map in the
% forward direction or MAP==-1 to map backwards. The sampling frequency
% FS should be defined in Hertz and the time lags should be set in
% milliseconds between TMIN and TMAX.
%
% [...,PRED,MODEL] = MTRFCROSSVAL(...) also returns the predictions PRED
% and the linear mapping functions MODEL.
Expand All @@ -25,7 +25,7 @@
% Outputs:
% r - correlation coefficients
% p - p-values of the correlations
% mse - mean squared errors
% rmse - root-mean-square errors
% pred - prediction [MAP==1: cell{1,trials}(lambdas by time by chans),
% MAP==-1: cell{1,trials}(lambdas by time by feats)]
% model - linear mapping function (MAP==1: trials by lambdas by feats by
Expand All @@ -42,11 +42,11 @@
% toolbox for relating neural signals to continuous stimuli. Front
% Hum Neurosci 10:604.

% Author: Michael Crosse
% Authors: Mick Crosse, Giovanni Di Liberto, Edmund Lalor
% Email: mickcrosse@gmail.com, edmundlalor@gmail.com
% Website: www.lalorlab.net
% Lalor Lab, Trinity College Dublin, IRELAND
% Email: edmundlalor@gmail.com
% Website: http://lalorlab.net/
% April 2014; Last revision: 31 May 2016
% April 2014; Last revision: 4-Feb-2019

% Define x and y
if tmin > tmax
Expand All @@ -69,23 +69,23 @@
tmax = ceil(tmax/1e3*fs*map);

% Set up regularisation
dim1 = size(x{1},2)*length(tmin:tmax)+size(x{1},2);
dim1 = size(x{1},2)*length(tmin:tmax)+1;
dim2 = size(y{1},2);
model = zeros(numel(x),numel(lambda),dim1,dim2);
if size(x{1},2) == 1
d = 2*eye(dim1,dim1); d([1,end]) = 1;
d = 2*eye(dim1);d([dim1+2,end]) = 1;
u = [zeros(dim1,1),eye(dim1,dim1-1)];
l = [zeros(1,dim1);eye(dim1-1,dim1)];
M = d-u-l;
M = d-u-l; M(:,1) = 0; M(1,:) = 0;
else
M = eye(dim1,dim1);
M = eye(dim1,dim1); M(1,1) = 0;
end

% Training
X = cell(1,numel(x));
for i = 1:numel(x)
% Generate lag matrix
X{i} = [ones(size(x{i})),lagGen(x{i},tmin:tmax)];
X{i} = [ones(size(x{i},1),1),lagGen(x{i},tmin:tmax)];
% Calculate model for each lambda value
for j = 1:length(lambda)
model(i,j,:,:) = (X{i}'*X{i}+lambda(j)*M)\(X{i}'*y{i});
Expand All @@ -96,7 +96,7 @@
pred = cell(1,numel(x));
r = zeros(numel(x),numel(lambda),dim2);
p = zeros(numel(x),numel(lambda),dim2);
mse = zeros(numel(x),numel(lambda),dim2);
rmse = zeros(numel(x),numel(lambda),dim2);
for i = 1:numel(x)
pred{i} = zeros(numel(lambda),size(y{i},1),dim2);
% Define training trials
Expand All @@ -107,10 +107,9 @@
% Calculate prediction
pred{i}(j,:,:) = X{i}*squeeze(mean(model(trials,j,:,:),1));
% Calculate accuracy
for k = 1:dim2
[r(i,j,k),p(i,j,k)] = corr(y{i}(:,k),squeeze(pred{i}(j,:,k))');
mse(i,j,k) = mean((y{i}(:,k)-squeeze(pred{i}(j,:,k))').^2);
end
[rtmp,ptmp] = corr(y{i},squeeze(pred{i}(j,:,:)));
r(i,j,:) = diag(rtmp); p(i,j,:) = diag(ptmp);
rmse(i,j,:) = sqrt(mean((y{i}-squeeze(pred{i}(j,:,:))).^2,1));
end
end

Expand Down

0 comments on commit 80c26d5

Please sign in to comment.