added all my stuff

This commit is contained in:
Jan Benda 2014-11-12 18:39:02 +01:00
parent 0fdcf2f82e
commit 350ee7ca2b
160 changed files with 5869 additions and 253 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

View File

@ -0,0 +1,60 @@
\documentclass[pdftex]{beamer}
\usepackage{beamerthemedefault}
\usepackage{multimedia}
\usepackage{wasysym}
\useoutertheme[subsection=false]{smoothbars}
\useinnertheme[shadow=true]{rounded}
\setbeamercolor{block title}{fg=black,bg=gray}
\setbeamercolor{block title alerted}{use=alerted text,fg=black,bg=alerted text.fg!75!bg}
\setbeamercolor{block title example}{use=example text,fg=black,bg=example text.fg!75!bg}
\setbeamercolor{block body}{parent=normal text,use=block title,bg=block title.bg!25!bg}
\setbeamercolor{block body alerted}{parent=normal text,use=block title alerted,bg=block title alerted.bg!25!bg}
\setbeamercolor{block body example}{parent=normal text,use=block title example,bg=block title example.bg!25!bg}
\usepackage{hyperref}
\usepackage[english]{babel} % language set to new-german
\usepackage[utf8]{inputenc} % coding of german special characters
\usepackage{graphicx} % \includegraphics[options]{file.eps}
\usepackage{array}
\usepackage{setspace}
\usepackage{color}
\usepackage{eqlist}
\usepackage{wallpaper}
\definecolor{tug}{HTML}{CC0000}
\newcommand{\rot}[1]{{\color{tug} #1}}
\definecolor{green}{HTML}{1C8C1C}
\newcommand{\gruen}[1]{{\color{green} #1}}
\definecolor{blue}{HTML}{2424AA}
\newcommand{\blau}[1]{{\color{blue} #1}}
\definecolor{gray}{rgb}{0.8,0.8,0.8}
\definecolor{gray2}{rgb}{0.5,0.5,0.5}
\definecolor{gray2}{rgb}{0.5,0.5,0.5}
\newcommand{\grau}[1]{{\color{gray2} #1}}
\setbeamercolor{footline}{fg=black,bg=gray}
%\setbeamertemplate{headline}[text line]{
% \begin{beamercolorbox}[wd=\paperwidth,ht=8ex,dp=4ex]{}%\vskip-4pt
% \insertnavigation{0.85\paperwidth}
% \hskip-1pt\rule{\paperwidth}{0.3pt}
% \end{beamercolorbox}
%}
\setlength{\unitlength}{0.01\paperwidth}
\setbeamercolor{background canvas}{bg=}
\begin{document}
\begin{frame}
\frametitle{Evalutation}
In Ilias:\\[2ex]
Go to {\em Evaluation} and fill out the forms!\\[6ex]
\includegraphics[width=0.8\textwidth]{correlationcartoon}
\end{frame}
\end{document}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,52 @@
% some vectors:
x = [ -1:0.02:1 ];
y = x*0.5 + 0.1*randn( size(x) );
plot( x, y, '.b' );
hold on
plot( x(10), y(10), '.r' );
% new coordinate system:
%e1 = [ 3/5 4/5 ];
%e2 = [ -4/5 3/5 ];
e1 = [ 3 4 ];
e2 = [ -4 3 ];
me1 = sqrt( e1*e1' );
e1 = e1/me1;
me2 = sqrt( e2*e2' );
e2 = e2/me2;
quiver( 0.0, 0.0 , e1(1), e1(2), 1.0, 'r' )
quiver( 0.0, 0.0 , e2(1), e2(2), 1.0, 'g' )
axis( 'equal' )
% project [x y] onto e1 and e2:
% % the long way:
% nx = zeros( size( x ) ); % new x coordinate
% ny = zeros( size( y ) ); % new y coordinates
% for k=1:length(x)
% xvec = [ x(k) y(k) ];
% nx(k) = xvec * e1';
% ny(k) = xvec * e2';
% end
% plot( nx, ny, '.g' );
% the short way:
%nx = [ x' y' ] * e1';
%nx = [x; y]' * e1';
% nx = e1 * [ x; y ];
% ny = e2 * [ x; y ];
% plot( nx, ny, '.g' );
% even shorter:
n = [e1; e2 ] * [ x; y ];
plot( n(1,:), n(2,:), '.g' );
hold off

View File

@ -0,0 +1,37 @@
% some vectors:
x=[-1:0.02:1]'; % column vector!
y=4*x/3 + 0.1*randn( size( x ) );
plot( x, y, '.b' );
axis( 'equal' );
hold on;
% new coordinate system:
% e1 = [ 3 4 ]
% e2 = [ -4 3 ]
% and normalized to unit length (factor 1/5):
e = [ 3/5 -4/5; 4/5 3/5 ];
quiver( [0 0], [0 0], e(1,:), e(2,:), 1.0, 'r' );
% project [x y] onto e1 and e2:
% % the long way:
% nx = x;
% ny = y;
% for k=1:length(x)
% nx(k) = [x(k) y(k)]*e(:,1);
% ny(k) = [x(k) y(k)]*e(:,2);
% end
% plot( nx, ny, '.g' );
% the short way
% nx = [x y]*e(:,1);
% ny = [x y]*e(:,2);
% plot( nx, ny, '.g' );
% even shorter:
n = [x y]*e;
plot( n(:,1), n(:,2), '.g' );
xlabel( 'x' );
ylabel( 'y' );
hold off;

View File

@ -0,0 +1,29 @@
set( 0, 'DefaultTextFontSize', 22.0 );
set( 0, 'DefaultAxesFontSize', 22.0 );
n = 10000;
x = 1.0*randn( n, 1 );
z = 1.0*randn( n, 1 );
for r=-1:0.2:1
y = r*x + sqrt(1.0-r^2.0)*z;
cv = cov( x, y );
cr = corrcoef( x, y );
scatter( x, y, 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' );
ylabel( 'y' );
text( 0.05, 0.9, sprintf( 'r = %.2f', r ), 'Units', 'normalized' )
text( 0.05, 0.8, sprintf( 'cor = %.2f %.2f', cr(1,1), cr(1,2) ), 'Units', 'normalized' )
text( 0.05, 0.7, sprintf( 'cov = %.2f %.2f', cv(1,1), cv(1,2) ), 'Units', 'normalized' )
waitforbuttonpress;
end
y = x.^2.0 + 0.5*z;
cv = cov( x, y );
cr = corrcoef( x, y );
scatter( x, y, 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' );
ylabel( 'y' );
text( 0.05, 0.9, sprintf( 'x^2', r ), 'Units', 'normalized' )
text( 0.05, 0.8, sprintf( 'cor = %.2f %.2f', cr(1,1), cr(1,2) ), 'Units', 'normalized' )
text( 0.05, 0.7, sprintf( 'cov = %.2f %.2f', cv(1,1), cv(1,2) ), 'Units', 'normalized' )

View File

@ -44,11 +44,16 @@ function covareigen( x, y, pm, w, h )
% plot eigenvectors: % plot eigenvectors:
quiver( ones( 1, 2 ).*mean( x ), ones( 1, 2 )*mean(y), v(1,:).*sqrt(diag(d))', v(2,:).*sqrt(diag(d))', 'r', 'LineWidth', 3, 'AutoScale', 'off', 'AutoScaleFactor', 1.0, 'MaxHeadSize', 0.7 ) quiver( ones( 1, 2 ).*mean( x ), ones( 1, 2 )*mean(y), v(1,:).*sqrt(diag(d))', v(2,:).*sqrt(diag(d))', 'r', 'LineWidth', 3, 'AutoScale', 'off', 'AutoScaleFactor', 1.0, 'MaxHeadSize', 0.7 )
xlabel( 'x' );
ylabel( 'y' );
axis( 'equal' ); axis( 'equal' );
hold off; hold off;
% histogram of x values:
subplot( 2, 2, 3 ); subplot( 2, 2, 3 );
hist( x, 50, 'b' ); hist( x, 50, 'b' );
xlabel( 'x' );
ylabel( 'n_x' );
% sort the eigenvalues: % sort the eigenvalues:
[d,inx] = sort( diag(d), 'descend' ); [d,inx] = sort( diag(d), 'descend' );
@ -59,24 +64,28 @@ function covareigen( x, y, pm, w, h )
x = x - mean( x ); x = x - mean( x );
y = y - mean( y ); y = y - mean( y );
% project onto eigenvectors: % project onto eigenvectors:
nx = [ x y ] * v(:,inx(1)); nc = [ x y ] * v(:,inx);
ny = [ x y ] * v(:,inx(2)); cv = cov( nc )
cv = cov( [nx, ny] )
[ v , d] = eig( cv ) [ v , d] = eig( cv )
if (pm > 0) & (nargin == 5) if (pm > 0) & (nargin == 5)
if pm == 1 if pm == 1
[n,c] = hist3([nx ny], { xp, yp } ); [n,c] = hist3( nc, { xp, yp } );
contourf( c{1}, c{2}, n' ); contourf( c{1}, c{2}, n' );
else else
gauss = reshape( exp(-0.5*diag(xy*inv(cv)*xy'))/sqrt((2.0*pi)^2.0*det(cv)), size( xg ) ); gauss = reshape( exp(-0.5*diag(xy*inv(cv)*xy'))/sqrt((2.0*pi)^2.0*det(cv)), size( xg ) );
contourf( xp, yp, gauss ) contourf( xp, yp, gauss )
end end
else else
scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' ); scatter( nc(:,1), nc(:,2), 'b', 'filled', 'MarkerEdgeColor', 'white' );
end end
xlabel( 'x' );
ylabel( 'y' );
axis( 'equal' ); axis( 'equal' );
hold off; hold off;
% histogram of new x values:
subplot( 2, 2, 4 ); subplot( 2, 2, 4 );
hist( nx, 50, 'b' ); hist( nc(:,1), 50, 'b' );
xlabel( 'new x' );
ylabel( 'n_newx' );
end end

View File

@ -27,18 +27,33 @@ function covareigen3( x, y, z )
%axis( 'equal' ); %axis( 'equal' );
hold off; hold off;
% 2D scatter plots:
subplot( 2, 6, 4 );
scatter( x, y, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' )
ylabel( 'y' )
subplot( 2, 6, 5 );
scatter( x, z, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' )
ylabel( 'z' )
subplot( 2, 6, 6 );
scatter( y, z, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'y' )
ylabel( 'z' )
% sort the eigenvalues: % sort the eigenvalues:
[d,inx] = sort( diag(d), 'descend' ); [d,inx] = sort( diag(d), 'descend' );
subplot( 2, 2, 2 ); subplot( 2, 2, 4 );
hold on; hold on;
% subtract means: % subtract means:
x = x - mean( x ); x = x - mean( x );
y = y - mean( y ); y = y - mean( y );
% project onto eigenvectors: % project onto eigenvectors:
nx = [ x y z ] * v(:,inx(1)); nx = [ x y z ] * v(:,inx);
ny = [ x y z ] * v(:,inx(2)); scatter( nx(:,1), nx(:,2), 'b', 'filled', 'MarkerEdgeColor', 'white' );
scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' ); xlabel( 'ex' )
ylabel( 'ey' )
axis( 'equal' ); axis( 'equal' );
hold off; hold off;

View File

@ -0,0 +1,19 @@
scrsz = get( 0, 'ScreenSize' );
set( 0, 'DefaultFigurePosition', [ scrsz(3)/2 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2 ] );
n = 10000;
% three distributions:
x = randn( n, 1 );
y = randn( n, 1 );
z = randn( n, 1 );
dx = [ 0 8 0 0 ];
dy = [ 0 0 8 0 ];
dz = [ 0 0 0 8 ];
for k = 1:4
x((k-1)*n/4+1:k*n/4) = x((k-1)*n/4+1:k*n/4) + dx(k);
y((k-1)*n/4+1:k*n/4) = y((k-1)*n/4+1:k*n/4) + dy(k);
z((k-1)*n/4+1:k*n/4) = z((k-1)*n/4+1:k*n/4) + dz(k);
end
f = figure( 1 );
covareigen3( x, y, z );

View File

@ -5,11 +5,11 @@ set( 0, 'DefaultFigurePosition', [ scrsz(3)/2 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2 ]
n = 10000; n = 10000;
x = randn( n, 1 ); x = randn( n, 1 );
f = figure( 1 ); f = figure( 1 );
for r = 0.01:0.199:1 for r = 0.01:0.19:1
fprintf( 'Correlation = %g\n', r ); fprintf( 'Correlation = %g\n', r );
clf( f ); clf( f );
y = r*x + sqrt(1-r^2)*randn( n, 1 ); y = r*x + sqrt(1-r^2)*randn( n, 1 );
covareigen( x, y, 2, 5.0, 3.0 ); covareigen( x, y, 0, 5.0, 3.0 );
key = waitforbuttonpress; key = waitforbuttonpress;
end end
return return
@ -29,7 +29,7 @@ for d = 0:1:5
x = [ x1; x2 ]; x = [ x1; x2 ];
y = [ y1+d2; y2-d2 ]; y = [ y1+d2; y2-d2 ];
scrsz = get(0,'ScreenSize'); scrsz = get(0,'ScreenSize');
covareigen( x, y, 1, 10.0, 7.0 ); covareigen( x, y, 0, 10.0, 7.0 );
%key = waitforbuttonpress; %key = waitforbuttonpress;
pause( 1.0 ); pause( 1.0 );
end end

Binary file not shown.

View File

@ -0,0 +1,54 @@
% this script simulates extracellularly recorded
% spike waveforms and saves them in extdata.mat.
% generate spikes:
n = 1000;
misi = 0.01;
isis = exprnd( misi, n, 1 );
isis = isis + 0.01;
spikes = cumsum( isis );
p = rand( size( spikes ) );
% spike waveforms:
dt = 0.0001;
waveformt = -0.01:dt:0.01;
waveform1 = 2.0*exp( -(waveformt-0.0003).^2/2.0/0.0005^2 ) - 1.4*exp( -(waveformt-0.0005).^2/2.0/0.0005^2 );
waveform2 = exp( -waveformt.^2/2.0/0.002^2 ).*cos(2.0*pi*waveformt/0.005);
p12 = 0.5;
% voltage trace:
noise = 0.2;
time = 0:dt:spikes(end)+3.0*waveformt(end);
voltage = noise*randn( 1, length( time ) );
for k = 1:length( spikes )
inx = ceil( spikes(k)/dt );
if p(k) < p12
voltage(inx:inx+length(waveformt)-1) = voltage(inx:inx+length(waveformt)-1) + waveform1;
else
voltage(inx:inx+length(waveformt)-1) = voltage(inx:inx+length(waveformt)-1) + waveform2;
end
end
figure( 1 );
clf;
plot( time(time<1.0), voltage(time<1.0) );
hold on;
% find peaks:
thresh = 0.7;
inx = find( voltage(2:end-1) > thresh & voltage(1:end-2)<voltage(2:end-1) & voltage(2:end-1) > voltage(3:end) ) + 1;
spiketimes = time(inx);
spikevoltage = voltage(inx);
tinx = inx;
for k=1:2
inx = find( ( spiketimes(2:end-1)-spiketimes(1:end-2)>0.005 | spikevoltage(2:end-1) > spikevoltage(1:end-2) ) & ( spiketimes(3:end)-spiketimes(2:end-1)>0.005 | spikevoltage(2:end-1) > spikevoltage(3:end) ) )+1;
spiketimes = spiketimes(inx);
spikevoltage = spikevoltage(inx);
tinx = tinx(inx);
end
scatter( spiketimes(spiketimes<1.0), spikevoltage(spiketimes<1.0), 100.0, 'r', 'filled' );
%scatter( t(tinx), v(tinx), 100.0, 'r', 'filled' );
hold off;
% save data to file:
save( 'extdata', 'time', 'voltage', 'spiketimes', 'waveformt', 'waveform1', 'waveform2' );

View File

@ -0,0 +1,25 @@
% Gaussian density from histogram:
x = randn( 1000000, 1 );
[ n, c ] = hist( x, 100 );
n = n/sum(n)/(c(2)-c(1));
bar( c, n );
hold on;
% equation p(x):
xx = -5:0.01:5;
p=exp(-xx.^2/2.0)/sqrt(2.0*pi);
plot( xx, p, 'r', 'LineWidth', 3 )
% with mean=2 and sigma=0.5:
mu = 2.0;
sig = 0.5;
x = sig*x + mu;
[ n, c ] = hist( x, 100 );
n = n/sum(n)/(c(2)-c(1));
bar( c, n );
% equation:
p=exp(-(xx-mu).^2/2.0/sig^2)/sqrt(2.0*pi*sig^2);
plot( xx, p, 'r', 'LineWidth', 3 )
hold off;
xlabel( 'x' );
ylabel( 'p(x)' );
title( 'Gaussian distribution' );

View File

@ -0,0 +1,21 @@
% Visualize some common matrix transformations
% in a 2D coordinate system
disp( 'Click into the plot to advance to the next matrix' )
matrixbox( [ 1 0; 0 1], 'Identity' );
matrixbox( [ 2 0; 0 1], 'Scale x' );
matrixbox( [ 1 0; 0 2], 'Scale y' );
matrixbox( [ 2 0; 0 2], 'Scale x and y' );
matrixbox( [ 0.5 0; 0 0.5], 'Scale x and y' );
matrixbox( [ -1 0; 0 1], 'Flip x' );
matrixbox( [ 1 0; 0 -1], 'Flip y' );
matrixbox( [ -1 0; 0 -1], 'Flip both' );
matrixbox( [ 1 2; 0 1], 'Shear x' );
matrixbox( [ 1 0; 2 1], 'Shear y' );
matrixbox( [ 0.5 1; 1 0.5], 'Something A' );
matrixbox( [ 0.5 1; 1.2 0.6], 'Something B' );
% rotation matrices:
for deg = 0:10:360
phi = deg*pi/180.0;
matrixbox( [ cos(phi) -sin(phi); sin(phi) cos(phi)], sprintf( 'Rotate %.0f', deg ) );
end

View File

@ -0,0 +1,45 @@
function matrixbox( m, s )
% visualizes the effect of a matrix m on a set of vectors forming a box
% m: a 2x2 matrix
% s: a string plotted as the title of the plot
% this function is called by matrix2dtrafos.m
% the 5 vectors that point into the cornes of a unit square:
v = [ 0 1 1 0 0;
0 0 1 1 0 ];
% transform v by means of m into new vector w:
w = m*v;
clf;
hold on;
% axis:
plot( [-2 2], [0 0], 'k', 'LineWidth', 1 );
plot( [0 0], [-2 2], 'k', 'LineWidth', 1 );
% old vectors:
plot( v(1,:), v(2,:), 'k', 'LineWidth', 1.0 )
quiver( v(1,1), v(2,1), v(1,3), v(2,3), 1.0, 'k', 'LineWidth', 2.0 );
scatter( v(1,2), v(2,2), 60.0, 'filled', 'k' );
% transformed vectors:
plot( w(1,:), w(2,:), 'b', 'LineWidth', 2.0 )
quiver( w(1,1), w(2,1), w(1,3), w(2,3), 1.0, 'b', 'LineWidth', 3.0 );
scatter( w(1,2), w(2,2), 100.0, 'filled', 'b' );
% eigenvectors:
[ev ed] = eig(m);
n = ev*ed;
if isreal( n )
quiver( [0 0], [0 0], n(1,:), n(2,:), 1.0, 'r', 'LineWidth', 2.0 );
text( 0.1, 0.2, sprintf( '\\lambda_1 = %.3g', ed(1,1) ), 'Units', 'normalized' )
text( 0.1, 0.1, sprintf( '\\lambda_2 = %.3g', ed(2,2) ), 'Units', 'normalized' )
end
hold off;
xlim( [ -2 2 ] );
ylim( [ -2 2 ] );
axis( 'equal' );
m( abs(m) < 1e-3 ) = 0.0; % make zeros really a zero
text( 0.7, 0.15, 'A =', 'Units', 'normalized' )
text( 0.8, 0.2, sprintf( '%.3g', m(1,1) ), 'Units', 'normalized' )
text( 0.9, 0.2, sprintf( '%.3g', m(1,2) ), 'Units', 'normalized' )
text( 0.8, 0.1, sprintf( '%.3g', m(2,1) ), 'Units', 'normalized' )
text( 0.9, 0.1, sprintf( '%.3g', m(2,2) ), 'Units', 'normalized' )
title( s );
waitforbuttonpress;
end

View File

@ -0,0 +1,85 @@
% open a file to write in the LaTeX commands:
f = fopen( 'matrices.tex','w');
fprintf( f, '\\documentclass{exam}\n' );
fprintf( f, '\\usepackage{amsmath}\n' );
fprintf( f, '\\begin{document}\n' );
for k = 1:40
% compute row and column numbers:
pd = rand( 1, 1 );
if pd < 0.05
% row vector multiplication that might not be possible:
am = 1;
an = randi( [ 2 4 ]);
bm = randi( [ 2 4 ]);
bn = 1;
elseif pd < 0.1
% column vector multiplication that might not be possible:
am = randi( [ 2 4 ]);
an = 1;
bm = 1;
bn = randi( [ 2 4 ]);
elseif pd < 0.4
% row vector multiplication that is possible:
am = 1;
an = randi( [ 2 4 ]);
bm = an;
bn = 1;
elseif pd < 0.5
% column vector multiplication that is possible:
am = randi( [ 2 4 ]);
an = 1;
bm = 1;
bn = am;
elseif pd < 0.6
% matrix multiplication that might not be possible:
am = randi( [ 2 4 ]);
an = randi( [ 2 4 ]);
bm = randi( [ 2 4 ]);
bn = randi( [ 2 4 ]);
else
% matrix multiplication that is possible:
am = randi( [ 2 4 ]);
an = randi( [ 2 4 ]);
bm = an;
bn = randi( [ 2 4 ]);
end
% generate the matrices:
a = randi( [-4 4], am, an );
b = randi( [-4 4], bm, bn );
% write them out as LaTeX code:
% matrix a:
fprintf( f, ' \\[ \\begin{pmatrix}' );
for r = 1:size( a, 1 )
for c = 1:size( a, 2 )
if c > 1
fprintf( f, ' &' );
end
fprintf( f, ' %d', a(r,c) );
end
if r < size( a, 1 )
fprintf( f, ' \\\\' );
end
end
fprintf( f, ' \\end{pmatrix} \\cdot\n' );
% matrix b:
fprintf( f, ' \\begin{pmatrix}' );
for r = 1:size( b, 1 )
for c = 1:size( b, 2 )
if c > 1
fprintf( f, ' &' );
end
fprintf( f, ' %d', b(r,c) );
end
if r < size( b, 1 )
fprintf( f, ' \\\\' );
end
end
fprintf( f, ' \\end{pmatrix} = \\]\n\n' );
end
% close the document and the file:
fprintf( f, '\\end{document}\n' );
fclose( f );

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,95 @@
function pca2d( x, y, pm, w, h )
% computes covariance matrix from the pairs x, y
% diagonalizes covariance matrix, i.e. performs a PCA on [ x, y ]
% x and y are column vectors
% pm: 0 - scatter of data, 1 - histogram, 2 - multivariate gauss from
% covariance matrix, 1 and 2 require w and h
% w and h are the width and the height (in data units) for plotting
% histograms instead of scatter
% covariance matrix:
cv = cov( [ x y ] );
% eigen values:
[ v , d] = eig( cv )
s = sign( v );
s(1,:) = s(2,:);
v = v .* s;
% plots:
subplot( 2, 2, 1 );
hold on;
if (pm > 0) & (nargin == 5)
if pm == 1
% histogram of data:
xp = -w:0.5:w;
yp = -h:0.5:h;
[n,c] = hist3([x y], { xp, yp } );
contourf( c{1}, c{2}, n' );
else
% bivariate Gaussian:
xp = -w:0.1:w;
yp = -h:0.1:h;
[xg,yg] = meshgrid( xp, yp );
xy = [ xg(:) yg(:) ];
gauss = reshape( exp(-0.5*diag(xy*inv(cv)*xy'))/sqrt((2.0*pi)^2.0*det(cv)), size( xg ) );
contourf( xp, yp, gauss )
end
colormap( 'gray' );
else
% scatter plot:
scatter( x, y, 'b', 'filled', 'MarkerEdgeColor', 'white' );
end
% plot eigenvectors:
quiver( ones( 1, 2 ).*mean( x ), ones( 1, 2 )*mean(y), v(1,:).*sqrt(diag(d))', v(2,:).*sqrt(diag(d))', 'r', 'LineWidth', 3, 'AutoScale', 'off', 'AutoScaleFactor', 1.0, 'MaxHeadSize', 0.7 )
xlabel( 'x' );
ylabel( 'y' );
axis( 'equal' );
hold off;
% histogram of x values:
subplot( 2, 2, 3 );
hist( x, 50, 'b' );
xlabel( 'x' );
ylabel( 'count' );
% sort the eigenvalues:
[d,inx] = sort( diag(d), 'descend' );
subplot( 2, 2, 2 );
hold on;
% subtract means:
x = x - mean( x );
y = y - mean( y );
% project onto eigenvectors:
nc = [ x y ] * v(:,inx);
cv = cov( nc )
[ v , d] = eig( cv )
if (pm > 0) & (nargin == 5)
if pm == 1
% histogram of data:
[n,c] = hist3( nc, { xp, yp } );
contourf( c{1}, c{2}, n' );
else
% bivariate Gaussian:
gauss = reshape( exp(-0.5*diag(xy*inv(cv)*xy'))/sqrt((2.0*pi)^2.0*det(cv)), size( xg ) );
contourf( xp, yp, gauss )
end
else
% scatter plot:
scatter( nc(:,1), nc(:,2), 'b', 'filled', 'MarkerEdgeColor', 'white' );
end
xlabel( 'n_x' );
ylabel( 'n_y' );
axis( 'equal' );
hold off;
% histogram of new x values:
subplot( 2, 2, 4 );
hist( nc(:,1), 50, 'b' );
xlabel( 'n_x' );
ylabel( 'count' );
end

View File

@ -0,0 +1,33 @@
scrsz = get( 0, 'ScreenSize' );
set( 0, 'DefaultFigurePosition', [ scrsz(3)/2 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2 ] );
% correlation coefficients:
n = 10000;
x = randn( n, 1 );
f = figure( 1 );
for r = 0.01:0.19:1
fprintf( 'Correlation = %g\n', r );
clf( f );
y = r*x + sqrt(1-r^2)*randn( n, 1 );
pca2d( x, y, 0, 5.0, 3.0 );
waitforbuttonpress;
end
% two distributions:
n = 10000;
x1 = randn( n/2, 1 );
y1 = randn( n/2, 1 );
x2 = randn( n/2, 1 );
y2 = randn( n/2, 1 );
f = figure( 1 );
pause( 'on' );
for d = 0:1:5
fprintf( 'Distance = %g\n', d );
clf( f );
d2 = d / sqrt( 2.0 );
x = [ x1; x2 ];
y = [ y1+d2; y2-d2 ];
scrsz = get(0,'ScreenSize');
pca2d( x, y, 0, 10.0, 7.0 );
waitforbuttonpress;
end

View File

@ -0,0 +1,60 @@
function pca3d( x, y, z )
% computes covariance matrix from the triples x, y, z
% diagonalizes covariance matrix, i.e. performs pca on [ x, y, z ]
% x, y and z are column vectors
% covariance matrix:
cv = cov( [ x y z ] );
% eigen values:
[ v , d] = eig( cv )
% plots:
subplot( 1, 2, 1 );
hold on;
% scatter plot:
view( 3 );
scatter3( x, y, z, 0.1, 'b', 'filled', 'MarkerEdgeColor', 'blue' );
xlabel( 'x' );
ylabel( 'y' );
zlabel( 'z' );
grid on;
% plot eigenvectors:
quiver3( ones( 1, 3 ).*mean( x ), ones( 1, 3 )*mean(y), ones( 1, 3 )*mean(z), v(1,:).*sqrt(diag(d))', v(2,:).*sqrt(diag(d))', v(3,:).*sqrt(diag(d))', 'r', 'LineWidth', 3, 'AutoScale', 'off', 'AutoScaleFactor', 1.0, 'MaxHeadSize', 0.7 )
%axis( 'equal' );
hold off;
% 2D scatter plots:
subplot( 2, 6, 4 );
scatter( x, y, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' )
ylabel( 'y' )
subplot( 2, 6, 5 );
scatter( x, z, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'x' )
ylabel( 'z' )
subplot( 2, 6, 6 );
scatter( y, z, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'y' )
ylabel( 'z' )
% sort the eigenvalues:
[d,inx] = sort( diag(d), 'descend' );
subplot( 2, 2, 4 );
hold on;
% subtract means:
x = x - mean( x );
y = y - mean( y );
% project onto eigenvectors:
nx = [ x y z ] * v(:,inx);
scatter( nx(:,1), nx(:,2), 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'ex' )
ylabel( 'ey' )
axis( 'equal' );
hold off;
end

View File

@ -0,0 +1,19 @@
scrsz = get( 0, 'ScreenSize' );
set( 0, 'DefaultFigurePosition', [ scrsz(3)/2 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2 ] );
n = 10000;
% three distributions:
x = randn( n, 1 );
y = randn( n, 1 );
z = randn( n, 1 );
dx = [ 0 8 0 0 ];
dy = [ 0 0 8 0 ];
dz = [ 0 0 0 8 ];
for k = 1:4
x((k-1)*n/4+1:k*n/4) = x((k-1)*n/4+1:k*n/4) + dx(k);
y((k-1)*n/4+1:k*n/4) = y((k-1)*n/4+1:k*n/4) + dy(k);
z((k-1)*n/4+1:k*n/4) = z((k-1)*n/4+1:k*n/4) + dz(k);
end
f = figure( 1 );
pca3d( x, y, z );

View File

@ -0,0 +1,21 @@
% Visualize some common matrix transformations
% in a 2D coordinate system
% this uses the simplematrixbox() function for visualization
% use the matrix2dtrafos script for the the nicer matrixbox() function.
disp( 'Click into the plot to advance to the next matrix' )
simplematrixbox( [ 1 0; 0 1], 'Identity' );
simplematrixbox( [ 2 0; 0 1], 'Scale x' );
simplematrixbox( [ 1 0; 0 2], 'Scale y' );
simplematrixbox( [ 2 0; 0 2], 'Scale x and y' );
simplematrixbox( [ 0.5 0; 0 0.5], 'Scale x and y' );
simplematrixbox( [ -1 0; 0 1], 'Flip x' );
simplematrixbox( [ 1 0; 0 -1], 'Flip y' );
simplematrixbox( [ -1 0; 0 -1], 'Flip both' );
simplematrixbox( [ 1 1; 0 1], 'Shear x' );
simplematrixbox( [ 1 0; 1 1], 'Shear y' );
% rotation matrices:
for deg = 0:10:360
phi = deg*pi/180.0;
simplematrixbox( [ cos(phi) -sin(phi); sin(phi) cos(phi)], sprintf( 'Rotate %.0f', deg ) );
end

View File

@ -0,0 +1,21 @@
function simplematrixbox( a, s )
% visualizes the effect of a matrix a on a set of vectors forming a box
% a: a 2x2 matrix
% s: a string plotted as the title of the plot
% this function is called by simplematrix2dtrafos.m
% this is a simple version of the more elaborate matrixbox() function.
x = [ 0 1 1 0 0 1; 0 0 1 1 0 1 ];
plot( x(1,:), x(2,:), '-b' );
hold on;
y = a*x;
plot( y(1,:), y(2,:), '-r' );
[ ev ed ] = eig( a );
ev = ev * ed;
quiver( [0 0], [0 0], ev(1,:), ev(2,:), 1.0, 'g' )
hold off;
xlim( [-2 2 ] )
ylim( [-2 2] )
title( s );
waitforbuttonpress;
end

View File

@ -0,0 +1,72 @@
% read in wav files:
[s1, fs1 ] = audioread( 'PeterUndDerWolf.wav' );
[s2, fs2 ] = audioread( 'Tielli-Kraulis.wav' );
[s3, fs3 ] = audioread( 'Chorthippus_biguttulus.wav' );
% take out left channel and minimum number of samples:
n = min( [ size( s1, 1 ), size( s2, 1 ), size( s3, 1 ) ] );
%n = 300000;
x1 = s1(1:n,1)';
x2 = s2(1:n,1)';
x3 = s3(1:n,1)';
clear s1 s2 s3;
% plot the sound waves:
% dt = 1/fs1;
% time = 0:dt:(length(x1)-1)*dt;
% plot( time, x1 );
% plot( time, x2 );
% plot( time, x3 );
% play original sounds:
% disp( 'Playing x1 (Peter und der Wolf)' )
% a = audioplayer( x1, fs1 );
% playblocking( a );
% disp( 'Playing x2 (Martin Tielli)' )
% a = audioplayer( x2, fs2 );
% playblocking( a );
% disp( 'Playing x3 (Grasshopper song)' )
% a = audioplayer( x3, fs3 );
% playblocking( a );
% mix them:
m = [ 1.0 0.3 0.4; 0.1 0.6 0.4; 0.7 0.1 0.7 ];
y = m*[ x1; x2; x3 ];
% add noise:
%y = y + 0.03*randn(size(y));
% play mixtures:
% disp( 'Playing mixture y1' )
% a = audioplayer( y(1,:), fs1 );
% playblocking( a );
% disp( 'Playing mixture y2' )
% a = audioplayer( y(2,:), fs2 );
% playblocking( a );
% disp( 'Playing mixture y3' )
% a = audioplayer( y(3,:), fs3 );
% playblocking( a );
% demix them:
disp( 'Inverse mixing matrix:' )
dm = inv(m)
dx = dm*y;
% estimate demixing matrix:
size( y )
cv = cov( y' );
[ ev ed ] = eig( cv );
disp( 'Estimated demixing matrix:' )
ev
%play mixtures:
% disp( 'Playing x1 (Peter und der Wolf) recovered from mixtures' )
% a = audioplayer( dx(1,:), fs1 );
% playblocking( a );
% disp( 'Playing x3 (Martin Tielli) recovered from mixtures' )
% a = audioplayer( dx(2,:), fs2 );
% playblocking( a );
% disp( 'Playing x3 (Grasshopper song) recovered from mixtures' )
% a = audioplayer( dx(3,:), fs3 );
% playblocking( a );

View File

@ -0,0 +1,118 @@
% load data into time, voltage and spiketimes
load( 'extdata' );
% indices into voltage trace of spike times:
dt = time( 2) - time(1);
tinx = round(spiketimes/dt)+1;
% plot voltage trace with dettected spikes:
figure( 1 );
clf;
plot( time, voltage, '-b' )
hold on
scatter( time(tinx), voltage(tinx), 'r', 'filled' );
xlabel( 'time [ms]' );
ylabel( 'voltage' );
hold off
% spike waveform snippets:
w = ceil( 0.005/dt );
vs = [];
for k=1:length(tinx)
vs = [ vs; voltage(tinx(k)-w:tinx(k)+w-1) ];
end
ts = time(1:size(vs,2));
ts = ts - ts(floor(length(ts)/2));
% % plot snippets:
figure( 2 );
clf;
hold on
for k=1:size(vs,1)
plot( ts, vs(k,:), '-b' );
end
xlabel( 'time [ms]' );
ylabel( 'voltage' );
hold off
% pca:
cv = cov( vs );
[ ev , ed ] = eig( cv );
[d,dinx] = sort( diag(ed), 'descend' );
figure( 3 );
clf;
subplot( 4, 2, 1 );
imagesc( cv );
xlabel( 'time bin' );
ylabel( 'time bin' );
title( 'covariance matrix' );
caxis([-0.1 0.1])
% spectrum of eigenvalues:
subplot( 4, 2, 2 );
scatter( 1:length(d), d, 'b', 'filled' );
xlabel( 'index' );
ylabel( 'eigenvalue' );
% features:
subplot( 4, 2, 5 );
plot( 1000.0*ts, ev(:,dinx(1)), 'r', 'LineWidth', 2 );
xlabel( 'time [ms]' );
ylabel( 'eigenvector 1' );
subplot( 4, 2, 6 );
plot( 1000.0*ts, ev(:,dinx(2)), 'g', 'LineWidth', 2 );
xlabel( 'time [ms]' );
ylabel( 'eigenvector 2' );
% project onto eigenvectors:
nx = vs * ev(:,dinx(1));
ny = vs * ev(:,dinx(2));
%scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' );
% clustering (two clusters):
%kx = kmeans( [ nx, ny ], 2 );
% nx smaller or greater a threshold:
kthresh = 1.6;
kx = ones( size( nx ) );
kx(nx<kthresh) = 2;
subplot( 4, 1, 2 );
scatter( nx(kx==1), ny(kx==1), 'r', 'filled', 'MarkerEdgeColor', 'white' );
hold on;
scatter( nx(kx==2), ny(kx==2), 'g', 'filled', 'MarkerEdgeColor', 'white' );
hold off;
xlabel( 'projection onto eigenvector 1' );
ylabel( 'projection onto eigenvector 2' );
% show sorted spike waveforms:
subplot( 4, 2, 7 );
hold on
kinx1 = find(kx==1);
for k=1:length(kinx1)
plot( 1000.0*ts, vs(kinx1(k),:), '-r' );
end
plot( 1000.0*waveformt, waveform2, '-k', 'LineWidth', 2 );
xlim( [ 1000.0*ts(1) 1000.0*ts(end) ] )
xlabel( 'time [ms]' );
ylabel( 'waveform 1' );
hold off
subplot( 4, 2, 8 );
hold on
kinx2 = find(kx==2);
for k=1:length(kinx2)
plot( 1000.0*ts, vs(kinx2(k),:), '-g' );
end
plot( 1000.0*waveformt, waveform1, '-k', 'LineWidth', 2 );
xlim( [ 1000.0*ts(1) 1000.0*ts(end) ] )
xlabel( 'time [ms]' );
ylabel( 'waveform 2' );
hold off
% spike trains:
figure( 1 );
hold on;
scatter( time(tinx(kinx1)), voltage(tinx(kinx1)), 100.0, 'r', 'filled' );
scatter( time(tinx(kinx2)), voltage(tinx(kinx2)), 100.0, 'g', 'filled' );
hold off;

227
linearalgebra/code/sta.m Normal file
View File

@ -0,0 +1,227 @@
function [ stavg, stavgtime, spikesnippets, stimsnippets, meanrate ] = sta( stimulus, spikes, left, right )
% computes the spike-triggered average
% stimulus: the stimulus as a nx2 matrix with the first column being time
% in seconds and the second column being the actual stimulus
% spikes: a cell array of vectors of spike times
% left: the time to the left of each spike
% right: the time to the right of each spike
% returns
% stavg: the spike-triggered average
% stavgtime: the corresponding time axis
% spikesnippets: the spike-triggered waveforms as a nspikes x stavgtimes
% matrix
% meanrate: the mean firing rate
% time indices:
dt = stimulus(2,1) - stimulus(1,1);
wl = round( left/dt );
wr = round( right/dt );
nw = wl+wr+1;
% total number of spikes:
nspikes = 0;
for k = 1:length( spikes )
nspikes = nspikes + length( spikes{k} );
end
% loop over trials:
spikesnippets = zeros( nspikes, nw );
nspikes = 0;
for k = 1:length( spikes )
times = spikes{k};
for j = 1:length(times)
% index of spike in stimulus:
inx = round(times(j)/dt);
if ( inx-wl > 0 ) & ( inx+wr <= size( stimulus, 1 ) )
nspikes = nspikes + 1;
snip = stimulus( inx-wl:inx+wr, 2 );
spikesnippets( nspikes, : ) = snip; % - mean(snip);
end
end
end
% delete not used snippets:
spikesnippets(nspikes+1:end,:) = [];
stavgtime = [-left:dt:right];
meanrate = nspikes/length(spikes)/(stimulus(end,1)-stimulus(1,1));
% spike-triggered average:
stavg = mean( spikesnippets, 1 );
% loop over stimulus:
nstim = size( stimulus, 1 )-nw+1;
stimsnippets = zeros( nstim, nw );
stimsnippetstime = zeros( nstim, 1 );
for j=1:nstim
snip = stimulus( j:j+wr+wl, 2 );
stimsnippets(j,:) = snip; % - mean(snip);
stimsnippetstime(j) = j*dt;
end
% projection onto sta:
spikeonsta = spikesnippets * stavg';
stimonsta = stimsnippets * stavg';
% projection onto orthogonal to sta:
orthos = null( stavg );
mixcoef = rand(size( orthos, 2 ), 1);
mixcoef(length(mixcoef)/10:end) = 0.0;
staortho = orthos*mixcoef;
% stavg*staortho
staortho = staortho/(staortho'*staortho);
spikeonstaortho = spikesnippets * staortho;
stimonstaortho = stimsnippets * staortho;
% psth binned:
ratetime = 0:dt:stimulus(end,1);
% rate = zeros( size( ratetime ) );
% for k = 1:length( spikes )
% [n, ~] = hist( spikes{k}, ratetime );
% rate = rate + n/dt/length( spikes );
% end
% kernel psth:
kernelsigma = 0.001;
windowtime = -5.0*kernelsigma:dt:5.0*kernelsigma;
window = normpdf( windowtime, 0.0, kernelsigma )/length(spikes);
% plot( 1000.0*windowtime, window );
w2 = floor( length( windowtime )/2 );
kernelrate = zeros( size( ratetime ) );
for k = 1:length( spikes )
times = spikes{k};
for j = 1:length(times)
% index of spike in rate:
inx = round(times(j)/dt);
if ( inx - w2 > 0 ) & ( inx + w2 < length( kernelrate ) )
kernelrate(inx-w2:inx+w2) = kernelrate(inx-w2:inx+w2) + window;
end
end
end
if nargout == 0
% sta plot:
figure( 1 );
subplot( 3, 2, 1 )
plot( 1000.0*stavgtime, staortho, '-r', 'LineWidth', 3 )
hold on;
plot( 1000.0*stavgtime, stavg, '-b', 'LineWidth', 3 )
hold off;
xlabel( 'time [ms]' );
ylabel( 'stimulus' );
title( 'Spike-triggered average' );
legend( 'ortho', 'STA' );
% 2D scatter of projections:
subplot( 3, 2, 2 )
scatter( stimonsta, stimonstaortho, 40.0, 'b', 'filled', 'MarkerEdgeColor', 'white' )
hold on;
scatter( spikeonsta, spikeonstaortho, 20.0, 'r', 'filled', 'MarkerEdgeColor', 'white', 'LineWidth', 1.0 )
hold off;
xlabel( 'projection sta' );
ylabel( 'projection ortho' );
title( 'Projections' );
% histogram of projections onto sta:
subplot( 3, 2, 3 )
[ n, projections ] = hist( stimonsta, 50 );
bw = (projections(2)-projections(1));
pstim = n / sum(n)/bw;
bar( projections, pstim, 'b' );
hold on;
[ n, ~ ] = hist( spikeonsta, projections );
pstimspike = n / sum(n)/bw;
bar( projections, pstimspike, 'r' );
xlabel( 'projection x' );
title( 'Projection onto STA' );
xlim( [projections(1) projections(end)] );
hold off;
legend( 'p(x)', 'p(x|spikes)' );
% nonlinearity for orthogonal projections:
subplot( 3, 2, 5 )
nonlinearity = meanrate*pstimspike./pstim;
plot( projections(pstim>0.01), nonlinearity(pstim>0.01), '-r', 'LineWidth', 3 );
xlim( [projections(1) projections(end)] );
ylim( [0 1000 ])
xlabel( 'projection x' );
ylabel( 'meanrate*p(x|spikes)/p(x) [Hz]' );
title( 'Nonlinearity');
% histogram of projections onto orthogonal sta:
subplot( 3, 2, 4 )
[ n, ~] = hist( stimonstaortho, projections );
pstimortho = n / sum(n)/bw;
bar( projections, pstimortho, 'b' );
hold on;
[ n, ~ ] = hist( spikeonstaortho, projections );
pstimspikeortho = n / sum(n)/bw;
bar( projections, pstimspikeortho, 'r' );
xlim( [projections(1) projections(end)] );
xlabel( 'projection x' );
title( 'Projection onto orthogonal to STA' );
hold off;
legend( 'p(x)', 'p(x|spikes)' );
% nonlinearity for orthogonal projections:
subplot( 3, 2, 6 )
nonlinearityortho = meanrate*pstimspikeortho./pstimortho;
plot( projections(pstimortho>0.01), nonlinearityortho(pstimortho>0.01), '-r', 'LineWidth', 3 );
xlim( [projections(1) projections(end)] );
ylim( [0 1000 ])
xlabel( 'projection x' );
ylabel( 'meanrate*p(x|spikes)/p(x) [Hz]' );
title( 'Nonlinearity');
end
% stimulus reconstruction with STA:
stareconstruction = zeros( size( stimulus, 1 ), 1 );
for k = 1:length( spikes )
times = spikes{k};
for j = 1:length(times)
% index of spike in stimulus:
inx = round(times(j)/dt);
if ( inx-wl > 0 ) & ( inx+wr <= size( stimulus, 1 ) )
stareconstruction( inx-wl:inx+wr ) = stareconstruction( inx-wl:inx+wr ) + stavg';
end
end
end
stareconstruction = stareconstruction/length(spikes);
if nargout == 0
% linear stimulus reconstruction:
figure( 2 )
ax1 = subplot( 3, 1, 1 );
plot( 1000.0*stimulus(:,1), stimulus(:,2), 'g', 'LineWidth', 2 );
hold on;
plot( 1000.0*stimulus(:,1), stareconstruction, 'r', 'LineWidth', 2 );
ylabel( 'stimulus' );
hold off;
legend( 'stimulus', 'reconstruction' );
% stimulus projection onto sta:
ax2 = subplot( 3, 1, 2 );
% plot( 1000.0*ratetime, rate, '-b', 'LineWidth', 2 )
plot( 1000.0*ratetime, kernelrate-mean(kernelrate), '-b', 'LineWidth', 2 )
hold on;
plot( 1000.0*(stimsnippetstime+left), 2.0*stimonsta*meanrate, 'r', 'LineWidth', 2 );
ylabel( 'rate [Hz]' );
hold off;
legend( 'rate', 'stimulus projection on STA' );
% sta with nonlinearity:
ax3 = subplot( 3, 1, 3 );
plot( 1000.0*ratetime, kernelrate, '-b', 'LineWidth', 2 )
hold on;
xmax = max(projections(pstim>0.01));
stimonstax = stimonsta;
stimonstax( stimonstax > xmax ) = xmax;
sinx = round((stimonstax-projections(1))/bw);
sinx( sinx < 1 ) = 1;
stastimulus = nonlinearity( sinx );
plot( 1000.0*(stimsnippetstime+left), stastimulus, 'r', 'LineWidth', 2 );
legend( 'rate', 'LNP' );
xlabel( 'time [ms]' );
ylabel( 'rate [Hz]' );
hold off;
linkaxes( [ax1 ax2 ax3], 'x' );
end
end

View File

@ -0,0 +1,31 @@
clear;
addpath( '../../pointprocesses/simulations/' );
set( 0, 'DefaultTextFontSize', 22.0 );
set( 0, 'DefaultAxesFontSize', 22.0 );
% load data
load( 'p-unit_stimulus.mat' );
load( 'p-unit_spike_times.mat' );
%load( 'pyramidal_noise_2014-09-02-af_cutoff_50_contr_5.mat' );
% load( 'pyramidal_noise_2014-09-02-ab_cutoff_300_contr_5.mat' );
% for k = 1:length( spike_times )
% spike_times{k} = spike_times{k} * 0.001;
% end
% stimulus = stimulus(1:20000*5,:);
%dt = stimulus(2,1) - stimulus(1,1);
%spike_times = lifadaptspikes( 20, 50+100.0*stimulus(:,2), dt, 0.1, 0.04, 10.0 );
%spike_times = lifspikes( 20, 12+30.0*stimulus(:,2), dt, 0.1 );
%spike_times = lifspikes( 20, 20.0+30.0*stimulus(:,2), dt, 0.0001 );
%figure( 1 );
%clf;
%spikeraster( spike_times );
%isivec = isis( spike_times );
%isihist( isivec );
%isiserialcorr( isivec, 20 );
%fano( spike_times );
sta( stimulus(1:5:length(stimulus),:), spike_times, 0.05, 0.01 );
%stc( stimulus(1:5:length(stimulus),:), spike_times, 0.05, 0.01 );

66
linearalgebra/code/stc.m Normal file
View File

@ -0,0 +1,66 @@
function stc( stimulus, spikes, left, right )
% computes the spike-triggered covariance matrix
% stimulus: the stimulus as a nx2 matrix with the first column being time
% in seconds and the second column being the actual stimulus
% spikes: a cell array of vectors of spike times
% left: the time to the left of each spike
% right: the time to the right of each spike
% time indices:
dt = stimulus(2,1) - stimulus(1,1);
wl = round( left/dt );
wr = round( right/dt );
nw = wl+wr+1;
% spike-triggered average with snippets:
[ stavg, stavgtime, spikesnippets, stimsnippets, meanrate ] = sta( stimulus, spikes, left, right );
% spike-triggered covariance matrix:
figure( 3 );
subplot( 2, 2, 1 );
spikescv = cov( spikesnippets );
imagesc( spikescv );
caxis([-0.1 0.1])
% stimulus covariance matrix:
subplot( 2, 2, 2 );
stimcv = cov( stimsnippets );
imagesc( stimcv );
caxis([-0.1 0.1])
subplot( 2, 1, 2 );
imagesc( spikescv-stimcv );
caxis([-0.01 0.01])
% eigenvalues:
%[ ev , ed ] = eig( spikescv-stimcv );
[ ev , ed ] = eig( spikescv );
[d,dinx] = sort( diag(ed), 'descend' );
% spectrum of eigenvalues:
figure( 4 );
subplot( 3, 1, 1 );
scatter( 1:length(d), d, 'b', 'filled' );
% scatter( 1:length(d), d/sum(abs(d)), 'b', 'filled' );
xlabel( 'index' );
ylabel( 'eigenvalue [% variance]' );
% features:
subplot( 3, 2, 5 );
plot( 1000.0*stavgtime, ev(:,dinx(1)), 'g', 'LineWidth', 2 );
xlabel( 'time [ms]' );
ylabel( 'eigenvector 1' );
subplot( 3, 2, 6 );
plot( 1000.0*stavgtime, ev(:,dinx(2)), 'r', 'LineWidth', 2 );
xlabel( 'time [ms]' );
ylabel( 'eigenvector 2' );
% project onto eigenvectors:
nx = spikesnippets * ev(:,dinx(1));
ny = spikesnippets * ev(:,dinx(2));
subplot( 3, 1, 2 );
scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'projection onto eigenvector 1' );
ylabel( 'projection onto eigenvector 2' );
end

Binary file not shown.

View File

@ -0,0 +1,95 @@
\documentclass[addpoints,10pt]{exam}
\usepackage{url}
\usepackage{color}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{amsmath}
\pagestyle{headandfoot}
\runningheadrule
\firstpageheadrule
\firstpageheader{Scientific Computing}{Principal Component Analysis}{Oct 29, 2014}
%\runningheader{Homework 01}{Page \thepage\ of \numpages}{23. October 2014}
\firstpagefooter{}{}{}
\runningfooter{}{}{}
\pointsinmargin
\bracketedpoints
%\printanswers
\shadedsolutions
\usepackage[mediumspace,mediumqspace,Gray]{SIunits} % \ohm, \micro
%%%%% listings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
numbers=left,
showstringspaces=false,
language=Matlab,
breaklines=true,
breakautoindent=true,
columns=flexible,
frame=single,
captionpos=t,
xleftmargin=2em,
xrightmargin=1em,
aboveskip=10pt,
%title=\lstname,
title={\protect\filename@parse{\lstname}\protect\filename@base.\protect\filename@ext}
}
\begin{document}
\sffamily
%%%%%%%%%%%%%% Questions %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{questions}
\question \textbf{Gaussian distribution}
\begin{parts}
\part Use \texttt{randn} to generate 1000000 normally (zero mean, unit variance) distributed random numbers.
\part Plot a properly normalized histogram of these random numbers.
\part Compare the histogram with the probability density of the Gaussian distribution
\[ p(x) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}} \]
where $\mu$ is the mean and $\sigma^2$ is the variance of the Gaussian distribution.
\part Generate Gaussian distributed random numbers with mean $\mu=2$ and
standard deviation $\sigma=\frac{1}{2}$.
\end{parts}
\question \textbf{Covariance and correlation coefficient}
\begin{parts}
\part Generate two vectors $x$ and $z$ with Gausian distributed random numbers.
\part Compute $y$ as a linear combination of $x$ and $z$ according to
\[ y = r \cdot x + \sqrt{1-r^2}\cdot z \]
where $r$ is a parameter $-1 \le r \le 1$.
What does $r$ do?
\part Plot a scatter plot of $y$ versus $x$ for about 10 different values of $r$.
What do you observe?
\part Also compute the covariance matrix and the correlation
coefficient matrix between $x$ and $y$ (functions \texttt{cov} and
\texttt{corrcoef}). How do these matrices look like for different
values of $r$? How do the values of the matrices change if you generate
$x$ and $z$ with larger variances?
\part Do the same analysis (Scatter plot, covariance, and correlation coefficient)
for \[ y = x^2 + 0.5 \cdot z \]
Are $x$ and $y$ really independent?
\end{parts}
\question \textbf{Principal component analysis}
\begin{parts}
\part Generate pairs $(x,y)$ of Gaussian distributed random numbers such
that all $x$ values have zero mean, half of the $y$ values have mean $+d$
and the other half mean $-d$, with $d \ge0$.
\part Plot scatter plots of the pairs $(x,y)$ for $d=0$, 1, 2, 3, 4 and 5.
Also plot a histogram of the $x$ values.
\part Apply PCA on the data and plot a histogram of the data projected onto
the PCA axis with the largest eigenvalue.
What do you observe?
\end{parts}
\end{questions}
\end{document}

Binary file not shown.

View File

@ -0,0 +1,205 @@
\documentclass[addpoints,10pt]{exam}
\usepackage{url}
\usepackage{color}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{amsmath}
\pagestyle{headandfoot}
\runningheadrule
\firstpageheadrule
\firstpageheader{Scientific Computing}{Matrix multiplication}{Oct 28, 2014}
%\runningheader{Homework 01}{Page \thepage\ of \numpages}{23. October 2014}
\firstpagefooter{}{}{}
\runningfooter{}{}{}
\pointsinmargin
\bracketedpoints
%\printanswers
\shadedsolutions
\usepackage[mediumspace,mediumqspace,Gray]{SIunits} % \ohm, \micro
%%%%% listings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
numbers=left,
showstringspaces=false,
language=Matlab,
breaklines=true,
breakautoindent=true,
columns=flexible,
frame=single,
captionpos=t,
xleftmargin=2em,
xrightmargin=1em,
aboveskip=10pt,
%title=\lstname,
title={\protect\filename@parse{\lstname}\protect\filename@base.\protect\filename@ext}
}
\begin{document}
\sffamily
%%%%%%%%%%%%%% Questions %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{questions}
\question \textbf{Matrix multiplication}
Calculate the results of the following matrix multiplications and
confirm the result using matlab.
\[ \begin{pmatrix} 2 \\ -4 \\ -1 \end{pmatrix} \cdot
\begin{pmatrix} 3 & -4 & -4 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 & -3 & -1 \end{pmatrix} \cdot
\begin{pmatrix} 2 \\ 3 \\ 0 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 & -1 & 2 \\ -1 & 3 & 1 \\ 4 & -2 & 1 \\ 4 & -3 & -2 \end{pmatrix} \cdot
\begin{pmatrix} -2 & -2 & 0 & -3 \\ 3 & -2 & 1 & 0 \\ 1 & -2 & -4 & 0 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 & 1 \\ 1 & 4 \end{pmatrix} \cdot
\begin{pmatrix} 0 & -3 & 4 & 1 \\ -2 & -1 & -2 & -3 \\ -3 & 1 & -2 & -3 \end{pmatrix} = \]
\[ \begin{pmatrix} 1 & 1 & -4 \end{pmatrix} \cdot
\begin{pmatrix} -1 \\ 2 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 & 1 & -2 \\ 2 & 1 & 3 \\ 1 & 1 & 2 \end{pmatrix} \cdot
\begin{pmatrix} 2 & 2 \\ -3 & 3 \\ -4 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 \\ 2 \end{pmatrix} \cdot
\begin{pmatrix} -3 & 2 & -4 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 \\ -4 \\ -1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & -4 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 & -2 & -2 & -4 \end{pmatrix} \cdot
\begin{pmatrix} 2 \\ 2 \\ 1 \\ -1 \end{pmatrix} = \]
\[ \begin{pmatrix} -2 & -3 & -4 \\ 1 & 3 & 2 \\ -4 & -2 & 1 \end{pmatrix} \cdot
\begin{pmatrix} 1 & 2 & -2 & 4 \\ 3 & -1 & 1 & -1 \\ -3 & 2 & -1 & 2 \end{pmatrix} = \]
\[ \begin{pmatrix} 2 & -4 & 4 & 4 \\ -3 & 3 & 2 & 1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 3 & 4 & -2 \\ -4 & -2 & -1 & 0 \\ 1 & 2 & -4 & -4 \\ 3 & 2 & -2 & -4 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 & 1 & -2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} -4 \\ 3 \\ -2 \\ 4 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 & 3 & 4 \end{pmatrix} \cdot
\begin{pmatrix} -1 \\ 4 \\ -3 \end{pmatrix} = \]
\[ \begin{pmatrix} 1 & -4 & 3 & 3 \end{pmatrix} \cdot
\begin{pmatrix} 1 \\ 0 \\ -4 \\ -1 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & -4 & -3 \\ -2 & -2 & 4 \\ -3 & 4 & -3 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 3 & -4 & 4 \\ -1 & -2 & -3 & 1 \\ 1 & -2 & 2 & 0 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & 0 & 4 & 1 \\ 0 & 1 & 1 & 4 \end{pmatrix} \cdot
\begin{pmatrix} -4 & 3 & 1 & 4 \\ 1 & -4 & 1 & -3 \\ -4 & 0 & -4 & -4 \\ 1 & -2 & 4 & 4 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 \\ 3 \\ 4 \\ -2 \end{pmatrix} \cdot
\begin{pmatrix} 2 & 4 & 3 & 3 \end{pmatrix} = \]
\[ \begin{pmatrix} 1 & 2 & 0 & 3 \end{pmatrix} \cdot
\begin{pmatrix} -3 \\ 1 \\ 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & 0 & -1 & 3 \\ 0 & -4 & 3 & -3 \end{pmatrix} \cdot
\begin{pmatrix} -1 & -4 & -1 \\ 3 & 2 & 0 \\ -2 & 3 & -2 \\ 1 & 2 & -2 \end{pmatrix} = \]
\[ \begin{pmatrix} 2 & 0 & 3 \\ 1 & -4 & -1 \\ 3 & 0 & -2 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 2 & -1 & -2 \\ -1 & -1 & -3 & 4 \\ 2 & 4 & -4 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 & 4 \end{pmatrix} \cdot
\begin{pmatrix} 0 \\ 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & 3 \\ -4 & 0 \\ -2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 1 & -4 & 2 \\ 2 & 3 & -2 & -1 \end{pmatrix} = \]
\[ \begin{pmatrix} -2 & -1 \end{pmatrix} \cdot
\begin{pmatrix} 1 \\ -2 \end{pmatrix} = \]
\[ \begin{pmatrix} -2 & 2 & -2 & -3 \\ 2 & -4 & -2 & 2 \\ 0 & 2 & -2 & -2 \\ 1 & -2 & -2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} 1 & -2 & 2 \\ -4 & -2 & -2 \\ 3 & 1 & 4 \\ -4 & 1 & -2 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 & -3 & 0 & -1 \\ 4 & -2 & 1 & 2 \end{pmatrix} \cdot
\begin{pmatrix} -3 & -4 \\ -4 & 0 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 & 1 & -2 \\ -2 & 2 & -4 \\ 1 & -2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} -1 & 2 & -4 \\ 1 & 3 & 0 \\ 1 & 4 & -4 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & 3 \\ -3 & 2 \end{pmatrix} \cdot
\begin{pmatrix} 2 & -3 \\ -2 & -4 \end{pmatrix} = \]
\[ \begin{pmatrix} 1 & 1 & -3 \end{pmatrix} \cdot
\begin{pmatrix} -1 \\ -2 \\ 3 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & 2 & 1 \\ 4 & 0 & -2 \\ 2 & 3 & -3 \\ -2 & -2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} -1 & 2 & 0 & -2 \\ 2 & -2 & 0 & -1 \\ -4 & 3 & -3 & 4 \end{pmatrix} = \]
\[ \begin{pmatrix} -2 & -4 & 2 & 4 \\ 3 & -3 & 2 & 1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 4 & -1 & -4 \\ 2 & 3 & -4 & -1 \\ 3 & 2 & -2 & 4 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & -2 & -1 & -3 \end{pmatrix} \cdot
\begin{pmatrix} 2 \\ -2 \\ 3 \\ -2 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 & 4 & 2 & 3 \end{pmatrix} \cdot
\begin{pmatrix} 3 \\ 3 \\ -2 \\ 1 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 & 2 & -2 \end{pmatrix} \cdot
\begin{pmatrix} 2 \\ 4 \\ 3 \end{pmatrix} = \]
\[ \begin{pmatrix} 2 & -1 & 0 & -2 \\ 0 & -4 & -3 & -1 \end{pmatrix} \cdot
\begin{pmatrix} 4 & -3 & 2 & 4 \\ -3 & -4 & 1 & 1 \\ 1 & 3 & -2 & 3 \\ -1 & -2 & 3 & 0 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & -3 & 3 & 2 \\ 2 & 2 & -3 & 1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & 1 \\ 4 & 2 \\ -3 & -1 \\ -3 & 4 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & -3 \end{pmatrix} \cdot
\begin{pmatrix} -2 \\ 3 \\ 4 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 & 4 \end{pmatrix} \cdot
\begin{pmatrix} 1 \\ 4 \\ -1 \end{pmatrix} = \]
\[ \begin{pmatrix} 1 & -2 & 3 \end{pmatrix} \cdot
\begin{pmatrix} 3 \\ 1 \\ 2 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & 2 \end{pmatrix} \cdot
\begin{pmatrix} -1 \\ 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -2 & -4 & -4 & 0 \\ 0 & 3 & 4 & -4 \\ 4 & 2 & -2 & -4 \\ 0 & 0 & 4 & -1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & -1 \\ -1 & 1 \\ -4 & -3 \\ 2 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 \\ 3 \\ -3 \\ -4 \end{pmatrix} \cdot
\begin{pmatrix} 2 & 4 & -2 & 1 \end{pmatrix} = \]
\[ \begin{pmatrix} 2 \\ 0 \end{pmatrix} \cdot
\begin{pmatrix} -1 & -3 & -2 & 2 \end{pmatrix} = \]
\[ \begin{pmatrix} 0 & -4 & -4 & 4 \end{pmatrix} \cdot
\begin{pmatrix} 1 \\ 4 \\ 0 \\ 4 \end{pmatrix} = \]
\[ \begin{pmatrix} -3 & -1 \\ -3 & -1 \end{pmatrix} \cdot
\begin{pmatrix} 0 & -3 & 3 & -2 \\ -4 & 1 & -1 & 4 \end{pmatrix} = \]
\[ \begin{pmatrix} 4 & 0 \\ -1 & 4 \\ 1 & -3 \end{pmatrix} \cdot
\begin{pmatrix} -4 & -4 \\ -4 & 2 \end{pmatrix} = \]
\[ \begin{pmatrix} -1 \\ 3 \\ 2 \\ 4 \end{pmatrix} \cdot
\begin{pmatrix} 0 & -1 & 0 & 0 \end{pmatrix} = \]
\[ \begin{pmatrix} 3 \\ -2 \\ 2 \\ 3 \end{pmatrix} \cdot
\begin{pmatrix} -2 & -3 & -4 & 2 \end{pmatrix} = \]
\[ \begin{pmatrix} 2 & -2 & -4 & 4 \\ 0 & 1 & -3 & -2 \\ -1 & 3 & 0 & -2 \end{pmatrix} \cdot
\begin{pmatrix} -4 & 1 \\ -4 & 3 \end{pmatrix} = \]
\[ \begin{pmatrix} -4 & -1 & 3 \end{pmatrix} \cdot
\begin{pmatrix} -4 \\ -3 \\ 3 \end{pmatrix} = \]
\question \textbf{Automatic generation of exercises}
Write some matlab code that generates exercises like this one automatically! :-)
\end{questions}
\end{document}

Binary file not shown.

View File

@ -1,14 +0,0 @@
n = 10000;
% three distributions:
x = randn( n, 1 );
y = randn( n, 1 );
z = randn( n, 1 );
f = figure( 'Position', [ scrsz(3)/2 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2 ]);
d = [ 0 4 -4 8 ];
for k = 1:4
x((k-1)*n/4+1:k*n/4) = x((k-1)*n/4+1:k*n/4) + d(k);
y((k-1)*n/4+1:k*n/4) = y((k-1)*n/4+1:k*n/4) - d(k);
z((k-1)*n/4+1:k*n/4) = z((k-1)*n/4+1:k*n/4) + d(k);
end
covareigen3( x, y, z );

View File

@ -1,74 +0,0 @@
m = [ 1 0; 0 1];
matrixbox( m );
title( 'Identity' );
waitforbuttonpress;
m = [ 2 0; 0 1];
matrixbox( m );
title( 'Scale x' );
waitforbuttonpress;
m = [ 1 0; 0 2];
matrixbox( m );
title( 'Scale y' );
waitforbuttonpress;
m = [ 2 0; 0 2];
matrixbox( m );
title( 'Scale both' );
waitforbuttonpress;
m = [ -1 0; 0 1];
matrixbox( m );
title( 'Flip x' );
waitforbuttonpress;
m = [ 1 0; 0 -1];
matrixbox( m );
title( 'Flip y' );
waitforbuttonpress;
m = [ -1 0; 0 -1];
matrixbox( m );
title( 'Flip both' );
waitforbuttonpress;
m = [ 1 0; 1 1];
matrixbox( m );
title( 'Shear x' );
waitforbuttonpress;
m = [ 1 1; 0 1];
matrixbox( m );
title( 'Shear y' );
waitforbuttonpress;
phi = 0.1667*pi;
m = [ cos(phi) -sin(phi); sin(phi) cos(phi)];
matrixbox( m );
title( 'Rotate 30' );
waitforbuttonpress;
phi = 0.333*pi;
m = [ cos(phi) -sin(phi); sin(phi) cos(phi)];
matrixbox( m );
title( 'Rotate 60' );
waitforbuttonpress;
phi = 0.5*pi;
m = [ cos(phi) -sin(phi); sin(phi) cos(phi)];
matrixbox( m );
title( 'Rotate 90' );
waitforbuttonpress;
phi = 0.75*pi;
m = [ cos(phi) -sin(phi); sin(phi) cos(phi)];
matrixbox( m );
title( 'Rotate 135' );
waitforbuttonpress;
phi = 1.0*pi;
m = [ cos(phi) -sin(phi); sin(phi) cos(phi)];
matrixbox( m );
title( 'Rotate 180' );
waitforbuttonpress;

View File

@ -1,24 +0,0 @@
function matrixbox( m )
% visualizes the effect of a matrix m on a set of vectors forming a box
% m: a 2x2 matrix
v = [ 0 1 1 0 0; 0 0 1 1 0];
w = m*v;
clf;
hold on;
%set(gca, 'Xtick', [], 'Ytick', [], 'box', 'off')
% axis:
plot( [-2 2], [0 0], 'k', 'LineWidth', 1 );
plot( [0 0], [-2 2], 'k', 'LineWidth', 1 );
% old box:
plot( v(1,:), v(2,:), 'k', 'LineWidth', 1.0 )
quiver( [v(1,1)], [v(2,1)], [v(1,3)], [v(2,3)], 1.0, 'k', 'LineWidth', 2.0 );
scatter( [v(1,2)], [v(2,2)], 60.0, 'filled', 'k' );
% transfomred box:
plot( w(1,:), w(2,:), 'b', 'LineWidth', 2.0 )
quiver( [w(1,1)], [w(2,1)], [w(1,3)], [w(2,3)], 1.0, 'b', 'LineWidth', 3.0 );
scatter( [w(1,2)], [w(2,2)], 100.0, 'filled', 'b' );
hold off;
xlim( [ -2 2 ] );
ylim( [ -2 2 ] );
end

View File

@ -1,127 +0,0 @@
% generate spikes:
n = 1000;
misi = 0.01;
isis = exprnd( misi, n, 1 );
isis = isis + 0.01;
spikes = cumsum( isis );
p = rand( size( spikes ) );
% spike waveforms:
dt = 0.0001;
x = -0.01:dt:0.01;
y1 = 2.0*exp( -(x-0.0003).^2/2.0/0.0005^2 ) - 1.4*exp( -(x-0.0005).^2/2.0/0.0005^2 );
y2 = exp( -x.^2/2.0/0.002^2 ).*cos(2.0*pi*x/0.005);
p12 = 0.5;
% voltage trace:
noise = 0.2;
t = 0:dt:spikes(end)+3.0*x(end);
v = noise*randn( 1, length( t ) );
for k = 1:length( spikes )
inx = ceil( spikes(k)/dt );
if p(k) < p12
v(inx:inx+length(x)-1) = v(inx:inx+length(x)-1) + y1;
else
v(inx:inx+length(x)-1) = v(inx:inx+length(x)-1) + y2;
end
end
figure( 1 );
clf;
plot( t(t<1.0), v(t<1.0) );
hold on;
% find peaks:
thresh = 0.7;
inx = find( v(2:end-1) > thresh & v(1:end-2)<v(2:end-1) & v(2:end-1) > v(3:end) ) + 1;
spiket = t(inx);
spikev = v(inx);
tinx = inx;
for k=1:2
inx = find( ( spiket(2:end-1)-spiket(1:end-2)>0.005 | spikev(2:end-1) > spikev(1:end-2) ) & ( spiket(3:end)-spiket(2:end-1)>0.005 | spikev(2:end-1) > spikev(3:end) ) )+1;
spiket = spiket(inx);
spikev = spikev(inx);
tinx = tinx(inx);
end
scatter( spiket(spiket<1.0), spikev(spiket<1.0), 100.0, 'r', 'filled' );
%scatter( t(tinx), v(tinx), 100.0, 'r', 'filled' );
hold off;
% spike waveform snippets:
w = ceil( 0.005/dt );
vs = [];
for k=1:length(tinx)
vs = [ vs; v(tinx(k)-w:tinx(k)+w-1) ];
end
ts = t(1:size(vs,2));
ts = ts - ts(floor(length(ts)/2));
figure( 2 );
clf;
hold on
for k=1:size(vs,1)
plot( ts, vs(k,:), '-b' );
end
hold off
% pca:
cv = cov( vs );
[ ev , ed ] = eig( cv );
[d,dinx] = sort( diag(ed), 'descend' );
% spectrum of eigenvalues:
figure( 3 );
clf;
subplot( 4, 1, 1 );
scatter( 1:length(d), d, 'b', 'filled' );
% project onto eigenvectors:
nx = vs * ev(:,dinx(1));
ny = vs * ev(:,dinx(2));
%scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' );
%hold on;
% features:
subplot( 4, 2, 5 );
plot( 1000.0*ts, ev(:,dinx(1)), 'g', 'LineWidth', 2 );
subplot( 4, 2, 6 );
plot( 1000.0*ts, ev(:,dinx(2)), 'r', 'LineWidth', 2 );
% clustering:
%kx = kmeans( [ nx, ny ], 2 );
% nx smaller or greater a threshold:
kthresh = 1.6;
kx = ones( size( vs, 1 ), 1 );
kx(nx>kthresh) = 2;
subplot( 4, 1, 2 );
scatter( nx(kx==1), ny(kx==1), 'g', 'filled', 'MarkerEdgeColor', 'white' );
hold on;
scatter( nx(kx==2), ny(kx==2), 'r', 'filled', 'MarkerEdgeColor', 'white' );
hold off;
% show sorted spike waveforms:
subplot( 4, 2, 7 );
hold on
kinx1 = find(kx==1);
for k=1:length(kinx1)
plot( 1000.0*ts, vs(kinx1(k),:), '-g' );
end
plot( 1000.0*x, y1, '-k', 'LineWidth', 2 );
xlim( [ 1000.0*ts(1) 1000.0*ts(end) ] )
hold off
subplot( 4, 2, 8 );
hold on
kinx2 = find(kx==2);
for k=1:length(kinx2)
plot( 1000.0*ts, vs(kinx2(k),:), '-r' );
end
plot( 1000.0*x, y2, '-k', 'LineWidth', 2 );
xlim( [ 1000.0*ts(1) 1000.0*ts(end) ] )
hold off
% spike trains:
figure( 1 );
hold on;
six1 = find( spiket(kinx1)<1.0 );
scatter( spiket(kinx1(six1)), spikev(kinx1(six1)), 100.0, 'g', 'filled' );
six2 = find( spiket(kinx2)<1.0 );
scatter( spiket(kinx2(six2)), spikev(kinx2(six2)), 100.0, 'r', 'filled' );
hold off;

BIN
moduledescription/Hiwis.odt Normal file

Binary file not shown.

BIN
moduledescription/Hiwis.pdf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,10 @@
function pcn = colorednoisepdf( x, misi, epsilon, tau )
% returns the ISI pdf for PIF with colored noise drive
% x: the input ISI
% misis: the mean isi
% epsilon: a parameter
% tau: the correlation time of the noise
gamma1 = x/tau+exp(-x/tau)-1.0;
gamma2 = 1.0-exp(-x/tau);
pcn=exp(-(x-misi).^2./(4.0*epsilon*tau.^2.*gamma1)).*(((misi-x).*gamma2+2*gamma1*tau).^2./(2*gamma1*tau^2)-epsilon*(gamma2.^2-2*gamma1.*exp(-x/tau))) ./ (2*tau*sqrt(4*pi*epsilon*gamma1.^3));
end

View File

@ -0,0 +1,24 @@
% misi = 0.02;
% epsilon = 1.0;
% tau = 0.1;
x=0:0.002:0.1;
% pcn = colorednoisepdf( x, misi, epsilon, tau )+10.0*randn( size( x ) );
% plot( x, pcn );
spikes = lifouspikes( 10, 15, 50.0, 1.0, 1.0 );
isivec = isis( spikes );
misi = mean( isivec );
1.0/misi
isibins = 0:0.0005:0.1;
[ n, c ] = hist( isivec, isibins );
n = n / sum(n)/(isibins(2)-isibins(1));
bar( c, n );
beta0 = [ 1.0, 0.01 ];
b = nlinfit(c(1:end-2), n(1:end-2), @(b,x)(colorednoisepdf(x, misi, b(1), b(2))), beta0)
pcn = colorednoisepdf( x, misi, b(1), b(2) );
hold on
plot( x, pcn, 'r', 'LineWidth', 3 );
hold off

View File

@ -0,0 +1,38 @@
function [ counts, bins ] = counthist( spikes, w )
% computes count histogram and compare them with Poisson distribution
% spikes: a cell array of vectors of spike times
% w: observation window duration for computing the counts
% collect spike counts:
tmax = spikes{1}(end);
n = [];
r = [];
for k = 1:length(spikes)
for tk = 0:w:tmax-w
nn = sum( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) );
%nn = length( find( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) ) );
n = [ n nn ];
end
rate = (length(spikes{k})-1)/(spikes{k}(end) - spikes{k}(1));
r = [ r rate ];
end
% histogram of spike counts:
maxn = max( n );
[counts, bins ] = hist( n, 0:1:maxn+1 );
counts = counts / sum( counts );
if nargout == 0
bar( bins, counts );
hold on;
% Poisson distribution:
rate = mean( r );
x = 0:1:20;
l = rate*w;
y = l.^x.*exp(-l)./factorial(x);
plot( x, y, 'r', 'LineWidth', 3 );
xlim( [ 0 20 ] );
hold off;
xlabel( 'counts k' );
ylabel( 'P(k)' );
end
end

View File

@ -0,0 +1,39 @@
function fano( spikes )
% computes fano factor as a function of window size
% spikes: a cell array of vectors of spike times
tmax = spikes{1}(end);
windows = 0.01:0.05:0.01*tmax;
mc = windows;
vc = windows;
ff = windows;
fs = windows;
for j = 1:length(windows)
w = windows( j );
% collect counts:
n = [];
for k = 1:length(spikes)
for tk = 0:w:tmax-w
nn = sum( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) );
%nn = length( find( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) ) );
n = [ n nn ];
end
end
% statistics for current window:
mc(j) = mean( n );
vc(j) = var( n );
ff(j) = vc( j )/mc( j );
fs(j) = sqrt(vc( j )/mc( j ));
end
subplot( 1, 2, 1 );
scatter( mc, vc, 'filled' );
xlabel( 'Mean count' );
ylabel( 'Count variance' );
subplot( 1, 2, 2 );
scatter( 1000.0*windows, fs, 'filled' );
xlabel( 'Window W [ms]' );
ylabel( 'Fano factor' );
end

View File

@ -0,0 +1,5 @@
function y = inversegauss( x, m, d )
% returns the inverse Gauss density with mean isi m and diffusion
% coefficent d
y = exp(-(x-m).^2./(4.0*d.*x.*m.^2.0))./sqrt(4.0*pi*d.*x.^3.0);
end

View File

@ -0,0 +1,28 @@
f = figure;
subplot( 1, 2, 1 );
dx=0.0001;
x = dx:dx:0.5;
hold all
m = 0.02;
for d = [ 0.1 1 10 50 200 ]
plot( 1000.0*x, inversegauss( x, m, d ), 'LineWidth', 3, 'DisplayName', sprintf( 'D=%.1f', d ) );
end
title( sprintf( 'm=%g ms', 1000.0*m ) )
xlim( [ 0 50 ] );
xlabel( 'ISI [ms]' );
ylabel( 'p(ISI)' );
legend( '-DynamicLegend' );
hold off;
subplot( 1, 2, 2 );
hold all;
d = 5.0;
for m = [ 0.005 0.01 0.02 0.05 ]
plot( 1000.0*x, inversegauss( x, m, d ), 'LineWidth', 3, 'DisplayName', sprintf( 'm=%g ms', 1000.0*m ) );
end
title( sprintf( 'D=%g Hz', d ) )
xlim( [ 0 50 ] )
xlabel( 'ISI [ms]' );
ylabel( 'p(ISI)' );
legend( '-DynamicLegend' )
hold off

View File

@ -0,0 +1,32 @@
function isihist( isis, binwidth )
% plot histogram of isis
% isis: vector of interspike intervals
% binwidth: optional width to be used for the isi bins
if nargin < 2
nperbin = 200; % average number of data points per bin
bins = length( isis )/nperbin; % number of bins
binwidth = max( isis )/bins;
if binwidth < 5e-4 % half a millisecond
binwidth = 5e-4;
end
end
bins = 0.5*binwidth:binwidth:max(isis);
% histogram:
[ nelements, centers ] = hist( isis, bins );
% normalization (integral = 1):
nelements = nelements / sum( nelements ) / binwidth;
% plot:
bar( 1000.0*centers, nelements );
xlabel( 'ISI [ms]' )
ylabel( 'p(ISI) [1/s]')
% annotation:
misi = mean( isis );
sdisi = std( isis );
disi = sdisi^2.0/2.0/misi^3;
text( 0.5, 0.6, sprintf( 'mean=%.1f ms', 1000.0*misi ), 'Units', 'normalized' )
text( 0.5, 0.5, sprintf( 'std=%.1f ms', 1000.0*sdisi ), 'Units', 'normalized' )
text( 0.5, 0.4, sprintf( 'CV=%.2f', sdisi/misi ), 'Units', 'normalized' )
%text( 0.5, 0.3, sprintf( 'D=%.1f Hz', disi ), 'Units', 'normalized' )
end

View File

@ -0,0 +1,24 @@
function isireturnmap( isis, lag2 )
% plot return maps for lag 1 and lag lag2
clf;
subplot( 1, 2, 1 );
lag = 1;
scatter( 1000.0*isis(1:end-lag)', 1000.0*isis(1+lag:end)', 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'ISI T_i [ms]' );
ylabel( 'ISI T_{i+1} [ms]' );
maxisi = max( isis );
maxy = ceil(maxisi/10)*10.0;
xlim( [0 1.5*maxy ])
ylim( [0 maxy ])
subplot( 1, 2, 2 );
lag = lag2;
scatter( 1000.0*isis(1:end-lag)', 1000.0*isis(1+lag:end)', 'b', 'filled', 'MarkerEdgeColor', 'white' );
xlabel( 'ISI T_i [ms]' );
ylabel( 'ISI T_{i+2} [ms]' );
xlim( [0 1.5*maxy ])
ylim( [0 maxy ])
end

View File

@ -0,0 +1,15 @@
function isivec = isis( spikes )
% returns a single list of isis computed from all trials in spikes
% spikes: a cell array of vectors of spike times
isivec = [];
for k = 1:length(spikes)
difftimes = diff( spikes{k} );
if ( size( difftimes, 1 ) == 1 )
isivec = [ isivec difftimes ];
elseif ( size( difftimes, 2 ) == 1 )
isivec = [ isivec difftimes' ];
end
end
end

View File

@ -0,0 +1,26 @@
function isicorr = isiserialcorr( isis, maxlag )
% serial correlation of isis
% isis: vector of interspike intervals
% maxlag: the maximum lag
lags = 0:maxlag;
isicorr = zeros( size( lags ) );
for k = 1:length(lags)
lag = lags(k);
if length( isis ) > lag+10
cc = corrcoef( [ isis(1:end-lag)', isis(1+lag:end)' ] );
isicorr(k) = cc( 1, 2 );
end
end
if nargout == 0
% plot:
plot( lags, isicorr, '-b' );
hold on;
scatter( lags, isicorr, 100.0, 'b', 'filled' );
hold off;
xlabel( 'Lag k' )
ylabel( '\rho_k')
end
end

View File

@ -0,0 +1,53 @@
function spikes = lifadaptspikes( trials, input, tmaxdt, D, tauadapt, adaptincr )
% Generate spike times of a leaky integrate-and-fire neuron
% with an adaptation current
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
% tauadapt: adaptation time constant
% adaptincr: adaptation strength
tau = 0.01;
if nargin < 4
D = 1e0;
end
if nargin < 5
tauadapt = 0.1;
end
if nargin < 6
adaptincr = 1.0;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if max( size( input ) ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
v = vreset;
a = 0.0;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
v = v + ( - v - a + noise(i) + input(i))*dt/tau;
a = a + ( - a )*dt/tauadapt;
if v >= vthresh
v = vreset;
a = a + adaptincr/tauadapt;
spiketime = i*dt;
if spiketime > 4.0*tauadapt
times(j) = spiketime - 4.0*tauadapt;
j = j + 1;
end
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,51 @@
function spikes = lifboltzmanspikes( trials, input, tmaxdt, D, imax, ithresh, slope )
% Generate spike times of a leaky integrate-and-fire neuron
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
% imax: maximum output of boltzman
% ithresh: threshold of boltzman input
% slope: slope factor of boltzman input
tau = 0.01;
if nargin < 4
D = 1e0;
end
if nargin < 5
imax = 20;
end
if nargin < 6
ithresh = 10;
end
if nargin < 7
slope = 1;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if length( input ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
inb = imax./(1.0+exp(-slope.*(input - ithresh)));
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
v = vreset;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
v = v + ( - v + noise(i) + inb(i))*dt/tau;
if v >= vthresh
v = vreset;
times(j) = i*dt;
j = j + 1;
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,23 @@
input = 65.0; % lifadapt 100Hz
%input = 8.0; % lifadapt 10Hz
%input = 15.7; % lif 100Hz
%input = 8.3; % lif 10Hz
trials = 10;
tmax = 100.0;
Dnoise = 0.1;
Dounoise = 5e1;
outau = 10.0;
adapttau = 0.1;
adaptincr = 5.0;
%spikes = lifouadaptspikes( trials, input, 1.0, Dnoise, Dounoise, outau, adapttau, adaptincr );
%spikeraster( spikes );
%return;
% generate spikes:
%spikes = lifspikes( trials, input, tmax, noise );
spikes = lifouspikes( trials, input, tmax, Dounoise, outau );
%spikes = lifadaptspikes( trials, input, tmax, Dnoise, adapttau, adaptincr );
%spikes = lifouadaptspikes( trials, input, tmax, Dnoise, Dounoise, outau, adapttau, adaptincr );
fano( spikes );

View File

@ -0,0 +1,36 @@
% lif:
noises = [ 1e-5 1e-4 1e-3 1e-2 1e-1 ];
inputs = 0:0.1:20;
duration = 50.0;
% pif:
% noises = [ 1e-1 1 1e1 1e2 1e3 ];
% inputs = -5:0.1:10;
% duration = 100.0;
f = figure;
hold all;
for noise = noises
fprintf( 'noise=%.0e\n', noise );
rates = [];
for input = inputs
spikes = lifspikes( 10, input, duration, noise );
% spikes = pifspikes( 50, input, duration, noise );
nspikes = 0;
for k = 1:length( spikes )
nspikes = nspikes + length( spikes{k} );
end
rate = nspikes/duration/length( spikes );
%fprintf( 'I=%g N=%d rate=%g\n', input, length( spikes ), rate )
rates = [ rates rate ];
end
plot( inputs, rates, 'LineWidth', 2, 'DisplayName', sprintf( 'D=%.0e', noise ) );
end
xlabel( 'Input' );
xlim( [ inputs(1) inputs(end) ] )
ylabel( 'Firing rate [Hz]' );
%title( 'Leaky integrate-and-fire' )
title( 'Perfect integrate-and-fire' )
legend( '-DynamicLegend', 'Location', 'NorthWest' )
hold off

View File

@ -0,0 +1,65 @@
%input = 15.7; % lif 100Hz
%input = 8.3; % lif 10Hz
trials = 10;
tmax = 50.0;
Dnoise = 1.0;
imax = 25.0;
ithresh = 10.0;
slope=0.2;
% inputs = 0:2:30;
% rates = zeros( size( inputs ) );
% for j = 1:length( inputs )
% input = inputs(j);
% spikes = lifboltzmanspikes( trials, input, tmax, Dnoise, imax, ithresh, slope );
% nspikes = 0;
% for k = 1:length( spikes )
% nspikes = nspikes + length( spikes{k} );
% end
% rate = nspikes/tmax/length( spikes );
% rates(j) = rate;
% end
% plot( inputs, rates );
% grid on;
% return
input = 10.0; % 80 Hz
window = 0.2;
slopes = 0.1:0.1:2.0;
pmax = zeros( size( slopes) );
for j = 1:length( slopes )
slope = slopes( j );
spikes = lifboltzmanspikes( trials, input, tmax, Dnoise, imax, ithresh, slope );
[ n1, bins1 ] = counthist( spikes, w );
spikes = lifboltzmanspikes( trials, input+1.0, tmax, Dnoise, imax, ithresh, slope );
[ n2, bins2 ] = counthist( spikes, w );
subplot( 2, 1, 1 );
bar( bins1, n1, 'b' );
hold on;
bar( bins2, n2, 'r' );
hold off;
subplot( 2, 1, 2 );
bmax = max( [ length( bins1 ), length( bins2 ) ] );
decision1 = zeros( bmax, 1 );
decision2 = zeros( bmax, 1 );
cs1 = ones( bmax, 1 );
cs1(1:length(n1)) = cumsum( n1 );
cs2 = ones( bmax, 1 );
cs2(1:length(n2)) = cumsum( n2 );
cbins = 0:1:bmax-1;
plot( cbins, cs1, 'b' );
hold on;
plot( cbins, cs2, 'r' );
plot( cbins, cs1-cs2, 'g' );
hold off;
pause( 0.1 );
pmax(j) = max( cs1-cs2 );
end
clf;
subplot( 1, 1, 1 );
plot( slopes, pmax );

View File

@ -0,0 +1,51 @@
input = 65.0; % lifadapt 100Hz
%input = 8.0; % lifadapt 10Hz
%input = 15.7; % lif 100Hz
%input = 8.3; % lif 10Hz
trials = 10;
tmax = 50.0;
Dnoise = 0.1;
Dounoise = 5e1;
outau = 10.0;
adapttau = 0.2;
adaptincr = 0.5;
windows = 0.05:0.05:1.0;
pmax = zeros( size( windows ) );
for j = 1:length( windows )
w = windows( j );
spikes = lifadaptspikes( trials, input, tmax, Dnoise, adapttau, adaptincr );
%spikes = lifouspikes( trials, input, tmax, Dounoise, outau);
[ n1, bins1 ] = counthist( spikes, w );
spikes = lifadaptspikes( trials, input+10.0, tmax, Dnoise, adapttau, adaptincr );
%spikes = lifouspikes( trials, input+10.0, tmax, Dounoise, outau );
[ n2, bins2 ] = counthist( spikes, w );
subplot( 2, 1, 1 );
bar( bins1, n1, 'b' );
hold on;
bar( bins2, n2, 'r' );
hold off;
subplot( 2, 1, 2 );
bmax = max( [ length( bins1 ), length( bins2 ) ] );
decision1 = zeros( bmax, 1 );
decision2 = zeros( bmax, 1 );
cs1 = ones( bmax, 1 );
cs1(1:length(n1)) = cumsum( n1 );
cs2 = ones( bmax, 1 );
cs2(1:length(n2)) = cumsum( n2 );
cbins = 0:1:bmax-1;
plot( cbins, cs1, 'b' );
hold on;
plot( cbins, cs2, 'r' );
plot( cbins, cs1-cs2, 'g' );
hold off;
pause( 0.1 );
pmax(j) = max( cs1-cs2 );
end
clf;
subplot( 1, 1, 1 );
plot( windows, pmax );

View File

@ -0,0 +1,35 @@
%input = 65.0; % lifadapt 100Hz
%input = 8.0; % lifadapt 10Hz
input = 15.7; % lif 100Hz
%input = 8.3; % lif 10Hz
trials = 10;
tmax = 100.0;
noise = 1e-1;
adapttau = 0.1;
adaptincr = 5.0;
% generate spikes:
spikes = lifspikes( trials, input, tmax, noise );
%spikes = lifadaptspikes( trials, input, tmax, noise, adapttau, adaptincr );
% interspike intervals:
isivec = isis( spikes );
% histogram
f = figure( 1 );
isihist( isivec, 10e-4 );
hold on
% theoretical density:
misi = mean( isivec );
disi = var( isivec )/2.0/misi^3;
xmax = 3.0*misi;
x = 0:0.0001:xmax;
plot( 1000.0*x, inversegauss( x, misi, disi ), 'r', 'LineWidth', 3 );
% plot details:
title( sprintf( 'LIF, input=%g, nisi=%d', input, length( isivec ) ) )
xlim( [ 0.0 1000.0*xmax ] )
legend( 'data', 'inverse Gaussian' )
hold off
% serial correlations:
f = figure( 2 );
isiserialcorr( isivec, 10 );

View File

@ -0,0 +1,63 @@
inputs = 0:0.1:20; % lif
inputs = 0:0.1:10; % pif
avisi = [];
sdisi = [];
cvisi = [];
dcisi = [];
for input = inputs
input
% spikes = lifspikes( 100, input, 100.0, 1e-2 );
spikes = pifspikes( 100, input, 100.0, 1e-1 );
isivec = isis( spikes );
if length( isivec ) <= 1
av = Inf;
sd = NaN;
cv = NaN;
dc = NaN;
else
av = mean( isivec );
sd = std( isivec );
if av > 0.0
cv = sd/av;
dc = sd^2.0/2.0/av^3;
else
cv = NaN;
dc = NaN;
end
end
avisi = [ avisi av ];
sdisi = [ sdisi sd ];
cvisi = [ cvisi cv ];
dcisi = [ dcisi dc ];
end
f = figure;
subplot( 2, 2, 1 );
plot( inputs, 1.0./avisi, '-b', 'LineWidth', 3 );
xlabel( 'Input' );
xlim( [ inputs(1) inputs(end) ] )
title( 'Mean rate [Hz]' );
subplot( 2, 2, 2 );
plot( inputs, 1000.0*avisi, '-b', 'LineWidth', 3 );
hold on;
plot( inputs, 1000.0*sdisi, '-c', 'LineWidth', 3 );
hold off;
xlabel( 'Input' );
xlim( [ inputs(1) inputs(end) ] )
ylim( [ 0 1000 ] )
title( 'ISI [ms]' );
legend( 's.d. ISI', 'mean ISI' );
subplot( 2, 2, 3 );
plot( inputs, cvisi, '-b', 'LineWidth', 3 );
xlabel( 'Input' );
xlim( [ inputs(1) inputs(end) ] )
title( 'CV' );
subplot( 2, 2, 4 );
plot( inputs, dcisi, '-b', 'LineWidth', 3 );
xlabel( 'Input' );
xlim( [ inputs(1) inputs(end) ] )
title( 'D [Hz]' );

View File

@ -0,0 +1,64 @@
function spikes = lifouadaptspikes( trials, input, tmaxdt, D, Dou, outau, tauadapt, adaptincr )
% Generate spike times of a leaky integrate-and-fire neuron
% with colored noise and an adaptation current
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive noise
% Dou: the strength of additive colored noise
% outau: time constant of the colored noise
% tauadapt: adaptation time constant
% adaptincr: adaptation strength
tau = 0.01;
if nargin < 4
D = 1e0;
end
if nargin < 5
Dou = 1e0;
end
if nargin < 6
outau = 1.0;
end
if nargin < 7
tauadapt = 0.1;
end
if nargin < 8
adaptincr = 1.0;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if max( size( input ) ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
v = vreset;
n = 0.0;
a = 0.0;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
noiseou = sqrt(2.0*Dou)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
n = n + ( - n + noiseou(i))*dt/outau;
v = v + ( - v - a + noise(i) + n + input(i))*dt/tau;
a = a + ( - a )*dt/tauadapt;
if v >= vthresh
v = vreset;
a = a + adaptincr;
spiketime = i*dt;
if spiketime > 4.0*tauadapt
times(j) = spiketime - 4.0*tauadapt;
j = j + 1;
end
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,44 @@
function spikes = lifouspikes( trials, input, tmaxdt, D, outau )
% Generate spike times of a leaky integrate-and-fire neuron
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
% outau: time constant of the colored noise
tau = 0.01;
if nargin < 4
D = 1e0;
end
if nargin < 5
outau = 1.0;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if length( input ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
n = 0.0;
v = vreset;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
n = n + ( - n + noise(i))*dt/outau;
v = v + ( - v + n + input(i))*dt/tau;
if v >= vthresh
v = vreset;
times(j) = i*dt;
j = j + 1;
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,34 @@
% relation between firing rate and serieller correlation
input = 65.0; % lifadapt 100Hz
%input = 8.0; % lifadapt 10Hz
trials = 10;
tmax = 50.0;
noise = 1e-5;
adapttau = 0.1;
adaptincr = 0.5;
clf;
for adapttau = 0.01:0.02:0.2
inputs = 1:5:120;
iscs = zeros( size( inputs ) );
rates = zeros( size( inputs ) );
for k = 1:length(inputs)
input = inputs(k);
% generate spikes:
spikes = lifadaptspikes( trials, input, tmax, noise, adapttau, adaptincr );
isivec = isis( spikes );
isc = isiserialcorr( isivec, 10 );
iscs(k) = isc(2);
rates(k) = 1.0/mean( isivec );
end
subplot( 2, 1, 1 );
hold on;
plot( inputs, rates );
hold off;
subplot( 2, 1, 2 );
hold on;
plot( rates, iscs );
hold off;
end

View File

@ -0,0 +1,38 @@
function spikes = lifspikes( trials, input, tmaxdt, D )
% Generate spike times of a leaky integrate-and-fire neuron
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
tau = 0.01;
if nargin < 4
D = 1e0;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if length( input ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
v = vreset;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
v = v + ( - v + noise(i) + input(i))*dt/tau;
if v >= vthresh
v = vreset;
times(j) = i*dt;
j = j + 1;
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,44 @@
function spikes = pifouspikes( trials, input, tmaxdt, D, outau )
% Generate spike times of a perfect integrate-and-fire neuron
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
% outau: time constant of the colored noise
tau = 0.01;
if nargin < 4
D = 1e0;
end
if nargin < 5
outau = 1.0;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if length( input ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
n = 0.0;
v = vreset;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
n = n + ( - n + noise(i))*dt/outau;
v = v + ( n + input(i))*dt/tau;
if v >= vthresh
v = vreset;
times(j) = i*dt;
j = j + 1;
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,38 @@
function spikes = pifspikes( trials, input, tmaxdt, D )
% Generate spike times of a perfect integrate-and-fire neuron
% trials: the number of trials to be generated
% input: the stimulus either as a single value or as a vector
% tmaxdt: in case of a single value stimulus the duration of a trial
% in case of a vector as a stimulus the time step
% D: the strength of additive white noise
tau = 0.01;
if nargin < 4
D = 1e-1;
end
vreset = 0.0;
vthresh = 10.0;
dt = 1e-4;
if length( input ) == 1
input = input * ones( ceil( tmaxdt/dt ), 1 );
else
dt = tmaxdt;
end
spikes = cell( trials, 1 );
for k=1:trials
times = [];
j = 1;
v = vreset;
noise = sqrt(2.0*D)*randn( length( input ), 1 )/sqrt(dt);
for i=1:length( noise )
v = v + ( noise(i) + input(i))*dt/tau;
if v >= vthresh
v = vreset;
times(j) = i*dt;
j = j + 1;
end
end
spikes{k} = times;
end
end

View File

@ -0,0 +1,27 @@
rate = 100.0;
trials = 50;
tmax = 100.0;
% generate spikes:
spikes = poissonspikes( trials, rate, tmax );
% interspike intervals:
isivec = isis( spikes );
% histogram
f = figure( 1 );
isihist( isivec );
hold on
% theoretical density:
xmax = 5.0/rate;
x = 0:0.0001:xmax;
y = rate*exp(-rate*x);
plot( 1000.0*x, y, 'r', 'LineWidth', 3 );
% plot details:
title( sprintf( 'Poisson spike trains, rate=%g Hz, nisi=%d', rate, length( isivec ) ) )
xlim( [ 0.0 1000.0*xmax ] )
ylim( [ 0.0 1.1*rate ] )
legend( 'data', 'poisson' )
hold off
% serial correlations:
f = figure( 2 );
isiserialcorr( isivec, 10 );

View File

@ -0,0 +1,46 @@
rates = 1:1:100;
avisi = [];
sdisi = [];
cvisi = [];
for rate = rates
spikes = poissonspikes( 10, rate, 100.0 );
isivec = isis( spikes );
av = mean( isivec );
sd = std( isivec );
cv = sd/av;
avisi = [ avisi av ];
sdisi = [ sdisi sd ];
cvisi = [ cvisi cv ];
end
f = figure;
subplot( 1, 3, 1 );
scatter( rates, 1000.0*avisi, 'b', 'filled' );
hold on;
plot( rates, 1000.0./rates, 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 1000 ] );
title( 'Mean ISI [ms]' );
legend( 'simulation', 'theory 1/\lambda' );
subplot( 1, 3, 2 );
scatter( rates, 1000.0*sdisi, 'b', 'filled' );
hold on;
plot( rates, 1000.0./rates, 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 1000 ] )
title( 'Standard deviation ISI [ms]' );
legend( 'simulation', 'theory 1/\lambda' );
subplot( 1, 3, 3 );
scatter( rates, cvisi, 'b', 'filled' );
hold on;
plot( rates, ones( size( rates ) ), 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 2 ] )
title( 'CV' );
legend( 'simulation', 'theory' );

View File

@ -0,0 +1,20 @@
function spikes = poissonspikes( trials, rate, tmax )
% Generate spike times of a homogeneous poisson process
% trials: number of trials that should be generated
% rate: the rate of the Poisson process in Hertz
% tmax: the duration of each trial in seconds
% returns a cell array of vectors of spike times
dt = 3.33e-5;
p = rate*dt; % probability of event per bin of width dt
% make sure p is small enough:
if p > 0.1
p = 0.1
dt = p/rate;
end
spikes = cell( trials, 1 );
for k=1:trials
x = rand( 1, round(tmax/dt) ); % uniform random numbers for each bin
spikes{k} = find( x < p ) * dt;
end
end

Binary file not shown.

View File

@ -0,0 +1,28 @@
function savefigpdf( fig, name, width, height )
% Saves figure fig in pdf file name.pdf with appropriately set page size
% and fonts
% default width:
if nargin < 3
width = 11.7;
end
% default height:
if nargin < 4
height = 9.0;
end
% paper:
set( fig, 'PaperUnits', 'centimeters' );
set( fig, 'PaperSize', [width height] );
set( fig, 'PaperPosition', [0.0 0.0 width height] );
set( fig, 'Color', 'white')
% font:
set( findall( fig, 'type', 'axes' ), 'FontSize', 12 )
set( findall( fig, 'type', 'text' ), 'FontSize', 12 )
% save:
saveas( fig, name, 'pdf' )
end

View File

@ -0,0 +1,17 @@
function spikeraster( spikes )
% Display a spike raster of the spike times given in spikes.
% spikes: a cell array of vectors of spike times
ntrials = length(spikes);
for k = 1:ntrials
times = 1000.0*spikes{k}; % conversion to ms
for i = 1:length( times )
line([times(i) times(i)],[k-0.4 k+0.4], 'Color', 'k' );
end
end
xlabel( 'Time [ms]' );
ylabel( 'Trials');
ylim( [ 0.3 ntrials+0.7 ] )
end

View File

@ -0,0 +1,18 @@
% generate spike times:
rate = 20.0;
spikes = hompoissonspikes( 10, rate, 50.0 );
% isi histogram:
isivec = isis( spikes );
isihist( isivec );
hold on
% theoretical density:
xmax = 5.0/rate;
x = 0:0.0001:xmax;
y = rate*exp(-rate*x);
plot( 1000.0*x, y, 'r', 'LineWidth', 3 );
% plot details:
title( sprintf( 'Poisson spike trains, rate=%g Hz, nisi=%d', rate, length( isivec ) ) )
xlim( [ 0.0 1000.0*xmax ] )
ylim( [ 0.0 1.1*rate ] )
legend( 'data', 'poisson' )
hold off

View File

@ -0,0 +1,46 @@
rates = 1:1:100;
avisi = [];
sdisi = [];
cvisi = [];
for rate = rates
spikes = hompoissonspikes( 10, rate, 100.0 );
isivec = isis( spikes );
av = mean( isivec );
sd = std( isivec );
cv = sd/av;
avisi = [ avisi av ];
sdisi = [ sdisi sd ];
cvisi = [ cvisi cv ];
end
f = figure;
subplot( 1, 3, 1 );
scatter( rates, 1000.0*avisi, 'b', 'filled' );
hold on;
plot( rates, 1000.0./rates, 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 1000 ] );
title( 'Mean ISI [ms]' );
legend( 'simulation', 'theory 1/\lambda' );
subplot( 1, 3, 2 );
scatter( rates, 1000.0*sdisi, 'b', 'filled' );
hold on;
plot( rates, 1000.0./rates, 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 1000 ] )
title( 'Standard deviation ISI [ms]' );
legend( 'simulation', 'theory 1/\lambda' );
subplot( 1, 3, 3 );
scatter( rates, cvisi, 'b', 'filled' );
hold on;
plot( rates, ones( size( rates ) ), 'r' );
hold off;
xlabel( 'Rate \lambda [Hz]' );
ylim( [ 0 2 ] )
title( 'CV' );
legend( 'simulation', 'theory' );

View File

@ -0,0 +1,19 @@
function spikes = hompoissonspikes( trials, rate, tmax )
% Generate spike times of a homogeneous poisson process
% trials: number of trials that should be generated
% rate: the rate of the Poisson process in Hertz
% tmax: the duration of each trial in seconds
% returns a cell array of vectors of spike times
dt = 3.33e-5;
p = rate*dt;
if p > 0.2
p = 0.2
dt = p/rate;
end
x = rand( trials, ceil(tmax/dt) );
spikes = cell( trials, 1 );
for k=1:trials
spikes{k} = find( x(k,:) >= 1.0-p ) * dt;
end
end

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,142 @@
\documentclass[addpoints,10pt]{exam}
\usepackage{url}
\usepackage{color}
\usepackage{hyperref}
\usepackage{graphicx}
\pagestyle{headandfoot}
\runningheadrule
\firstpageheadrule
\firstpageheader{Scientific Computing}{Integrate-and-fire models}{Oct 28, 2014}
%\runningheader{Homework 01}{Page \thepage\ of \numpages}{23. October 2014}
\firstpagefooter{}{}{}
\runningfooter{}{}{}
\pointsinmargin
\bracketedpoints
%\printanswers
\shadedsolutions
\usepackage[mediumspace,mediumqspace,Gray]{SIunits} % \ohm, \micro
%%%%% listings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
numbers=left,
showstringspaces=false,
language=Matlab,
breaklines=true,
breakautoindent=true,
columns=flexible,
frame=single,
captionpos=t,
xleftmargin=2em,
xrightmargin=1em,
aboveskip=10pt,
%title=\lstname,
title={\protect\filename@parse{\lstname}\protect\filename@base.\protect\filename@ext}
}
\begin{document}
\sffamily
%%%%%%%%%%%%%% Questions %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{questions}
\question \textbf{Statistics of integrate-and-fire neurons}
For the following use different variants of the leaky integrate-and-fire models provided in \texttt{lifspikes.m},
\texttt{lifouspikes.m}, and \texttt{lifadaptspikes.m} do generate some spike train data.
Use the functions you wrote for the Poisson process to analyze the statistics of the spike trains.
\begin{parts}
\part Generate a few trials of the two models for two different inputs
that result in qualitatively different spike trains and display
them in a raster plot. Decide for a noise strength (good values to try are 0.001, 0.01, 0.1, 1).
\begin{solution}
\begin{lstlisting}
spikes = pifspikes( 10, 1.0, 0.5, 0.01 );
%spikes = pifspikes( 10, 10.0, 0.5, 0.01 );
%spikes = lifspikes( 10, 11.0, 0.5, 0.001 );
%spikes = lifspikes( 10, 15.0, 0.5, 0.001 );
spikeraster( spikes )
\end{lstlisting}
\mbox{}\\[-3ex]
\colorbox{white}{\includegraphics[width=0.48\textwidth]{pifraster02}}
\colorbox{white}{\includegraphics[width=0.48\textwidth]{pifraster10}}\\
\colorbox{white}{\includegraphics[width=0.48\textwidth]{lifraster10}}
\colorbox{white}{\includegraphics[width=0.48\textwidth]{lifraster15}}
\end{solution}
\part The inverse Gaussian describes the interspike interval distribution of a PIF driven with white noise:
\[ p(T) = \frac{1}{\sqrt{4\pi D T^3}}\exp\left[-\frac{(T-\langle T \rangle)^2}{4DT\langle T \rangle^2}\right] \]
where $\langle T \rangle$ is the mean interspike interval and
\[ D = \frac{\langle(T - \langle T \rangle)^2\rangle}{2 \langle T \rangle^3} \]
is the diffusion coefficient (variance of the interspike intervals
$T$ divided by two times the mean cubed). Show in two plots how
this distribution depends on $\langle T \rangle$ and $D$.
\begin{solution}
\lstinputlisting{simulations/inversegauss.m}
\lstinputlisting{simulations/inversegaussplot.m}
\colorbox{white}{\includegraphics[width=0.98\textwidth]{inversegauss}}
\end{solution}
\part Extent your function plotting an interspike interval histogram
to also report the diffusion coefficient $D$.
\begin{solution}
\begin{lstlisting}
...
% annotation:
misi = mean( isis );
sdisi = std( isis );
disi = sdisi^2.0/2.0/misi^3;
text( 0.6, 0.7, sprintf( 'mean=%.1f ms', 1000.0*misi ), 'Units', 'normalized' )
text( 0.6, 0.6, sprintf( 'std=%.1f ms', 1000.0*sdisi ), 'Units', 'normalized' )
text( 0.6, 0.5, sprintf( 'CV=%.2f', sdisi/misi ), 'Units', 'normalized' )
text( 0.6, 0.4, sprintf( 'D=%.1f Hz', disi ), 'Units', 'normalized' )
...
\end{lstlisting}
\end{solution}
\part Compare intersike interval histograms obtained from the LIF and PIF models with the inverse Gaussian.
\begin{solution}
\lstinputlisting{simulations/lifisih.m}
\colorbox{white}{\includegraphics[width=0.48\textwidth]{pifisih01}}
\colorbox{white}{\includegraphics[width=0.48\textwidth]{pifisih10}}\\
\colorbox{white}{\includegraphics[width=0.48\textwidth]{lifisih08}}
\colorbox{white}{\includegraphics[width=0.48\textwidth]{lifisih16}}
\end{solution}
\part Plot the firing rate (inverse mean interspike interval),
mean interspike interval, the corresponding standard deviation,
CV, and diffusion coefficient as a function of the input to the LIF
and the PIF with noise strength set to 0.01.
\begin{solution}
\lstinputlisting{simulations/lifisistats.m}
Leaky integrate-and-fire:\\
\colorbox{white}{\includegraphics[width=0.8\textwidth]{lifisistats}}\\
Perfect integrate-and-fire:\\
\colorbox{white}{\includegraphics[width=0.8\textwidth]{pifisistats}}
\end{solution}
\part Plot the firing rate as a function of input of the LIF and the PIF for various values
of the noise strength.
\begin{solution}
\lstinputlisting{simulations/lifficurves.m}
Leaky integrate-and-fire:\\
\colorbox{white}{\includegraphics[width=0.7\textwidth]{lifficurves}}\\
Perfect integrate-and-fire:\\
\colorbox{white}{\includegraphics[width=0.7\textwidth]{pifficurves}}
\end{solution}
\part Use the functions for computing serial correlations, count statistics and fano factors
to further explore the statistics of the integrate-and-fire models!
\end{parts}
\end{questions}
\end{document}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More