plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
tsajed/nmr-pred-master
|
secularity.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/secularity.m
| 437 |
utf_8
|
4dececf297c793c5ecc049c8cc08358f
|
% A trap for legacy function calls.
%
% [email protected]
function secularity(varargin)
% Direct the user to the new function
error('This function is deprecated, use assume() instead.');
end
% You told us you would release Spinach on 1 October 2011 and you actually
% released Spinach on 1 October 2011. It's not very often that people actu-
% ally deliver on what they say these days.
%
% Dieter Suter, to IK
|
github
|
tsajed/nmr-pred-master
|
contour_plot.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/contour_plot.m
| 597 |
utf_8
|
0a8656a515a8827cca670b531c450d13
|
% A trap for legacy function calls.
%
% [email protected]
function contour_plot(varargin)
% Direct the user to the new function
error('This function is deprecated, use plot_2d() instead.');
end
% According to a trade legend, Uhlenbeck and Goudsmit (students of
% Ehrenfest when they stumbled upon an explanation for the anomalo-
% us g-factor) presented it to Ehrenfest and said, in effect "here's
% our theory, but don't publish it - it can't be right". He submit-
% ted it anyway with the justification that they were "young enough
% to be able to afford a stupidity".
|
github
|
tsajed/nmr-pred-master
|
combnk.m
|
.m
|
nmr-pred-master/spinach/kernel/external/combnk.m
| 1,407 |
utf_8
|
9e6b7b79ccf707597f84b82264aee2da
|
% All combinations of the N elements in V taken K at a time.
% C = COMBNK(V,K) produces a matrix, with K columns. Each row of C has
% K of the elements in the vector V. C has N!/K!(N-K)! rows. K must be
% a nonnegative integer.
%
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.2.2 $ $Date: 2004/12/24 20:46:48 $
function c = combnk(v,k)
[m, n] = size(v);
if min(m,n) ~= 1
error('stats:combnk:VectorRequired','First argument has to be a vector.');
end
if n == 1
n = m;
flag = 1;
else
flag = 0;
end
if n == k
c = v(:).';
elseif n == k + 1
tmp = v(:).';
c = tmp(ones(n,1),:);
c(1:n+1:n*n) = [];
c = reshape(c,n,n-1);
elseif k == 1
c = v.';
elseif n < 17 && (k > 3 || n-k < 4)
rows = 2.^(n);
ncycles = rows;
for count = 1:n
settings = (0:1);
ncycles = ncycles/2;
nreps = rows./(2*ncycles);
settings = settings(ones(1,nreps),:);
settings = settings(:);
settings = settings(:,ones(1,ncycles));
x(:,n-count+1) = settings(:); %#ok<AGROW>
end
idx = x(sum(x,2) == k,:);
nrows = size(idx,1);
[rows,~] = find(idx');
c = reshape(v(rows),k,nrows).';
else
P = [];
if flag == 1,
v = v.';
end
if k < n && k > 1
for idx = 1:n-k+1
Q = combnk(v(idx+1:n),k-1);
P = [P; [v(ones(size(Q,1),1),idx) Q]]; %#ok<AGROW>
end
end
c = P;
end
end
|
github
|
tsajed/nmr-pred-master
|
phantom3d.m
|
.m
|
nmr-pred-master/spinach/kernel/external/phantom3d.m
| 7,917 |
utf_8
|
54651ef6f65a0fe3d1d5e068339b469b
|
% Three-dimensional analogue of MATLAB Shepp-Logan phantom. Generates a 3D
% head phantom that can be used to test 3-D reconstruction algorithms.
%
% DEF is a string that specifies the type of head phantom to generate.
% Valid values are:
%
% 'Shepp-Logan' A test image used widely by researchers in
% tomography
% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom
% in which the contrast is improved for better
% visual perception.
%
% N is a scalar that specifies the grid size of P.
% If you omit the argument, N defaults to 64.
%
% P = PHANTOM3D(E,N) generates a user-defined phantom, where each row
% of the matrix E specifies an ellipsoid in the image. E has ten columns,
% with each column containing a different parameter for the ellipsoids:
%
% Column 1: A the additive intensity value of the ellipsoid
% Column 2: a the length of the x semi-axis of the ellipsoid
% Column 3: b the length of the y semi-axis of the ellipsoid
% Column 4: c the length of the z semi-axis of the ellipsoid
% Column 5: x0 the x-coordinate of the center of the ellipsoid
% Column 6: y0 the y-coordinate of the center of the ellipsoid
% Column 7: z0 the z-coordinate of the center of the ellipsoid
% Column 8: phi phi Euler angle (in degrees) (rotation about z-axis)
% Column 9: theta theta Euler angle (in degrees) (rotation about x-axis)
% Column 10: psi psi Euler angle (in degrees) (rotation about z-axis)
%
% For purposes of generating the phantom, the domains for the x-, y-, and
% z-axes span [-1,1]. Columns 2 through 7 must be specified in terms
% of this range.
%
% [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom.
%
% Class Support
% -------------
% All inputs must be of class double. All outputs are of class double.
%
% Remarks
% -------
% For any given voxel in the output image, the voxel's value is equal to the
% sum of the additive intensity values of all ellipsoids that the voxel is a
% part of. If a voxel is not part of any ellipsoid, its value is 0.
%
% The additive intensity value A for an ellipsoid can be positive or negative;
% if it is negative, the ellipsoid will be darker than the surrounding pixels.
% Note that, depending on the values of A, some voxels may have values outside
% the range [0,1].
%
% Example
% -------
% ph = phantom3d(128);
% figure, imshow(squeeze(ph(64,:,:)))
%
% Matthias Christian Schabel ([email protected])
% University of Utah Department of Radiology
% Utah Center for Advanced Imaging Research
% 729 Arapeen Drive
% Salt Lake City, UT 84108-1218
function [p,ellipse]=phantom3d(varargin)
[ellipse,n] = parse_inputs(varargin{:});
p = zeros([n n n]);
rng = ( (0:n-1)-(n-1)/2 ) / ((n-1)/2);
[x,y,z] = meshgrid(rng,rng,rng);
coord = [x(:) y(:) z(:)]'; p = p(:)';
for k = 1:size(ellipse,1)
A = ellipse(k,1); % Amplitude change for this ellipsoid
asq = ellipse(k,2)^2; % a^2
bsq = ellipse(k,3)^2; % b^2
csq = ellipse(k,4)^2; % c^2
x0 = ellipse(k,5); % x offset
y0 = ellipse(k,6); % y offset
z0 = ellipse(k,7); % z offset
phi = ellipse(k,8)*pi/180; % first Euler angle in radians
theta = ellipse(k,9)*pi/180; % second Euler angle in radians
psi = ellipse(k,10)*pi/180; % third Euler angle in radians
cphi = cos(phi);
sphi = sin(phi);
ctheta = cos(theta);
stheta = sin(theta);
cpsi = cos(psi);
spsi = sin(psi);
% Euler rotation matrix
alpha = [ cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta;
-spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta;
stheta*sphi -stheta*cphi ctheta];
% rotated ellipsoid coordinates
coordp = alpha*coord;
idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1);
p(idx) = p(idx) + A;
end
p = reshape(p,[n n n]);
end
function [e,n] = parse_inputs(varargin)
% e is the m-by-10 array which defines ellipsoids
% n is the size of the phantom brain image
n = 128; % The default size
e = [];
defaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'};
for i=1:nargin
if ischar(varargin{i}) % Look for a default phantom
def = lower(varargin{i});
idx = strmatch(def,defaults); %#ok<MATCH2>
if isempty(idx)
eid = sprintf('Images:%s:unknownPhantom',mfilename);
msg = 'Unknown default phantom selected.';
error(eid,'%s',msg);
end
switch defaults{idx}
case 'shepp-logan'
e = shepp_logan;
case 'modified shepp-logan'
e = modified_shepp_logan;
case 'yu-ye-wang'
e = yu_ye_wang;
end
elseif numel(varargin{i})==1
n = varargin{i}; % a scalar is the image size
elseif ismatrix(varargin{i})&&size(varargin{i},2)==10
e = varargin{i}; % user specified phantom
else
eid = sprintf('Images:%s:invalidInputArgs',mfilename);
msg = 'Invalid input arguments.';
error(eid,'%s',msg);
end
end
% ellipse is not yet defined
if isempty(e)
e = modified_shepp_logan;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default head phantoms: %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function e = shepp_logan
e = modified_shepp_logan;
e(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01];
end
function e = modified_shepp_logan
%
% This head phantom is the same as the Shepp-Logan except
% the intensities are changed to yield higher contrast in
% the image. Taken from Toft, 199-200.
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ 1 .6900 .920 .810 0 0 0 0 0 0
-.8 .6624 .874 .780 0 -.0184 0 0 0 0
-.2 .1100 .310 .220 .22 0 0 -18 0 10
-.2 .1600 .410 .280 -.22 0 0 18 0 10
.1 .2100 .250 .410 0 .35 -.15 0 0 0
.1 .0460 .046 .050 0 .1 .25 0 0 0
.1 .0460 .046 .050 0 -.1 .25 0 0 0
.1 .0460 .023 .050 -.08 -.605 0 0 0 0
.1 .0230 .023 .020 0 -.606 0 0 0 0
.1 .0230 .046 .020 .06 -.605 0 0 0 0 ];
end
function e = yu_ye_wang
%
% Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ 1 .6900 .920 .900 0 0 0 0 0 0
-.8 .6624 .874 .880 0 0 0 0 0 0
-.2 .4100 .160 .210 -.22 0 -.25 108 0 0
-.2 .3100 .110 .220 .22 0 -.25 72 0 0
.2 .2100 .250 .500 0 .35 -.25 0 0 0
.2 .0460 .046 .046 0 .1 -.25 0 0 0
.1 .0460 .023 .020 -.08 -.65 -.25 0 0 0
.1 .0460 .023 .020 .06 -.65 -.25 90 0 0
.2 .0560 .040 .100 .06 -.105 .625 90 0 0
-.2 .0560 .056 .100 0 .100 .625 0 0 0 ];
end
|
github
|
tsajed/nmr-pred-master
|
lgwt.m
|
.m
|
nmr-pred-master/spinach/kernel/external/lgwt.m
| 1,126 |
utf_8
|
ac4205aaceb3726f4eea42d9460d9ec6
|
% This script is for computing definite integrals using Legendre-Gauss
% Quadrature. Computes the Legendre-Gauss nodes and weights on an interval
% [a,b] with truncation order N
%
% Suppose you have a continuous function f(x) which is defined on [a,b]
% which you can evaluate at any x in [a,b]. Simply evaluate it at all of
% the values contained in the x vector to obtain a vector f. Then compute
% the definite integral using sum(f.*w);
%
% Written by Greg von Winckel - 02/25/2004
function [x,w]=lgwt(N,a,b)
% Set point counters
N=N-1; N1=N+1; N2=N+2;
% Initial guess
y=cos((2*(0:N)'+1)*pi/(2*N+2))+(0.27/N1)*sin(pi*linspace(-1,1,N1)'*N/N2);
% Preallocate the arrays
L=zeros(N1,N2); Lp=zeros(N1,N2); y0=2;
% Iterate until convergence
while max(abs(y-y0))>eps
L(:,1)=1; L(:,2)=y;
for k=2:N1
L(:,k+1)=( (2*k-1)*y.*L(:,k)-(k-1)*L(:,k-1) )/k;
end
Lp=(N2)*( L(:,N1)-y.*L(:,N2) )./(1-y.^2);
y0=y; y=y0-L(:,N2)./Lp;
end
% Linear map from[-1,1] to [a,b]
x=(a*(1-y)+b*(1+y))/2;
% Compute the weights
w=(b-a)./((1-y.^2).*Lp.^2)*(N2/N1)^2;
end
|
github
|
tsajed/nmr-pred-master
|
b2r.m
|
.m
|
nmr-pred-master/spinach/kernel/external/b2r.m
| 1,889 |
utf_8
|
20310193c425104c056c7e75205b86af
|
% Blue -> white -> red color map. White always corresponds
% to value zero.
%
% Cunjie Zhang
% Ilya Kuprov
function newmap=b2r(cmin,cmax)
% Check the input
if nargin~=2
error('incorrect number of input arguments.')
end
if cmin>=cmax
error('the first argument must be smaller than the second one.');
end
% Set basic colors
red_top = [1 0 0];
white_middle= [1 1 1];
blue_bottom = [0 0 1];
% Set up color interpolation
color_num = 255;
color_input = [blue_bottom; white_middle; red_top];
oldsteps = linspace(-1, 1, length(color_input));
newsteps = linspace(-1, 1, color_num);
% Interpolate colors
newmap_all = NaN(size(newsteps,2),3);
if (cmin<0)&&(cmax>0)
if abs(cmin)<cmax
for j=1:3
newmap_all(:,j) = min(max(transpose(interp1(oldsteps, color_input(:,j), newsteps)), 0), 1);
end
start_point = round((cmin+cmax)/2/cmax*color_num);
newmap = squeeze(newmap_all(start_point:color_num,:));
elseif abs(cmin)>=cmax
for j=1:3
newmap_all(:,j) = min(max(transpose(interp1(oldsteps, color_input(:,j), newsteps)), 0), 1);
end
end_point = round((cmax-cmin)/2/abs(cmin)*color_num);
newmap = squeeze(newmap_all(1:end_point,:));
end
elseif cmin>=0
for j=1:3
newmap_all(:,j) = min(max(transpose(interp1(oldsteps, color_input(:,j), newsteps)), 0), 1);
end
start_point = round((cmin+cmax)/2/cmax*color_num);
newmap = squeeze(newmap_all(start_point:color_num,:));
elseif cmax <= 0
for j=1:3
newmap_all(:,j) = min(max(transpose(interp1(oldsteps, color_input(:,j), newsteps)), 0), 1);
end
end_point = round((cmax-cmin)/2/abs(cmin)*color_num);
newmap = squeeze(newmap_all(1:end_point,:));
end
end
|
github
|
tsajed/nmr-pred-master
|
jacobianest.m
|
.m
|
nmr-pred-master/spinach/kernel/external/jacobianest.m
| 5,840 |
utf_8
|
4c955378155f9dffa7cf48c2abaab7d7
|
function [jac,err] = jacobianest(fun,x0)
% gradest: estimate of the Jacobian matrix of a vector valued function of n variables
% usage: [jac,err] = jacobianest(fun,x0)
%
%
% arguments: (input)
% fun - (vector valued) analytical function to differentiate.
% fun must be a function of the vector or array x0.
%
% x0 - vector location at which to differentiate fun
% If x0 is an nxm array, then fun is assumed to be
% a function of n*m variables.
%
%
% arguments: (output)
% jac - array of first partial derivatives of fun.
% Assuming that x0 is a vector of length p
% and fun returns a vector of length n, then
% jac will be an array of size (n,p)
%
% err - vector of error estimates corresponding to
% each partial derivative in jac.
%
%
% Example: (nonlinear least squares)
% xdata = (0:.1:1)';
% ydata = 1+2*exp(0.75*xdata);
% fun = @(c) ((c(1)+c(2)*exp(c(3)*xdata)) - ydata).^2;
%
% [jac,err] = jacobianest(fun,[1 1 1])
%
% jac =
% -2 -2 0
% -2.1012 -2.3222 -0.23222
% -2.2045 -2.6926 -0.53852
% -2.3096 -3.1176 -0.93528
% -2.4158 -3.6039 -1.4416
% -2.5225 -4.1589 -2.0795
% -2.629 -4.7904 -2.8742
% -2.7343 -5.5063 -3.8544
% -2.8374 -6.3147 -5.0518
% -2.9369 -7.2237 -6.5013
% -3.0314 -8.2403 -8.2403
%
% err =
% 5.0134e-15 5.0134e-15 0
% 5.0134e-15 0 2.8211e-14
% 5.0134e-15 8.6834e-15 1.5804e-14
% 0 7.09e-15 3.8227e-13
% 5.0134e-15 5.0134e-15 7.5201e-15
% 5.0134e-15 1.0027e-14 2.9233e-14
% 5.0134e-15 0 6.0585e-13
% 5.0134e-15 1.0027e-14 7.2673e-13
% 5.0134e-15 1.0027e-14 3.0495e-13
% 5.0134e-15 1.0027e-14 3.1707e-14
% 5.0134e-15 2.0053e-14 1.4013e-12
%
% (At [1 2 0.75], jac should be numerically zero)
%
%
% See also: derivest, gradient, gradest
%
%
% Author: John D'Errico
% e-mail: [email protected]
% Release: 1.0
% Release date: 3/6/2007
% get the length of x0 for the size of jac
nx = numel(x0);
MaxStep = 100;
StepRatio = 2.0000001;
% was a string supplied?
if ischar(fun)
fun = str2func(fun);
end
% get fun at the center point
f0 = fun(x0);
f0 = f0(:);
n = length(f0);
if n==0
% empty begets empty
jac = zeros(0,nx);
err = jac;
return
end
relativedelta = MaxStep*StepRatio .^(0:-1:-25);
nsteps = length(relativedelta);
% total number of derivatives we will need to take
jac = zeros(n,nx);
err = jac;
for i = 1:nx
x0_i = x0(i);
if x0_i ~= 0
delta = x0_i*relativedelta;
else
delta = relativedelta;
end
% evaluate at each step, centered around x0_i
% difference to give a second order estimate
fdel = zeros(n,nsteps);
for j = 1:nsteps
fdif = fun(swapelement(x0,i,x0_i + delta(j))) - fun(swapelement(x0,i,x0_i - delta(j)));
fdel(:,j) = fdif(:);
end
% these are pure second order estimates of the
% first derivative, for each trial delta.
derest = fdel.*repmat(0.5 ./ delta,n,1);
% The error term on these estimates has a second order
% component, but also some 4th and 6th order terms in it.
% Use Romberg exrapolation to improve the estimates to
% 6th order, as well as to provide the error estimate.
% loop here, as rombextrap coupled with the trimming
% will get complicated otherwise.
for j = 1:n
[der_romb,errest] = rombextrap(StepRatio,derest(j,:),[2 4]);
% trim off 3 estimates at each end of the scale
nest = length(der_romb);
trim = [1:3, nest+(-2:0)];
[der_romb,tags] = sort(der_romb);
der_romb(trim) = [];
tags(trim) = [];
errest = errest(tags);
% now pick the estimate with the lowest predicted error
[err(j,i),ind] = min(errest);
jac(j,i) = der_romb(ind);
end
end
end % mainline function end
% =======================================
% sub-functions
% =======================================
function vec = swapelement(vec,ind,val)
% swaps val as element ind, into the vector vec
vec(ind) = val;
end % sub-function end
% ============================================
% subfunction - romberg extrapolation
% ============================================
function [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)
% do romberg extrapolation for each estimate
%
% StepRatio - Ratio decrease in step
% der_init - initial derivative estimates
% rombexpon - higher order terms to cancel using the romberg step
%
% der_romb - derivative estimates returned
% errest - error estimates
% amp - noise amplification factor due to the romberg step
srinv = 1/StepRatio;
% do nothing if no romberg terms
nexpon = length(rombexpon);
rmat = ones(nexpon+2,nexpon+1);
% two romberg terms
rmat(2,2:3) = srinv.^rombexpon;
rmat(3,2:3) = srinv.^(2*rombexpon);
rmat(4,2:3) = srinv.^(3*rombexpon);
% qr factorization used for the extrapolation as well
% as the uncertainty estimates
[qromb,rromb] = qr(rmat,0);
% the noise amplification is further amplified by the Romberg step.
% amp = cond(rromb);
% this does the extrapolation to a zero step size.
ne = length(der_init);
rhs = vec2mat(der_init,nexpon+2,ne - (nexpon+2));
rombcoefs = rromb\(qromb'*rhs);
der_romb = rombcoefs(1,:)';
% uncertainty estimate of derivative prediction
s = sqrt(sum((rhs - rmat*rombcoefs).^2,1));
rinv = rromb\eye(nexpon+1);
cov1 = sum(rinv.^2,2); % 1 spare dof
errest = s'*12.7062047361747*sqrt(cov1(1));
end % rombextrap
% ============================================
% subfunction - vec2mat
% ============================================
function mat = vec2mat(vec,n,m)
% forms the matrix M, such that M(i,j) = vec(i+j-1)
[i,j] = ndgrid(1:n,0:m-1);
ind = i+j;
mat = vec(ind);
if n==1
mat = mat';
end
end % vec2mat
|
github
|
tsajed/nmr-pred-master
|
expv.m
|
.m
|
nmr-pred-master/spinach/kernel/external/expv.m
| 4,863 |
utf_8
|
c8732ae90e0aa822b4d89d0835ebf115
|
% [w, err, hump] = expv( t, A, v, tol, m )
% EXPV computes an approximation of w = exp(t*A)*v for a
% general matrix A using Krylov subspace projection techniques.
% It does not compute the matrix exponential in isolation but instead,
% it computes directly the action of the exponential operator on the
% operand vector. This way of doing so allows for addressing large
% sparse problems. The matrix under consideration interacts only
% via matrix-vector products (matrix-free method).
%
% w = expv( t, A, v )
% computes w = exp(t*A)*v using a default tol = 1.0e-7 and m = 30.
%
% [w, err] = expv( t, A, v )
% renders an estimate of the error on the approximation.
%
% [w, err] = expv( t, A, v, tol )
% overrides default tolerance.
%
% [w, err, hump] = expv( t, A, v, tol, m )
% overrides default tolerance and dimension of the Krylov subspace,
% and renders an approximation of the `hump'.
%
% The hump is defined as:
% hump = max||exp(sA)||, s in [0,t] (or s in [t,0] if t < 0).
% It is used as a measure of the conditioning of the matrix exponential
% problem. The matrix exponential is well-conditioned if hump = 1,
% whereas it is poorly-conditioned if hump >> 1. However the solution
% can still be relatively fairly accurate even when the hump is large
% (the hump is an upper bound), especially when the hump and
% ||w(t)||/||v|| are of the same order of magnitude (further details in
% reference below).
%
% Example 1:
% ----------
% n = 100;
% A = rand(n);
% v = eye(n,1);
% w = expv(1,A,v);
%
% Example 2:
% ----------
% % generate a random sparse matrix
% n = 100;
% A = rand(n);
% for j = 1:n
% for i = 1:n
% if rand < 0.5, A(i,j) = 0; end;
% end;
% end;
% v = eye(n,1);
% A = sparse(A); % invaluable for a large and sparse matrix.
%
% tic
% [w,err] = expv(1,A,v);
% toc
%
% disp('w(1:10) ='); disp(w(1:10));
% disp('err ='); disp(err);
%
% tic
% w_matlab = expm(full(A))*v;
% toc
%
% disp('w_matlab(1:10) ='); disp(w_matlab(1:10));
% gap = norm(w-w_matlab)/norm(w_matlab);
% disp('||w-w_matlab|| / ||w_matlab|| ='); disp(gap);
%
% In the above example, n could have been set to a larger value,
% but the computation of w_matlab will be too long (feel free to
% discard this computation).
%
% See also MEXPV, EXPOKIT.
% Roger B. Sidje ([email protected])
% EXPOKIT: Software Package for Computing Matrix Exponentials.
% ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
function [w, err, hump] = expv( t, A, v, tol, m )
[n,n] = size(A);
if nargin == 3,
tol = 1.0e-7;
m = min(n,30);
end;
if nargin == 4,
m = min(n,30);
end;
anorm = norm(A,'inf');
mxrej = 10; btol = 1.0e-7;
gamma = 0.9; delta = 1.2;
mb = m; t_out = abs(t);
nstep = 0; t_new = 0;
t_now = 0; s_error = 0;
rndoff= anorm*eps;
k1 = 2; xm = 1/m; normv = norm(v); beta = normv;
fact = (((m+1)/exp(1))^(m+1))*sqrt(2*pi*(m+1));
t_new = (1/anorm)*((fact*tol)/(4*beta*anorm))^xm;
s = 10^(floor(log10(t_new))-1); t_new = ceil(t_new/s)*s;
sgn = sign(t); nstep = 0;
w = v;
hump = normv;
while t_now < t_out
nstep = nstep + 1;
t_step = min( t_out-t_now,t_new );
V = zeros(n,m+1);
H = zeros(m+2,m+2);
V(:,1) = (1/beta)*w;
for j = 1:m
p = A*V(:,j);
for i = 1:j
H(i,j) = V(:,i)'*p;
p = p-H(i,j)*V(:,i);
end;
s = norm(p);
if s < btol,
k1 = 0;
mb = j;
t_step = t_out-t_now;
break;
end;
H(j+1,j) = s;
V(:,j+1) = (1/s)*p;
end;
if k1 ~= 0,
H(m+2,m+1) = 1;
avnorm = norm(A*V(:,m+1));
end;
ireject = 0;
while ireject <= mxrej,
mx = mb + k1;
F = expm(sgn*t_step*H(1:mx,1:mx));
if k1 == 0,
err_loc = btol;
break;
else
phi1 = abs( beta*F(m+1,1) );
phi2 = abs( beta*F(m+2,1) * avnorm );
if phi1 > 10*phi2,
err_loc = phi2;
xm = 1/m;
elseif phi1 > phi2,
err_loc = (phi1*phi2)/(phi1-phi2);
xm = 1/m;
else
err_loc = phi1;
xm = 1/(m-1);
end;
end;
if err_loc <= delta * t_step*tol,
break;
else
t_step = gamma * t_step * (t_step*tol/err_loc)^xm;
s = 10^(floor(log10(t_step))-1);
t_step = ceil(t_step/s) * s;
if ireject == mxrej,
error('The requested tolerance is too high.');
end;
ireject = ireject + 1;
end;
end;
mx = mb + max( 0,k1-1 );
w = V(:,1:mx)*(beta*F(1:mx,1));
beta = norm( w );
hump = max(hump,beta);
t_now = t_now + t_step;
t_new = gamma * t_step * (t_step*tol/err_loc)^xm;
s = 10^(floor(log10(t_new))-1);
t_new = ceil(t_new/s) * s;
err_loc = max(err_loc,rndoff);
s_error = s_error + err_loc;
end;
err = s_error;
hump = hump / normv;
|
github
|
tsajed/nmr-pred-master
|
fourdif.m
|
.m
|
nmr-pred-master/spinach/kernel/external/fourdif.m
| 2,782 |
utf_8
|
a00d709f10e1499cbbbdaad00c7907a4
|
% The function [x, DM] = fourdif(N,m) computes the m'th derivative Fourier
% spectral differentiation matrix on grid with N equispaced points in [0,2pi)
%
% Input:
% N: Size of differentiation matrix.
% M: Derivative required (non-negative integer)
%
% Output:
% x: Equispaced points 0, 2pi/N, 4pi/N, ... , (N-1)2pi/N
% DM: m'th order differentiation matrix
%
% Explicit formulas are used to compute the matrices for m=1 and 2.
% A discrete Fouier approach is employed for m>2. The program
% computes the first column and first row and then uses the
% toeplitz command to create the matrix.
%
% For m=1 and 2 the code implements a "flipping trick" to
% improve accuracy suggested by W. Don and A. Solomonoff in
% SIAM J. Sci. Comp. Vol. 6, pp. 1253--1268 (1994).
% The flipping trick is necesary since sin t can be computed to high
% relative precision when t is small whereas sin (pi-t) cannot.
%
% S.C. Reddy, J.A.C. Weideman 1998. Corrected for MATLAB R13
% by JACW, April 2003.
function [x, DM] = fourdif(N,m)
x=2*pi*(0:N-1)'/N; % gridpoints
h=2*pi/N; % grid spacing
zi=sqrt(-1);
kk=(1:N-1)';
n1=floor((N-1)/2); n2=ceil((N-1)/2);
if m==0 % compute first column
col1=[1; zeros(N-1,1)]; % of zeroth derivative
row1=col1; % matrix, which is identity
elseif m==1 % compute first column
if rem(N,2)==0 % of 1st derivative matrix
topc=cot((1:n2)'*h/2);
col1=[0; 0.5*((-1).^kk).*[topc; -flipud(topc(1:n1))]];
else
topc=csc((1:n2)'*h/2);
col1=[0; 0.5*((-1).^kk).*[topc; flipud(topc(1:n1))]];
end;
row1=-col1; % first row
elseif m==2 % compute first column
if rem(N,2)==0 % of 2nd derivative matrix
topc=csc((1:n2)'*h/2).^2;
col1=[-pi^2/3/h^2-1/6; -0.5*((-1).^kk).*[topc; flipud(topc(1:n1))]];
else
topc=csc((1:n2)'*h/2).*cot((1:n2)'*h/2);
col1=[-pi^2/3/h^2+1/12; -0.5*((-1).^kk).*[topc; -flipud(topc(1:n1))]];
end;
row1=col1; % first row
else % employ FFT to compute
N1=floor((N-1)/2); % 1st column of matrix for m>2
N2 = (-N/2)*rem(m+1,2)*ones(rem(N+1,2));
mwave=zi*[(0:N1) N2 (-N1:-1)];
col1=real(ifft((mwave.^m).*fft([1 zeros(1,N-1)])));
if rem(m,2)==0,
row1=col1; % first row even derivative
else
col1=[0 col1(2:N)]';
row1=-col1; % first row odd derivative
end;
end;
DM=toeplitz(col1,row1);
end
|
github
|
tsajed/nmr-pred-master
|
simps.m
|
.m
|
nmr-pred-master/spinach/kernel/external/simps.m
| 3,044 |
utf_8
|
f3d545adb2c382d803770cbc778b8c92
|
% Simpson's numerical integration.
%
% Z = SIMPS(Y) computes an approximation of the integral of Y using
% Simpson's method (with unit spacing). To compute the integral for
% spacing different from one, multiply Z by the spacing increment.
%
% For vectors, SIMPS(Y) is the integral of Y. For matrices, SIMPS(Y)
% is a row vector with the integral over each column. For N-D arrays,
% SIMPS(Y) works across the first non-singleton dimension.
%
% Z = SIMPS(X,Y) computes the integral of Y with respect to X using
% Simpson's rule. X and Y must be vectors of the same length, or X
% must be a column vector and Y an array whose first non-singleton
% dimension is length(X). SIMPS operates along this dimension.
%
% Z = SIMPS(X,Y,DIM) or SIMPS(Y,DIM) integrates across dimension DIM
% of Y. The length of X must be the same as size(Y,DIM).
%
% [email protected]
% [email protected]
function z = simps(x,y,dim)
% Make sure x and y are column vectors, or y is a matrix.
perm = []; nshifts = 0;
if nargin == 3 % simps(x,y,dim)
perm = [dim:max(ndims(y),dim) 1:dim-1];
yp = permute(y,perm);
[m,n] = size(yp);
elseif nargin==2 && isscalar(y) % simps(y,dim)
dim = y; y = x;
perm = [dim:max(ndims(y),dim) 1:dim-1];
yp = permute(y,perm);
[m,n] = size(yp);
x = 1:m;
else % simps(y) or simps(x,y)
if nargin < 2, y = x; end
[yp,nshifts] = shiftdim(y);
[m,n] = size(yp);
if nargin < 2, x = 1:m; end
end
x = x(:);
if length(x) ~= m
if isempty(perm) % dim argument not given
error('MATLAB:simps:LengthXmismatchY',...
'LENGTH(X) must equal the length of the first non-singleton dimension of Y.');
else
error('MATLAB:simps:LengthXmismatchY',...
'LENGTH(X) must equal the length of the DIM''th dimension of Y.');
end
end
% The output size for [] is a special case when DIM is not given.
if isempty(perm) && isequal(y,[])
z = zeros(1,class(y));
return;
end
% Use TRAPZ if m<3
if m<3
if exist('dim','var')
z = trapz(x,y,dim);
else
z = trapz(x,y);
end
return
end
% Simpson's rule
y = yp;
clear yp
dx = repmat(diff(x,1,1),1,n);
dx1 = dx(1:end-1,:);
dx2 = dx(2:end,:);
alpha = (dx1+dx2)./dx1/6;
a0 = alpha.*(2*dx1-dx2);
a1 = alpha.*(dx1+dx2).^2./dx2;
a2 = alpha.*dx1./dx2.*(2*dx2-dx1);
z = sum(a0(1:2:end,:).*y(1:2:m-2,:) +...
a1(1:2:end,:).*y(2:2:m-1,:) +...
a2(1:2:end,:).*y(3:2:m,:),1);
if rem(m,2) == 0 % Adjusting if length(x) is even
state0 = warning('query','MATLAB:nearlySingularMatrix');
state0 = state0.state;
warning('off','MATLAB:nearlySingularMatrix')
C = vander(x(end-2:end))\y(end-2:end,:);
z = z + C(1,:).*(x(end,:).^3-x(end-1,:).^3)/3 +...
C(2,:).*(x(end,:).^2-x(end-1,:).^2)/2 +...
C(3,:).*dx(end,:);
warning(state0,'MATLAB:nearlySingularMatrix')
end
% Resizing
siz = size(y); siz(1) = 1;
z = reshape(z,[ones(1,nshifts),siz]);
if ~isempty(perm), z = ipermute(z,perm); end
end
|
github
|
unamfi/Cuantizacion-vectorial-master
|
LPCC.m
|
.m
|
Cuantizacion-vectorial-master/LPCC.m
| 2,289 |
utf_8
|
3352b9c3cd158718279a760df20b0e89
|
%% LPCC
function LPCCres = LPCC(s)
[R LPC p] = lpc(s);
Q = 3*p/2;
for i=1:1:length(LPC)
C = zeros(1,Q+1);
C(1) = log(sqrt(R{i}(1)));
for m=1:Q
if m>=1 && m<=p
C(m+1)=LPC{i}(m);
for k=1:m-1
C(m+1)=C(m+1)+((k/m)*C(k+1)*LPC{i}(m-k));
end
end
if m>p
C(m+1)=0;
for k=m-p:m-1
C(m+1)=C(m+1)+((k/m)*C(k+1)*LPC{i}(m-k));
end
end
end
LPCCres{i} = C;
end
end
function [R LPC p] = lpc(s)
% LPC Example of a local function.
fid = fopen(s, 'r');
senal0 = fread(fid, inf, 'int16');
%senal0 = Recortar(senal0);
b = [1 -0.95];
a = [1];
p = 8;
senal0 = filter(b, a, senal0);
lenX = length(senal0);
numMuestrasVentana = 128;
nV = lenX/numMuestrasVentana;
%display(lenX)
for trama=1:nV
%senal = senal(1:128);
senal = senal0((trama*128)-127:(trama*128));
senal = senal.*hamming(128);
r = zeros(p+1,1);
for k=0:p
for m=1:127-k+1
r(k+1) = r(k+1) + senal(m)*senal(m+k);
end
end
R{trama} = r;
%display(r); %Hasta aqui esta bien.
e = zeros(p+1,1);
e(1,1) = r(1);
k = zeros(p,1);
alpha = zeros(p,p);
for i=1:p
suma = 0;
for j=1:(i-1)
suma = suma + alpha(j,i-1)*r(abs(i-j+1));
end
k(i) = (r(i+1) - suma) / e(i,1);
%fprintf('k(%i) = %i\n', i, k(i) )
alpha(i,i) = k(i);
%display(alpha(i,i))
for j=1:i-1
alpha(j,i)= alpha(j,i-1) - k(i)*alpha(i-j,i-1);
%display(alpha)
end
e(i+1,1) = (1-k(i)*k(i))*e(i,1); %esta bien
%fprintf('e(%i) = %i\n', i + 1, k(i) )
end
%display(alpha)
am = zeros(p,1);
for m=1:p
am(m) = alpha(m,p);
end
LPC{trama} = am;
%display(am)
end
end
|
github
|
unamfi/Cuantizacion-vectorial-master
|
Itakura.m
|
.m
|
Cuantizacion-vectorial-master/Itakura.m
| 97 |
utf_8
|
a77eac098d163cc4aa6e1add2ecccb08
|
%% ITAKURA
function d = Itakura(y,Ry,x)
d = log((x*Ry*transpose(x))/(y*Ry*transpose(y)));
|
github
|
unamfi/Cuantizacion-vectorial-master
|
kMedias.m
|
.m
|
Cuantizacion-vectorial-master/kMedias.m
| 1,202 |
utf_8
|
ef907879c1d603d0e3a63604aae4a1e7
|
%% K-MEDIAS
function centroides = kMedias(vectores,k)
for i = 1:k
z{i} = vectores{i};
zAnt{i} = zeros(1,length(vectores{i}));
end
while notEqual(z,zAnt,k)
zAnt = z;
display('entro')
for vector = 1:length(vectores)
for cent = 1:length(z)
d{vector}(cent) = sum((z{cent}-vectores{vector}).^2);
end
end
vect=cell(1,k);
for vector = 1:length(vectores)
[val,ind]=min(d{vector});
display(ind)
temp=[vectores{vector};vect{ind}];
vect{ind}=temp;
end
for n = 1:k
z{n} = mean(vect{n},1);
end
centroides = z;
%display(d)
end
centroides = z;
%display(z)
%centroides=0;
end
function res = notEqual(z,zAnt,k)
res = 1;
for s = 1:k
b{s} = isequal(z{s},zAnt{s});
res = res & b{s};
end
if res == 0
res = 1;
else
res = 0;
end
end
|
github
|
shuoli-robotics/ppzr-master
|
dialog.m
|
.m
|
ppzr-master/sw/logalizer/dialog.m
| 34,826 |
utf_8
|
5407ab492113a3d0358e62c19dc1feab
|
%--------------------------------------------------------------------
%A simple MATLAB GUI for paparazzi autopilot log-file plotting
%Paparazzi Project [http://www.nongnu.org/paparazzi/]
%by Roman Krashhanitsa 28/10/2005
%adjustable parabeters:
% maxnum - increase if dialog window hangs up or doesnt refresh
% Nres - number or interpolated points in the plot, decrease to improve
% plotting performance or increase to improve resolution
%--------------------------------------------------------------------
function varargout = dialog(varargin)
% DIALOG M-file for dialog.fig
% DIALOG, by itself, creates a new DIALOG or raises the existing
% singleton*.
%
% H = DIALOG returns the handle to a new DIALOG or the handle to
% the existing singleton*.
%
% DIALOG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DIALOG.M with the given input arguments.
%
% DIALOG('Property','Value',...) creates a new DIALOG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before dialog_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to dialog_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help dialog
% Last Modified by GUIDE v2.5 18-Sep-2006 11:05:50
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @dialog_OpeningFcn, ...
'gui_OutputFcn', @dialog_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
function [m,n]=set2Plot(handles,section,field)
axes(handles.axes1);
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
N=max(size(labelsSections));
n=1; while n<=N && ~strcmpi(labelsSections(n),section), n=n+1; end;
if strcmpi(labelsSections(n),section),
set(handles.ListSections,'Value',n);
ListSections_Callback(0, 0, handles);
M=max(size(labelsFields));
m=1; while m<=M && ~strcmpi(labelsFields(m),field), m=m+1; end;
if strcmpi(labelsFields(m),field),
return;
end;
end;
m=0;
n=0;
return;
function [x,y]=setXY2plot(m,n,k)
%fetch xy data for section n, field m
global X0;
global logData;
global x;
global y;
x=[]; y=[];
len=max(size(logData));
last_time=0;
for j=1:len,
if logData(j).type==n && logData(j).plane_id==k,
if logData(j).time>last_time,
x=[x;logData(j).time];
y=[y;logData(j).fields(m)];
last_time=x(max(size(x)));
end;
end;
end;
x=x-X0; % shift timer to start at the boot time
function h=plotlog(x,y)
%plot data for section n, field m, plane_id k
% minimum number of points in the plot (resolution)
%if actual number of points if greater we dont need to change anything, but
%if it is less, interpolate using nearest neighbor as closest model of
%signals incoming to ground station. Previous value is used in the ap
%until a new value is obtained
Nres=1000;
if ~isempty(x) && ~isempty(y),
MIN=min(x);
MAX=max(x);
X=MIN:(MAX-MIN)/Nres:MAX;
if max(size(X))<=max(size(x)) %plot as it is
h=plot(x,y);
else
h=plot(x,y,'x');
%plot(X,interp1(x,y,X,'nearest')); %interpolate using nearest neighbor
end;
end;
% --- Executes just before dialog is made visible.
function dialog_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to dialog (see VARARGIN)
% Choose default command line output for dialog
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
if strcmp(get(hObject,'Visible'),'off')
plot([0 1],[0 0]);
end
set(handles.ListSections,'Enable','off');
set(handles.ListFields,'Enable','off');
set(handles.ListDevices,'Enable','off');
global X0;
X0=0;
% UIWAIT makes dialog wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = dialog_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
if ~isempty(handles)
varargout{1} = handles.output;
end;
% --------------------------------------------------------------------
function FileMenu_Callback(hObject, eventdata, handles)
% hObject handle to FileMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function OpenMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to OpenMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
file = uigetfile('*.fig');
if ~isequal(file, 0)
open(file);
end
% --------------------------------------------------------------------
function PrintMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to PrintMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
printdlg(handles.figure1)
% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to CloseMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
['Close ' get(handles.figure1,'Name') '...'],...
'Yes','No','Yes');
if strcmp(selection,'No')
return;
end
delete(handles.figure1)
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
set(hObject, 'String', {'plot(rand(5))', 'plot(sin(1:0.01:25))', 'comet(cos(1:.01:10))', 'bar(1:10)', 'plot(membrane)', 'surf(peaks)'});
% --- Executes on selection change in popupmenu3.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popupmenu3 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu3
% --- Executes on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global logData;
global labelsSections;
res=0;
[FileName,PathName,res] = uigetfile('*.log','Open Log file...');
if res~=0,
%read protocol specification
global nodeList;
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
global id_Devices;
try
node=xmlread(fullfile(PathName,FileName));
catch
warning('File ',fullfile(PathName,FileName),' does not exist');
close(gcf);
return;
end;
%find name of the data file
dataFileName=char(node.getFirstChild.getAttributes.item(0).getValue);
%find ground altitude
global ground_alt;
j=0;
found=0
while ~found && j<=node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.getLength,
if ~strcmpi(node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.item(j).getName,'GROUND_ALT'),
j=j+1;
found=1;
end;
end;
if j<=node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.getLength,
ground_alt=str2num(char(node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.item(j).getValue));
else ground_alt=0;
end;
%---read protocol---------------------------------
set(handles.text1,'String','Reading protocol specification');
notfound=1; %found messages or not
finish=0; %structure traversing finished
nodeList=node.getChildNodes;
i=1; %level in the structure
J=[0];
val='';
while notfound && ~finish,
while J(i)<nodeList.getLength && notfound,
drawnow; %flash event queue
val=node.getNodeName;
notfound=~strcmp(val,'message');
if notfound
while node.getChildNodes.getLength~=0 && notfound %go to the next level
nodeList=node.getChildNodes;
i=i+1;
J(i)=0;
node=nodeList.item(J(i));
val=node.getNodeName;
notfound=~strcmp(val,'message');
end;
J(i)=J(i)+1;
if J(i)<nodeList.getLength
node=nodeList.item(J(i));
end;
end;
end;
if i>=3 && notfound % if not a root node
nodeList=node.getParentNode.getParentNode.getChildNodes;
i=i-1;
J(i)=J(i)+1;
if J(i)<nodeList.getLength
node=nodeList.item(J(i));
end;
else
%nothing, will get caught by while loop
finish=1;
end;
end;
%make labels for the first list menu
count=nodeList.getLength;
labelsSections=[];
lineSections=[];
sectionsIndex=[];
for j=0:count-1,
if (nodeList.item(j).getNodeName=='message')
lineSections=[lineSections,char(nodeList.item(j).getAttributes.item(1).getValue),'|'];
sectionsIndex=[sectionsIndex,j];
labelsSections=[labelsSections,{char(nodeList.item(j).getAttributes.item(1).getValue)}];
end;
end;
lineSections=lineSections(1:max(size(lineSections))-1); %cut off last '|' character
set(handles.ListSections,'String',lineSections);
%make labels for the fields list (submenu)
nn=get(handles.ListSections,'Value');
nn=nn(1);
childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
count=childList.getLength;
labelsFields=[];
for j=0:count-1,
if childList.item(j).getNodeName=='field',
attr=childList.item(j).getAttributes;
cattr=attr.getLength; k=0;
while k<cattr && ~strcmp(attr.item(k).getName,'name'),
k=k+1;
end;
labelsFields=[labelsFields,char(attr.item(k).getValue),'|'];
fieldsIndex=[fieldsIndex,k];
end;
end;
labelsFields=labelsFields(1:max(size(labelsFields))-1); %cut off last '|' character
set(handles.ListFields,'String',labelsFields);
%--- read data ----------------------------
try
fid=fopen(fullfile(PathName,dataFileName));
catch
warning('File ',fullfile(PathName,dataFileName),' does not exist');
end;
fseek(fid,0,'eof'); %ff to end
endpos=ftell(fid); %find file size
fseek(fid,0,'bof'); %rewind to start
tline = fgetl(fid);
% while ~(feof(fid) || ~isempty(findstr(tline,'<data>'))),
% tline = fgetl(fid);
% end;
%read data
logData=[];
num=0; maxnum=100; %used to flush event queue
while ~feof(fid),
tline = fgetl(fid);
[tok,tline]=strtok(tline);
t=sscanf(tok,'%g'); %extract time
[tok,tline]=strtok(tline);
plane=sscanf(tok,'%g'); %airplane id?
[lab,tline]=strtok(tline); %extract message label
fld=sscanf(tline,'%g'); %extract a vector of fields
found=0; j=1; count=max(size(labelsSections));
%find index of the message label in the protocol
while j<count+1 && ~found,
%found=~isempty(strmatch(lab,cell2mat(labelsSections(j))));
found=strcmp(lab,cell2mat(labelsSections(j)));
j=j+1;
end;
j=j-1;
if ~found,
warning('Protocol specification in messages.xml does not match protocol in log file.');
else % if found
s=struct('time',t,'type',j,'plane_id',plane,'fields',fld);
logData=[logData,s];
end;
pos=ftell(fid);
set(handles.text1,'String',[num2str(double(pos)/double(endpos)*100.0,'%5.2f'),'%']);
num=num+1;
if num>maxnum,
num=0;
drawnow; %flash event queue
end;
end;
%make labels for Device ID listbox
global id_Devices;
id_Devices=[];
count=max(size(logData));
for j=1:count,
k=1; nn=max(size(id_Devices));
tag=logData(j).plane_id; notfound=1;
while k<=nn && notfound,
notfound=~(tag==id_Devices(k));
if notfound,
k=k+1;
end;
end;
if notfound,
id_Devices=[id_Devices,tag];
end;
end;
labelsDevices=num2str(id_Devices(1));
for j=2:max(size(id_Devices)),
labelsDevices=[labelsDevices,'|',num2str(id_Devices(j))];
end;
set(handles.ListDevices,'String',labelsDevices);
set(handles.text1,'String',FileName);
set(handles.ListSections,'Enable','on');
set(handles.ListFields,'Enable','on');
set(handles.ListDevices,'Enable','on');
else
%file was not selected
end;
j=1;
while (~strcmp(labelsSections{j},'BOOT') && j<max(size(labelsSections)) )
j=j+1;
end;
k=1;
while logData(k).type~=j && k<max(size(logData))
k=k+1;
end;
if (k<max(size(logData)))
X0=logData(k).time;
else
warning('BOOT message not found.. Corrupted log?');
end;
% --- Executes during object creation, after setting all properties.
function ListFields_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListFields (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListFields.
function ListFields_Callback(hObject, eventdata, handles)
% hObject handle to ListFields (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListFields contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListFields
%make labels for the fields list (submenu)
% --- Executes on button press in keepToggleButton.
function keepToggleButton_Callback(hObject, eventdata, handles)
% hObject handle to keepToggleButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of keepToggleButton
% --- Executes during object creation, after setting all properties.
function ListSections_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListSections (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListSections.
function ListSections_Callback(hObject, eventdata, handles)
% hObject handle to ListSections (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListSections contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListSections
% global nodeList;
% global labelsSections;
% global sectionsIndex;
% global labelsFields;
% global fieldsIndex;
%
% nn=get(handles.ListSections,'Value');
% nn=nn(1);
% childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
% count=childList.getLength;
% labelsFields=[];
% for j=0:count-1,
% if childList.item(j).getNodeName=='field',
% attr=childList.item(j).getAttributes;
% cattr=attr.getLength; k=0;
% while k<cattr && ~strcmp(attr.item(k).getName,'name'),
% k=k+1;
% end;
% labelsFields=[labelsFields,char(attr.item(k).getValue),'|'];
% fieldsIndex=[fieldsIndex,k];
% end;
% end;
% labelsFields=labelsFields(1:max(size(labelsFields))-1); %cut off last '|' character
% set(handles.ListFields,'String',labelsFields);
% set(handles.ListFields,'Value',1);
global nodeList;
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
nn=get(handles.ListSections,'Value');
nn=nn(1);
childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
count=childList.getLength;
labelsFields=[];
lineFields=[];
fieldsIndex=[];
for j=0:count-1,
if childList.item(j).getNodeName=='field',
attr=childList.item(j).getAttributes;
cattr=attr.getLength; k=0;
while k<cattr && ~strcmp(attr.item(k).getName,'name'),
k=k+1;
end;
labelsFields=[labelsFields,{char(attr.item(k).getValue)}];
lineFields=[lineFields,char(attr.item(k).getValue),'|'];
fieldsIndex=[fieldsIndex,k];
end;
end;
lineFields=lineFields(1:max(size(lineFields))-1); %cut off last '|' character
set(handles.ListFields,'String',lineFields);
set(handles.ListFields,'Value',1);
% --- Executes on button press in plotButton.
function plotButton_Callback(hObject, eventdata, handles)
% hObject handle to plotButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global logData;
global id_Devices;
global x;
global y;
Nres=1000; % minimum number of points in the plot (resolution)
%if actual number of points if greater we dont need to change anything, but
%if it is less, interpolate using nearest neighbor as closest model of
%signals incoming to ground station. Previous value is used in the ap
%until a new value is obtained
axes(handles.axes1);
if ~get(handles.keepToggleButton,'Value')
cla;
else
hold on;
end;
n=get(handles.ListSections,'Value');
n=n(1);
m=get(handles.ListFields,'Value'); m=m(1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
xlim([t1 t2]);
axis 'auto y';
end;
% --- Executes on button press in printButton.
function printButton_Callback(hObject, eventdata, handles)
% hObject handle to printButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
printpreview(gcf);
% --- Executes on button press in edit.
function edit_Callback(hObject, eventdata, handles)
% hObject handle to edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if ~get(handles.edit,'Value')
plotedit off;
else
plotedit(gcf);
end;
% --- Executes during object creation, after setting all properties.
function ListDevices_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListDevices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListDevices.
function ListDevices_Callback(hObject, eventdata, handles)
% hObject handle to ListDevices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListDevices contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListDevices
% --- Executes on button press in zoomin.
function zoomin_Callback(hObject, eventdata, handles)
% hObject handle to zoomin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')==get(hObject,'Max')
zoom on;
else
zoom off;
end;
% --- Executes on button press in zoomout.
function zoomout_Callback(hObject, eventdata, handles)
% hObject handle to zoomout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')==get(hObject,'Min')
zoom on;
else
zoom off;
end;
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function edit2_Callback(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit2 as text
% str2double(get(hObject,'String')) returns contents of edit2 as a double
% --- Executes on button press in rotate3d.
function rotate3d_Callback(hObject, eventdata, handles)
% hObject handle to rotate3d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of rotate3d
if get(hObject,'Value')==get(hObject,'Min')
rotate3d off;
else
rotate3d on;
end;
% --- Executes on button press in roll_button_button.
function roll_button_Callback(hObject, eventdata, handles)
% hObject handle to roll_button_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
[m,n]=set2Plot(handles,'attitude','phi');
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'desired','roll');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_roll','desired\_roll');
% --- Executes on button press in pitch_button.
function pitch_button_Callback(hObject, eventdata, handles)
% hObject handle to pitch_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devces(k);
[m,n]=set2Plot(handles,'attitude','theta');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'desired','pitch');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_pitch','desired\_pitch');
% --- Executes on button press in heading_button.
function heading_button_Callback(hObject, eventdata, handles)
% hObject handle to heading_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'GPS','course');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'navigation','desired_course');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_course','desired\_course');
% --- Executes on button press in altitude_button.
function altitude_button_Callback(hObject, eventdata, handles)
% hObject handle to altitude_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'desired','desired_altitude');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_altitude','desired\_altitude');
% --- Executes on button press in traj_button.
function traj_button_Callback(hObject, eventdata, handles)
% hObject handle to traj_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global z;
global t;
global id_Devices;
axes(handles.axes1);
xx=[];
yy=[];
zz=[];
k=get(handles.ListDevices,'Value'); k=id_Devices(1);
[m,n]=set2Plot(handles,'navigation','pos_x');
if m*n~=0,
[tx,xx]=setXY2plot(m,n,k);
end;
[m,n]=set2Plot(handles,'navigation','pos_y');
if m*n~=0,
[ty,yy]=setXY2plot(m,n,k);
yy=interp1(ty,yy,tx);
end;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[tz,zz]=setXY2plot(m,n,k);
zz=interp1(tz,zz,tx);
end;
x=xx;
y=yy;
global ground_alt;
z=zz-ground_alt;
t=tx;
if ~isempty(x) && ~isempty(y) && ~isempty(z) && ~isempty(t),
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2 && t1<=t(max(size(t)-1)),
N=max(size(t));
n1=1; while n1<=N && t(n1)<t1, n1=n1+1; end;
n2=n1+1; while n2<=N && t(n2)<t2, n2=n2+1; end;
h=plot3(x(n1:n2),y(n1:n2),z(n1:n2));
else
h=plot3(x,y,z);
end;
set(h,'LineWidth',1.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
box;
grid on;
end;
% --- Executes on button press in vel_button.
function vel_button_Callback(hObject, eventdata, handles)
% hObject handle to vel_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global z;
global t;
axes(handles.axes1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'GPS','speed');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
xx=[];
yy=[];
zz=[];
[m,n]=set2Plot(handles,'navigation','pos_x');
if m*n~=0,
[tx,xx]=setXY2plot(m,n,k);
end;
[m,n]=set2Plot(handles,'navigation','pos_y');
if m*n~=0,
[ty,yy]=setXY2plot(m,n,k);
yy=interp1(ty,yy,tx);
end;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[tz,zz]=setXY2plot(m,n,k);
zz=interp1(tz,zz,tx);
end;
v=[];N=max(size(xx));
for j=2:N, v=[v sqrt((xx(j)-xx(j-1))^2+(yy(j)-yy(j-1))^2+(zz(j)-zz(j-1))^2)/(tx(j)-tx(j-1))]; end;
y=v;
x=tx(2:N);
h=plotlog(x,y);
if ~isempty(x) && ~isempty(y),
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2 && t1<=t(max(size(t)-1)),
axis([t1 t2 -inf inf]); axis 'auto y';
end;
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
legend('GPS\_speed','computed\_speed');
% --- Executes on button press in gaz_button.
function gaz_button_Callback(hObject, eventdata, handles)
% hObject handle to gaz_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
axes(handles.axes1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'servos','thrust');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
% --- Executes on button press in ap_mode_pushbutton_pushbutton.
function ap_mode_pushbutton_Callback(hObject, eventdata, handles)
% hObject handle to ap_mode_pushbutton_pushbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
xl=xlim;
yl=ylim;
xscale=xl(2)-xl(1);
yscale=yl(2)-yl(1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'PPRZ_MODE','ap_mode');
if m*n==0,
return;
end;
n1=1;
[x,y]=setXY2plot(m,n,k);
N=max(size(x));
while x(n1)<xl(1) && n1<N, n1=n1+1; end;
while x(n1)<xl(2) && n1<N,
m1=y(n1+1);
C=[0 0 0]; %color
switch m1
case 0
C=[1 0.3 0];
txt='manual';
case 1
C=[1 0.5 0];
txt='auto1';
case 2
C=[1 0.7 0];
txt='auto2';
case 3
C=[1 1 0];
txt='home';
end;
n2=n1+1; while y(n2)==m1 && x(n2)<xl(2) && n2<N, n2=n2+1; end;
hold on;
if x(n1)<xl(1), t1=xl(1)+0.01*xscale; else t1=x(n1); end;
if x(n2)>xl(2), t2=xl(2)-0.01*xscale; else t2=x(n2); end;
line([t1 t2],[yl(1)+0.1*yscale yl(1)+0.1*yscale],'LineWidth',0.5,'Color',C);
if x(n1)>=xl(1), patch([1,0,1]*xscale*0.01+x(n1),[-1 0 1]*yscale*0.01+yl(1)+0.1*yscale,C); end;
if x(n2)<=xl(2), patch(-1*[1,0,1]*xscale*0.01+x(n2),[-1 0 1]*yscale*0.01+yl(1)+0.1*yscale,C); end;
if t2-t1>0.15*xscale, text(t1+0.5*(t2-t1),yl(1)+0.1*yscale,txt,...
'EdgeColor',C,'BackgroundColor',get(handles.axes1,'Color'),'HorizontalAlignment','Center'); end;
hold off;
n1=n2;
end;
legend_handle=legend;
if ~isempty(legend_handle), legend(legend_handle); end; %refresh legend
% --- Executes during object creation, after setting all properties.
function vel_button_CreateFcn(hObject, eventdata, handles)
% hObject handle to vel_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
|
github
|
shuoli-robotics/ppzr-master
|
dialog.m
|
.m
|
ppzr-master/sw/logalizer/matlab_log/dialog.m
| 41,728 |
utf_8
|
8a40368512745e70d158a49ee08c5926
|
%--------------------------------------------------------------------
%A simple MATLAB GUI for paparazzi autopilot log-file plotting
%Paparazzi Project [http://www.nongnu.org/paparazzi/]
%by Roman Krashhanitsa 28/10/2005
%adjustable parabeters:
% maxnum - increase if dialog window hangs up or doesnt refresh
% Nres - number or interpolated points in the plot, decrease to improve
% plotting performance or increase to improve resolution
%--------------------------------------------------------------------
function varargout = dialog(varargin)
% DIALOG M-file for dialog.fig
% DIALOG, by itself, creates a new DIALOG or raises the existing
% singleton*.
%
% H = DIALOG returns the handle to a new DIALOG or the handle to
% the existing singleton*.
%
% DIALOG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DIALOG.M with the given input arguments.
%
% DIALOG('Property','Value',...) creates a new DIALOG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before dialog_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to dialog_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help dialog
% Last Modified by GUIDE v2.5 18-Sep-2006 11:05:50
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @dialog_OpeningFcn, ...
'gui_OutputFcn', @dialog_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
function [m,n]=set2Plot(handles,section,field)
axes(handles.axes1);
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
N=max(size(labelsSections));
n=1; while n<=N && ~strcmpi(labelsSections(n),section), n=n+1; end;
if strcmpi(labelsSections(n),section),
set(handles.ListSections,'Value',n);
ListSections_Callback(0, 0, handles);
M=max(size(labelsFields));
m=1; while m<=M && ~strcmpi(labelsFields(m),field), m=m+1; end;
if strcmpi(labelsFields(m),field),
return;
end;
end;
m=0;
n=0;
return;
function [x,y]=setXY2plot(m,n,k)
%fetch xy data for section n, field m
global X0;
global logData;
global x;
global y;
x=[]; y=[];
len=max(size(logData));
last_time=0;
for j=1:len,
if logData(j).type==n && logData(j).plane_id==k,
if logData(j).time>last_time,
x=[x;logData(j).time];
y=[y;logData(j).fields(m)];
last_time=x(max(size(x)));
end;
end;
end;
x=x-X0; % shift timer to start at the boot time
function h=plotlog(x,y)
%plot data for section n, field m, plane_id k
% minimum number of points in the plot (resolution)
%if actual number of points if greater we dont need to change anything, but
%if it is less, interpolate using nearest neighbor as closest model of
%signals incoming to ground station. Previous value is used in the ap
%until a new value is obtained
Nres=1000;
h=0;
if ~isempty(x) && ~isempty(y),
MIN=min(x);
MAX=max(x);
X=MIN:(MAX-MIN)/Nres:MAX;
if max(size(X))<=max(size(x)) %plot as it is
h=plot(x,y);
else
h=plot(x,y,'x');
%plot(X,interp1(x,y,X,'nearest')); %interpolate using nearest neighbor
end;
end;
% --- Executes just before dialog is made visible.
function dialog_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to dialog (see VARARGIN)
% Choose default command line output for dialog
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
if strcmp(get(hObject,'Visible'),'off')
plot([0 1],[0 0]);
end
set(handles.ListSections,'Enable','off');
set(handles.ListFields,'Enable','off');
set(handles.ListDevices,'Enable','off');
global X0;
X0=0;
pp_home=getenv('PAPARAZZI_HOME');
if (max(size(pp_home))==0)
warning('PAPARAZZI_HOME environment variable was not found. Using current dir..');
pp_home=pwd; % otherwise use curent directory
else
pp_home=fullfile(pp_home,'conf');
end;
%read protocol specification
global nodeList;
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
global X0;
X0=0;
try
node=xmlread(fullfile(pp_home,'messages.xml'));
catch
warning('messages.xml not found. trying var/messages.xml...')
try
node=xmlread(fullfile(pp_home,'var/messages.xml'));
catch
warning('messages.xml not found. Exiting...');
close(gcf);
% delete(handles.figure1);
return;
end;
end;
nodeList=node.getChildNodes.item(0).getChildNodes;
%make labels for the first list menu
count=nodeList.getLength;
labelsSections=[];
lineSections=[];
sectionsIndex=[];
j=0; found=false;
while j<count && ~found,
if (nodeList.item(j).getNodeType == nodeList.item(j).ELEMENT_NODE & ...
strcmp(nodeList.item(j).getNodeName,'class') & ...
strcmp(nodeList.item(j).getAttributes.getNamedItem('name').getValue,'telemetry'))
found=true;
else j=j+1;
end;
end;
nodeList=nodeList.item(j).getChildNodes;
count=nodeList.getLength;
for j=0:count-1,
if (nodeList.item(j).getNodeType == nodeList.item(j).ELEMENT_NODE & ...
strcmp(nodeList.item(j).getNodeName,'message'))
lineSections=[lineSections,char(nodeList.item(j).getAttributes.getNamedItem('name').getValue),'|'];
sectionsIndex=[sectionsIndex,j];
labelsSections=[labelsSections,{char(nodeList.item(j).getAttributes.getNamedItem('name').getValue)}];
end;
end;
lineSections=lineSections(1:max(size(lineSections))-1); %cut off last '|' character
set(handles.ListSections,'String',lineSections);
%make labels for the fields list (submenu)
nn=get(handles.ListSections,'Value');
nn=nn(1);
childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
count=childList.getLength;
labelsFields=[];
for j=0:count-1,
if strcmp(childList.item(j).getNodeName,'field'),
attr=childList.item(j).getAttributes;
cattr=attr.getLength; k=0;
while k<cattr && ~strcmp(attr.item(k).getName,'name'),
k=k+1;
end;
labelsFields=[labelsFields,char(attr.item(k).getValue),'|'];
fieldsIndex=[fieldsIndex,k];
end;
end;
labelsFields=labelsFields(1:max(size(labelsFields))-1); %cut off last '|' character
set(handles.ListFields,'String',labelsFields);
% UIWAIT makes dialog wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = dialog_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
if ~isempty(handles)
varargout{1} = handles.output;
end;
% --------------------------------------------------------------------
function FileMenu_Callback(hObject, eventdata, handles)
% hObject handle to FileMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function OpenMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to OpenMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
file = uigetfile('*.fig');
if ~isequal(file, 0)
open(file);
end
% --------------------------------------------------------------------
function PrintMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to PrintMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
printdlg(handles.figure1)
% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to CloseMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
['Close ' get(handles.figure1,'Name') '...'],...
'Yes','No','Yes');
if strcmp(selection,'No')
return;
end
delete(handles.figure1)
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
set(hObject, 'String', {'plot(rand(5))', 'plot(sin(1:0.01:25))', 'comet(cos(1:.01:10))', 'bar(1:10)', 'plot(membrane)', 'surf(peaks)'});
% --- Executes on selection change in popupmenu3.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popupmenu3 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu3
% --- Executes on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global logData;
global labelsSections;
res=0;
[FileName,PathName,res] = uigetfile('*.log','Open Log file...');
if res~=0,
%read protocol specification
global nodeList;
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
global id_Devices;
% try
% node=xmlread(fullfile(PathName,FileName));
% catch
% warning('File ',fullfile(PathName,FileName),' does not exist');
% close(gcf);
% return;
% end;
%
% %find name of the data file
% dataFileName=char(node.getFirstChild.getAttributes.item(0).getValue);
% %find ground altitude
% global ground_alt;
% j=0;
% found=0
% while ~found && j<=node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.getLength,
% if ~strcmpi(node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.item(j).getName,'GROUND_ALT'),
% j=j+1;
% found=1;
% end;
% end;
% if j<=node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.getLength,
% ground_alt=str2num(char(node.getFirstChild.getChildNodes.item(1).getChildNodes.item(1).getChildNodes.item(1).getAttributes.item(j).getValue));
% else ground_alt=0;
% end;
%
%
% %---read protocol---------------------------------
% set(handles.text1,'String','Reading protocol specification');
% notfound=1; %found messages or not
% finish=0; %structure traversing finished
% nodeList=node.getChildNodes;
% i=1; %level in the structure
% J=[0];
% val='';
% while notfound && ~finish,
% while J(i)<nodeList.getLength && notfound,
% drawnow; %flash event queue
% val=node.getNodeName;
% notfound=~strcmp(val,'message');
% if notfound
% while node.getChildNodes.getLength~=0 && notfound %go to the next level
% nodeList=node.getChildNodes;
% i=i+1;
% J(i)=0;
% node=nodeList.item(J(i));
% val=node.getNodeName;
% notfound=~strcmp(val,'message');
% end;
% J(i)=J(i)+1;
% if J(i)<nodeList.getLength
% node=nodeList.item(J(i));
% end;
% end;
% end;
% if i>=3 && notfound % if not a root node
% nodeList=node.getParentNode.getParentNode.getChildNodes;
% i=i-1;
% J(i)=J(i)+1;
% if J(i)<nodeList.getLength
% node=nodeList.item(J(i));
% end;
% else
% %nothing, will get caught by while loop
% finish=1;
% end;
% end;
% %make labels for the first list menu
% count=nodeList.getLength;
% labelsSections=[];
% lineSections=[];
% sectionsIndex=[];
% for j=0:count-1,
% if (nodeList.item(j).getNodeName=='message')
% lineSections=[lineSections,char(nodeList.item(j).getAttributes.item(1).getValue),'|'];
% sectionsIndex=[sectionsIndex,j];
% labelsSections=[labelsSections,{char(nodeList.item(j).getAttributes.item(1).getValue)}];
% end;
% end;
% lineSections=lineSections(1:max(size(lineSections))-1); %cut off last '|' character
% set(handles.ListSections,'String',lineSections);
% %make labels for the fields list (submenu)
% nn=get(handles.ListSections,'Value');
% nn=nn(1);
% childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
% count=childList.getLength;
% labelsFields=[];
% for j=0:count-1,
% if childList.item(j).getNodeName=='field',
% attr=childList.item(j).getAttributes;
% cattr=attr.getLength; k=0;
% while k<cattr && ~strcmp(attr.item(k).getName,'name'),
% k=k+1;
% end;
% labelsFields=[labelsFields,char(attr.item(k).getValue),'|'];
% fieldsIndex=[fieldsIndex,k];
% end;
% end;
% labelsFields=labelsFields(1:max(size(labelsFields))-1); %cut off last '|' character
% set(handles.ListFields,'String',labelsFields);
if res~=0,
try
fid=fopen(fullfile(PathName,FileName));
catch
error(lasterror);
end;
%find beginning of data
fseek(fid,0,'eof'); %ff to end
endpos=ftell(fid); %find file size
fseek(fid,0,'bof'); %rewind to start
tline = fgetl(fid);
while ~(feof(fid) || ~isempty(findstr(tline,'data_file='))),
tline = fgetl(fid);
end;
[name,value]=strread(tline,'%q%q','delimiter','"');
dataFileName=value{2};
fclose(fid);
%--- read data ----------------------------
try
fid=fopen(fullfile(PathName,dataFileName));
catch
warning('File ',fullfile(PathName,dataFileName),' does not exist');
end;
fseek(fid,0,'eof'); %ff to end
endpos=ftell(fid); %find file size
fseek(fid,0,'bof'); %rewind to start
%tline = fgetl(fid);
% while ~(feof(fid) || ~isempty(findstr(tline,'<data>'))),
% tline = fgetl(fid);
% end;
%read data
logData=[];
num=0; maxnum=100; %used to flush event queue
while ~feof(fid),
tline = fgetl(fid);
[tok,tline]=strtok(tline);
t=sscanf(tok,'%g'); %extract time
[tok,tline]=strtok(tline);
plane=sscanf(tok,'%g'); %airplane id?
[lab,tline]=strtok(tline); %extract message label
fld=sscanf(tline,'%g'); %extract a vector of fields
found=0; j=1; count=max(size(labelsSections));
%find index of the message label in the protocol
while j<count+1 && ~found,
%found=~isempty(strmatch(lab,cell2mat(labelsSections(j))));
found=strcmp(lab,cell2mat(labelsSections(j)));
j=j+1;
end;
j=j-1;
if ~found,
warning('Protocol specification in messages.xml does not match protocol in log file.');
else % if found
s=struct('time',t,'type',j,'plane_id',plane,'fields',fld);
logData=[logData,s];
end;
pos=ftell(fid);
set(handles.text1,'String',[num2str(double(pos)/double(endpos)*100.0,'%5.2f'),'%']);
num=num+1;
if num>maxnum,
num=0;
drawnow; %flash event queue
end;
end;
%make labels for Device ID listbox
global id_Devices;
id_Devices=[];
count=max(size(logData));
for j=1:count,
k=1; nn=max(size(id_Devices));
tag=logData(j).plane_id; notfound=1;
while k<=nn && notfound,
notfound=~(tag==id_Devices(k));
if notfound,
k=k+1;
end;
end;
if notfound,
id_Devices=[id_Devices,tag];
end;
end;
labelsDevices=num2str(id_Devices(1));
for j=2:max(size(id_Devices)),
labelsDevices=[labelsDevices,'|',num2str(id_Devices(j))];
end;
set(handles.ListDevices,'String',labelsDevices);
set(handles.text1,'String',FileName);
set(handles.ListSections,'Enable','on');
set(handles.ListFields,'Enable','on');
set(handles.ListDevices,'Enable','on');
else
%file was not selected
end;
j=1;
while (~strcmp(labelsSections{j},'BOOT') && j<max(size(labelsSections)) )
j=j+1;
end;
k=1;
while logData(k).type~=j && k<max(size(logData))
k=k+1;
end;
if (k<max(size(logData)))
X0=logData(k).time;
else
warning('BOOT message not found.. Corrupted log?');
end;
end; %function
% --- Executes during object creation, after setting all properties.
function ListFields_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListFields (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListFields.
function ListFields_Callback(hObject, eventdata, handles)
% hObject handle to ListFields (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListFields contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListFields
%make labels for the fields list (submenu)
% --- Executes on button press in keepToggleButton.
function keepToggleButton_Callback(hObject, eventdata, handles)
% hObject handle to keepToggleButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of keepToggleButton
% --- Executes during object creation, after setting all properties.
function ListSections_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListSections (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListSections.
function ListSections_Callback(hObject, eventdata, handles)
% hObject handle to ListSections (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListSections contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListSections
% global nodeList;
% global labelsSections;
% global sectionsIndex;
% global labelsFields;
% global fieldsIndex;
%
% nn=get(handles.ListSections,'Value');
% nn=nn(1);
% childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
% count=childList.getLength;
% labelsFields=[];
% for j=0:count-1,
% if childList.item(j).getNodeName=='field',
% attr=childList.item(j).getAttributes;
% cattr=attr.getLength; k=0;
% while k<cattr && ~strcmp(attr.item(k).getName,'name'),
% k=k+1;
% end;
% labelsFields=[labelsFields,char(attr.item(k).getValue),'|'];
% fieldsIndex=[fieldsIndex,k];
% end;
% end;
% labelsFields=labelsFields(1:max(size(labelsFields))-1); %cut off last '|' character
% set(handles.ListFields,'String',labelsFields);
% set(handles.ListFields,'Value',1);
global nodeList;
global labelsSections;
global sectionsIndex;
global labelsFields;
global fieldsIndex;
nn=get(handles.ListSections,'Value');
nn=nn(1);
childList=nodeList.item(sectionsIndex(nn)).getChildNodes;
count=childList.getLength;
labelsFields=[];
lineFields=[];
fieldsIndex=[];
for j=0:count-1,
if childList.item(j).getNodeName=='field',
attr=childList.item(j).getAttributes;
cattr=attr.getLength; k=0;
while k<cattr && ~strcmp(attr.item(k).getName,'name'),
k=k+1;
end;
labelsFields=[labelsFields,{char(attr.item(k).getValue)}];
lineFields=[lineFields,char(attr.item(k).getValue),'|'];
fieldsIndex=[fieldsIndex,k];
end;
end;
lineFields=lineFields(1:max(size(lineFields))-1); %cut off last '|' character
set(handles.ListFields,'String',lineFields);
set(handles.ListFields,'Value',1);
% --- Executes on button press in plotButton.
function plotButton_Callback(hObject, eventdata, handles)
% hObject handle to plotButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global logData;
global id_Devices;
global x;
global y;
Nres=1000; % minimum number of points in the plot (resolution)
%if actual number of points if greater we dont need to change anything, but
%if it is less, interpolate using nearest neighbor as closest model of
%signals incoming to ground station. Previous value is used in the ap
%until a new value is obtained
axes(handles.axes1);
if ~get(handles.keepToggleButton,'Value')
cla;
else
hold on;
end;
n=get(handles.ListSections,'Value');
n=n(1);
m=get(handles.ListFields,'Value'); m=m(1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
xlim([t1 t2]);
axis 'auto y';
end;
fig=figure('Position',[250, 280, 600,240]);
ax=gca;
[x,y]=setXY2plot(m,n,k);
axes(ax);
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
[c,j1]=min(abs(x-t1)); j1
[c,j2]=min(abs(x-t2)); j2
p=plotlog(x(j1:j2)-x(j1),y(j1:j2));
xlim([0 t2-t1]);
axis 'auto y';
else
p=plotlog(x,y);
axis 'auto y';
end;
setTemplate(p,ax,fig);
xlabel('Time, s');
ylabel('Throttle');
% --- Executes on button press in printButton.
function printButton_Callback(hObject, eventdata, handles)
% hObject handle to printButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
printpreview(gcf);
% --- Executes on button press in edit.
function edit_Callback(hObject, eventdata, handles)
% hObject handle to edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if ~get(handles.edit,'Value')
plotedit off;
else
plotedit(gcf);
end;
% --- Executes during object creation, after setting all properties.
function ListDevices_CreateFcn(hObject, eventdata, handles)
% hObject handle to ListDevices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in ListDevices.
function ListDevices_Callback(hObject, eventdata, handles)
% hObject handle to ListDevices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ListDevices contents as cell array
% contents{get(hObject,'Value')} returns selected item from ListDevices
% --- Executes on button press in zoomin.
function zoomin_Callback(hObject, eventdata, handles)
% hObject handle to zoomin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')==get(hObject,'Max')
zoom on;
else
zoom off;
end;
% --- Executes on button press in zoomout.
function zoomout_Callback(hObject, eventdata, handles)
% hObject handle to zoomout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')==get(hObject,'Min')
zoom on;
else
zoom off;
end;
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function edit2_Callback(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit2 as text
% str2double(get(hObject,'String')) returns contents of edit2 as a double
% --- Executes on button press in rotate3d.
function rotate3d_Callback(hObject, eventdata, handles)
% hObject handle to rotate3d (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of rotate3d
if get(hObject,'Value')==get(hObject,'Min')
rotate3d off;
else
rotate3d on;
end;
% --- Executes on button press in roll_button_button.
function roll_button_Callback(hObject, eventdata, handles)
% hObject handle to roll_button_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
[m,n]=set2Plot(handles,'attitude','phi');
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'desired','roll');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y*180/pi);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_roll','desired\_roll');
figure('Position',[250, 280, 600,270]);
hh=gca;
[m,n]=set2Plot(handles,'desired','roll');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
axes(hh);
h=plotlog(x,y*180/pi);
set(h,'LineWidth',3.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
set(h,'Color',[0.6 0.6 1]);
end;
hold on;
[m,n]=set2Plot(handles,'attitude','phi');
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
axes(hh);
h=plotlog(x,y);
set(h,'LineWidth',1.);
set(h,'Marker','none');
set(h,'LineStyle','-');
set(h,'Color',[0 0 0]);
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('Desired roll','Estimated roll');
xlabel('Time, s');
ylabel('Angle, deg');
set(hh,'FontName','Times');
set(hh,'FontSize',9);
set(get(hh,'XLabel'),'FontName','Times','FontSize',9);
set(get(hh,'YLabel'),'FontName','Times','FontSize',9);
% --- Executes on button press in pitch_button.
function pitch_button_Callback(hObject, eventdata, handles)
% hObject handle to pitch_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'attitude','theta');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'desired','pitch');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_pitch','desired\_pitch');
% --- Executes on button press in heading_button.
function heading_button_Callback(hObject, eventdata, handles)
% hObject handle to heading_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'GPS','course');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y*0.1);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'navigation','desired_course');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y*0.1);
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_course','desired\_course');
% --- Executes on button press in altitude_button.
function altitude_button_Callback(hObject, eventdata, handles)
% hObject handle to altitude_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global id_Devices;
axes(handles.axes1);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'desired','desired_altitude');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',3.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y/100);
set(h,'LineWidth',1);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('estimated\_altitude','desired\_altitude');
figure('Position',[250, 280, 600,270]);
hh=gca;
axes(hh);
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
[m,n]=set2Plot(handles,'desired','desired_altitude');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
axes(hh);
h=plotlog(x,y);
set(h,'LineWidth',3.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
set(h,'Color',[0.6,0.6,1]);
end;
hold on;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
axes(hh);
h=plotlog(x,y/100);
set(h,'LineWidth',1);
set(h,'Marker','none');
set(h,'LineStyle','-');
set(h,'Color',[0,0,0]);
end;
hold off;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
legend('Desired altitude','Estimated altitude');
xlabel('Time, s');
ylabel('Altitude, m');
set(hh,'FontName','Times','FontSize',9);
set(get(hh,'XLabel'),'FontName','Times','FontSize',9);
set(get(hh,'YLabel'),'FontName','Times','FontSize',9);
% --- Executes on button press in traj_button.
function traj_button_Callback(hObject, eventdata, handles)
% hObject handle to traj_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global z;
global t;
global id_Devices;
axes(handles.axes1);
xx=[];
yy=[];
zz=[];
k=get(handles.ListDevices,'Value'); k=id_Devices(k);
format long;
[m,n]=set2Plot(handles,'navigation','pos_x');
%[m,n]=set2Plot(handles,'GPS','utm_east');
if m*n~=0,
[tx,xx]=setXY2plot(m,n,k);
end;
[m,n]=set2Plot(handles,'navigation','pos_y');
%[m,n]=set2Plot(handles,'GPS','utm_north');
if m*n~=0,
[ty,yy]=setXY2plot(m,n,k);
% yy=interp1(ty,yy,tx,'spline');
end;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[tz,zz]=setXY2plot(m,n,k);
zz=interp1(tz,zz,tx,'nearest');
end;
x=xx;
y=yy;
global ground_alt;
z=zz/100-ground_alt;
t=tx;
if ~isempty(x) && ~isempty(y) && ~isempty(z) && ~isempty(t),
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2 && t1<=t(max(size(t)-1)),
N=max(size(t));
n1=1; while n1<=N && t(n1)<t1, n1=n1+1; end;
n2=n1+1; while n2<=N && t(n2)<t2, n2=n2+1; end;
h=plot3(x(n1:n2),y(n1:n2),z(n1:n2));
else
h=plot3(x,y,z);
end;
set(h,'LineWidth',1.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
xlabel('x');
ylabel('y');
zlabel('z');
box;
grid on;
end;
figure('Position',[250, 280, 600,270]);
hh=gca;
axes(hh);
if ~isempty(x) && ~isempty(y) && ~isempty(z) && ~isempty(t),
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2 && t1<=t(max(size(t)-1)),
N=max(size(t));
n1=1; while n1<=N && t(n1)<t1, n1=n1+1; end;
n2=n1+1; while n2<=N && t(n2)<t2, n2=n2+1; end;
axes(hh);
h=plot3(x(n1:n2),y(n1:n2),z(n1:n2));
else
axes(hh);
h=plot3(x,y,z);
end;
set(h,'LineWidth',1.0);t
set(h,'Marker','none');
set(h,'LineStyle','-');
xlabel('x');
ylabel('y');
zlabel('z');
box;
grid on;
end;
% --- Executes on button press in vel_button.
function vel_button_Callback(hObject, eventdata, handles)
% hObject handle to vel_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
global z;
global t;
axes(handles.axes1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'GPS','speed');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y/100);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold on;
xx=[];
yy=[];
zz=[];
[m,n]=set2Plot(handles,'navigation','pos_x');
if m*n~=0,
[tx,xx]=setXY2plot(m,n,k);
end;
[m,n]=set2Plot(handles,'navigation','pos_y');
if m*n~=0,
[ty,yy]=setXY2plot(m,n,k);
yy=interp1(ty,yy,tx);
end;
[m,n]=set2Plot(handles,'GPS','alt');
if m*n~=0,
[tz,zz]=setXY2plot(m,n,k);
zz=interp1(tz,zz,tx)/100;
end;
v=[];N=max(size(xx));
for j=2:N, v=[v sqrt((xx(j)-xx(j-1))^2+(yy(j)-yy(j-1))^2+(zz(j)-zz(j-1))^2)/(tx(j)-tx(j-1))]; end;
y=v;
x=tx(2:N);
h=plotlog(x,y);
if ~isempty(x) && ~isempty(y),
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2 && t1<=t(max(size(t)-1)),
axis([t1 t2 -inf inf]); axis 'auto y';
end;
set(h,'LineWidth',2.0);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
hold off;
legend('GPS\_speed','computed\_speed');
% --- Executes on button press in gaz_button.
function gaz_button_Callback(hObject, eventdata, handles)
% hObject handle to gaz_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global x;
global y;
axes(handles.axes1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'servos','thrust');
if m*n~=0,
[x,y]=setXY2plot(m,n,k);
h=plotlog(x,y);
set(h,'LineWidth',0.5);
set(h,'Marker','none');
set(h,'LineStyle','-');
end;
t1=str2num(get(handles.edit1,'String'));
t2=str2num(get(handles.edit2,'String'));
if t1~=t2 && t1<t2,
axis([t1 t2 -inf inf]); axis 'auto y';
end;
% --- Executes on button press in ap_mode_pushbutton_pushbutton.
function ap_mode_pushbutton_Callback(hObject, eventdata, handles)
% hObject handle to ap_mode_pushbutton_pushbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
xl=xlim;
yl=ylim;
xscale=xl(2)-xl(1);
yscale=yl(2)-yl(1);
k=get(handles.ListDevices,'Value');
global id_Devices;
k=id_Devices(k);
[m,n]=set2Plot(handles,'PPRZ_MODE','ap_mode');
if m*n==0,
return;
end;
n1=1;
[x,y]=setXY2plot(m,n,k);
N=max(size(x));
while x(n1)<xl(1) && n1<N, n1=n1+1; end;
while x(n1)<xl(2) && n1<N,
m1=y(n1+1);
C=[0 0 0]; %color
switch m1
case 0
C=[1 0.3 0];
txt='manual';
case 1
C=[1 0.5 0];
txt='auto1';
case 2
C=[1 0.7 0];
txt='auto2';
case 3
C=[1 1 0];
txt='home';
end;
n2=n1+1; while y(n2)==m1 && x(n2)<xl(2) && n2<N, n2=n2+1; end;
hold on;
if x(n1)<xl(1), t1=xl(1)+0.01*xscale; else t1=x(n1); end;
if x(n2)>xl(2), t2=xl(2)-0.01*xscale; else t2=x(n2); end;
line([t1 t2],[yl(1)+0.1*yscale yl(1)+0.1*yscale],'LineWidth',0.5,'Color',C);
if x(n1)>=xl(1), patch([1,0,1]*xscale*0.01+x(n1),[-1 0 1]*yscale*0.01+yl(1)+0.1*yscale,C); end;
if x(n2)<=xl(2), patch(-1*[1,0,1]*xscale*0.01+x(n2),[-1 0 1]*yscale*0.01+yl(1)+0.1*yscale,C); end;
if t2-t1>0.15*xscale, text(t1+0.5*(t2-t1),yl(1)+0.1*yscale,txt,...
'EdgeColor',C,'BackgroundColor',get(handles.axes1,'Color'),'HorizontalAlignment','Center'); end;
hold off;
n1=n2;
end;
legend_handle=legend;
if ~isempty(legend_handle), legend(legend_handle); end; %refresh legend
% --- Executes during object creation, after setting all properties.
function vel_button_CreateFcn(hObject, eventdata, handles)
% hObject handle to vel_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
function setTemplate(pl,ax,fig)
set(fig,'Position',[250, 280, 600,240])
set(pl,'LineWidth',1,'Color',[0,0,0]);
set(pl,'LineWidth',1.0);
set(pl,'Marker','x');
set(pl,'LineStyle','-');
set(ax,'YLimMode','auto');
set(ax,'LineWidth',1.0);
set(ax,'LineStyle','-');
set(ax,'FontName','Times');
set(ax,'FontSize',10);
box on;
|
github
|
shuoli-robotics/ppzr-master
|
tilt.m
|
.m
|
ppzr-master/sw/logalizer/matlab/tilt.m
| 3,005 |
utf_8
|
28f19a8ce44283009a8f4ba0410e4c0b
|
%
% this is a 2 states kalman filter used to fuse the readings of a
% two axis accelerometer and one axis gyro.
% The filter estimates the angle and the gyro bias.
%
%
function [angle, bias, rate, cov] = tilt(status, gyro, accel)
TILT_UNINIT = 0;
TILT_PREDICT = 1;
TILT_UPDATE = 2;
persistent tilt_angle; % our state
persistent tilt_bias; %
persistent tilt_rate; % unbiased rate
persistent tilt_P; % covariance matrix
tilt_dt = 0.015625; % prediction time step
tilt_R = 0.3; % measurement covariance noise
% means we expect a 0.3 rad jitter from the
% accelerometer
if (status == TILT_UNINIT)
[tilt_angle, tilt_bias, tilt_rate, tilt_P] = tilt_init(gyro, accel);
else
[tilt_angle, tilt_rate, tilt_P] = ...
tilt_predict(gyro, tilt_P, ...
tilt_angle, tilt_bias, tilt_rate, ...
tilt_dt);
if (status == TILT_UPDATE)
[tilt_angle, tilt_bias, tilt_P] = tilt_update(accel, tilt_R, tilt_P, ...
tilt_angle, tilt_bias);
end
end
angle = tilt_angle;
bias = tilt_bias;
rate = tilt_rate;
cov = tilt_P;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Initialisation
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [angle, bias, rate, P] = tilt_init(gyro, accel)
angle = theta_of_accel(accel);
%angle = phi_of_accel(accel);
bias = gyro(2);
rate = 0;
P = [ 1 0
0 0 ];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Prediction
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [angle_out, rate_out, P_out] = tilt_predict(gyro, P_in, ...
angle_in, bias, rate,...
dt)
rate_out = gyro(2) - bias;
%rate_out = gyro(1) - bias;
% update state ( X += Xdot * dt )
angle_out = angle_in + (rate + rate_out) / 2 * dt;
% update covariance ( Pdot = F*P + P*F' + Q )
% ( P += Pdot * dt )
%
% F is the Jacobian of Xdot with respect to the states:
%
% F = [ d(angle_dot)/d(angle) d(angle_dot)/d(gyro_bias) ]
% [ d(gyro_bias_dot)/d(angle) d(gyro_bias_dot)/d(gyro_bias) ]
%
F = [ 0 -1 % jacobian of state dot wrt state
0 0 ];
Q = [ 0 0 % process covariance noise
0 8e-3 ];
Pdot = F * P_in + P_in * F' + Q;
P_out = P_in + Pdot * dt;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Update
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [angle_out, bias_out, P_out] = tilt_update(accel, R, P_in, ...
angle_in, ...
bias_in)
measure_angle = theta_of_accel(accel);
%measure_angle = phi_of_accel(accel);
err = measure_angle - angle_in;
H = [ 1 0 ];
E = H * P_in * H' + R;
K = P_in * H' * inv(E);
P_out = P_in - K * H * P_in;
X = [ angle_in
bias_in ];
X = X + K *err;
angle_out = X(1);
bias_out = X(2);
|
github
|
shuoli-robotics/ppzr-master
|
theta_of_accel.m
|
.m
|
ppzr-master/sw/logalizer/matlab/theta_of_accel.m
| 186 |
utf_8
|
a68d408f14dcafd800965d810c91c1c1
|
%
% return pitch angle from an accelerometer reading
% under assumption that acceleration is vertical
%
function [theta] = theta_of_accel(accel)
theta = -asin( accel(1) / norm(accel));
|
github
|
shuoli-robotics/ppzr-master
|
eulers_of_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/eulers_of_quat.m
| 334 |
utf_8
|
aa4e8f9fcedb41872e29eb098aefa7d3
|
%
% initialise euler angles from a quaternion
%
function [eulers] = eulers_of_quat(quat)
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
phi = atan2(2*(q2*q3 + q0*q1), (q0^2 - q1^2 - q2^2 + q3^2));
theta = asin(-2*(q1*q3 - q0*q2));
psi = atan2(2*(q1*q2 + q0*q3), (q0^2 + q1^2 - q2^2 - q3^2));
eulers = [phi theta psi]';
|
github
|
shuoli-robotics/ppzr-master
|
synth_data.m
|
.m
|
ppzr-master/sw/logalizer/matlab/synth_data.m
| 923 |
utf_8
|
c23bbe3eb4319edf0890fc9bc4b033c2
|
%
% build synthetic data
%
function [t, rates, quat] = synth_data(dt, nb_samples)
t_end = dt * (nb_samples - 1);
t = 0:dt:t_end;
rates = zeros(3, nb_samples);
omega_q = 15;
amp_q = 2;
osc_start = floor(nb_samples/2);
osc_end = floor(osc_start+2*pi/(omega_q*dt));
for idx=osc_start:osc_end
rates(2, idx) = -amp_q*(1 - cos((idx-osc_start)*(omega_q*dt)));
end
osc_start = floor(nb_samples/2 + 8*pi/(omega_q*dt));
osc_end = floor(osc_start+2*pi/(omega_q*dt));
for idx=osc_start:osc_end
rates(2, idx) = amp_q*(1 - cos((idx-osc_start)*(omega_q*dt)));
end
quat(:, 1) = quat_of_eulers([0.2 -0.4 0.5]');
for idx=2:nb_samples
p = rates(1, idx-1);
q = rates(2, idx-1);
r = rates(3, idx-1);
omega = [ 0 -p -q -r
p 0 r -q
q -r 0 p
r q -p 0 ];
quat_dot = 0.5 * omega * quat(:, idx-1);
quat(:, idx) = quat(:, idx-1) + quat_dot * dt;
quat(:, idx) = normalize_quat(quat(:, idx));
end
|
github
|
shuoli-robotics/ppzr-master
|
theta_of_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/theta_of_quat.m
| 182 |
utf_8
|
1b15a8391b14bd82c12a4031d009657c
|
%
% initialise euler angles from a quaternion
%
function [theta] = theta_of_quat(quat)
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
theta = asin(-2*(q1*q3 - q0*q2));
|
github
|
shuoli-robotics/ppzr-master
|
synth_imu.m
|
.m
|
ppzr-master/sw/logalizer/matlab/synth_imu.m
| 382 |
utf_8
|
eb83cb7d22000974d367cc96ef11e37f
|
%
% build synthetic imu data
%
function [gyro, accel, mag] = synth_imu(rates, quat)
nb_samples = length(rates);
g_ned = [ 0
0
258.3275];
h_ned = [ 166.8120
0.0
203.3070];
for idx = 1:nb_samples
dcm = dcm_of_quat(quat(:, idx));
accel(:, idx) = sim_accel(g_ned, dcm);
mag(:, idx) = sim_mag(h_ned, dcm);
gyro(:, idx) = sim_gyro_2(rates(:, idx));
end;
|
github
|
shuoli-robotics/ppzr-master
|
sfun_ahrs.m
|
.m
|
ppzr-master/sw/logalizer/matlab/sfun_ahrs.m
| 7,062 |
utf_8
|
738df5f0b69d65203e9e7dea9d2b8c41
|
function [sys,x0,str,ts] = sfun_ahrs(t,x,u,flag)
AHRS_UNINIT = 0;
AHRS_STEP_PHI = 1;
AHRS_STEP_THETA = 2;
AHRS_STEP_PSI = 3;
persistent ahrs_state;
persistent ahrs_quat; % first four elements of our state
persistent ahrs_biases;% last three elements of our state
persistent ahrs_rates; % we get unbiased body rates as byproduct
persistent ahrs_P; % error covariance matrix
ahrs_dt = 0.015625;
%R = [ 1.3^2 % R is our measurement noise estimate
% 1.3^2
% 2.5^2 ];
R = [ 4^2 % R is our measurement noise estimate
4^2
4^2 ];
%qg = 8e-03;
qg = 8e-3;
Q = [ 0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 qg 0 0
0 0 0 0 0 qg 0
0 0 0 0 0 0 qg ];
%disp(sprintf('flag %d', flag));
switch flag,
%%%%%%%%%%%%%%%%%%
% Initialization %
%%%%%%%%%%%%%%%%%%
case 0,
ahrs_state = 0;
ahrs_quat = quat_of_eulers([0 0 0]');
ahrs_biases = [0 0 0]';
ahrs_rates = [0 0 0]';
ahrs_init(1, [0 0 0]', [0 0 0], [0 0 0]);
[sys,x0,str,ts]=mdlInitializeSizes(ahrs_dt);
%%%%%%%%%%
% Update %
%%%%%%%%%%
case 2,
gyro = u(1:3);
mag = u(4:6);
accel = u(7:9);
if (ahrs_state == AHRS_UNINIT)
[filter_initialised, ahrs_quat ahrs_biases ahrs_rates ahrs_P] = ...
ahrs_init(0, gyro, accel, mag);
if( filter_initialised ) ahrs_state = AHRS_STEP_PHI;, end;
else
[ahrs_quat ahrs_rates ahrs_P] = ...
ahrs_predict(ahrs_P, Q, gyro, ahrs_quat, ahrs_biases,...
ahrs_dt);
switch ahrs_state,
case AHRS_STEP_PHI,
measure = phi_of_accel(accel);
estimate = phi_of_quat(ahrs_quat);
wrap = pi;
H = get_dphi_dq(ahrs_quat);
case AHRS_STEP_THETA,
measure = theta_of_accel(accel);
estimate = theta_of_quat(ahrs_quat);
wrap = pi/2;
H = get_dtheta_dq(ahrs_quat);
case AHRS_STEP_PSI,
phi = phi_of_quat(ahrs_quat);
theta = theta_of_quat(ahrs_quat);
measure = psi_of_mag(mag, phi, theta);
estimate = psi_of_quat(ahrs_quat);
wrap = pi;
H = get_dpsi_dq(ahrs_quat);
end;
error = get_error(measure, estimate, wrap);
[ahrs_quat ahrs_biases ahrs_P] = ...
ahrs_update(H, error, R(ahrs_state), ahrs_P, ahrs_quat, ahrs_biases);
ahrs_state = ahrs_state+1;
if (ahrs_state > AHRS_STEP_PSI), ahrs_state = AHRS_STEP_PHI;, end;
end;
sys = [];
%%%%%%%%%%%
% Outputs %
%%%%%%%%%%%
case 3,
eulers = eulers_of_quat(ahrs_quat);
sys = [eulers(1) eulers(2) eulers(3) ahrs_rates(1) ahrs_rates(2) ...
ahrs_rates(3) ahrs_biases(1) ahrs_biases(2) ahrs_biases(3)];
%%%%%%%%%%%%%
% Terminate %
%%%%%%%%%%%%%
case 9,
sys = [];
%%%%%%%%%%%%%%%%%%%%
% Unexpected flags %
%%%%%%%%%%%%%%%%%%%%
otherwise
error(['Unhandled flag = ',num2str(flag)]);
end
%
% begin mdlInitializeSizes
%
function [sys,x0,str,ts]=mdlInitializeSizes (period)
sizes = simsizes();
sizes.NumContStates = 0;
sizes.NumDiscStates = 0;
sizes.NumOutputs = 9;
sizes.NumInputs = 9;
sizes.DirFeedthrough = 1;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0 = [];
str = [];
ts = [period 0];
% end mdlInitializeSizes
%
%
% Initialisation
%
%
function [filter_initialised, quat, biases, rates, P] = ...
ahrs_init(reset, gyro, accel, mag)
persistent saved_gyro;
persistent saved_accel;
persistent saved_mag;
persistent nb_init;
if (reset)
nb_init = 0;
saved_gyro = [];
saved_accel = [];
saved_mag = [];
return;
end;
nb_init = nb_init+1;
saved_gyro(:, nb_init) = gyro;
saved_accel(:, nb_init) = accel;
saved_mag(:, nb_init) = mag;
if (nb_init < 50)
quat = quat_of_eulers([0 0 0]');
biases = [0 0 0]';
filter_initialised = 0;
else
mean_gyro = average_vector(saved_gyro);
mean_accel = average_vector(saved_accel);
mean_mag = average_vector(saved_mag);
phi = phi_of_accel(mean_accel);
theta = theta_of_accel(mean_accel);
psi = psi_of_mag(mean_mag, phi, theta);
quat = quat_of_eulers([phi, theta, psi]);
biases = mean_gyro;
mgd = mean_gyro * 180 / pi;
atd = [phi, theta, psi] * 180 / pi;
disp('init done');
disp(sprintf('initial biases %f %f %f',mgd(1), mgd(2), mgd(3)));
disp(sprintf('initial attitude %f %f %f',atd(1), atd(2), atd(3)));
filter_initialised = 1;
end;
rates = [0 0 0];
P = [ 1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 ];
%
%
% Prediction
%
%
function [quat_out, rates_out, P_out] = ahrs_predict(P_in, Q_in, ...
gyro, quat_in, biases, ...
dt)
rates_out = gyro - biases;
p = rates_out(1);
q = rates_out(2);
r = rates_out(3);
omega = 0.5 * [ 0 -p -q -r
p 0 r -q
q -r 0 p
r q -p 0 ];
quat_dot = omega * quat_in;
quat_out = quat_in + quat_dot * dt;
quat_out = normalize_quat(quat_out);
% F is the Jacobian of Xdot with respect to the states
q0 = quat_out(1);
q1 = quat_out(2);
q2 = quat_out(3);
q3 = quat_out(4);
F = 0.5 * [ 0 -p -q -r q1 q2 q3
p 0 r -q -q0 q3 -q2
q -r 0 p -q3 -q0 q1
r q -p 0 q2 -q1 -q0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 ];
P_dot = F * P_in + P_in * F' + Q_in;
P_out = P_in + P_dot * dt;
%
%
% Update
%
%
function [quat_out, biases_out, P_out] = ahrs_update(H, err, R, P_in, ...
quat_in, biases_in)
E = H * P_in * H' + R;
K = P_in * H' * inv(E);
P_out = P_in - K * H * P_in;
X = [quat_in' biases_in']';
X = X + K *err;
quat_out = [X(1) X(2) X(3) X(4)]';
biases_out = [X(5) X(6) X(7)]';
quat_out = normalize_quat(quat_out);
%
% Jacobian of the measurements to the system states.
%
function [H] = get_dphi_dq(quat)
dcm = dcm_of_quat(quat);
phi_err = 2 / (dcm(3,3)^2 + dcm(2,3)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
H = [
(q1 * dcm(3,3)) * phi_err
(q0 * dcm(3,3) + 2 * q1 * dcm(2,3)) * phi_err
(q3 * dcm(3,3) + 2 * q2 * dcm(2,3)) * phi_err
(q2 * dcm(3,3)) * phi_err
0
0
0
]';
function [H] = get_dtheta_dq(quat)
dcm = dcm_of_quat(quat);
theta_err = 2 / sqrt(1 - dcm(1,3)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
H = [
q2 * theta_err
-q3 * theta_err
q0 * theta_err
-q1 * theta_err
0
0
0
]';
function [H] = get_dpsi_dq(quat)
dcm = dcm_of_quat(quat);
psi_err = 2 / (dcm(1,1)^2 + dcm(1,2)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
H = [
(q3 * dcm(1,1)) * psi_err
(q2 * dcm(1,1)) * psi_err
(q1 * dcm(1,1) + 2 * q2 * dcm(1,2)) * psi_err
(q0 * dcm(1,1) + 2 * q3 * dcm(1,2)) * psi_err
0
0
0
]';
function [err] = get_error(measure, estimate, wrap)
err = measure - estimate;
if (err > wrap), err = err - 2*wrap, end;
if (err < -wrap), err = err + 2*wrap, end;
function [avg] = average_vector(vector)
avg = [ mean(vector(1, 1:length(vector)))
mean(vector(2, 1:length(vector)))
mean(vector(3, 1:length(vector))) ];
|
github
|
shuoli-robotics/ppzr-master
|
quat_of_eulers.m
|
.m
|
ppzr-master/sw/logalizer/matlab/quat_of_eulers.m
| 629 |
utf_8
|
8783ebf9fadbb74652d2a366c9064c02
|
%
% initialise a quaternion from euler angles
%
function [quat] = quat_of_eulers(eulers)
phi2 = eulers(1) / 2.0;
theta2 = eulers(2) / 2.0;
psi2 = eulers(3) / 2.0;
sinphi2 = sin( phi2 );
cosphi2 = cos( phi2 );
sintheta2 = sin( theta2 );
costheta2 = cos( theta2 );
sinpsi2 = sin( psi2 );
cospsi2 = cos( psi2 );
q0 = cosphi2 * costheta2 * cospsi2 + sinphi2 * sintheta2 * sinpsi2;
q1 = sinphi2 * costheta2 * cospsi2 - cosphi2 * sintheta2 * sinpsi2;
q2 = cosphi2 * sintheta2 * cospsi2 + sinphi2 * costheta2 * sinpsi2;
q3 = cosphi2 * costheta2 * sinpsi2 - sinphi2 * sintheta2 * cospsi2;
quat = [q0 q1 q2 q3]';
|
github
|
shuoli-robotics/ppzr-master
|
dcm_of_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/dcm_of_quat.m
| 481 |
utf_8
|
b9950e5f461f13427a7c670158a92c14
|
%
% initialise a DCM from a quaternion
%
function [dcm] = dcm_of_quat(quat)
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
dcm00 = q0^2 + q1^2 - q2^2 - q3^2;
dcm01 = 2 * (q1*q2 + q0*q3);
dcm02 = 2 * (q1*q3 - q0*q2);
dcm10 = 2 * (q1*q2 - q0*q3);
dcm11 = q0^2 - q1^2 + q2^2 - q3^2;
dcm12 = 2 * (q2*q3 + q0*q1);
dcm20 = 2 * (q1*q3 + q0*q2);
dcm21 = 2 * (q2*q3 - q0*q1);
dcm22 = q0^2 - q1^2 - q2^2 + q3^2;
dcm = [ dcm00 dcm01 dcm02
dcm10 dcm11 dcm12
dcm20 dcm21 dcm22 ];
|
github
|
shuoli-robotics/ppzr-master
|
ahrs.m
|
.m
|
ppzr-master/sw/logalizer/matlab/ahrs.m
| 4,335 |
utf_8
|
5723f910e49a91fc556660bc06826fa8
|
function [quat, biases] = ahrs(status, gyro, accel, mag)
AHRS_UNINIT = 0;
AHRS_STEP_PHI = 1;
AHRS_STEP_THETA = 2;
AHRS_STEP_PSI = 3;
persistent ahrs_quat;
persistent ahrs_biases;
persistent ahrs_rates;
persistent ahrs_P; % covariance matrix
persistent ahrs_Q; % estimate noise variance
ahrs_dt = 0.015625;
R = [ 1.3^2 % R is our measurement noise estimate
1.3^2
2.5^2 ];
%R = [ 0.0046^2
% 0.0046^2
% 2.5^2 ];
if (status == AHRS_UNINIT)
[ahrs_quat ...
ahrs_biases ...
ahrs_rates ...
ahrs_P ...
ahrs_Q ] = ahrs_init(gyro, accel, mag);
else
[ahrs_quat ...
ahrs_rates...
ahrs_P] = ahrs_predict(ahrs_P, ahrs_Q, gyro, ahrs_quat, ahrs_biases,...
ahrs_dt);
if (status == AHRS_STEP_PHI)
measure = phi_of_accel(accel);
estimate = phi_of_quat(ahrs_quat);
C = get_dphi_dq(ahrs_quat);
elseif (status == AHRS_STEP_THETA)
measure = theta_of_accel(accel);
estimate = theta_of_quat(ahrs_quat);
C = get_dtheta_dq(ahrs_quat);
elseif (status == AHRS_STEP_PSI)
phi = phi_of_quat(ahrs_quat);
theta = theta_of_quat(ahrs_quat);
measure = psi_of_mag(mag, phi, theta);
estimate = psi_of_quat(ahrs_quat);
C = get_dpsi_dq(ahrs_quat);
end;
error = measure - estimate;
[ahrs_quat ...
ahrs_biases ...
ahrs_P] = ahrs_update(C, error, R(status), ahrs_P, ahrs_quat, ...
ahrs_biases);
end;
quat = ahrs_quat;
biases = ahrs_biases;
%
%
% Initialisation
%
%
function [quat, biases, rates, P, Q] = ahrs_init(gyro, accel, mag)
phi = phi_of_accel(accel);
theta = theta_of_accel(accel);
psi = psi_of_mag(mag, phi, theta);
quat = quat_of_eulers([phi, theta, psi]);
biases = gyro;
rates = [0 0 0]';
P = [ 1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 ];
qg = 8e-03;
%qg = 1e-04;
Q = [ 0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 qg 0 0
0 0 0 0 0 qg 0
0 0 0 0 0 0 qg ];
%
%
% Prediction
%
%
function [quat_out, rates_out, P_out] = ahrs_predict(P_in, Q_in, ...
gyro, quat_in, biases, ...
dt)
rates_out = gyro - biases;
p = rates_out(1);
q = rates_out(2);
r = rates_out(3);
omega = 0.5 * [ 0 -p -q -r
p 0 r -q
q -r 0 p
r q -p 0 ];
quat_dot = omega * quat_in;
quat_out = quat_in + quat_dot * dt;
quat_out = normalize_quat(quat_out);
% F is the Jacobian of Xdot with respect to the states
q0 = quat_out(1);
q1 = quat_out(2);
q2 = quat_out(3);
q3 = quat_out(4);
F = 0.5 * [ 0 -p -q -r q1 q2 q3
p 0 r -q -q0 q3 -q2
q -r 0 p -q3 -q0 q1
r q -p 0 q2 -q1 -q0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 ];
P_dot = F * P_in + P_in * F' + Q_in;
P_out = P_in + P_dot * dt;
%
%
% Update
%
%
function [quat_out, biases_out, P_out] = ahrs_update(C, err, R, P_in, ...
quat_in, biases_in)
E = C * P_in * C' + R;
K = P_in * C' * inv(E);
P_out = P_in - K * C * P_in;
X = [quat_in' biases_in']';
X = X + K *err;
quat_out = [X(1) X(2) X(3) X(4)]';
biases_out = [X(5) X(6) X(7)]';
quat_out = normalize_quat(quat_out);
%
% Jacobian of the measurements to the system states.
%
function [C] = get_dphi_dq(quat)
dcm = dcm_of_quat(quat);
phi_err = 2 / (dcm(3,3)^2 + dcm(2,3)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
C = [
(q1 * dcm(3,3)) * phi_err
(q0 * dcm(3,3) + 2 * q1 * dcm(2,3)) * phi_err
(q3 * dcm(3,3) + 2 * q2 * dcm(2,3)) * phi_err
(q2 * dcm(3,3)) * phi_err
0
0
0
]';
function [C] = get_dtheta_dq(quat)
dcm = dcm_of_quat(quat);
theta_err = 2 / sqrt(1 - dcm(1,3)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
C = [
q2 * theta_err
-q3 * theta_err
q0 * theta_err
-q1 * theta_err
0
0
0
]';
function [C] = get_dpsi_dq(quat)
dcm = dcm_of_quat(quat);
psi_err = 2 / (dcm(1,1)^2 + dcm(1,2)^2);
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
C = [
(q3 * dcm(1,1)) * psi_err
(q2 * dcm(1,1)) * psi_err
(q1 * dcm(1,1) + 2 * q2 * dcm(1,2)) * psi_err
(q0 * dcm(1,1) + 2 * q3 * dcm(1,2)) * psi_err
0
0
0
]';
|
github
|
shuoli-robotics/ppzr-master
|
range_meter_accel_kalman.m
|
.m
|
ppzr-master/sw/logalizer/matlab/range_meter_accel_kalman.m
| 2,603 |
utf_8
|
e73c363bd661f2f111583fc707bf8fde
|
%
%
%
%
function [sys,x0,str,ts] = range_meter_accel_kalman(t,x,u,flag)
period = 0.015625;
persistent X; % state (Z, Zdot, Zdotdot)
persistent P; % error covariance
switch flag,
%%%%%%%%%%%%%%%%%%
% Initialization %
%%%%%%%%%%%%%%%%%%
case 0,
X=[0. 0. 0.]';
P=[1. 0. 0.
0. 1. 0.
0. 0. 1.];
[sys,x0,str,ts]=mdlInitializeSizes(period);
%%%%%%%%%%
% Update %
%%%%%%%%%%
case 2,
sys=[];
%%%%%%%%%%%
% Outputs %
%%%%%%%%%%%
case 3,
accel = u(1) - 9.81;
rangemeter = u(2);
% state transition model
F = [1. period 0.
0. 1. period
0. 0. 1. ];
% control-input model
B = [0];
% process noise covariance
Q = [period^4/4 period^3/2 period^2/2
period^3/2 period^2 period
period^2/2 period 1.];
% observation model
H_a = [0 0 1];
% observation noise covariance
R_a = [.01];
% observation model
H_r = [1 0 0];
% observation noise covariance
R_r = [.0025];
% predict
X = F*X; % + B*u
P = F*P*F'+ Q;
% update rangemeter
err = rangemeter - H_r*X;
S = H_r*P*H_r' + R_r;
K = P*H_r'*inv(S);
X = X + err * K;
P = (eye(3,3) - K*H_r)*P;
% update accel
err = accel - H_a*X;
S = H_a*P*H_a' + R_a;
K = P*H_a'*inv(S);
X = X + err * K;
P = (eye(3,3) - K*H_a)*P;
sys = [X(3) X(2) X(1)];
case 9,
sys=[];
%%%%%%%%%%%%%%%%%%%%
% Unexpected flags %
%%%%%%%%%%%%%%%%%%%%
otherwise
error(['Unhandled flag = ',num2str(flag)]);
end
% end sfuntmpl
%
%=============================================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the S-function.
%=============================================================================
%
function [sys,x0,str,ts]=mdlInitializeSizes (period)
%
% call simsizes for a sizes structure, fill it in and convert it to a
% sizes array.
%
% Note that in this example, the values are hard coded. This is not a
% recommended practice as the characteristics of the block are typically
% defined by the S-function parameters.
%
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 0;
sizes.NumOutputs = 3;
sizes.NumInputs = 2;
sizes.DirFeedthrough = 1;
sizes.NumSampleTimes = 1; % at least one sample time is needed
sys = simsizes(sizes);
%
% initialize the initial conditions
%
x0 = [];
%
% str is always an empty matrix
%
str = [];
%
% initialize the array of sample times
%
ts = [period 0];
% end mdlInitializeSizes
|
github
|
shuoli-robotics/ppzr-master
|
psi_of_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/psi_of_quat.m
| 205 |
utf_8
|
821c1b678bcc85fbf97dd6fe3a1b3e3d
|
%
% initialise euler angles from a quaternion
%
function [psi] = psi_of_quat(quat)
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
psi = atan2(2*(q1*q2 + q0*q3), (q0^2 + q1^2 - q2^2 - q3^2));
|
github
|
shuoli-robotics/ppzr-master
|
phi_of_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/phi_of_quat.m
| 205 |
utf_8
|
577a048517be0669ac35e0f7fc8f3b30
|
%
% initialise euler angles from a quaternion
%
function [phi] = phi_of_quat(quat)
q0 = quat(1);
q1 = quat(2);
q2 = quat(3);
q3 = quat(4);
phi = atan2(2*(q2*q3 + q0*q1), (q0^2 - q1^2 - q2^2 + q3^2));
|
github
|
shuoli-robotics/ppzr-master
|
phi_of_accel.m
|
.m
|
ppzr-master/sw/logalizer/matlab/phi_of_accel.m
| 175 |
utf_8
|
7f341eaa185852c295e0a3d39219d885
|
%
% returns roll angle from an accelerometer reading
% under assumption that acceleration is vertical
%
function [phi] = phi_of_accel(accel)
phi = atan2(accel(2), accel(3));
|
github
|
shuoli-robotics/ppzr-master
|
dcm_of_eulers.m
|
.m
|
ppzr-master/sw/logalizer/matlab/dcm_of_eulers.m
| 607 |
utf_8
|
d49ff8d4658100d798e02d14b725d7b8
|
%
% initialise a DCM from a set of eulers
%
function [dcm] = dcm_of_eulers(eulers)
phi = eulers(1);
theta = eulers(2);
psi = eulers(3);
dcm00 = cos(theta) * cos(psi);
dcm01 = cos(theta) * sin(psi);
dcm02 = -sin(theta);
dcm10 = sin(phi) * sin(theta) * cos(psi) - cos(phi) * sin(psi);
dcm11 = sin(phi) * sin(theta) * sin(psi) + cos(phi) * cos(psi);
dcm12 = sin(phi) * cos(theta);
dcm20 = cos(phi) * sin(theta) * cos(psi) + sin(phi) * sin(psi);
dcm21 = cos(phi) * sin(theta) * sin(psi) - sin(phi) * cos(psi);
dcm22 = cos(phi) * cos(theta);
dcm = [ dcm00 dcm01 dcm02
dcm10 dcm11 dcm12
dcm20 dcm21 dcm22 ];
|
github
|
shuoli-robotics/ppzr-master
|
psi_of_mag.m
|
.m
|
ppzr-master/sw/logalizer/matlab/psi_of_mag.m
| 1,076 |
utf_8
|
04a2ed36a67c0a29c793684357f7f95d
|
%
% return yaw angle from a magnetometer reading, knowing roll and pitch
%
% The rotation matrix to rotate from NED frame to body frame without
% rotating in the yaw axis is:
%
% [ 1 0 0 ] [ cos(Theta) 0 -sin(Theta) ]
% [ 0 cos(Phi) sin(Phi) ] [ 0 1 0 ]
% [ 0 -sin(Phi) cos(Phi) ] [ sin(Theta) 0 cos(Theta) ]
%
% This expands to:
%
% [ cos(Theta) 0 -sin(Theta) ]
% [ sin(Phi)*sin(Theta) cos(Phi) sin(Phi)*cos(Theta)]
% [ cos(Phi)*sin(Theta) -sin(Phi) cos(Phi)*cos(Theta)]
%
% However, to untilt the compass reading, we need to use the
% transpose of this matrix.
%
% [ cos(Theta) sin(Phi)*sin(Theta) cos(Phi)*sin(Theta) ]
% [ 0 cos(Phi) -sin(Phi) ]
% [ -sin(Theta) sin(Phi)*cos(Theta) cos(Phi)*cos(Theta) ]
%
function [psi] = psi_of_mag(mag, phi, theta)
mn = cos(theta) * mag(1)+ ...
sin(phi) * sin(theta) * mag(2)+ ...
cos(phi) * sin(theta) * mag(3);
me = cos(phi)* mag(2) + ...
-sin(phi) * mag(3);
psi = -atan2( me, mn );
|
github
|
shuoli-robotics/ppzr-master
|
normalize_quat.m
|
.m
|
ppzr-master/sw/logalizer/matlab/normalize_quat.m
| 84 |
utf_8
|
059325b9c340c1295d2d86b71c7f0d02
|
function [quat_out] = normalize_quat(quat_in)
quat_out = quat_in / norm(quat_in);
|
github
|
shuoli-robotics/ppzr-master
|
plot_prop.m
|
.m
|
ppzr-master/sw/logalizer/matlab/plot_prop.m
| 1,636 |
utf_8
|
a1b37b753e6331884f03d5edc92a7ad1
|
%
% plot a serie of measures realised with the black 10*4.5 prop
%
function [] = plot_prop()
rpm = [ 2800 3350 3720 4450 5250 ];
thrust_g = [ 122 175 219 310 445 ];
torque_g = [ 10 16 19 26 44 ];
omega = rpm / 60 * 2 * pi;
omega_square = omega.^2;
thrust_n = thrust_g .* ( 9.81 / 1000 );
torque_n = torque_g .* ( 9.81 / 1000 );
K = fminsearch(@lin_model, [1, 1]);
Kt = K(1);
Kq = K(2);
% F = 0.5 * rho * prop_area * ct * prop_rad^2 * omega^2
rho = 1.225;
prop_area = 0.005;
prop_rad = 0.125;
Ct = Kt / (0.5 * rho * prop_area * prop_rad^2)
Cq = Kq / (0.5 * rho * prop_area * prop_rad^2)
plot(omega_square, thrust_n, ...
omega_square, Kt * omega_square, ...
omega_square, torque_n, ...
omega_square, Kq * omega_square )
title('Propeller caracterisation (EPP 10*4.5)');
legend('thrust', 'fitted thrust', 'torque', 'fitted torque');
xlabel('omega square in rad^2/s^2');
ylabel('forces in N');
tb = annotation('textbox', [0.2 0.65 0.1 0.1]);
set(tb, 'String', ...
[sprintf('Thrust = %.2e * omega^2 ( Ct = %.2e )\n\n', Kt, Ct) ...
sprintf('Torque = %.2e * omega^2 ( Cq = %.2e )', Kq, Cq)], ...
'FitHeightToText', 'on' );
function [sse] = lin_model(params)
Kt = params(1);
Kq = params(2);
fitted_thrust = Kt * omega_square;
fitted_torque = Kq * omega_square;
err_t = fitted_thrust - thrust_n;
err_q = fitted_torque - torque_n;
sse = sum(err_t .^ 2) + sum(err_q .^ 2);
end
end
|
github
|
shuoli-robotics/ppzr-master
|
eulers_ahrs.m
|
.m
|
ppzr-master/sw/logalizer/matlab/eulers_ahrs.m
| 3,448 |
utf_8
|
ff18ecc6efcad8ecea4cb1c04b4153e3
|
function [eulers, biases] = eulers_ahrs(status, gyro, accel, mag, dt)
AHRS_UNINIT = 0;
AHRS_PREDICT = 1;
AHRS_UPDATE_PHI = 2;
AHRS_UPDATE_THETA = 3;
AHRS_UPDATE_PSI = 4;
persistent ahrs_eulers;
persistent ahrs_biases;
persistent ahrs_rates;
persistent ahrs_P;
if (status == AHRS_UNINIT)
[ahrs_eulers ahrs_biases ahrs_rates ahrs_P] = ahrs_init(gyro, accel, mag);
else
[ahrs_eulers, ahrs_rates, ahrs_P] = ahrs_predict(gyro, ahrs_P, ...
ahrs_eulers, ...
ahrs_rates, ahrs_biases, dt);
if (status >= AHRS_UPDATE_PHI)
[ahrs_eulers, ahrs_biases, ahrs_P] = ahrs_update(status, accel, mag, ...
ahrs_P, ahrs_eulers, ahrs_biases);
end
end
eulers = ahrs_eulers;
biases = ahrs_biases;
%
%
% Initialisation
%
%
function [eulers, biases, rates, P] = ahrs_init(gyro, accel, mag)
eulers(1, 1) = phi_of_accel(accel);
eulers(2, 1) = theta_of_accel(accel);
eulers(3, 1) = psi_of_mag(mag, eulers(1), eulers(2));
biases = gyro;
rates = [0 0 0]';
P = [ 1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 ];
%
%
% Prediction
%
%
function [eulers_out, rates_out, P_out] = ahrs_predict(gyro, P_in, ...
eulers_in, rates_in, biases, ...
dt)
rates_out = gyro - biases;
phi = eulers_in(1);
theta = eulers_in(2);
psi = eulers_in(3);
p = rates_out(1);
q = rates_out(2);
r = rates_out(3);
rted = [ 1 sin(phi)*tan(theta) cos(phi)*tan(theta)
0 cos(phi) -sin(phi)
0 sin(phi)/cos(theta) cos(phi)/cos(theta) ];
eulers_dot = rted * (rates_out + rates_in)/2;
eulers_out = eulers_in + eulers_dot * dt;
d_phidot_d_state = [ cos(phi)*tan(theta)*q - sin(phi)*tan(theta)*r
1/(1+theta^2) * (sin(phi)*q+cos(phi)*r)
0
-1
-sin(phi)*tan(theta)
-cos(phi)*tan(theta) ]';
d_thetadot_d_state = [ -sin(phi)*q - cos(phi)*r
0
0
0
-cos(phi)
sin(phi) ]';
d_psidot_d_state = [ cos(phi)/cos(theta)*q - sin(phi)/cos(theta)*r
sin(theta)/cos(theta)^2*(sin(phi)*q+cos(phi)*r)
0
0
-sin(phi)/cos(theta)
-cos(phi)/cos(theta)
]';
% jacobian of state_dot wrt state
F = [ d_phidot_d_state
d_thetadot_d_state
d_psidot_d_state
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
];
% estimate noise covariance
Q = 8e-3 * [ 0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1 ];
P_dot = F * P_in + P_in * F' + Q;
P_out = P_in + P_dot * dt;
%
%
% Update
%
%
function [eulers_out, biases_out, P_out] = ahrs_update(status, accel, mag, ...
P_in, eulers_in, biases_in)
if (status == 2)%AHRS_UPDATE_PHI)
measure = phi_of_accel(accel);
estimate = eulers_in(1);
H = [ 1 0 0 0 0 0 ];
R = 1.3^2;
elseif (status == 3)%AHRS_UPDATE_THETA)
measure = theta_of_accel(accel);
estimate = eulers_in(2);
H = [ 0 1 0 0 0 0 ];
R = 1.3^2;
elseif (status == 4)%AHRS_UPDATE_PSI)
measure = psi_of_mag(mag, eulers_in(1), eulers_in(2));
estimate = eulers_in(3);
H = [ 0 0 1 0 0 0 ];
R = 2.5^2;
end
%R = [ 1.3^2 % R is our measurement noise estimate
% 1.3^2
% 2.5^2 ];
E = H * P_in * H' + R;
K = P_in * H' * inv(E);
P_out = P_in - K * H * P_in;
X = [eulers_in' biases_in']';
error = measure - estimate;
X = X + K * error;
eulers_out = [X(1) X(2) X(3)]';
biases_out = [X(4) X(5) X(6)]';
|
github
|
shuoli-robotics/ppzr-master
|
eulers_of_quat.m
|
.m
|
ppzr-master/sw/airborne/test/ahrs/plot/eulers_of_quat.m
| 789 |
utf_8
|
e5d898a1c84e280d2b3097f8a270c990
|
%% EULERS OF QUATERNION
%
% [euler] = eulers_of_quat(quat)
%
% transposes a quaternion to euler angles
function [euler] = eulers_of_quat(quat)
algebra_common;
if size(quat)(2)==4
quat = quat';
transpose = 1;
end
dcm00 = 1.0 - 2*(quat(Q_QY,:).*quat(Q_QY,:) + quat(Q_QZ,:).*quat(Q_QZ,:));
dcm01 = 2*(quat(Q_QX,:).*quat(Q_QY,:) + quat(Q_QI,:).*quat(Q_QZ,:));
dcm02 = 2*(quat(Q_QX,:).*quat(Q_QZ,:) - quat(Q_QI,:).*quat(Q_QY,:));
dcm12 = 2*(quat(Q_QY,:).*quat(Q_QZ,:) + quat(Q_QI,:).*quat(Q_QX,:));
dcm22 = 1.0 - 2*(quat(Q_QX,:).*quat(Q_QX,:) + quat(Q_QY,:).*quat(Q_QY,:));
phi = atan2( dcm12, dcm22 );
theta = -asin( dcm02 );
psi = atan2( dcm01, dcm00 );
euler = [phi; theta; psi];
if transpose
euler = euler';
end
endfunction
|
github
|
shuoli-robotics/ppzr-master
|
unwrap.m
|
.m
|
ppzr-master/sw/airborne/test/ahrs/plot/unwrap.m
| 360 |
utf_8
|
88eb2f76dedb25dfbdeb635ff1af9f1e
|
%% unwrap
%
% [unwraped] = unwrap(wraped)
%
%
function [unwraped] = unwrap(wraped)
unwraped = zeros(length(wraped), 1);
cnt = 0;
for i=2:length(wraped)
dif = wraped(i) - wraped(i-1);
if (dif > pi/2)
cnt=cnt-1;
elseif (dif <-pi/2)
cnt=cnt+1;
end
unwraped(i) = wraped(i)+2*pi*cnt;
end
endfunction
|
github
|
shuoli-robotics/ppzr-master
|
deg_of_rad.m
|
.m
|
ppzr-master/sw/airborne/test/ahrs/plot/deg_of_rad.m
| 124 |
utf_8
|
b8cf99172588f77a253dd84982a9d2e7
|
%% degres of radians
%
% [deg] = deg_of_rad(rad)
%
%
function [deg] = deg_of_rad(rad)
deg = rad * 180 / pi;
endfunction
|
github
|
wpisailbot/boat-master
|
MovableBallastSimulation.m
|
.m
|
boat-master/control/matlab/MovableBallastSimulation.m
| 8,602 |
utf_8
|
6afbd0132248cfbb2917460b1eed281a
|
function MovableBallastSimulation(x0, phigoal)
global Vmax ka ks kssq ku kf J Jmb rightingweight;
global Kfast Kslow pgoal;
pgoal = phigoal;
stage1 = 16/64;
stage2 = 16/64;
G = stage1 * stage2;
Vmax = 12;
mbmass = 10;
J = 12 * 1.2^2; % kg * m^2
Jmb = mbmass * .7^2; % kg * m^2
MBMotorStallTorque = 9.8 / G; % N-m
MBMotorStallCurrent = 28; % Amps
MBMotorFreeCurrent = 5; % Amps
MBMotorFreeSpeed = 86 * 2 * pi / 60 * G; % rad / sec
MBmaxAngle = 45;
rightingweight = mbmass * 9.8; % N
ka = 120 * 1.2 / J; %torque of keel when heeled at 90 deg (1 / s^2)
%ka = 60 * 1.2;
% drag of keel
% Multiplying by radius thrice: twice for rotation->real velocity; once for force->torque
% 0.5 * rho * area * C(=1) * u_0(=nominal velocity=nom rot vel * nom radius) * nom radius * nom radius / J
% = kg / m^3 * m^2 * m / s * m^2 / (kg * m^2) = 1 / sec
nom_rad = 0.8;
nom_vel = 1.0;
kssq = 0.5 * 1000 * 0.2 * 1 * nom_rad^3 / J;
ks = kssq * nom_vel;
% V = IR + omega / Kv
% alpha = KtI / J
% alpha = Kt (V - omega / Kv) / (R * J)
% ku = Kt / (R * J)
% kf = Kt / (Kv * R * J)
% Kt = stall_torque * J / stall_cur
% R = nominal_volts / stall_cur
% Kv = free_speed / (nominal_volts - free_cur * R)
Kt = MBMotorStallTorque * Jmb / MBMotorStallCurrent;
R = Vmax / MBMotorStallCurrent;
Kv = MBMotorFreeSpeed / (Vmax - MBMotorFreeCurrent * R);
ku = Kt / (R * Jmb); %voltage effect on arm acceleration
kf = Kt / (Kv * R * Jmb); %frictional resistance to arm acceleration
xgoal = desx(phigoal)
xnaught = xgoal;
xnaught(1) = -0.5;
[A, B, ~, Aslow, Bslow, ~] = linsys(xnaught)
Aslow
Bslow
% For this, xslow = [phi, phidot, phiddot], uslow = [phidddot]
Aslow = [0 1 0;
0 0 1;
0 0 0];
Bslow = [0; 0; 1];
ctr = rank(ctrb(A, B))
[vecA, eigA] = eig(A)
[vecAslow, eigAslow] = eig(Aslow)
K = lqr(A, B, diag([100.1 10.0 1.0 1.0]), [1e0])
Kfast = 15.1;
Kslow = lqr(Aslow, Bslow, diag([100 100 10]), [0.1])
%Kslow = place(Aslow, Bslow, [-10, -2, -3])
%Kslow(1) = 0;
%Kslow = [0 -0.1 -0.00]
eigABK = eig(A - B * K)
[vecABKslow, eigABKslow] = eig(Aslow - Bslow * Kslow)
f = @(t, x) full_dyn(x, utrans(x, K * (xgoal - x)), t);
%fsplit = @(t, x) full_dyn(x, utrans(x, Kfast * (Kslow * (xgoal([1 3 4]) - x([1 3 4])) - x(2))), t);
%f = @(t, x) simple_dyn(x, K * (xgoal - x));
%f = @(t, x) A * x + B * K * (xgoal - x);
%[ts, xs] = ode45(f, [0 30], x0);
%[ts, xs] = ode45(fsplit, [0 10], x0);
[ts, xs] = ode45(@call_flin_ctrl, [0 3], x0);
uprimes = K * (repmat(xgoal, 1, length(ts)) - xs');
gammadotdes = Kslow * (repmat(xgoal([1 3 4]), 1, length(ts)) - xs(:, [1 3 4])');
uprimes = Kfast * (gammadotdes - xs(:, 2)');
jerks = [];
phiddots = [];
for i = 1:numel(ts)
[xdot, jerk, gdot, gddot, ~] = fully_flin_control(ts(i), xs(i, :));
jerks(i) = jerk;
gammadotdes(i) = gdot;
uprimes(i) = gddot;
phiddots(i) = xdot(4);
end
subplot(221);
plot(ts, [xs(:, [1 2]) gammadotdes']);
ylim([-1.5, 1.5])
legend('\gamma', 'gammadot', 'gammadotdes');
subplot(222);
plot(ts, [xs(:, [3 4]), phiddots']);
legend('\phi', 'phidot', 'phiaccel');
subplot(223);
plot(ts, [uprimes' jerks']);
legend('gammaddot', 'jerks');
title('Control Inputs');
subplot(224);
for i = 1:length(ts)
u(i) = max(min(utrans(xs(i, :), uprimes(i)), Vmax), -Vmax);
end
plot(ts, u);
title('u');
end
% Compute righting moment for given phi/gamma
function tau = MBRight(phi, gamma)
global rightingweight;
[tau, ~, ~] = calcMBRightingMoment(phi, gamma, rightingweight);
end
% Compute motor load from ballast for given phi/gamma
function tau = MBTorque(phi, gamma)
global rightingweight;
% Stage values are dealt with later...
tau = calcMBTorque(phi, gamma, 1, 1, rightingweight);
end
function xdot = call_flin_ctrl(t, x)
[xdot, ~, ~, ~, ~] = fully_flin_control(t, x);
end
function [xdot, phijerk, gammadot_des, gammaddot, u] = fully_flin_control(t, x)
global Kfast Kslow pgoal;
% Extract phiddot so that we can work with it.
xdot = full_dyn(x, 0, t, 0);
gamma = x(1);
gammadot = x(2);
phi = x(3);
phidot = x(4);
phiddot = xdot(4);
phigoal = pgoal;
if t > 20
phigoal = -pgoal;
end
phijerk = Kslow * ([phigoal; 0; 0] - [phi; phidot; phiddot]);
gammadot_des = gammainv(gamma, [phi; phidot; phiddot; phijerk]);
% If we just want to try feed-forwardsing it.
%gammadot_des = 1 * (sign(phigoal) - gamma);
gammaddot = Kfast * (gammadot_des - gammadot);
u = utrans(x, gammaddot);
xdot = full_dyn(x, u, t, 0);
end
% State vector is of form [gamma, gammadot, phi, phidot]
% Full dynamics, with u as motor voltage
function xdot = full_dyn(x, u, t, do_jerk)
global ka ks kssq ku kf J Jmb Vmax;
u = max(min(u, Vmax), -Vmax);
gamma = x(1);
gammadot = x(2);
phi = x(3);
phidot = x(4);
D0 = 100;
D = D0;
Ddot = 0;
if t > 20 && t < 21
D = D0 * 2 * (20.5 - t);
Ddot = -2 * D0;
elseif t > 21
D = -D0;
end
D = D * cos(phi);
Ddot = Ddot * cos(phi) - D * sin(phi) * phidot;
phiddot = -ka * sin(phi) - kssq * phidot * abs(phidot) + (MBRight(phi, gamma) + D) / J;
phijerk = calcjerk(x, D, Ddot);
gammaddot = ku * u - kf * gammadot + MBTorque(phi, gamma) / Jmb;
if gamma > pi / 2
gammadot = min(gammadot, 0);
elseif gamma < -pi / 2
gammadot = max(gammadot, 0);
end
xdot = [gammadot; gammaddot; phidot; phiddot];
if exist('do_jerk') && do_jerk == 1
xdot = [xdot; phijerk];
end
end
% Compute dynamics, but with uprime (gammaddot) instead of u
function xdot = simple_dyn(x, uprime)
global ka ks ku kf J;
gamma = x(1);
gammadot = x(2);
phi = x(3);
phidot = x(4);
D = 00;
phiddot = -ka * sin(phi) - ks * phidot + (MBRight(phi, gamma) + D) / J;
gammaddot = uprime;
xdot = [gammadot; gammaddot; phidot; phiddot];
end
% Compute u at some given x and desired gammaddot
function u = utrans(x, gammaddot_des)
global ka ks ku kf Jmb;
gamma = x(1);
gammadot = x(2);
phi = x(3);
u = (gammaddot_des - MBTorque(phi, gamma) / Jmb + kf * gammadot) / ku;
end
function phijerk = calcjerk(x, D, Ddot)
global ka rightingweight kssq J;
gamma = x(1);
gammadot = x(2);
phi = x(3);
phidot = x(4);
[R, dRdphi, dRdgamma] = calcMBRightingMoment(phi, gamma, rightingweight);
phiaccel = -ka * sin(phi) - kssq * phidot * abs(phidot) + (R + D) / J;
phijerk = -ka * cos(phi) * phidot - 2 * kssq * abs(phidot) * phiaccel + (dRdphi * phidot + dRdgamma * gammadot + Ddot) / J;
end
% Compute appropriate gammadot for a given phidddot
% phis = [phi, phidot, phiddot, phidddot]
function gammadot = gammainv(gamma, phis)
global ka rightingweight kssq J;
phi = phis(1);
phidot = phis(2);
phiaccel = phis(3);
phijerk = phis(4);
% phiddot = -ka * sin(phi) - kssq * phidot * abs(phidot) + (MBRight(phi, gamma) + D) / J;
% phijerk = -ka cos(phi) phidot - 2 kssq abs(phidot) phiddot + (dR/dphi phidot + dR/dgamma gammadot + Ddot) / J
% gammadot = ((phijerk + ka cos(phi) phidot + 2 kssq abs(phidot) phiddot) J - Ddot - dR/dphi phidot) / (dR/dgamma)
% Note that for dR/dgamma near zero, explodes
[~, dRdphi, dRdgamma] = calcMBRightingMoment(phi, gamma, rightingweight);
% Clip the edges and prevent singularities
% TODO(james): Prevent going past max righting moment points.
dRdgamma = min(dRdgamma, -0.01);
% Ddot = 0
gammadot = ((phijerk + ka * cos(phi) * phidot + 2 * kssq * abs(phidot) * phiaccel) * J - 0 - dRdphi * phidot) / dRdgamma;
end
% Compute linearized system as function of uprime
function [A, B, c, Aslow, Bslow, cslow] = linsys(x0);
global ka ks ku kf J;
% Start with clearly linear terms, then figure out MBRight
% Note that we account for gammaddot in uprime, so zero out kf.
A = [0 1 0 0;
0 0 0 0;
0 0 0 1;
0 0 -ka -ks];
B = [0; 1; 0; 0];
% Compute constant term (c)
c = simple_dyn(x0, 0);
Aright = jacobian(@(y) MBRight(y(1), y(2)), x0([3 1]));
A(4, [3 1]) = A(4, [3 1]) + Aright;
% The "slow" components of the system, where we
% now treat gammadot as an input.
slow = [1 3 4];
Aslow = A(slow, slow);
Bslow = [1; 0; 0];
cslow = c(slow);
end
% Compute needed x for a desired phi
% u will be zero at equilibrium because gammaddot=0.
function [x] = desx(phi)
foptions = optimoptions('fsolve', 'MaxFunctionEvaluations', 100000, 'Display', 'Off', 'Algorithm', 'levenberg-marquardt');
gamma = fsolve(@(gam) simple_dyn([gam; 0; phi; 0], 0), 0, foptions);
x = [gamma; 0; phi; 0];
end
% Invert the computation of the movable ballast righting moment
function [gamma] = invright(desright, curphi)
global rightingweight
% TODO: Do this cleanly
gamma = fsolve(@(gam) calcMBRightingMoment(curphi, gamma, rightingweight), 0, optimset('Display', 'off'));
end
|
github
|
Yadaizi/LLC-image-classification-master
|
sp_find_sift_grid.m
|
.m
|
LLC-image-classification-master/sift/sp_find_sift_grid.m
| 4,187 |
utf_8
|
029daeb5a3d4d49bb26b0e1a64cc4b97
|
function sift_arr = sp_find_sift_grid(I, grid_x, grid_y, patch_size, sigma_edge)
% parameters
num_angles = 8;
num_bins = 4;
num_samples = num_bins * num_bins;
alpha = 9;
if nargin < 5
sigma_edge = 1;
end
angle_step = 2 * pi / num_angles;
angles = 0:angle_step:2*pi;
angles(num_angles+1) = []; % bin centers
[hgt wid] = size(I);
num_patches = numel(grid_x);
sift_arr = zeros(num_patches, num_samples * num_angles);
[G_X,G_Y]=gen_dgauss(sigma_edge);
I_X = filter2(G_X, I, 'same'); % vertical edges
I_Y = filter2(G_Y, I, 'same'); % horizontal edges
I_mag = sqrt(I_X.^2 + I_Y.^2); % gradient magnitude
I_theta = atan2(I_Y,I_X);
I_theta(find(isnan(I_theta))) = 0; % necessary????
% make default grid of samples (centered at zero, width 2)
interval = 2/num_bins:2/num_bins:2;
interval = interval - (1/num_bins + 1);
[sample_x sample_y] = meshgrid(interval, interval);
sample_x = reshape(sample_x, [1 num_samples]);
sample_y = reshape(sample_y, [1 num_samples]);
% make orientation images
I_orientation = zeros(hgt, wid, num_angles);
% for each histogram angle
for a=1:num_angles
% compute each orientation channel
tmp = cos(I_theta - angles(a)).^alpha;
tmp = tmp .* (tmp > 0);
% weight by magnitude
I_orientation(:,:,a) = tmp .* I_mag;
end
% for all patches
for i=1:num_patches
r = patch_size/2;
cx = grid_x(i) + r - 0.5;
cy = grid_y(i) + r - 0.5;
% find coordinates of sample points (bin centers)
sample_x_t = sample_x * r + cx;
sample_y_t = sample_y * r + cy;
sample_res = sample_y_t(2) - sample_y_t(1);
% find window of pixels that contributes to this descriptor
x_lo = grid_x(i);
x_hi = grid_x(i) + patch_size - 1;
y_lo = grid_y(i);
y_hi = grid_y(i) + patch_size - 1;
% find coordinates of pixels
[sample_px, sample_py] = meshgrid(x_lo:x_hi,y_lo:y_hi);
num_pix = numel(sample_px);
sample_px = reshape(sample_px, [num_pix 1]);
sample_py = reshape(sample_py, [num_pix 1]);
% find (horiz, vert) distance between each pixel and each grid sample
dist_px = abs(repmat(sample_px, [1 num_samples]) - repmat(sample_x_t, [num_pix 1]));
dist_py = abs(repmat(sample_py, [1 num_samples]) - repmat(sample_y_t, [num_pix 1]));
% find weight of contribution of each pixel to each bin
weights_x = dist_px/sample_res;
weights_x = (1 - weights_x) .* (weights_x <= 1);
weights_y = dist_py/sample_res;
weights_y = (1 - weights_y) .* (weights_y <= 1);
weights = weights_x .* weights_y;
% % make sure that the weights for each pixel sum to one?
% tmp = sum(weights,2);
% tmp = tmp + (tmp == 0);
% weights = weights ./ repmat(tmp, [1 num_samples]);
% make sift descriptor
curr_sift = zeros(num_angles, num_samples);
for a = 1:num_angles
tmp = reshape(I_orientation(y_lo:y_hi,x_lo:x_hi,a),[num_pix 1]);
tmp = repmat(tmp, [1 num_samples]);
curr_sift(a,:) = sum(tmp .* weights);
end
sift_arr(i,:) = reshape(curr_sift, [1 num_samples * num_angles]);
% % visualization
% if sigma_edge >= 3
% subplot(1,2,1);
% rescale_and_imshow(I(y_lo:y_hi,x_lo:x_hi) .* reshape(sum(weights,2), [y_hi-y_lo+1,x_hi-x_lo+1]));
% subplot(1,2,2);
% rescale_and_imshow(curr_sift);
% pause;
% end
end
function G=gen_gauss(sigma)
if all(size(sigma)==[1, 1])
% isotropic gaussian
f_wid = 4 * ceil(sigma) + 1;
G = fspecial('gaussian', f_wid, sigma);
% G = normpdf(-f_wid:f_wid,0,sigma);
% G = G' * G;
else
% anisotropic gaussian
f_wid_x = 2 * ceil(sigma(1)) + 1;
f_wid_y = 2 * ceil(sigma(2)) + 1;
G_x = normpdf(-f_wid_x:f_wid_x,0,sigma(1));
G_y = normpdf(-f_wid_y:f_wid_y,0,sigma(2));
G = G_y' * G_x;
end
function [GX,GY]=gen_dgauss(sigma)
% laplacian of size sigma
%f_wid = 4 * floor(sigma);
%G = normpdf(-f_wid:f_wid,0,sigma);
%G = G' * G;
G = gen_gauss(sigma);
[GX,GY] = gradient(G);
GX = GX * 2 ./ sum(sum(abs(GX)));
GY = GY * 2 ./ sum(sum(abs(GY)));
|
github
|
erlichlab/elutils-master
|
test_nonblocking.m
|
.m
|
elutils-master/+net/test_nonblocking.m
| 617 |
utf_8
|
8e2a79f129ba256b08ce855cf41c2630
|
function zmqlistener = test_nonblocking()
zmqlistener = timer();
zmqlistener.StartFcn = @setup_zmq;
zmqlistener.TimerFcn = @wait_for_msg;
zmqlistener.ExecutionMode = 'fixedSpacing';
zmqlistener.BusyMode = 'drop';
zmqlistener.Period = 2;
zmqlistener.TasksToExecute = +inf;
zmqlistener.StartDelay = 0.1;
start(zmqlistener)
end
function setup_zmq(obj,event)
obj.userdata = net.zmqsub('hammer');
end
function wait_for_msg(obj,event)
sub = obj.userdata;
[addr, data] = sub.recvjson();
if ~isempty(data)
disp(data)
else
disp('no data')
end
end
|
github
|
erlichlab/elutils-master
|
zmqhelper.m
|
.m
|
elutils-master/+net/zmqhelper.m
| 5,299 |
utf_8
|
66a815982b07bdab722a7ad311761f8b
|
classdef zmqhelper < handle
% The ZMQHandler class is a wrapper for the jeromq java class.
%
%
properties
url
socktype
socket
subscriptions
end
methods
function obj = zmqhelper(varargin)
if nargin == 0
help(mfilename)
end
inpd = @utils.inputordefault;
obj.socktype = inpd('type', 'pub', varargin);
obj.url = inpd('url', [], varargin);
obj.subscriptions = inpd('subscriptions', [], varargin);
if isempty(obj.url)
obj.url = net.zmqhelper.loadconf(obj.socktype);
end
import org.zeromq.ZMQ;
context = ZMQ.context(1);
obj.socket = context.socket(ZMQ.(upper(obj.socktype)));
%obj.socket.HEARTBEAT_INTERVAL = 60000; % seems not available in jeromq
obj.socket.connect(obj.url);
% This assumes you want to use connect. if you want to bind... you are an advanced user. Do it yourself.
if ~isempty(obj.subscriptions)
for sx = 1:numel(obj.subscriptions)
obj.socket.subscribe(uint8(obj.subscriptions{sx}));
end
end
end
function out = sendkv(obj, key, value)
msg = uint8(sprintf('%s %s',key, json.mdumps(value)));
out = send(obj.socket, msg);
end
function out = sendmsg(obj, msg)
out = send(obj.socket, uint8(msg));
end
function out = sendbytes(obj, msg)
out = obj.socket.send(msg);
end
function [key, val] = recvkv(obj)
out = char(obj.socket.recvStr(1)); % The one gets msg without blocking
[key, tval] = strtok(out, ' ');
val = json.mloads(tval(2:end));
end
function out = recvmsg(obj)
out = char(obj.socket.recvStr(1)); % The one gets msg without blocking
end
function out = recvbytes(obj)
out = obj.socket.recv(1); % The one gets msg without blocking
end
function [addr, out] = recvjson(obj)
msg = recvmsg(obj); % get msg with nonblocking and convert from java string to char
if isempty(msg)
addr = [];
out = [];
else
[addr, out] = parsejson(msg);
end
end
function out = waitformsg(obj)
out = char(obj.socket.recvStr()); % The one gets msg with blocking
end
function [addr, out] = waitforjson(obj)
msg = waitformsg(obj); % get msg with blocking
if isempty(msg)
addr = [];
out = [];
else
[addr, out] = parsejson(msg);
end
end
function out = waitfordata(obj)
out = obj.socket.recv(); % The one gets msg with blocking
end
end
methods (Static)
function zmqconf = loadconf(prop, fname)
if nargin == 1
fname = '~/.dbconf';
end
ini = utils.ini2struct(fname);
switch prop
case 'pub'
zmqconf = sprintf('%s:%d', ini.zmq.url, ini.zmq.pubport);
case 'sub'
zmqconf = sprintf('%s:%d', ini.zmq.url, ini.zmq.subport);
case 'push'
zmqconf = sprintf('%s:%d', ini.zmq.url, ini.zmq.pushport);
otherwise
error('If not using pub or sub you must specify the URL to use.')
end
end
function zpub = getPublisher()
% all publishers can share one publisher.
persistent localpub;
if isempty(localpub)
localpub = net.zmqhelper('type','pub');
end
zpub = localpub;
end
function zpub = getPusher()
% all publishers can share one publisher.
persistent localpush;
if isempty(localpush)
localpush = net.zmqhelper('type','push');
end
zpub = localpush;
end
function zsub = getSubscriber(subscriptions)
if ischar(subscriptions)
subscriptions = {subscriptions};
end
zsub = net.zmqhelper('type','sub', 'subscriptions',subscriptions);
end
end % methods
end % classdef
function [addr, out] = parsejson(msg)
try
json_start = find(msg=='{',1,"first");
json_end = find(msg=='}',1,"last");
jstr = msg(json_start:json_end);
addr = strtrim(msg(1:json_start-1));
%out = json.fromjson(jstr); % decode the json string and return the address and the json object
out = jsondecode(jstr);
catch me
utils.showerror(me)
display(msg)
addr = [];
out = [];
end
end
|
github
|
erlichlab/elutils-master
|
sig4inv.m
|
.m
|
elutils-master/+stats/sig4inv.m
| 114 |
utf_8
|
832d02d929f5449eafd190461040b711
|
function x=sig4inv(beta,y)
%% sig4
y0=beta(1);
a=beta(2);
x0=beta(3);
b=beta(4);
x = -b*log((a./(y-y0))-1)+x0;
|
github
|
erlichlab/elutils-master
|
KernelRegressionA.m
|
.m
|
elutils-master/+stats/KernelRegressionA.m
| 4,999 |
utf_8
|
dab81ba78e55468e744502b7999bcd76
|
classdef KernelRegressionA
properties
baseline_per_trial = false
core_kernel % this is the matrix for a single kernel. Will use it as a convolution kernel
core_kernel_matrix % This is the core_kernel convolued with the event times.
event_times
kernel_bin_size = 0.01 % seconds
kernel_dof = 50
kernel_duration = 2 % seconds
kernel_smoothing = 3
kernel_smoothing_style = 'normal'
kernel_weights % The result of the kernel estimation step.
spiketimes
trial_types
trial_weights % The result of the trial weight estimation step
weighted_kernel_matrix % core_kernel_matrix multiplied by trial_weights
end
properties (Dependent)
number_of_events
kernel_bins
kernels % Combine the kernel_weights with core_kernel to get the kernels
total_time_steps
end
methods
function obj = KernelRegressionA(e, s, t)
obj.event_times = e;
obj.spiketimes = s;
if nargin < 3
obj.trial_types = col(1:size(e,1));
else
obj.trial_types = t;
% This allows you to fit fewer than # of trial trial_weights. Eg. if you want to assume the weights on
% the same trial type is the same.
end
obj.trial_weights = ones(numel(unique(obj.trial_types)),1);
end
function obj = run(obj)
generateCoreKernel(obj);
generateKernelMatrix(obj);
generateCoreWeights(obj);
generateWeightMatrix(obj);
fit(obj);
end
function obj = generateCoreKernel(obj) % tested, OK
% To do the kernel regression we need a regression matrix to specify
% where each element of the kernel influences the firing rate.
% We will start with the
% assumption that all kernels have the same length: kernel_duration.
% Initialize the matrix to be the right size.
obj.core_kernel = zeros(obj.kernel_bins, obj.kernel_dof);
obj.kernel_weights = ones(size(obj.event_times,2), obj.kernel_dof);
% Put ones every where they should be.
bins_per_dof = obj.kernel_bins/ obj.kernel_dof;
tmpA = repmat(1:obj.kernel_bins:numel(obj.core_kernel),bins_per_dof,1) + (0:(bins_per_dof-1))';
idx = tmpA + (0:bins_per_dof:(obj.kernel_bins-1));
obj.core_kernel(idx(:)) = 1;
% Apply smoothing
if obj.kernel_smoothing > 0
smooth_factor = obj.kernel_smoothing * bins_per_dof;
switch obj.kernel_smoothing_style
case 'normal'
smooth_krn = normpdf(-(5*smooth_factor):(5*smooth_factor), 0, smooth_factor)';
case 'box'
smooth_krn = ones(smooth_factor,1);
otherwise
error('Do not know how to smooth using %s');
end
obj.core_kernel = conv2(obj.core_kernel, smooth_krn, 'same');
obj.core_kernel = obj.core_kernel ./ sum(obj.core_kernel,2);
end
end
function obj = generateKernelMatrix(obj)
% Initialize a matrix that is [session_duration / bin_size x # of
% kernels * kernel_bins + 1] (the one is for baseline). o
if obj.baseline_per_trial
% Should baseline be allowed to vary for different trials of the same trial_type? I guess yes.
obj.core_kernel_matrix = zeros(obj.total_time_steps, obj.number_of_events*obj.kernel_bins + size(obj.event_times,1));
else
obj.core_kernel_matrix = zeros(obj.total_time_steps, obj.number_of_events*obj.kernel_bins + 1);
end
kernel_matrix = zeros(obj.total_time_steps, obj.number_of_events*obj.kernel_bins);
% just for the kernels. Deal with the baseline later
% We have a big matrix of zeros. We want to put the core_kernel
% everywhere there is an event. Our plan for doing this is to put a 1
% whereever we want the kernel and then convolve this with our
% core_kernel. We can then use this to estimate the kernel_weights.
row_offset = floor(obj.kernel_bins/2);
col_offset = floor(obj.kernel_dof/2);
krn_offset = obj.kernel_dof;
event_index = floor((obj.event_times - min(obj.event_times(:))) /obj.kernel_bin_size); % Converts event_times to indices
row_idx = event_index(:) + row_offset;
col_idx = col(repmat((0:(obj.number_of_events-1))*krn_offset,obj.) +
idx = sub2ind(size(kernel_matrix), row_idx, col_idx);
kernel_matrix(idx) = 1;
kernel_matrix = conv2(kernel_matrix, obj.core_kernel, 'same');
end
function number_of_events = get.number_of_events(obj)
number_of_events = size(obj.event_times, 2);
end
function total_time_steps = get.total_time_steps(obj)
total_time_steps = (max(obj.event_times(:)) - min(obj.event_times(:))) ./ obj.kernel_bin_size + obj.kernel_bins;
end
function kernel_bins = get.kernel_bins(obj)
kernel_bins = obj.kernel_duration/obj.kernel_bin_size;
assert(rem(kernel_bins,1)==0, 'The kernel_duration should be an integer multiple of kernel_bin_size');
end
function kernels = get.kernels(obj)
% tested, OK
kernels = obj.kernel_weights * obj.core_kernel';
end
end
end
function y = col(x)
y = x(:);
end
|
github
|
erlichlab/elutils-master
|
sig4.m
|
.m
|
elutils-master/+stats/sig4.m
| 173 |
utf_8
|
ff976a6673d16b218ccb1651af766178
|
% y=sig4(beta,x)
% y0=beta(1);
% a=beta(2);
% x0=beta(3);
% b=beta(4);
function y=sig4(beta,x)
y0=beta(1);
a=beta(2);
x0=beta(3);
b=beta(4);
y=y0+a./(1+ exp(-(x-x0)./b));
|
github
|
erlichlab/elutils-master
|
nanstderr.m
|
.m
|
elutils-master/+stats/nanstderr.m
| 142 |
utf_8
|
d09ca0d1a2ee8c2b698c5055f9e29d0e
|
function y = nanstderr(x,dim)
if nargin==1
dim=1;
end
gd=sum(~isnan(x),dim);
y=nanstd(x,0,dim)./sqrt(gd-1);
y(y==Inf)=nan;
y(gd==0)=nan;
|
github
|
erlichlab/elutils-master
|
cellmean.m
|
.m
|
elutils-master/+stats/cellmean.m
| 326 |
utf_8
|
3582f4fc2f25ad0b0db1325cfddfabf2
|
function [mu, se]=cellmean(M,varargin)
% [mu, se]=cellmean(M,varargin)
dim=1;
utils.overridedefaults(who,varargin)
mu=nan(1,numel(M));
se=mu;
for fx=1:numel(M)
if numel(M{fx})<2
mu(fx)=nan;
se(fx)=nan;
else
mu(fx)=nanmean(M{fx},dim);
se(fx)=stats.nanstderr(M{fx},dim);
end
end
|
github
|
erlichlab/elutils-master
|
bootsigmoid_val.m
|
.m
|
elutils-master/+stats/bootsigmoid_val.m
| 1,722 |
utf_8
|
06b7b18967ce489fc03a39b3af42dbb8
|
function [p,D]=bootsigmoid(A,B,varargin)
% [p,D]=bootsigmoid(A,B,varargin)
% Takes two sets of N x 2 binomial data A and B, and fits sigmoids to them
% both. It then uses the mean and covariance of the fits to calculate the
% distance (using the projection of the fits onto fisher's linear
% discriminant) of the fits.
% Then we permute the rows of A and B to generate permuted data sets and
% perform the same fits and estimates of "distance". Finally, the distance
% between A and B fits are compared to the distribution of distances
% generated by permuting A and B.
BOOTS=100000;
utils.overridedefaults(who,varargin);
import stats.*
[dAB, D]=get_dist(A,B);
n_A=size(A,1);
n_B=size(B,1);
permAB=nan(BOOTS,1);
M=[A;B];
parfor bx=1:BOOTS
rperm=randperm(n_A+n_B);
rA=M(rperm(1:n_A),:);
rB=M(rperm((n_A+1):end),:);
permAB(bx)=get_dist(rA,rB);
end
p= stats.get_p(dAB,permAB);
D.permAB=permAB;
D.p=p;
end %sfunction
function [dAB,D]=get_dist(A,B)
n_A=size(A,1);
n_B=size(B,1);
aidx=randperm(n_A);
bidx=randperm(n_B);
Alim=floor(n_A/2);
Blim=floor(n_B/2);
trainAdx=aidx(1:Alim);
trainBdx=bidx(1:Blim);
testAdx=aidx(Alim+1:end);
testBdx=bidx(Blim+1:end);
[nbetaA,~,~,covA,~]=nlinfit(A(trainAdx,1),A(trainAdx,2),@sig4,[0 1 0 10]);
[nbetaB,~,~,covB,~]=nlinfit(B(trainBdx,1),B(trainBdx,2),@sig4,[0 1 0 10]);
vAB=flda(nbetaA,nbetaB,covA,covB,Alim,Blim);
[betaA,~,~,~,~]=nlinfit(A(testAdx,1),A(testAdx,2),@sig4,[0 1 0 10]);
[betaB,~,~,~,~]=nlinfit(B(testBdx,1),B(testBdx,2),@sig4,[0 1 0 10]);
dAB=abs(betaA*vAB-betaB*vAB);
D.trainbetaA=nbetaA;
D.trainbetaB=nbetaB;
D.testbetaA=betaA;
D.testbetaB=betaB;
D.covA=covA;
D.covB=covB;
D.vAB=vAB;
D.dAB=dAB;
end % subfunction
|
github
|
erlichlab/elutils-master
|
sig4_invB.m
|
.m
|
elutils-master/+stats/sig4_invB.m
| 181 |
utf_8
|
c08cb89c2c6b4038f98284bc884f552e
|
% y=sig4(beta,x)
% y0=beta(1);
% a=beta(2);
% x0=beta(3);
% b=beta(4);
function y=sig4_invB(beta,x)
y0=beta(1);
a=beta(2);
x0=beta(3);
b=1./beta(4);
y=y0+a./(1+ exp(-(x-x0)./b));
|
github
|
erlichlab/elutils-master
|
sig2.m
|
.m
|
elutils-master/+stats/sig2.m
| 120 |
utf_8
|
c287dd7909e5ebcb805a5626775fe6f9
|
% y=sig2(beta,x)
% x0=beta(3);
% b=beta(4);
function y=sig2(beta,x)
x0=beta(1);
b=beta(2);
y=1./(1+ exp(-(x-x0)./b));
|
github
|
erlichlab/elutils-master
|
flda.m
|
.m
|
elutils-master/+stats/flda.m
| 1,152 |
utf_8
|
9bdfccc574b6158b470380ab74d3a6af
|
function v=flda(varargin)
% v = flda(G1,G2)
% v = flda(mean1,mean2,cov1,cov2,n1,n2)
%
% v is fisher's linear discriminant between the two "groups" of data
% Using syntax 1
% G1 is an n x d matrix
% G2 is an m x d matrix
% Using syntax 2
% Group1 has mean mu1, covariance cov1, and n1 number of samples
% Group2 has mean mu2, covariance cov2, and n2 number of samples
% v is a d x 1 vector
%
% http://www.csd.uwo.ca/~olga/Courses//CS434a_541a//Lecture8.pdf
if nargin==2
X=varargin{1};
Y=varargin{2};
[x_n, xdim]=size(X);
[y_n, ydim]=size(Y);
if xdim~=ydim
error
end
muX=nanmean(X,1);
muY=nanmean(Y,1);
nX=X-repmat(muX,x_n,1);
nY=Y-repmat(muY,y_n,1);
nX(isnan(nX))=0;
nY(isnan(nY))=0;
S1 = nX'*nX; % This is an estimate of the covariance matrix -> divide by x_n to get COV(X)
S2 = nY'*nY;
elseif nargin==6
muX=varargin{1};
muY=varargin{2};
cx=varargin{3};
cy=varargin{4};
nx=varargin{5};
ny=varargin{6};
S1 = cx*(nx-1);
S2 = cy*(ny-1);
end
Sw=S1+S2;
% Solve eigenproblem Sb*V = Lambda*Sw*V
v=Sw\(muX-muY)';
|
github
|
erlichlab/elutils-master
|
binned2.m
|
.m
|
elutils-master/+stats/binned2.m
| 3,374 |
utf_8
|
b96f93e8a24ff24b02339784a67566ca
|
function [xbinc, ybinc, mu, se, n]=binned2(x,y,z, varargin)
% [binc, mu, se, n]=binned2(x,y,z,bin_e)
% Takes a vector x and a vector y and returns mean and standard error of
% values of z for bins of x and y.
%
% Input:
% x 1xn vector of x values to bin
% y 1xn vector of y values to bin
% z 1xn vector of z values to average in each bin
%
% Optional Input [=default]:
%
% n_bins=10 Optional # of bins.
% n_x_bins=n_bins Specify # of x bins. Overrides n_bins
% n_y_bins=n_bins Specify # of y bins. Overrides n_bins
% even_bins=false By default bins have equal # of data points. If this is
% true then bins are evenly spaced and have uneven sample
% sizes
%
% xbin_e=[] Optional bin edges for the x-axis. Overrides all
% earlier options
%
% ybin_e=[]; Optional bin edges for the y-axis. Overrides all
% earlier options
% plot_it=false;
% marker if plot_it then use this marker ['o']
% linestyle if plot_it then use this linestyle ['-']
% ax=[]; if plot_it=true, plot to this axis
%
% Output:
% binc 1xm bin centers
% mu 1xm The average value of y at that bin
% se 1xm The standard error of y at that bin
% n 1xm The number of values of y in this bin
check_inputs(x,y,z)
xbin_e=[];
ybin_e=[];
ax=[];
plot_it=false;
n_bins=7;
n_x_bins=n_bins;
n_y_bins=n_bins;
even_bins=false;
func=@nanmean;
linestyle = '-';
marker = 'o';
utils.overridedefaults(who,varargin);
if isempty(ax) && plot_it
ax=gca;
end
if isempty(xbin_e)
if even_bins
xbin_e=linspace(min(x),max(x),n_x_bins+1);
else
pbins=linspace(0,100,n_x_bins+1);
xbin_e=unique(prctile(x,pbins));
end
end
if isempty(ybin_e)
if even_bins
ybin_e=linspace(min(y),max(y),n_y_bins+1);
else
pbins=linspace(0,100,n_y_bins+1);
ybin_e=unique(prctile(y,pbins));
end
end
clr=cool(numel(ybin_e)-1);
xbinc=(xbin_e(2:end)+xbin_e(1:end-1))/2;
ybinc=(ybin_e(2:end)+ybin_e(1:end-1))/2;
mu=repmat(nan,numel(ybinc),numel(xbinc));
se=mu;
x=x(:);
y=y(:);
z=z(:);
% split the data up by y
[~,yind]=histc(y,ybin_e);
[~,xind]=histc(x,xbin_e);
if all(z==1 | z==0)
binomial_data = true;
else
binomial_data = false;
end
for ny=1:numel(ybinc)
for nx=1:numel(xbinc)
tmp = func(z(xind==nx & yind==ny));
if isempty(tmp)
tmp=nan;
end
mu(ny,nx)=tmp;
if binomial_data
sigma = sum(z(xind==nx & yind==ny));
count = sum(xind==nx & yind==ny);
[~,ci]= binofit(sigma,count);
se(ny,nx)=max(abs(ci-mu(ny,nx)));
else
se(ny,nx)=stats.nanstderr(z(xind==nx & yind==ny));
end
n(ny,nx)=sum(~isnan(z(xind==nx & yind==ny)));
end
end
if plot_it
for ny=1:numel(ybinc)
hh(ny,:)=draw.errorplot(ax,xbinc, mu(ny,:), se(ny,:),'Marker',marker,'Color',clr(ny,:));
set(hh(ny,2),'LineStyle',linestyle,'LineWidth',2)
end
end
function check_inputs(x,y,z)
if ~iscolumn(x) || ~iscolumn(y) || ~iscolumn(z)
error('x,y & z must all be column vectors');
end
if ~isequal(size(x), size(y)) || ~isequal(size(x), size(z)) || ~isequal(size(y), size(z))
error('x, y & z must all be column vectors of equal length');
end
|
github
|
erlichlab/elutils-master
|
align_hv.m
|
.m
|
elutils-master/+stats/align_hv.m
| 3,594 |
utf_8
|
5e557d2b0e614ee7d069e455658e2889
|
function [offset,inc_t,x,y]=align_hv(ev,ts,val,varargin)
% [offset,inc_t,x,y]=align_hv(ev, ts,val, varargin)
%
% pairs={'pre' 3;...
% 'post' 3;...
% 'binsz' 0.001;...
% 'meanflg' 0;...
% 'krn' 0.25;...
% 'max_offset' 1;...
% 'pre_mask', -inf;...
% 'post_mask',+inf;...
% 'do_plot' false;...
% 'max_iter' 100;...
% 'max_peak' 1000;...
% 'var_thres' 0.05;...
% 'save_plot' '';...
% 'col_axis' [-50 500];...
% 'col_map' jet;...
% 'mark_this',[];...
% }; parseargs(varargin,pairs,{},1);
% %
pre = 3;
post = 3;
binsz = 0.001;
% pre_mask = -inf;
% post_mask = +inf;
max_offset = 1;
do_plot = false;
max_iter = 100;
max_peak = 1000;
var_thres = 0.05;
save_plot = '';
col_axis = [-50 500];
col_map = jet;
mark_this = [];
utils.overridedefaults(who, varargin);
old_var=10e10;
done=0;
thres=1000;
offset=zeros(size(ev));
if do_plot
clf;ax(1)=axes('Position',[0.1 0.1 0.2 0.2]);
ax(2)=axes('Position',[0.1 0.1 0.2 0.2]);
hold on;
end
cnt=1;
inc_t=ones(size(ev))==1;
%% Calculate the mean and ci of the
while ~done
[y,x]=stats.cdraster(ev+offset,ts(:),val(:),pre,post,binsz);
y(isnan(y))=0;
[rowi,coli]=find(abs(y)>max_peak);
inc_t(unique(rowi))=false;
% [y x]=maskraster(x,y,pre_mask(ref),post_mask(ref));
ymn = nanmean(y(inc_t,:));
yst = stats.nanstderr(y(inc_t,:));
if do_plot
plot_this(ax,x,y,inc_t,offset,save_plot,pre,post,cnt,0,col_axis,col_map,mark_this);
end
for tx=1:numel(ev);
if inc_t(tx)
[xcy,xcx]=xcorr(y(tx,:)-mean(y(tx,:)),ymn-mean(ymn));
[v,peakx]=max(xcy);
offset(tx)=offset(tx)+xcx(peakx)*binsz;
if abs(offset(tx))>max_offset
inc_t(tx)=false;
end
end
end
new_var=sum(nanvar(y));
var_diff=(old_var-new_var)/old_var;
if do_plot
fprintf('Variance improved by %2.3g %% of total variance\n',100*var_diff);
end
old_var=new_var;
cnt=cnt+1;
if abs(var_diff)<var_thres || cnt>max_iter
done=true;
if do_plot
plot_this(ax,x,y,inc_t,offset,save_plot,pre,post,cnt+1,0,col_axis,col_map,mark_this);
end
end
end
function plot_this(ax,x,y,inc_t,offset,save_plot,pre,post,cnt,do_sort,col_axis,col_map,mark_this)
cla(ax(1));
cla(ax(2));
ymn = nanmean(y(inc_t,:));
yst = stats.nanstderr(y(inc_t,:));
if mean(mean(y))<0
iy=-y;
else
iy=y;
end
if do_sort
[so,si]=sort(-offset);
offset=offset(si);
inc_t=inc_t(si);
iy=iy(si,:);
end
imagesc(x,[],iy(inc_t,:),'Parent',ax(1));
set(ax(1), 'Ydir','normal')
hold(ax(1),'on');
caxis(ax(1),col_axis);
colormap(ax(1),col_map);
if cnt==1
cbh=colorbar('peer',ax(1),'East');
set(cbh,'Position',get(cbh,'Position')-[0.2 0 0 0])
end
% plot(ax,x,ymn-yst,x,ymn+yst,'Color',[1-0.2*cnt, 0 ,0]);
% plot(ax(2),x,ymn-yst,x,ymn+yst,'Color',[0.2 0.2 0.9],'LineWidth',2);
% set(ax(1),'YTick',[]);
set(ax,'YTick',[]);
set(ax(2),'Color','none');
set(ax,'XLim', [-pre post],'YLim',[1 sum(inc_t)])
%ylim([0 maxy])
xlabel(ax(2),'Time (s)')
% ylabel(ax(2),'degrees/sec')
yss=1:sum(inc_t==1);
plot(ax(1),-offset(inc_t),yss(:) ,'w.');
if ~isempty(mark_this)
plot(ax(1),-offset(inc_t)+mark_this(inc_t), yss(:), 'gx');
end
drawnow
if ~isempty(save_plot)
saveas(gcf,sprintf('ahv_%s_%d.eps',save_plot,cnt),'epsc2');
end
if cnt==1
set(cbh, 'Visible','off')
end
|
github
|
erlichlab/elutils-master
|
sig3.m
|
.m
|
elutils-master/+stats/sig3.m
| 239 |
utf_8
|
031ac0a7d8b32a57722315ef985581b3
|
% y=sig4(beta,x)
% y0=beta(1);
% a=beta(2);
% x0=beta(3);
% b=beta(4);
function y=sig3(beta,X)
x0=beta(1);
b=beta(2);
w=beta(3);
dx=X(:,2)-X(:,1);
L=X(:,1);
R=X(:,2);
w=min(max(w,0),1);
y=1./(1+ exp(-(dx-x0)./((1+w*R+(1-w)*L).^b)));
|
github
|
erlichlab/elutils-master
|
stderr.m
|
.m
|
elutils-master/+stats/stderr.m
| 101 |
utf_8
|
70cccd93f718ca93def51627c9e5d4da
|
function y=stderr(x,dim)
if ~exist('dim','var')
dim=1;
end
y=std(x,0,dim)/sqrt(size(x,dim)-1);
|
github
|
erlichlab/elutils-master
|
sig5.m
|
.m
|
elutils-master/+stats/sig5.m
| 265 |
utf_8
|
0e840ad915c8b249461ff617952c70f1
|
% y=sig4(beta,x)
% y0=beta(1);
% a=beta(2);
% x0=beta(3);
% b=beta(4);
function y=sig5(beta,X)
y0=beta(1);
a=beta(2);
x0=beta(3);
b=beta(4);
w=beta(5);
dx=X(:,2)-X(:,1);
rx=X(:,2);
lx=X(:,1);
w=min(max(0,w),1);
y=y0+a./(1+ exp(-(dx-x0)./((w*rx+(1-w)*lx).^b)));
|
github
|
erlichlab/elutils-master
|
untiedrank.m
|
.m
|
elutils-master/+stats/untiedrank.m
| 1,862 |
utf_8
|
6209b20bdf331ab606146b08e4c2e830
|
function r = untiedrank(x)
% function r = untiedrank(x)
%
% Similar to tiedrank, but arbitrarily breaks ties (with consistency each
% time called)
% reset random number generator to same start
% RandStream.setDefaultStream(RandStream('mrg32k3a','Seed',10));
RandStream.setGlobalStream(RandStream('mrg32k3a','Seed',10));
if isvector(x)
r = tr(x);
else
if isa(x,'single')
outclass = 'single';
else
outclass = 'double';
end
% Operate on each column vector of the input (possibly > 2 dimensional)
sz = size(x);
ncols = sz(2:end); % for 2x3x4, ncols will be [3 4]
r = zeros(sz,outclass);
for j=1:prod(ncols)
r(:,j)= tr(x(:,j));
end
end
% --------------------------------
function r = tr(x)
%TR Local untiedrank function to compute results for one column
% Sort, then leave the NaNs (which are sorted to the end) alone
[sx, rowidx] = sort(x(:));
numNaNs = sum(isnan(x));
xLen = numel(x) - numNaNs;
% Use ranks counting from low end
ranks = [1:xLen NaN(1,numNaNs)]';
if isa(x,'single')
ranks = single(ranks);
end
% "randomly" break ties. Avoid using diff(sx) here in case there are infs.
ties = (sx(1:xLen-1) == sx(2:xLen));
tieloc = [find(ties); xLen+2];
maxTies = numel(tieloc);
tiecount = 1;
while (tiecount < maxTies)
tiestart = tieloc(tiecount);
ntied = 2;
while(tieloc(tiecount+1) == tieloc(tiecount)+1)
tiecount = tiecount+1;
ntied = ntied+1;
end
% Compute mean of tied ranks
% ranks(tiestart:tiestart+ntied-1) = sum(ranks(tiestart:tiestart+ntied-1)) / ntied;
% "randomly" reassign ties
temp = ranks(tiestart:tiestart+ntied-1);
ranks(tiestart:tiestart+ntied-1) = temp(randperm(ntied));
tiecount = tiecount + 1;
end
% Broadcast the ranks back out, including NaN where required.
r(rowidx) = ranks;
r = reshape(r,size(x));
|
github
|
erlichlab/elutils-master
|
softplus.m
|
.m
|
elutils-master/+stats/softplus.m
| 337 |
utf_8
|
7d105e1e04014e4ca55b507a27f2307e
|
function y=softplus(beta,x)
% y=softplus(beta,x)
% a=beta(1);
% x0=beta(2);
% b=beta(3);
a=beta(1);
x0=beta(2);
b=beta(3);
y = a.*(log(1 + exp((x - x0).*b)));
y/a = log(1 + exp(x-x0)*b)
exp(y/a) = 1 + exp(x-x0)*b
exp(y/a) - 1 = exp(x-x0)*b
b*(exp(y/a) - 1 = exp(x-x0)
log(b*exp(y) - a - 1) = x - x0
y = log(b*(exp(x) - a)) + x0;
|
github
|
erlichlab/elutils-master
|
sig4m.m
|
.m
|
elutils-master/+stats/sig4m.m
| 219 |
utf_8
|
05fdc096552ca475647fbe1ea82ca18f
|
% y=sig4(beta,x)
% y0=beta(1);
% a=beta(2);
% x0=beta(3);
% b=beta(4);
function y=sig4m(beta,X)
y0=beta(1);
a=beta(2);
x0=beta(3);
b=beta(4);
dx=X(:,2)-X(:,1);
sx=X(:,2)+X(:,1);
y=y0+a./(1+ exp(-(dx-x0)./(sx.^b)));
|
github
|
erlichlab/elutils-master
|
number_of_pairs.m
|
.m
|
elutils-master/+stats/number_of_pairs.m
| 1,817 |
utf_8
|
98688df40539000277d8a7cf6dd31647
|
% [n] = number_of_pairs(sh, p) Compute number of expected simultaneously-recorded pairs of "interesting" neurons
%
% Given a histogram of (# of sessions) versus (# of single-units recorded
% per session), and given a probability of a neuron being an "interesting"
% neuron (i.e., having a high enough firing rate, task-related
% activity, etc), produces an estimate of number of pairs of interesting,
% simultaneously recorded neurons.
%
% PARAMETERS:
% -----------
%
% sh A vector. The ith element in this vector should contain the
% number of sessions in which there were i single units recorded.
%
% p The probability that a recorded neuron is "interesting" (however
% you want to define it).
%
% RETURNS:
% --------
%
% n Expected number of simultaneously recorded "interesting" pairs
%
%
%
% EXAMPLE CALL:
% -------------
%
% >> number_of_pairs([4 5 3], 0.3)
%
% 1.7460
%
% gives the number of expected interesting pairs if in 4 sessions you
% recorded only one single unit (those produce no pairs, of course), in 5
% sessions you recorded two single units, and in 3 sessions you recorded
% three single units; and the probability of an "interesting" cell is 0.3.
%
% CDB 15-June-2012
function [n] = number_of_pairs(sh, p)
n=0;
for i=2:numel(sh), % i is going to be the # of singles recorded
for k=2:i % k is going to be the number of "interesting" neurons
pk = nchoosek(i,k)*p.^k*(1-p).^(i-k); % probability of k "interesting" neurons in i recorded neurons, assuming independence
ek = sh(i)*pk; % expected number of sessions in which we got k "interesting" neurons
n = n + ek*nchoosek(k,2); % number of pairs we get out of k neurons (e.g., when k=3 that's three different pairs)
end
end;
|
github
|
erlichlab/elutils-master
|
loglikelihood.m
|
.m
|
elutils-master/+stats/loglikelihood.m
| 917 |
utf_8
|
e4392f988006d99eee42fadd1ad6a4a0
|
% [L,bic]=loglikelihood(M,y,np)
%
% Input
% M: a vector of probabilities (model predictions)
% y: a vector of binomial outcomes
% np: the number of parameters in the model
%
% Output
% L: the log likelihood
% bic: the bayesian information criteria
function [L,bic]=loglikelihood(M,y,np)
% if isnumeric(M)
N = nan+M;
N(y==1)=M(y==1);
N(y==0)=1-M(y==0);
N(isnan(N) | isnan(M) | isnan(y))=[];
L=sum(log(N));
bic=2*-L+np*log(numel(N));
% not implemented yet
% else
% modeltype = class(M);
% nobs = M.NumObservations;
% resp = M.Variables.(M.ResponseName);
% fit = fitted(M);
% llpt = log(fitted(M)*resp + (1-fitted(M))*(1-resp));
% llpt(isnan(resp))=[];
% switch modeltype
% case 'GeneralizedLinearMixedModel'
% case {'GeneralizedLinearModel','NonLinearModel'}
% nparams = M.NumPredictors;
% end
|
github
|
erlichlab/elutils-master
|
rm_nans.m
|
.m
|
elutils-master/+db/rm_nans.m
| 333 |
utf_8
|
0cf78edb18bd0054cdeece3c5559a2c9
|
function S = rm_nans(S)
% This is useful since NaNs can't be sent to the DB.
fnames = fieldnames(S);
for fx = 1:numel(fnames)
try
if isnan(S.(fnames{fx}))
S = rmfield(S,fnames{fx});
end
catch me
% Skip for fields that can't be tested for nan.
end
end
end
|
github
|
erlichlab/elutils-master
|
labdb.m
|
.m
|
elutils-master/+db/labdb.m
| 12,393 |
utf_8
|
b2b6dd69cc2d0ad6541952434691faa5
|
classdef (Sealed) labdb < handle
% Class labdb
% This is a wrapper class for the JDBC MySQL driver.
% It has several features which are generally useful
% 1. It reads credentials configurations from ~/.dbconf so that you don't have to type in credentials or store them in code.
% 2. It maintains a single connection per configuration (a configuration is a user/hostname pair) for memory efficiency.
% 3. It has several useful functions for getting and saving data to MySQL
% 4. By default, automatically checks that the connection is alive and well before trying to communicate with the database.
% This incurs a small overhead, and can be turned off with `obj.autocheck = false`
%
% To see a list of the functions for the class type db.labdb.help
% To get help for a specific function call db.labdb.help(function_name), e.g. db.labdb.help('query')
properties (SetAccess=public,GetAccess=protected)
config = [];
end
properties (SetAccess=public,GetAccess=public)
dbconn = [];
autocheck = true;% Normally this class checks for DB connectivity before queries. If you are running many you can skip the autocheck.
end
methods (Access=private)
function obj = labdb
end
end
methods (Access=public)
function setConfig(obj, config)
% Manually set the user, passwd, host.
% input should be a struct with those fields
obj.config = config;
end
function host = getHost(obj)
% host = getHost()
% output: the hostname from the current config
host = obj.config.host;
end
function user = getUser(obj)
% host = getUser()
% output: the user from the current config
user = obj.config.user;
end
function out = getConnectionInfo(obj)
% out = getConnectionInfo
% returns a struct with connection information (driver version, connection URL, etc)
out = ping(obj.dbconn);
end
function list = list_enums(obj, tablename, column)
out = obj.query('show columns from %s where field="%s"',{tablename, column});
enums = out.COLUMN_TYPE{1}(6:end-1);
done = false;
list = {};
while ~done
[this_one, enums] = strtok(enums, ',');
list = [list, {strtrim(replace(this_one,'''',''))}];
if isempty(enums)
done = true;
else
enums = enums(2:end);
end
end
end
function list = column_names(obj,tablename)
out = obj.query('show columns from %s',{tablename});
list = out.COLUMN_NAME;
end
function cur = execute(obj, sqlstr, args)
% cur = execute(sql_command, [input arguments])
% executes the sql_command and returns a cursor object.
% Place holders can be used using sprintf style syntax.
% e.g. execute('insert into foo (a,b) values (%.3f,"%s")',{3.1441241, 'some text goes here'})
if nargin<3
args = {};
end
if obj.autocheck
checkConnection(obj);
end
sqlquery = sprintf(sqlstr, args{:});
cur = exec(obj.dbconn, sqlquery);
if cur.Message
% There was an error
fprintf(2,'SQL ERROR: %s \n',cur.Message);
end
end
function use(obj, schema)
% use(schema)
% sets the default schema
cur = execute(obj,sprintf('use %s', schema));
if cur.Message
error('Failed to switch schemas')
end
end
function out = explain(obj, table)
% explain(something)
% a shortcut for 'explain ...'
out = query(obj,sprintf('explain %s', table));
end
function out = last_insert_id(obj)
% out = last_insert_id
% returns the last_insert_id
out = query(obj,'select last_insert_id() as id');
out = out.id;
end
function varargout = get(obj, sqlstr, args)
% varargout = get(sql_command, [input arguments])
% Like query, this command uses sprintf style parsing to execute a MySQL SELECT command.
% However, get is special in that it returns one variable for each column in the SELECT
% whereas query returns a single table for the entire query.
%
% e.g. sessid = obj.get('select sessid from sessions limit 1') % sessid will be a float
% [sessdate, sessid] = obj.get('select sessiondate, sessid from sessions') % sessdate will be a cell array and sessid will be a vector of float
if nargin < 3
args = {};
end
out = query(obj,sqlstr,args);
varargout = cell(1,nargout);
if isempty(out) || strcmp(out{1,1},'No Data')
return;
end
for vx = 1:nargout
varargout{vx} = out.(out.Properties.VariableNames{vx});
end
end
function call(obj, sqlstr, args)
% call('storedProcedure(2456)')
% call('storedProcedure(%d,"%s")',{1234,'stuff'})
% Calls the stored procedure with the passed arguments.
if nargin<3
args={};
end
execute(obj,sprintf('call %s', sprintf(sqlstr, args{:})));
end
function out = query(obj, sqlstr, args)
% tableout = query(sql_command, [input arguments])
% Like execute, this command uses sprintf style parsing. But instead of returning a cursor,
% query returns a `table` object.
%
% e.g. sessid = obj.query('select sessid from sessions limit 1') % sessid will be a table with a sessid column.
% [sessdate, sessid] = obj.get('select sessiondate, sessid from sessions') % sessdate will be a cell array and sessid will be a vector of float
if obj.autocheck
checkConnection(obj);
end
if nargin < 3
args = {};
end
sqlquery = sprintf(sqlstr, args{:});
cur = exec(obj.dbconn, sqlquery);
if cur.Message
% There was an error
fprintf(2,'SQL ERROR: %s \n',cur.Message);
out = [];
else
data = fetch(cur);
%if cur.rows <= 0
%cur.rows have been removed for the lastest version of MATLAB
if isempty(cur.Data)
out = {};
elseif iscell(cur.Data) && strcmp(cur.Data{1},'No Data')
out = {};
else
out = data.Data;
end
end
close(cur);
end
function saveData(obj, tablename, data, varargin)
% saveData(obj, tablename, data, colnames)
if obj.autocheck
checkConnection(obj);
end
if nargin < 4
if isstruct(data)
colnames = fields(data);
data = struct2table(data,'AsArray',true);
elseif istable(data)
colnames = data.Properties.VariableNames;
else
error('labdb:saveData','Must specify column names if not using table or struct type')
end
end
datainsert(obj.dbconn, tablename, colnames, data);
end
function ok = isopen(obj)
try
cur = obj.dbconn.exec('select 1 from dual');
assert(isempty(cur.Message));
ok = true;
catch me
ok = false;
end
end
function checkConnection(obj)
try
getId(obj.dbconn.Handle);
cur = obj.dbconn.exec('select 1 from dual');
assert(isempty(cur.Message));
catch
obj.dbconn = [];
end
if isempty(obj.dbconn) || ~obj.dbconn.isopen
obj.dbconn = database(obj.config.db,obj.config.user,obj.config.passwd,'Vendor','MySQL',...
'Server',obj.config.host,'PortNumber',obj.config.port);
end
if ~isempty(obj.dbconn.Message)
fprintf(2,'%s\n',obj.dbconn.Message);
obj.dbconn = [];
end
end
function close(obj)
close(obj.dbconn);
obj.dbconn = [];
end
end
methods (Static)
% We use a static method to give the matlab client a database object
% for each configuration (IP, username) we only make one connection and then re-use it.
% This is ok for MATLAB since it is single threaded.
% It could potentially cause strange behavior if a user was doing inserts in a timer and also in the main
% thread and using `last_insert_id`
function help(fname)
if nargin == 0
help('db.labdb')
methods('db.labdb')
else
help(sprintf('db.labdb.%s',fname))
end
end
function so = getConnection(varargin)
setdbprefs('DataReturnFormat','table')
persistent localObj; % This is where we store existing connections.
if nargin == 1
% The user provided a config name, so use that.
configsec = varargin{1};
elseif nargin ==0
% The user provided nothing. Use the default config.
configsec = 'client';
else
configsec = utils.inputordefault('config','client',varargin);
end
% Check if we have a connection with the right name.
try
so = localObj.(configsec);
return;
catch ME
if ~strcmp(ME.identifier, {'MATLAB:nonExistentField', 'MATLAB:structRefFromNonStruct'})
rethrow(ME)
end
end
% No connection exists
localObj.(configsec) = [];
addMysqlConnecterToPath(); % Make sure the driver is on the path.
if nargin < 3
config = readDBconf(configsec);
else
config.host = varargin{1};
config.user = varargin{2};
config.passwd = varargin{3};
if nargin > 3
config.db = varargin{4};
else
config.db = 'met';
end
end
localObj.(configsec) = db.labdb;
setConfig(localObj.(configsec), config);
checkConnection(localObj.(configsec));
so = localObj.(configsec);
end
end
end
function cfg = readDBconf(cfgname)
% A private function to help the labdb class read credentials from the
% .dbconf file in the user's home directory.
def.db = ''; % In case db is not passed in set it by default to nothing.
def.port = 3306;
if nargin == 0
cfgname = 'client';
end
if ispc
cfgpath = getenv('USERPROFILE');
else
cfgpath = getenv('HOME');
end
cfgfile = fullfile(cfgpath,'.dbconf');
if ~exist(cfgfile,'file')
error('labdb:dbconf','.dbconf file not found in home directory');
end
allcfg = utils.ini2struct(cfgfile);
fopts = allcfg.(cfgname);
cfg = utils.apply_struct(def, fopts);
end
function addMysqlConnecterToPath()
jcp = javaclasspath('-all');
jarfile = 'mysql-connector-java-5.1.42-bin.jar';
if isempty(cell2mat(regexp(jcp,jarfile)))
% Mysql is not on the path
this_file = mfilename('fullpath');
[this_path] = fileparts(this_file);
javaaddpath(fullfile(this_path, jarfile));
end
end
|
github
|
erlichlab/elutils-master
|
drawgaussian.m
|
.m
|
elutils-master/+draw/drawgaussian.m
| 2,055 |
utf_8
|
5ec4d56c987f84917fba34d436c525cd
|
%drawgaussian Draw the 1-sigma lines for a 2d gaussian
%
% [h] = drawgaussian(mean, [sigmax, sigmay, r | C], ...
% {'angstart', 0}, {'angend', 360}, {'useC', 0})
%
% Draws the nth-sigma lines for a gaussian in the current
% figure. Since it uses LINE to do this, it returns a handle to
% that line.
%
% 'mean' must be a 2 element vector, first component <x>, second
% <y>.
%
% sigmax is the standard deviation of x; sigma y the standard
% deviation of y; and r is defined as
% <(x-<x>)*(y-<y>)>/(sigmax*sigmay) and thus lies in [0,1). If
% only two arguments are passed, the second is assumed to be a
% two-by-two covariance matrix.
%
function [hout] = drawgaussian(mean, sigmax, sigmay, r, varargin)
pairs = { ...
'angstart' 0 ; ...
'angend' 360 ; ...
'useC' 0 ; ...
'filled' 0 ; ...
'alph' 1 ; ...
'nth_sigma' 1 ; ...
'drawline' 0 ; ...
}; parseargs(varargin, pairs);
if ~isempty(find(isnan(sigmax(:)))) || ...
(nargin>2 && ~isempty(find(isnan(sigmay(:))))),
hout = [];
return;
end;
npoints = 100;
X = zeros(2, npoints+1);
p = zeros(2,1);
if nargin <= 2 || useC,
covar = sigmax;
else
covar = [sigmax^2, r*sigmax*sigmay; ...
r*sigmax*sigmay, sigmay^2];
end;
[E, D] = eig(covar);
D = nth_sigma * sqrt(D); % sigma, not sigma^2
for i=1:npoints
theta = (angend - angstart)*(i-1)/(npoints-1) + angstart;
theta = pi*theta/180;
p(1) = D(1,1) * cos(theta);
p(2) = D(2,2) * sin(theta);
X(:,i) = E*p;
end;
if rem(angend,360) == rem(angstart,360),
X(:,end) = X(:,1);
else
X = X(:,1:end-1);
end;
if drawline, edgecolor = 'k'; else edgecolor = 'none'; end;
if filled,
h = patch(X(1,:)+mean(1), X(2,:)+mean(2), 'r', 'FaceAlpha', min(1, alph), 'EdgeColor', edgecolor);
else
h = line(X(1,:)+mean(1), X(2,:)+mean(2));
end;
if nargout > 0,
hout = h;
end;
|
github
|
erlichlab/elutils-master
|
shadeplot2.m
|
.m
|
elutils-master/+draw/shadeplot2.m
| 8,902 |
utf_8
|
5dd5f789c4d2ec7140fb7028dc7f27ec
|
function fhand=shadeplot2(x,y1,y2,varargin)
%
% shadeplot2(x,y1,y2,settings)
% plots two shaded regions without the use of alpha, this allows the renderer to be
% set as painters rather than openGL, giving a vector rather than raster image.
% use shadeplot to quickly view graphs and choose colors, use shadeplot2 for final
% rendered plot.
% calls my_shadeplot over and over again onto the same figure to draw each region
% relies on find_blocks in order to find contiguous regions of overlapping and
% non-overlapping regions.
% relies on mydeal to instantiate variables from structure called "options"
% relies on find_xcross for interpolating between boundaries of overlapping and
% non-overlapping regions.
% x - x vector
% y1 - 2 by x vector, 1st row contains lower bound, 2nd row contains upper bounds
% y2 - "
% options
% .colors - 3x3 matrix, each row is an rgb color for y1, y2, and intersection, respectively
% .fhand - figure handle to plot into, if not specified creates new one
%
% Written by Joseph Jun, 09.23.2008
%
inpd = @utils.inputordefault;
colors = inpd('colors',[0.498*ones(1,3); 0.898*ones(1,3); 0.647*ones(1,3)],varargin);
fhand = inpd('fhand', [], varargin);
if isempty(fhand)
fhand=axes;
end
if size(x,1)>size(x,2), x=x'; end
if size(y1,1)>size(y1,2), y1=y1'; end
if size(y2,1)>size(y2,2), y2=y2'; end
nx=length(x);
isOverlap=true(1,nx); % true whenever bounds overlap
dy.ll=y1(1,:)-y2(1,:); % the four combinations of differences between lower and upper bounds of curve 1 and 2
dy.lh=y1(1,:)-y2(2,:);
dy.hl=y1(2,:)-y2(1,:);
dy.hh=y1(2,:)-y2(2,:);
blocks.non = dy.lh>0 | dy.hl<0; % all bins where curves do not overlap
blocks.o12 = dy.hh>0 & dy.lh<0 & dy.ll>0; % curves overlap with 1 on top
blocks.o21 = dy.hh<0 & dy.hl>0 & dy.ll<0; % curves overlap with 2 on top
blocks.i12 = dy.hh<=0 & dy.ll>=0; % curves overlap with 1 inside of 2
blocks.i21 = dy.hh>=0 & dy.ll<=0; % curves overlap with 2 inside of 1
% calculate curves of overlapping regions
% c1 and c2 are 1D vectors that define upper (c2) and lower (c1) bounds of overlapped curves
c2(blocks.o12)=y2(2,blocks.o12); % 1 over 2
c1(blocks.o12)=y1(1,blocks.o12);
c2(blocks.o21)=y1(2,blocks.o21); % 2 over 1
c1(blocks.o21)=y2(1,blocks.o21);
c2(blocks.i12)=y1(2,blocks.i12); % 1 inside 2
c1(blocks.i12)=y1(1,blocks.i12);
c2(blocks.i21)=y2(2,blocks.i21); % 2 inside 1
c1(blocks.i21)=y2(1,blocks.i21);
% fill in non-overlapping points for interpolation of boundaries between blocks
temp=blocks.non & dy.lh>=0;
c1(temp)=y1(1,temp);
c2(temp)=y2(2,temp);
temp=blocks.non & dy.hl<=0;
c1(temp)=y2(1,temp);
c2(temp)=y1(2,temp);
hold on;
% -------- first plot y1 then y2 as shade plots
my_shadeplot(x,y1(1,:),y1(2,:),{colors(1,:),fhand,1});
my_shadeplot(x,y2(1,:),y2(2,:),{colors(2,:),fhand,1});
% -------- next plot over the two curves wherever there is an overlap (must be done in blocks)
if sum(~blocks.non)>0
[b,v]=find_blocks(blocks.non); % each row of b has where blocks are, v has whether block is overlapping (false) or non (true)
nb=length(v);
for k=1:nb
if ~v(k)
if sum(b(k,:))>1
my_shadeplot(x(b(k,:)), c1(b(k,:)),c2(b(k,:)), {colors(3,:),fhand,1});
end
end
end
end
% -------- now worry about interpolation inbetween discretization
% ---- first detect any intersection of lines
isll = dy.ll.*[dy.ll(2:end) dy.ll(end)]<0;
islh = dy.lh.*[dy.lh(2:end) dy.lh(end)]<0;
ishl = dy.hl.*[dy.hl(2:end) dy.hl(end)]<0;
ishh = dy.hh.*[dy.hh(2:end) dy.hh(end)]<0;
inds=find(isll | islh | ishl | ishh);
ninds=length(inds);
for k=1:ninds
il=inds(k);
ir=inds(k)+1;
xl=x(il);
xr=x(ir);
templateType=0;
% ---- check to see what kind of overlap exists, create new labeled lines that push
% intersections into templates
if y1(2,il)<y2(1,il)
gy=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
ry=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=1;
elseif y2(2,il)<y1(1,il)
ry=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
gy=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=1;
elseif y1(1,il)>y2(1,il) && y1(1,il)<y2(2,il) && y1(2,il)>y2(2,il)
gy=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
ry=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=2;
elseif y2(1,il)>y1(1,il) && y2(1,il)<y1(2,il) && y2(2,il)>y1(2,il)
ry=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
gy=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=2;
elseif y1(1,il)>y2(1,il) && y1(1,il)<y2(2,il) && y1(2,il)>y2(1,il) && y1(2,il)<y2(2,il)
gy=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
ry=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=3;
elseif y2(1,il)>y1(1,il) && y2(1,il)<y1(2,il) && y2(2,il)>y1(1,il) && y2(2,il)<y1(2,il)
ry=[y1(1,il) y1(1,ir); y1(2,il) y1(2,ir)];
gy=[y2(1,il) y2(1,ir); y2(2,il) y2(2,ir)];
templateType=3;
end
[xll yll]=calc_xcross([xl xr],gy(1,:),[xl xr],ry(1,:));
[xlh ylh]=calc_xcross([xl xr],gy(1,:),[xl xr],ry(2,:));
[xhl yhl]=calc_xcross([xl xr],gy(2,:),[xl xr],ry(1,:));
[xhh yhh]=calc_xcross([xl xr],gy(2,:),[xl xr],ry(2,:));
if xll<xl || xll>xr, xll=[]; yll=[]; end
if xlh<xl || xlh>xr, xlh=[]; ylh=[]; end
if xhl<xl || xhl>xr, xhl=[]; yhl=[]; end
if xhh<xl || xhh>xr, xhh=[]; yhh=[]; end
switch templateType
case 1 % case where green is below red and not intersecting
if isempty(xll)
if isempty(xhh), px=[xhl xr xr]; py=[yhl gy(2,2) ry(1,2)];
else px=[xhl xhh xr xr]; py=[yhl yhh ry(2,2) ry(1,2)];
end
else
if isempty(xhh), px=[xhl xr xr xll]; py=[yhl gy(2,2) gy(1,2) yll];
else
if isempty(xlh), px=[xhl xhh xr xr xll]; py=[yhl yhh ry(2,2) ry(1,2) yll];
else px=[xhl xhh xlh xll]; py=[yhl yhh ylh yll];
end
end
end
case 2 % case where green straddles red from below
if ~isempty(xlh)
px=[xl xl xlh]; py=[gy(1,1) ry(2,1) ylh];
else
if isempty(xll)
px=[xl xl xhh xr xr]; py=[gy(1,1) ry(2,1) yhh gy(2,2) gy(1,2)];
else
if isempty(xhh)
px=[xl xl xr xr xll]; py=[gy(1,1) ry(2,1) ry(2,2) ry(1,2) yll];
else
if isempty(xhl)
px=[xl xl xhh xr xr xll]; py=[gy(1,1) ry(2,1) yhh gy(2,2) ry(1,2) yll];
else
px=[xl xl xhh xhl xll]; py=[gy(1,1) ry(2,1) yhh yhl yll];
end
end
end
end
case 3
if isempty(xhh)
if isempty(xhl)
px=[xl xl xr xr xll]; py=[gy(1,1) gy(2,1) gy(2,2) ry(1,2) yll];
else
px=[xl xl xhl xll]; py=[gy(1,1) gy(2,1) yhl yll];
end
else
if isempty(xll)
if isempty(xlh)
px=[xl xl xhh xr xr]; py=[gy(1,1) gy(2,1) yhh ry(2,2) gy(1,2)];
else
px=[xl xl xhh xlh]; py=[gy(1,1) gy(2,1) yhh ylh];
end
else
px=[xl xl xhh xr xr xll]; py=[gy(1,1) gy(2,1) yhh ry(2,2) ry(1,2) yll];
end
end
end
patch(fhand,px,py,colors(3,:),'linestyle','none');
end
% -------- return a VECTOR graphic hurray!
set(gcf,'renderer','painters');
function h=my_shadeplot(x,y1,y2,opt)
% function h=shadeplot(x,y1,y2,opt)
% you need x, sorry
% y1, y2 can be for example lower and upper confidence intervals.
% opt={color, fighandle, alpha}
if nargin <4
h=axes;
clr='k';
alp=0.5;
else
h=opt{2};
alp=opt{3};
clr=opt{1};
end
y2=y2(:)-y1(:);
y1=y1(:);
Y=[y1, y2];
h1=area(h,x,Y);
set(h1(2),'EdgeColor','none','FaceColor',clr);
if ~isempty(alp), alpha(alp); end
set(h1(1),'EdgeColor','none','FaceColor','none');
function [b,v]=find_blocks(x)
%
% [b,v]=find_blocks(x)
% x - single dimensional vector, assumed to be row
% b - boolean matrix containing one row for each discovered block,
% and one column for each element of x, true means that element belongs in the block
%
x=x(:)';
nx=length(x);
cval=x(1);
block_beg=1;
nblocks=0;
if isnumeric(x(end)), x(end+1)=x(end)+1;
else x(end+1)=~x(end);
end
for k=1:(nx+1)
if x(k)~=cval
nblocks=nblocks+1;
b(nblocks,:)=false(1,nx);
b(nblocks,block_beg:(k-1))=true;
block_beg=k;
v(nblocks)=cval;
cval=x(k);
end
end
if block_beg==1, b=true(1,nx); end
v=v';
function [xstar,ystar]=calc_xcross(x,y,u,v)
%
% [xstar,ystar]=calc_xcross(x,y,u,v)
% calculates where two lines cross and value at meeting point
% x - 2 element vector, defines x-coord of 1st line
% y - 2 element vector, defines y-coord of 1st line
% u - 2 element vector, defines x-coord of 2nd line
% v - 2 element vector, defines y-coord of 2nd line
%
y0=(y(1)*x(2)-y(2)*x(1))/(x(2)-x(1));
v0=(v(1)*u(2)-v(2)*u(1))/(u(2)-u(1));
a=(y(2)-y(1))/(x(2)-x(1));
b=(v(2)-v(1))/(u(2)-u(1));
xstar=(y0-v0)/(b-a);
ystar=y0+a*xstar;
|
github
|
erlichlab/elutils-master
|
histsig.m
|
.m
|
elutils-master/+draw/histsig.m
| 2,024 |
utf_8
|
316408eb6cf67188ef14a168aadd6c59
|
function [ hx]=histsig(x, x_sig, varargin)
% [ hx]=histsig(x, x_sig, x_lim)
inpd = @utils.inputordefault;
[origin, args]=inpd('origin', 0.1, varargin);
[wdth, args]=inpd('width',0.2,args);
[hist_h, args]=inpd('height',0.180,args);
[num_bins, args]=inpd('n_bins',17,args);
[bins, args]=inpd('bins',[],args);
[ax, args]=inpd('ax',[],args);
[x_lim, args]=inpd('x_lim',[],args);
[y_lim, args]=inpd('y_lim',[],args);
[normed, args]=inpd('normed',false,args);
[zero, args]=inpd('zero',0,args);
[pval_threshold,args] = inpd('pval_threshold','.05',args);
inpd(args)
gd=~isnan(x);
x=x(gd);
x_sig=x_sig(gd);
x_lim_b=[min(x)-0.1 max(x)+0.1];
if isempty(x_lim)
x_lim=x_lim_b;
end
if isempty(ax)
ax=draw.jaxes([origin origin wdth hist_h]);
end
marker_size=zeros(size(x))+12;
marker_size(x_sig==1)=24;
% make the x-axis histogram
if isempty(bins)
bins=linspace(x_lim_b(1),x_lim_b(2),num_bins);
end
nsig=histcounts(x(x_sig==0), bins);
sig=histcounts(x(x_sig==1), bins);
if normed
total = sum(nsig) + sum(sig);
nsig = nsig / total;
sig = sig / total;
end
maxy=max(nsig(:)+sig(:))*1.3;
cbins=edge2cen(bins);
[hh]=bar(ax,cbins, [sig(:) nsig(:)],'stacked');
xlim(ax,x_lim);
set(ax, 'YAxisLocation','left');
set(hh(1),'FaceColor','k')
set(hh(2),'FaceColor',[1 1 1])
if isempty(y_lim)
y_lim = [0 maxy];
end
set(ax,'box','off','YLim',y_lim)
set(ax,'Color','none')
text(ax, getx(ax),gety(ax),sprintf('%d%% p<%s, n=%d',round(100*mean(x_sig)),pval_threshold,sum(~isnan(x))))
%text(ax, getx(ax),gety(ax),[num2str(round(100*mean(x_sig))) '% p<0.05'])
x_mean=nanmean(x);
[xt_sig,~,B]=stats.bootmean(x-zero);
[CI]=prctile(B+zero,[2.5 97.5]);
if xt_sig<0.05
y_lim=ylim(ax);
y_pos=0.85 * y_lim(2);
plot(ax,x_mean, y_pos,'.k','MarkerSize',6);
plot(ax,[CI(1) CI(2)], [y_pos y_pos], '-k');
end
function y=edge2cen(x)
b2b_dist=x(2)-x(1);
y=x+0.5*b2b_dist;
y=y(1:end-1);
function y=getx(ax)
x=xlim(ax);
y=0.03*(x(2)-x(1))+x(1);
function y=gety(ax)
x=ylim(ax);
y=1.1*(x(2)-x(1))+x(1);
|
github
|
erlichlab/elutils-master
|
isosum_psycho.m
|
.m
|
elutils-master/+draw/isosum_psycho.m
| 2,131 |
utf_8
|
26192d5421145a85a198eccfe1297c00
|
% [X Y E]= isosum_psycho(x1,x2,wr,varargin)
% A function to plot psychometrics with isosum lines.
function [X Y E bfit bci]= isosum_psycho(x1,x2,wr,varargin)
nsumbins=5;
sum_bin_e=[];
x_bin_e=[];
nxbins=6;
ax=[];
plot_it=true;
clrs=[.85 0 0;
0 .1 .8;
0 .8 .1;
.8 0 1;
1 .5 0;
0 0 0;
];
fit=false;
mod=@erf3;
beta=[0 1 0.5];
model_marker_size=0.3;
data_marker_size=2;
utils.overridedefaults(who,varargin);
if isempty(ax) && plot_it
ax=axes;
end
if isempty(clrs)
clrs=clrs(1:nsumbins,:) ;
end
sumx=x1+x2;
diffx=x2-x1;
if isempty(sum_bin_e)
pbins=linspace(0,100,nsumbins+1);
sum_bin_e=prctile(sumx,pbins);
end
if isempty(x_bin_e)
pbins=linspace(0,100,nxbins+1);
x_bin_e=prctile(diffx,pbins);
end
Y=nan(nsumbins,nxbins);
E=Y;
X=Y;
set(ax,'NextPlot','add');
if fit
[bfit,resid,J,Sigma]=nlinfit([x1 x2],wr,mod,beta);
bci=nlparci(bfit,resid,'covar',Sigma);
[ll,bb]=loglikelihood(mod(bfit,[x1 x2]),wr,numel(beta));
fprintf('The BIC is %0.2f\n',bb);
fprintf('The -LL is %0.2f\n',-ll);
else
bfit=0;
bci=[0 0];
end
for sx=1:nsumbins
gt=sumx>=sum_bin_e(sx) & sumx<sum_bin_e(sx+1);
dc=diffx(gt);
x_bin_e=prctile(dc,pbins);
[X(sx,:) Y(sx,:) E(sx,:)]=binned(dc,wr(gt),'bin_e',x_bin_e);
if plot_it
if fit
mp=plot(ax,dc,mod(bfit,[x1(gt) x2(gt)]),'.','Color',(clrs(sx,:)+1)/2);
set(mp,'MarkerSize',model_marker_size);
end
he=draw.errorplot(ax,X(sx,:)+0.2*sx,Y(sx,:), E(sx,:),'Color',clrs(sx,:),'Marker','o');
set(he(2),'MarkerFaceColor',clrs(sx,:),'MarkerSize',data_marker_size);
end
end
if fit
ch=get(ax,'Children');
mch=findobj(ch,'Marker','.');
cdh=setdiff(ch,mch);
set(ax,'Children',[cdh; mch]);
end
function y=erf2(b,x)
lapse=b(1);
gain=b(2);
ipsC=x(:,1);
conC=x(:,2);
inp=gain*(conC-ipsC)./(ipsC+conC).^0.5;
y=lapse + (1-2*lapse)*(0.5*(erf(inp)+1));
function y=erf3(b,x)
lapse=b(1);
gain=b(2);
noise=b(3);
ipsC=x(:,1);
conC=x(:,2);
inp=gain*(conC-ipsC)./(ipsC+conC).^noise;
y=lapse + (1-2*lapse)*(0.5*(erf(inp)+1));
|
github
|
erlichlab/elutils-master
|
unity.m
|
.m
|
elutils-master/+draw/unity.m
| 474 |
utf_8
|
a15b90de629093e2f2703b1e54bcfe07
|
% This function draws an unity line on the plot.
%h=unity(ax,s)
% ax (optional) plot to this axis, default gca
% s (optional) use this linestyle, default ':k'
function h=unity(ax,s)
if nargin<2
s=':k';
end
if nargin<1
ax=gca;
end
bax=ax;
for axx=1:numel(bax)
ax=bax(axx);
oldhold=get(ax,'NextPlot');
xlim=get(ax, 'XLim');
ylim=get(ax, 'YLim');
hold(ax,'on')
ll=min([xlim ylim]);
ul=max([xlim ylim]);
h=plot(ax,[ll ul],[ll ul],s);
set(ax,'NextPlot',oldhold);
end
|
github
|
erlichlab/elutils-master
|
task_timing.m
|
.m
|
elutils-master/+draw/task_timing.m
| 1,446 |
utf_8
|
fda761f48f0aeadf229643406b1b62b1
|
function task_timing(statetable, varargin)
% draw.task_timing(statetable)
%
% names = { "Start Cue", "Nose in Fixation","Target Cue","Go Sound", "Nose in Target"}';
% start_state = [ 0, 0.15, 0.3, 1.3, 1.65]';
% stop_state = [ 0.15, 1.5, 1.65, 1.35, 1.8]';
% color = cellfun(@(x)x/255, {[48, 110, 29], [0,0,0], [48, 122, 242], [241, 151, 55],[140,40,93]}, 'UniformOutput',0)';
%
% T = table(names, start_state, stop_state, color);
%
% draw.task_timing(T)
%
% % You can adjust the width after using Position
% set(gca,'Position',[0.1 0.1 0.3 0.7])
% saveas(gcf, 'mytask.pdf')
if nargin==0
names = {"Test State"};
color = {'r'};
start_state = 0;
stop_state = 0.3;
statetable = table(names, color, start_state, stop_state);
end
clf;
ax = draw.jaxes;
for x = 1:size(statetable,1)
plot_state(ax,statetable(x,:), -0.2, max(statetable.stop_state)+0.2, 9.5-x)
end
plot(ax,[0 0.5],[9-x 9-x],'k','LineWidth',2);
sh = text(0.25,8.5-x,'0.5 s');
sh.HorizontalAlignment = 'center';
ax.Visible = 'off';
ax.YLim = [-1 10];
end
function [lh, th] = plot_state(ax, row, pre , post, ypos)
startx = row.start_state;
stopx = row.stop_state;
color = row.color{1};
sname = row.names{1};
x = [pre, startx, startx, stopx, stopx, post];
y = ypos + [0, 0, 0.6, 0.6, 0, 0];
lh = plot(ax, x,y, 'Color',color,'LineWidth',2);
th = text((pre)/2,ypos + 0.3, sname);
set(th,'Color',color,'HorizontalAlignment','right','FontWeight','bold');
end
|
github
|
erlichlab/elutils-master
|
psychoplot4.m
|
.m
|
elutils-master/+draw/psychoplot4.m
| 2,729 |
utf_8
|
c0531293fb3a8721188984342248cd17
|
function varargout=psychoplot4(x_vals, varargin)
% [stats]=psychoplot4(x_vals, went_right)
% [stats]=psychoplot4(x_vals, hits, sides)
%
% Fits a 4 parameter sigmoid to psychophysical data
%
% x_vals the experimenter controlled value on each trial.
% went_right a vector of [0,1]'s the same length as x_vals describing
% the response on that trials
% OR
%
% hits a vector of the correct/incorrect history as [0,1,nan]'s.
% Nans are exluded automatically
% sides a vector of [-1, 1]'s or ['LR']'s that say what the subject
% should have done on that trial
%
% The sigmoid is of the form
% y=y0+a./(1+ exp(-(x-x0)./b));
%
% y0=beta(1) sets the lower bound
% a=beta(2) a+y0 is the upper bound
% x0=beta(3) is the bias
% b=beta(4) is the slope
if nargin==2
went_right=varargin{1};
elseif nargin==3
hits=varargin{1};
sides=varargin{2};
gd=~isnan(hits);
hits=hits(gd);
sides=sides(gd);
x_vals=x_vals(gd);
if isnumeric(sides(1))
went_right=(hits==1 & sides==1) | (hits==0 & sides==-1);
else
sides=lower(sides);
went_right=(hits==1 & sides=='r') | (hits==0 & sides=='l');
end
end
[beta,resid,jacob,sigma,mse] = nlinfit(x_vals,went_right,@sig4,[0.1 .8 nanmean(x_vals) 10]);
x_s=linspace(min(x_vals), max(x_vals), 100);
[y_s,delta] = nlpredci(@sig4,x_s,beta,resid,'covar',sigma);
betaci = nlparci(beta,resid,'covar',sigma);
S.beta=beta;
S.betaci=betaci;
S.resid=resid;
S.mse=mse;
S.sigma=sigma;
S.ypred=y_s;
S.y95ci=delta;
fig_h=figure;
trial_types = unique(x_vals);
if numel(trial_types) > numel(went_right)*0.1,
sortedM=sortrows([x_vals(:) went_right(:)]);
rawD=jconv(normpdf(-10:10, 0, 2), sortedM(:,2)');
ax=plot(sortedM(:,1), rawD,'o');
else
meanD=zeros(size(trial_types));
seD=meanD;
for tx = 1:numel(trial_types),
meanD(tx) = mean(went_right(x_vals == trial_types(tx)));
%seD(tx) = stderr(went_right(x_vals == trial_types(tx)));
% it doesn't make sense to take the stderr of a bernoulli variable.
% instead , just make the error bars 1/sqrt(n);
seD(tx) = sqrt(meanD(tx)*(1-meanD(tx))/sum(x_vals == trial_types(tx)));
end;
ax=errorbar(trial_types, meanD,seD);
set(ax,'MarkerSize', 15);
set(ax,'LineStyle','none')
set(ax,'Marker','.')
end;
hold on
x_s=x_s(:);
y_s=y_s(:);
delta=delta(:);
plot(x_s, y_s,'k');
plot(x_s,y_s-delta,'k:');
plot(x_s,y_s+delta,'k:');
ylim([0 1]);
ylabel('% went right')
set(gca,'YTickLabel',[0:10:100]);
if nargout>=1
varargout{1}=S;
end
if nargout>=2
varargout{2}=ax;
end
function y=sig4(beta,x)
y0=beta(1);
a=beta(2);
x0=beta(3);
b=beta(4);
y=y0+a./(1+ exp(-(x-x0)./b));
|
github
|
erlichlab/elutils-master
|
twodcomp.m
|
.m
|
elutils-master/+draw/twodcomp.m
| 2,055 |
utf_8
|
a7d4f275c6ed7c0318d26d909ff0fa0a
|
function ax=twodcomp(A,B,varargin)
plot_type='surf';
plot_ax='v';
ax_h=0.2;
ax_w=0.2;
ax_h_off=0.1;
ax_w_off=0.1;
x=1:size(A,2);
y=1:size(A,1);
fig=[];
gap=0.05;
cmin=min([A(:);B(:);B(:)-A(:)]);
cmax=max([A(:);B(:);B(:)-A(:)]);
ax=[];
plot_colorbar=false;
utils.overridedefaults(who,varargin)
if isempty(fig)
fig=figure;
end
if isempty(ax)
ax=make_axes(plot_ax,ax_w,ax_h,gap,ax_w_off,ax_h_off);
end
switch plot_type,
case 'img'
imagesc(x,y,A,'parent',ax(3));
imagesc(x,y,B,'parent',ax(2)); %colorbar('peer',ax(2));
imagesc(x,y,B-A,'parent',ax(1));%colorbar('peer',ax(3));
set(ax,'CLim',[cmin,cmax]);
axis(ax,'xy');
if plot_colorbar
pos=get(ax(3),'Position');
colorbar('peer',ax(3),'Position',[pos(1)+pos(3)+0.01 pos(2) 0.03 pos(4)]);
end
case 'surf'
surf(ax(3),x,y,A);
surf(ax(2),x,y,B); %colorbar('peer',ax(2));
surf(ax(1),x,y,B-A);%colorbar('peer',ax(3));
set(ax,'CLim',[cmin,cmax]);
axis(ax,'xy');
if plot_colorbar
pos=get(ax(3),'Position');
colorbar('peer',ax(3),'Position',[pos(1)+pos(3)+0.01 pos(2) 0.03 pos(4)]);
end
case 'scatter'
switch style
case 'plane'
plot(ax(1),A(:),B(:),'.');
delete(ax(2));
delete(ax(3));
unity(ax(1));
end
end
function ax=make_axes(a,ax_w,ax_h,gap,ax_w_off,ax_h_off)
if a=='h'
ax(1)=axes('Position',[ax_w_off ax_h_off ax_w ax_h]);
ax(2)=axes('Position',[ax_w_off+ax_w+gap ax_h_off ax_w ax_h]);
ax(3)=axes('Position',[ax_w_off+2*ax_w+2*gap ax_h_off ax_w ax_h]);
else
ax(1)=axes('Position',[ax_w_off ax_h_off ax_w ax_h]);
ax(2)=axes('Position',[ax_w_off ax_h_off+ax_h+gap ax_w ax_h]);
ax(3)=axes('Position',[ax_w_off ax_h_off+2*ax_h+2*gap ax_w ax_h]);
end
|
github
|
erlichlab/elutils-master
|
scatter_histhist.m
|
.m
|
elutils-master/+draw/scatter_histhist.m
| 2,816 |
utf_8
|
9c312dad3bd2fb8084a228d6f093dac5
|
function [hm, hx, hy]=scatter_histhist(x, x_sig, y,y_sig, varargin)
% [hm, hx, hy]=scatter_histhist(x, x_sig, y,y_sig, x_lim, y_lim)
% Optional arguments:
% width, hist_height, num_bins, x_label, y_label
%
% E.g
% x = randn(150,1)*2;
% y = randn(250,1)*4+3;
% y = randn(150,1)*4+3;
% xsig = abs(x)>2;
% ysig = y<0;
% draw.scatter_histhist(x,xsig,y,ysig,'x_label','X','y_label','Y')
iod = @utils.inputordefault;
org=iod('org',0.15, varargin);%by default, orgy=org(x)
orgy=iod('orgy',[], varargin);
wdth=iod('width',0.5,varargin);
hist_h=iod('hist_height',0.2,varargin);
num_bns=iod('num_bins',17,varargin);
x_label=iod('x_label','',varargin);
y_label=iod('y_label','',varargin);
x_lim_b=[min(x)-0.1 max(x)+0.1];
y_lim_b=[min(y)-0.1 max(y)+0.1];
x_lim = iod('x_lim',x_lim_b,varargin);
y_lim = iod('y_lim',y_lim_b,varargin);
if isempty(orgy)
orgy = org;
end
figure
hm=draw.jaxes;
hm.Position = [org orgy wdth wdth];
set(hm,'Xlim',[-1 1]);
set(hm,'Ylim',[-1 1]);
hx=axes('Position',[org orgy+wdth+0.01 wdth hist_h]);
hy=axes('Position',[org+wdth+0.01 orgy hist_h wdth]);
marker_size=zeros(size(x))+12;
marker_size(x_sig==1)=24;
marker_size(y_sig==1)=24;
marker_size(x_sig+y_sig==2)=36;
% make the scatter plot
scatter(hm,x, y, 36,'k');
xlabel(hm,x_label);
ylabel(hm,y_label);
xlim(hm,x_lim);
ylim(hm,y_lim);
draw.xhairs(hm,'k:',0,0);
axes(hm);
text(getx,gety,['n=' num2str(numel(x))])
% make the y-axis histogram
bns=linspace(y_lim_b(1),y_lim_b(2),num_bns);
nsig=histc(y(y_sig==0), bns);
nsig=nsig(1:end-1);
sig=histc(y(y_sig==1), bns);
sig=sig(1:end-1);
cbns=edge2cen(bns);
[hh]=barh(hy,cbns, [sig nsig],'stacked');
set(hy, 'YTick',[]);
ylim(hy,y_lim);
set(hy, 'XAxisLocation','bottom');
set(hh(1),'FaceColor','k')
set(hh(2),'FaceColor',[1 1 1])
set(hy,'box','off')
set(hy,'Color','none')
axes(hy);
text(getx,gety,[num2str(round(100*mean(y_sig))) '% p<0.01'])
y_mean=mean(y);
[~,yt_sig]=ttest(y);
set(hy,'NextPlot','add');
xx=get(hy,'XLim');
plot(hy,[0 xx(2)],[y_mean, y_mean],'-k');
% make the x-axis histogram
bns=linspace(x_lim_b(1),x_lim_b(2),num_bns);
nsig=histc(x(x_sig==0), bns);
nsig=nsig(1:end-1);
sig=histc(x(x_sig==1), bns);
sig=sig(1:end-1);
cbns=edge2cen(bns);
[hh]=bar(hx,cbns, [sig(:) nsig(:)],'stacked');
set(hx, 'XTick',[]);
xlim(hx,x_lim);
set(gca, 'YAxisLocation','left');
set(hh(1),'FaceColor','k')
set(hh(2),'FaceColor',[1 1 1])
set(hx,'box','off')
set(hx,'Color','none')
axes(hx);
text(getx,gety,[num2str(round(100*mean(x_sig))) '% p<0.01'])
x_mean=mean(x);
[~,xt_sig]=ttest(x);
set(hx,'NextPlot','add');
yy=get(hx,'YLim');
plot(hx, [x_mean, x_mean],[0 yy(2)],'-k');
function y=edge2cen(x)
b2b_dist=x(2)-x(1);
y=x+0.5*b2b_dist;
y=y(1:end-1);
function y=getx
x=xlim;
y=0.1*(x(2)-x(1))+x(1);
function y=gety
x=ylim;
y=0.9*(x(2)-x(1))+x(1);
|
github
|
erlichlab/elutils-master
|
mloads.m
|
.m
|
elutils-master/+json/mloads.m
| 3,833 |
utf_8
|
82b3ff741f68f9d2bac6ea80362a2e77
|
function out = mloads(jstr, varargin)
% out = mdumps(obj, ['compress'])
% function that takes a matlab object (cell array, struct, vector) and converts it into json.
% It also creates a "sister" json object that describes the type and dimension of the "leaf" elements.
if isempty(jstr)
out = {};
return;
end
if ischar(jstr)
decompress = false;
elseif char(jstr(1))=='{'
decompress = false;
jstr = char(jstr(:))';
else
decompress = true;
end
decompress = utils.inputordefault('decompress',decompress,varargin);
if decompress
jstr = char(utils.zlibdecode(jstr));
end
jstr = regexprep(jstr, '\<NaN\>', 'null');
try
bigJ = jsondecode(jstr);
builtin_flag = true;
catch
bigJ = json.fromjson(jstr);
builtin_flag = false;
end
out = bigJ.vals;
meta = bigJ.info;
if builtin_flag
out = applyinfo_bi(out, meta);
else
out = applyinfo(out, meta);
end
end
function vals = applyinfo(vals, meta)
if isfield(meta,'type__')
% Then we are a leaf node
tsize =double([meta.dim__{1} meta.dim__{2}]);
tnumel = prod(tsize);
switch(meta.type__)
case {'cell', 'struct'}
for cx = 1:tnumel
vals{cx} = applyinfo(vals{cx}, meta.cell__{cx});
end
if strcmp(meta.type__, 'struct') % This is a struct array
vals = [vals{:}];
end
vals = reshape(vals, tsize);
case 'char'
vals = char(vals);
case 'double'
if tnumel == 1
vals = double(vals);
else
vals = double([vals{:}]);
vals = reshape(vals, tsize);
end
otherwise
f = @(x) cast(x, meta.type__);
if tnumel == 1 || strcmp(meta.type__, 'char')
vals = f(vals);
else
vals = cellfun(f, vals);
% vals = cell2mat(vals);
vals = reshape(vals, tsize);
end
end
else
fnames = fieldnames(meta);
for fx = 1:numel(fnames)
vals.(fnames{fx}) = applyinfo(vals.(fnames{fx}), meta.(fnames{fx}));
end
end
end
function vals = applyinfo_bi(vals, meta)
if iscell(meta)
meta = meta{1};
end
if isfield(meta,'type__')
% Then we are a leaf node
tsize =meta.dim__(:)';
tnumel = prod(tsize);
switch(meta.type__)
case {'cell', 'struct'}
newvals=cell(tnumel,1);
for cx = 1:tnumel
if iscell(vals)
newvals{cx} = applyinfo_bi(vals{cx}, meta.cell__(cx));
else
newvals{cx} = applyinfo_bi(vals(cx), meta.cell__(cx));
end
end
if strcmp(meta.type__, 'struct') % This is a struct array
newvals = [newvals{:}];
end
vals = reshape(newvals, tsize);
case 'char'
vals = char(vals);
case {'double','single','logical'}
if ~isempty(vals) && prod(tsize)>1
vals = reshape(vals, tsize);
end
otherwise
f = @(x) cast(x, meta.type__);
if tnumel == 1 || strcmp(meta.type__, 'char')
vals = f(vals);
else
vals = cellfun(f, vals);
% vals = cell2mat(vals);
vals = reshape(vals, tsize);
end
end
else
fnames = fieldnames(meta);
for fx = 1:numel(fnames)
vals.(fnames{fx}) = applyinfo_bi(vals.(fnames{fx}), meta.(fnames{fx}));
end
end
end
|
github
|
erlichlab/elutils-master
|
mdumps.m
|
.m
|
elutils-master/+json/mdumps.m
| 2,894 |
utf_8
|
8b81ff9b34a969aa5abdc3df1b2797f2
|
function out = mdumps(obj, varargin)
% out = mdumps(obj, ['compress'])
% function that takes a matlab object (cell array, struct, vector) and converts it into json.
% It also creates a "sister" json object that describes the type and dimension of the "leaf" elements.
% Warning: Simple cell arrays (e.g. cell-arrays of strings or scalar numbers) are supported. However, cell arrays of more complex types (cell-arrays, structs, matrices)
% Note: complex numbers should be converted into 2-vectors
if isempty(obj)
out = [];
return;
end
compress = false;
thorough = true;
utils.overridedefaults(who, varargin);
if thorough
[meta, obj] = get_info_flatten_thorough(obj);
else
[meta, obj] = get_info_flatten(obj);
end
TO.vals = obj;
TO.info = meta;
try
out = jsonencode(TO);
catch
out = json.tojson(TO);
end
if compress
out = utils.zlibencode(out);
end
end
function [M, S] = get_info_flatten(S)
if isnumeric(S) || ischar(S) || islogical(S) || iscell(S)
[M.type__, M.dim__] = getleafinfo(S);
S = S(:);
elseif isstruct(S) && numel(S)==1
fnames = fieldnames(S);
for fx = 1:numel(fnames)
[M.(fnames{fx}), S.(fnames{fx})] = get_info_flatten(S.(fnames{fx}));
end
elseif isstruct(S) % and numel is > 1, this is a struct array
[M.type__, M.dim__] = getleafinfo(S);
S = arrayfun(@(x){x},S); % Convert to cell array of struct
S = S(:);
elseif isobject(S)
S = struct(S);
[M.type__, M.dim__] = getleafinfo(S);
S = arrayfun(@(x){x},S); % Convert to cell array of struct
S = S(:);
else
[M.type__, M.dim__] = getleafinfo(S);
error('json:mdumps','Do not know how to handle data of type %s', M.type)
end
end
function [M, S] = get_info_flatten_thorough(S)
if isnumeric(S) || ischar(S) || islogical(S)
[M.type__, M.dim__] = getleafinfo(S);
S = S(:);
elseif isstruct(S) && numel(S)==1
fnames = fieldnames(S);
for fx = 1:numel(fnames)
[M.(fnames{fx}), S.(fnames{fx})] = get_info_flatten_thorough(S.(fnames{fx}));
end
elseif iscell(S) || isstruct(S)
[M.type__, M.dim__] = getleafinfo(S);
if isstruct(S)
S = arrayfun(@(x){x},S);
end
S = S(:);
for cx = 1:numel(S)
[M.cell__{cx}, S{cx}] = get_info_flatten_thorough(S{cx});
end
elseif isobject(S)
S = struct(S);
fnames = fieldnames(S);
for fx = 1:numel(fnames)
[M.(fnames{fx}), S.(fnames{fx})] = get_info_flatten_thorough(S.(fnames{fx}));
end
else
[M.type__, M.dim__] = getleafinfo(S);
error('json:mdumps','Do not know how to handle data of type %s', M.type__)
end
end
function [ttype, tsize] = getleafinfo(leaf)
ttype = class(leaf);
tsize = size(leaf);
end
|
github
|
erlichlab/elutils-master
|
showerror.m
|
.m
|
elutils-master/+utils/showerror.m
| 639 |
utf_8
|
c92f2f93b75dac33946442eaacee08f3
|
function out = showerror(le, varargin)
if nargin==0
le=lasterror;
end
[print_stack, args] = utils.inputordefault('print_stack', true, varargin);
utils.inputordefault(args)
if nargout > 0
out = sprintf('\n%s \n%s\n',le.identifier, le.message);
if print_stack
for xi=1:numel(le.stack)
out = sprintf('%s On line %i of %s\n',out, le.stack(xi).line, le.stack(xi).file);
end
end
else
fprintf(1,'\n%s \n%s\n',le.identifier, le.message);
if print_stack
for xi=1:numel(le.stack)
fprintf(1,'On line %i of %s\n',le.stack(xi).line, le.stack(xi).file);
end
end
end
|
github
|
erlichlab/elutils-master
|
date_diff.m
|
.m
|
elutils-master/+utils/date_diff.m
| 1,805 |
utf_8
|
1f82c41c56b44b8e57ed1e0569bc93c5
|
function out = date_diff(date1, date2, interval)
% out = date_diff(date1, date2, interval)
% Inputs
% date1 a date in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format
% date2 a date in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format
% interval one of 'year','day','hour','minute','second'
%
% Note: date1 and date2 can either be date character arrays or cell
% arrays (must be same size or only one should be a cell array)
% if they are both arrays the diff is taken element-wise. if only one is an
% array then the scalar date is compared to all elements of the array.
%
% Output
% The time passed from date2 to date1 in units of interval
if iscell(date1) && iscell(date2) % two cell arrays
assert(isequal(size(date1),size(date2)),'date1 and date2 must have same size');
out = cellfun(@(x,y)date_diff_int(x,y,interval),date1,date2);
elseif iscell(date1) % date1 is a cell
assert(ischar(date2),'If date2 is not a cell array it must be a char');
out = cellfun(@(x)date_diff_int(x,date2,interval),date1);
elseif iscell(date2) % date2 is a cell
assert(ischar(date1),'If date1 is not a cell array it must be a char');
out = cellfun(@(x)date_diff_int(date1,x,interval),date2);
else
out = date_diff_int(date1,date2,interval);
end
end
function out = date_diff_int(date1,date2,interval)
out_in_days = datenum(date1) - datenum(date2);
switch lower(interval(1:2)) % I only take the first 2 char to allow for plural.
case 'ye' %years
out = out_in_days / 365;
case 'da' %days
out = out_in_days;
case 'ho' %hours
out = out_in_days*24;
case 'mi' %minutes
out = out_in_days*24*60;
case 'se' %seconds
out = out_in_days*24*60*60;
otherwise
error('utils:date_diff','Do not know about interval %s',interval);
end
end
|
github
|
erlichlab/elutils-master
|
overridedefaults.m
|
.m
|
elutils-master/+utils/overridedefaults.m
| 3,788 |
utf_8
|
b307fdb8db5be4b0fa55b1d70d931d3a
|
%parseargs [opts] = overridedefaults(varnames, arguments, ignore_unknowns)
%
% Variable argument parsing
%
% function is meant to be used in the context of other functions
% which have variable arguments. Typically, the function using
% variable argument parsing would be written with the following
% header:
%
% function myfunction(args, ..., varargin)
%
% and would set up some default values for variables:
% bin_size = 0.1;
% thresh = 2;
%
% overridedefaults(whos, varargin);
%
%
% varargin can be of two forms:
% 1) A cell array where odd entries are variable names and even entries are
% the corresponding values
% 2) A struct where the fieldnames are the variable names and the values of
% the fields are the values (for pairs)
%
%
% OVERRIDEDEFAULTS USES ASSIGNIN COMMANDS TO CHANGE OR SET VALUES OF
% VARIABLES IN THE CALLING FUNCTION'S SPACE! THE RETURN VALUES ARE INTENDED
% FOR ACCOUNTING PURPOSES ONLY AND USE OF THEM IS NOT CRITICAL FOR THE
% CODE'S PRIMARY FUNCTIONALITY.
%
% OUTPUT:
%
% opts: Optional output that is a variable with fields corresponding to
% each varname passed in or newly created varname. Values of
% those fields are the final assigned value of the corresponding
% varname variable.
%
% PARAMETERS:
% -----------
% -varnames The list of variable names which are defined in the
% calling function
% -arguments The varargin list, I.e. a row cell array.
% value for the variable.
%
%
% Example:
% --------
% Let's say i have a function foo
% function foo(x,varargin)
% a = 5;
% b= 1;
% overridedefaults(whos, varargin);
%
% Then in the workspace I call:
% foo(100,'a',1,'b',2)
%
% This will override the values of a and b to be 1 and 2.
%
% Note that the arguments to `foo` may be in any order-- the
% only ordering restriction is that whatever immediately follows
% pair names (e.g. 'a') will be interpreted as the value to be
% assigned to them (e.g. 'a' takes on the value 1);
%
% We encourage the use of utils.inputordefault over this function.
%
function [varargout] = overridedefaults(varnames, arguments, ignore_unknowns)
if nargin < 3, ignore_unknowns=true; end;
if nargout>0
% to start, assign the default values to the optional output
for v=1:numel(varnames)
out.(varnames{v}) = evalin('caller',varnames{v});
end
end
% Now we assign the value to those passed by arguments.
if numel(arguments)==1 && isstruct(arguments{1})
arguments=arguments{1};
fn=fieldnames(arguments);
for arg=1:numel(fn)
switch fn{arg}
case varnames
assignin('caller',fn{arg}, arguments.(fn{arg}));
out.(fn{arg})=arguments.(fn{arg});
otherwise
if ignore_unknowns
warning('OD:unknown','Variable %s not defined in caller. Skipping.',fn{arg});
else
assignin('caller',fn{arg}, arguments.(fn{arg}));
end
end
end
else
arg = 1;
while arg <= length(arguments),
switch arguments{arg},
case varnames,
if arg+1 <= length(arguments)
assignin('caller', arguments{arg}, arguments{arg+1});
out.(arguments{arg})=arguments{arg+1};
arg = arg+1;
end;
otherwise
if ignore_unknowns
warning('OD:unknown','Variable %s not defined in caller. Skipping.',arguments{arg});
else
assignin('caller', arguments{arg}, arguments{arg+1});
out.(arguments{arg})=arguments{arg+1};
end
arg = arg+1;
end;
arg = arg+1;
end;
end
if nargout>0
varargout{1}=out;
end
return;
|
github
|
erlichlab/elutils-master
|
adaptive_mult.m
|
.m
|
elutils-master/+utils/adaptive_mult.m
| 2,123 |
utf_8
|
89328d00b41e6d0ae7f634db36b37b2c
|
% [val] = adaptive_mult(val, hit, {'hit_frac', 0}, {'stableperf', 0.75}, ...
% {'mx', 1}, {'mn', 0}, {'do_callback', 0})
%
% Implements multiplicative staircase adaptation of a variable.
%
% PARAMETERS:
% -----------
%
% val The value to be adapted.
%
% hit Pass this as 1 if latest trial was in the positive adaptation
% direction; passit as 0 if it was in the negative direction
%
% OPTIONAL PARAMETERS
% -------------------
%
% hit_frac How much to add to the parameter when hit==1. Default value
% is 0, meaning no adaptation whatsoever.
%
% stableperf The percentage of positive trials that would lead to no
% movement on average. stableperf is used to calculate the
% size of how much is substracted from the SPH when
% hit==0. Default value is 75%. Performance below this will
% (on average) lead to motion in the -hit_frac direction;
% performance above this will lead to motion in the hit_frac
% direction.
%
% mx Maximum bound on the value: value cannot go above this
%
% mn Minimum bound on the value: value cannot go below this
%
%
%
% RETURNS:
% --------
%
% val return the updated, post-adaptation value.
%
%
% EXAMPLE CALL:
% -------------
%
% >> block_length = adaptive_step(block_length, hit, 'hit_frac', -0.1, 'stableperf', 0.75, 'mx, ...
% 50, 'mn', 2)
%
% Will increase my_sph by 1 every time hit==1, and will decrease it
% by 3 every time hit==0. my_sph will be bounded within 90 and 100.
%
function [val] = adaptive_mult(val, hit, varargin)
inpd = @utils.inputordefault;
hit_frac = inpd('hit_frac',0 ,varargin);
stableperf = inpd('stableperf', 0.75, varargin);
mx = inpd('mx', 1, varargin);
mn = inpd('mn', 0, varargin);
log_hit_step = log10(1 + hit_frac);
log_miss_step = stableperf*log_hit_step/(1-stableperf);
if hit==1,
val = val * (10.^log_hit_step);
elseif hit==0
val = val / (10.^log_miss_step);
end
% if hit is nan don't adapt
if val > mx
val = mx;
end
if val < mn
val = mn
end
|
github
|
erlichlab/elutils-master
|
parseargs.m
|
.m
|
elutils-master/+utils/parseargs.m
| 6,636 |
utf_8
|
c8ed076c97d377f6a6807576765b9992
|
%parseargs [opts] = parseargs(arguments, pairs, singles, ignore_unknowns)
%
% Variable argument parsing-- supersedes parseargs_example. This
% function is meant to be used in the context of other functions
% which have variable arguments. Typically, the function using
% variable argument parsing would be written with the following
% header:
%
% function myfunction(args, ..., varargin)
%
% and would define the variables "pairs" and "singles" (in a
% format described below), and would then include the line
%
% parseargs(varargin, pairs, singles);
%
% 'pairs' and 'singles' specify how the variable arguments should
% be parsed; their format is decribed below. It is best
% understood by looking at the example at the bottom of these help
% comments.
%
% varargin can be of two forms:
% 1) A cell array where odd entries are variable names and even entries are
% the corresponding values
% 2) A struct where the fieldnames are the variable names and the values of
% the fields are the values (for pairs) or the existence of the field
% triggers acts as a single.
%
% pairs can be of two forms:
% 1) an n x 2 cell array where the first column are the variable names and
% the 2nd column are the default values.
% 2) A struct where the fieldnames are the variable names and the values of
% the fields are the values.
%
% PARSEARGS DOES NOT RETURN ANY VALUES; INSTEAD, IT USES ASSIGNIN
% COMMANDS TO CHANGE OR SET VALUES OF VARIABLES IN THE CALLING
% FUNCTION'S SPACE.
%
%
%
% PARAMETERS:
% -----------
%
% -arguments The varargin list, I.e. a row cell array.
%
% -pairs A cell array of all those arguments that are
% specified by argument-value pairs. First column
% of this cell array must indicate the variable
% names; the second column must indicate
% correponding default values.
%
% -singles A cell array of all those arguments that are
% specified by a single flag. The first column must
% indicate the flag; the second column must
% indicate the corresponding variable name that
% will be affected in the caller's workspace; the
% third column must indicate the value that that
% variable will take upon appearance of the flag;
% and the fourth column must indicate a default
% value for the variable.
%
%
% Example:
% --------
%
% In "pairs", the first column defines both the variable name and the
% marker looked for in varargin, and the second column defines that
% variable's default value:
%
% pairs = {'thingy' 20 ; ...
% 'blob' 'that'};
%
% In "singles", the first column is the flag to be looked for in varargin,
% the second column defines the variable name this flag affects, the third
% column defines the value the variable will take if the flag was found, and
% the last column defines the value the variable takes if the flag was NOT
% found in varargin.
%
% singles = {'no_plot' 'plot_fg' '0' '1'; ...
% {'plot' 'plot_fg' '1' '1'};
%
%
% Now for the function call from the user function:
%
% parseargs({'blob', 'fuff!', 'no_plot'}, pairs, singles);
%
% This will set, in the caller space, thingy=20, blob='fuff!', and
% plot_fg=0. Since default values are in the second column of "pairs"
% and the fourth column of "singles", and in the call to
% parseargs 'thingy' was not specified, 'thingy' takes on its
% default value of 20.
%
% Note that the arguments to parseargs may be in any order-- the
% only ordering restriction is that whatever immediately follows
% pair names (e.g. 'blob') will be interpreted as the value to be
% assigned to them (e.g. 'blob' takes on the value 'fuff!');
%
% If you never use singles, you can just call "parseargs(varargin, pairs)"
% without the singles argument.
%
function [varargout] = parseargs(arguments, pairs, singles,ignore_unknowns)
if nargin < 3, singles = {}; end;
if nargin < 4, ignore_unknowns=false; end;
% This assigns all the default values for pairs.
if isstruct(pairs)
out=pairs;
fn=fieldnames(pairs);
for fx=1:numel(fn)
assignin('caller',fn{fx}, pairs.(fn{fx}));
end
pairs=fn;
else
for i=1:size(pairs,1),
assignin('caller', pairs{i,1}, pairs{i,2});
end;
end
% This assigns all the default values for singles.
for i=1:size(singles,1),
assignin('caller', singles{i,2}, singles{i,4});
end;
if isempty(singles), singles = {'', '', [], []}; nosingles=true; else nosingles=false; end;
if isempty(pairs), pairs = {'', []}; nopairs=true; else nopairs=false; end;
% Now we assign the value to those passed by arguments.
if numel(arguments)==1 && isstruct(arguments{1})
arguments=arguments{1};
fn=fieldnames(arguments);
for arg=1:numel(fn)
switch fn{arg}
case pairs(:,1)
assignin('caller',fn{arg}, arguments.(fn{arg}));
out.(fn{arg})=arguments.(fn{arg});
case singles(:,1)
u = find(strcmp(fn{arg}, singles(:,1)));
out.(fn{arg})=singles(:,1);
assignin('caller', singles{u,2}, singles{u,3});
otherwise
if ~ignore_unknowns
fn{arg}
mname = evalin('caller', 'mfilename');
error([mname ' : Didn''t understand above parameter']);
end
end
end
else
arg = 1; while arg <= length(arguments),
switch arguments{arg},
case pairs(:,1),
if arg+1 <= length(arguments)
assignin('caller', arguments{arg}, arguments{arg+1});
arg = arg+1;
end;
case singles(:,1),
u = find(strcmp(arguments{arg}, singles(:,1)));
assignin('caller', singles{u,2}, singles{u,3});
otherwise
if ~ignore_unknowns
arguments{arg}
mname = evalin('caller', 'mfilename');
error([mname ' : Didn''t understand above parameter']);
else
if nosingles
arg=arg+1;
elseif nopairs
% don't increment args.
else
error('Cannot use ignore_unknown and a mix of singles and pairs')
end
end
end;
arg = arg+1; end;
end
if nargout>0
varargout{1}=out;
end
return;
|
github
|
erlichlab/elutils-master
|
to_string_date.m
|
.m
|
elutils-master/+utils/to_string_date.m
| 2,465 |
utf_8
|
3b79081714a1f10ba59298abc6fa29bb
|
% [str] = to_string_date(din, ['format', {'dashes'|'nodashes'})
%
% Takes a din that stands for a date and turns it into a string format that
% can be used to look for data files or that can be used with the SQL
% database.
%
% PARAMETERS:
% -----------
%
% din An integer. If it is an integer of magnitude less than 1000, it
% is interpreted as the difference, in days, between today and the
% desired date. For example, -3 means "three days before today" and
% 5 means "five days after today".
% If din is an integer with magnitude greater than 1000, then it
% is interpreted as a number whose last two digits are the day of
% the month, last two digits but two are the number of the month,
% and the last four digits but four are the year-2000. E.g., 80411
% means the 11th of April of 2008.
%
% If din is passed in as a vector, a cell of the same size is
% returned, with each element of the cell being the result of
% to_string_date applied to each element of din. (Note that f din
% is a vector of length one, the return will not be a cell but a
% string.)
%
% If din is a string, then it is returned as is, with no changes.
%
% str A string representing the date. If the optional parameter
% 'format' is not passed, i.e., it is left at its default value,
% then the format will be 'yyyy-mm-dd'. If format is 'nodashes',
% then the returned string will be in the format 'yyyymmdd'.
%
% written by Carlos Brody April 2009
function [str] = to_string_date(din, varargin)
format = utils.inputordefault('format','dashes',varargin);
if ischar(din), str = din; return; end;
if numel(din)>1,
str = cell(size(din));
for i=1:numel(din),
str{i} = to_string_date(din(i), 'format', format);
end;
return;
end;
if abs(din)>1000,
day = rem(din, 100); din = round((din-day)/100);
month = rem(din,100); din = round((din-day)/100);
if abs(din<1000),
year = din + 2000;
else
year = din;
end;
day = num2str(day);
day = ['0'*ones(1, 2-length(day)) day];
month = num2str(month);
month = ['0'*ones(1, 2-length(month)) month];
year = num2str(year);
if strcmp(format, 'nodashes'),
str = [year month day];
else
str = [year '-' month '-' day];
end;
else
str = datestr(now+din, 29);
if strcmp(format, 'nodashes'),
str = str(str~='-');
end;
end;
|
github
|
erlichlab/elutils-master
|
adaptive_step.m
|
.m
|
elutils-master/+utils/adaptive_step.m
| 2,067 |
utf_8
|
9f6646a5feea5b49c15bbcaab948d83d
|
% [val] = adaptive_step(val, hit, {'hit_step', 0}, {'stableperf', 0.75}, ...
% {'mx', 1}, {'mn', 0}, {'do_callback', 0})
%
% Implements staircase adaptation of a variable.
%
% PARAMETERS:
% -----------
%
% val The value to be adapted.
%
% hit Pass this as 1 if latest trial was in the positive adaptation
% direction; passit as 0 if it was in the negative direction
%
% OPTIONAL PARAMETERS
% -------------------
%
% hit_step How much to add to the parameter when hit==1. Default value
% is 0, meaning no adaptation whatsoever.
%
% stableperf The percentage of positive trials that would lead to no
% movement on average. stableperf is used to calculate the
% size of how much is substracted from the SPH when
% hit==0. Default value is 75%. Performance below this will
% (on average) lead to motion in the -hit_step direction;
% performance above this will lead to motion in the hit_step
% direction.
%
% mx Maximum bound on the value: value cannot go above this
%
% mn Minimum bound on the value: value cannot go below this
%
%
%
% RETURNS:
% --------
%
% val return the updated, post-adaptation value.
%
%
% EXAMPLE CALL:
% -------------
%
% >> block_length = adaptive_step(block_length, hit, 'hit_step', -1, 'stableperf', 0.75, 'mx, ...
% 50, 'mn', 2)
%
% Will increase my_sph by 1 every time hit==1, and will decrease it
% by 3 every time hit==0. my_sph will be bounded within 90 and 100.
%
function [val] = adaptive_step(val, hit, varargin)
inpd = @utils.inputordefault;
hit_step = inpd('hit_step',0 ,varargin);
stableperf = inpd('stableperf', 0.75, varargin);
mx = inpd('mx', 1, varargin);
mn = inpd('mn', 0, varargin);
miss_step = stableperf*hit_step/(1-stableperf);
if hit==1
val = val + hit_step;
elseif hit==0
val = val - miss_step;
else
warning('hit must be either 0 or 1!');
end;
if val > mx
val = mx;
end
if val < mn
val = mn;
end
|
github
|
erlichlab/elutils-master
|
combinator.m
|
.m
|
elutils-master/+utils/combinator.m
| 12,572 |
utf_8
|
b7227c1ea589711f5b1cacffff096fb1
|
function [A] = combinator(N,K,s1,s2)
%COMBINATOR Perform basic permutation and combination samplings.
% COMBINATOR will return one of 4 different samplings on the set 1:N,
% taken K at a time. These samplings are given as follows:
%
% PERMUTATIONS WITH REPETITION/REPLACEMENT
% COMBINATOR(N,K,'p','r') -- N >= 1, K >= 0
% PERMUTATIONS WITHOUT REPETITION/REPLACEMENT
% COMBINATOR(N,K,'p') -- N >= 1, N >= K >= 0
% COMBINATIONS WITH REPETITION/REPLACEMENT
% COMBINATOR(N,K,'c','r') -- N >= 1, K >= 0
% COMBINATIONS WITHOUT REPETITION/REPLACEMENT
% COMBINATOR(N,K,'c') -- N >= 1, N >= K >= 0
%
% Example:
%
% To see the subset relationships, do this:
% combinator(4,2,'p','r') % Permutations with repetition
% combinator(4,2,'p') % Permutations without repetition
% combinator(4,2,'c','r') % Combinations with repetition
% combinator(4,2,'c') % Combinations without repetition
%
%
% If it is desired to use a set other than 1:N, simply use the output from
% COMBINATOR as an index into the set of interest. For example:
%
% MySet = ['a' 'b' 'c' 'd'];
% MySetperms = combinator(length(MySet),3,'p','r'); % Take 3 at a time.
% MySetperms = MySet(MySetperms)
%
%
% Class support for input N:
% float: double, single
% integers: int8,int16,int32
%
%
% Notes:
% All of these algorithms have the potential to create VERY large outputs.
% In each subfunction there is an anonymous function which can be used to
% calculate the number of row which will appear in the output. If a rather
% large output is expected, consider using an integer class to conserve
% memory. For example:
%
% M = combinator(int8(30),3,'p','r'); % NOT uint8(30)
%
% will take up 1/8 the memory as passing the 30 as a double. See the note
% below on using the MEX-File.
%
% To make your own code easier to read, the fourth argument can be any
% string. If the string begins with an 'r' (or 'R'), the function
% will be called with the replacement/repetition algorithm. If not, the
% string will be ignored.
% For instance, you could use: 'No replacement', or 'Repetition allowed'
% If only two inputs are used, the function will assume 'p','r'.
% The third argument must begin with either a 'p' or a 'c' but can be any
% string beyond that.
%
% The permutations with repetitions algorithm uses cumsum. So does the
% combinations without repetition algorithm for the special case of K=2.
% Unfortunately, MATLAB does not allow cumsum to work with integer classes.
% Thus a subfunction has been placed at the end for the case when these
% classes are passed. The subfunction will automatically pass the
% necessary matrix to the built-in cumsum when a single or double is used.
% When an integer class is used, the subfunction first looks to see if the
% accompanying MEX-File (cumsumall.cpp) has been compiled. If not,
% then a MATLAB For loop is used to perform the cumsumming. This is
% VERY slow! Therefore it is recommended to compile the MEX-File when
% using integer classes.
% The MEX-File was tested by the author using the Borland 5.5 C++ compiler.
%
% See also, perms, nchoosek, npermutek (on the FEX)
%
% Author: Matt Fig
% Contact: [email protected]
% Date: 5/30/2009
%
% Reference: http://mathworld.wolfram.com/BallPicking.html
ng = nargin;
if ng == 2
s1 = 'p';
s2 = 'r';
elseif ng == 3
s2 = 'n';
elseif ng ~= 4
error('Only 2, 3 or 4 inputs are allowed. See help.')
end
if isempty(N) || K == 0
A = [];
return
elseif numel(N)~=1 || N<=0 || ~isreal(N) || floor(N) ~= N
error('N should be one real, positive integer. See help.')
elseif numel(K)~=1 || K<0 || ~isreal(K) || floor(K) ~= K
error('K should be one real non-negative integer. See help.')
end
STR = lower(s1(1)); % We are only interested in the first letter.
if ~strcmpi(s2(1),'r')
STR = [STR,'n'];
else
STR = [STR,'r'];
end
try
switch STR
case 'pr'
A = perms_rep(N,K); % strings
case 'pn'
A = perms_no_rep(N,K); % permutations
case 'cr'
A = combs_rep(N,K); % multichoose
case 'cn'
A = combs_no_rep(N,K); % choose
otherwise
error('Unknown option passed. See help')
end
catch
rethrow(lasterror) % Throw error from here, not subfunction.
% The only error thrown should be K>N for non-replacement calls.
end
function PR = perms_rep(N,K)
% This is (basically) the same as npermutek found on the FEX. It is the
% fastest way to calculate these (in MATLAB) that I know.
% pr = @(N,K) N^K; Number of rows.
% A speed comparison could be made with COMBN.m, found on the FEX. This
% is an excellent code which uses ndgrid. COMBN is written by Jos.
%
% % All timings represent the best of 4 consecutive runs.
% % All timings shown in subfunction notes used this configuration:
% % 2007a 64-bit, Intel Xeon, win xp 64, 16 GB RAM
% tic,Tc = combinator(single(9),7,'p','r');toc
% %Elapsed time is 0.199397 seconds. Allow Ctrl+T+C+R on block
% tic,Tj = combn(single(1:9),7);toc
% %Elapsed time is 0.934780 seconds.
% isequal(Tc,Tj) % Yes
if N==1
PR = ones(1,K,class(N));
return
elseif K==1
PR = (1:N).';
return
end
CN = class(N);
M = double(N); % Single will give us trouble on indexing.
L = M^K; % This is the number of rows the outputs will have.
PR = zeros(L,K,CN); % Preallocation.
D = ones(1,N-1,CN); % Use this for cumsumming later.
LD = M-1; % See comment on N.
VL = [-(N-1) D].'; % These values will be put into PR.
% Now start building the matrix.
TMP = VL(:,ones(L/M,1,CN)); % Instead of repmatting.
PR(:,K) = TMP(:); % We don't need to do two these in loop.
PR(1:M^(K-1):L,1) = VL; % The first column is the simplest.
% Here we have to build the cols of PR the rest of the way.
for ii = K-1:-1:2
ROWS = 1:M^(ii-1):L; % Indices into the rows for this col.
TMP = VL(:,ones(length(ROWS)/(LD+1),1,CN)); % Match dimension.
PR(ROWS,K-ii+1) = TMP(:); % Build it up, insert values.
end
PR(1,:) = 1; % For proper cumsumming.
PR = cumsum2(PR); % This is the time hog.
function PN = perms_no_rep(N,K)
% Subfunction: permutations without replacement.
% Uses the algorithm in combs_no_rep as a basis, then permutes each row.
% pn = @(N,K) prod(1:N)/(prod(1:(N-K))); Number of rows.
if N==K
PN = perms_loop(N); % Call helper function.
% [id,id] = sort(PN(:,1)); %#ok Not nec., uncomment for nice order.
% PN = PN(id,:); % Return values.
return
elseif K==1
PN = (1:N).'; % Easy case.
return
end
if K>N % Since there is no replacement, this cannot happen.
error(['When no repetitions are allowed, '...
'K must be less than or equal to N'])
end
M = double(N); % Single will give us trouble on indexing.
WV = 1:K; % Working vector.
lim = K; % Sets the limit for working index.
inc = 1; % Controls which element of WV is being worked on.
BC = prod(M-K+1:M); % Pre-allocation of return arg.
BC1 = BC / ( prod(1:K)); % Number of comb blocks.
PN = zeros(round(BC),K,class(N));
L = prod(1:K) ; % To get the size of the blocks.
cnt = 1+L;
P = perms_loop(K); % Only need to use this once.
PN(1:(1+L-1),:) = WV(P); % The first row.
for ii = 2:(BC1 - 1);
if logical((inc+lim)-N) % The logical is nec. for class single(?)
stp = inc; % This is where the for loop below stops.
flg = 0; % Used for resetting inc.
else
stp = 1;
flg = 1;
end
for jj = 1:stp
WV(K + jj - inc) = lim + jj; % Faster than a vector assignment!
end
PN(cnt:(cnt+L-1),:) = WV(P); % Assign block.
cnt = cnt + L; % Increment base index.
inc = inc*flg + 1; % Increment the counter.
lim = WV(K - inc + 1 ); % lim for next run.
end
V = (N-K+1):N; % Final vector.
PN(cnt:(cnt+L-1),:) = V(P); % Fill final block.
% The sorting below is NOT necessary. If you prefer this nice
% order, the next two lines can be un-commented.
% [id,id] = sort(PN(:,1)); %#ok This is not necessary!
% PN = PN(id,:); % Return values.
function P = perms_loop(N)
% Helper function to perms_no_rep. This is basically the same as the
% MATLAB function perms. It has been un-recursed for a runtime of around
% half the recursive version found in perms.m For example:
%
% tic,Tp = perms(1:9);toc
% %Elapsed time is 0.222111 seconds. Allow Ctrl+T+C+R on block
% tic,Tc = combinator(9,9,'p');toc
% %Elapsed time is 0.143219 seconds.
% isequal(Tc,Tp) % Yes
M = double(N); % Single will give us trouble on indexing.
P = 1; % Initializer.
G = cumprod(1:(M-1)); % Holds the sizes of P.
CN = class(N);
for n = 2:M
q = P;
m = G(n-1);
P = zeros(n*m,n,CN);
P(1:m, 1) = n;
P(1:m, 2:n) = q;
a = m + 1;
for ii = n-1:-1:1,
t = q;
t(t == ii) = n;
b = a + m - 1;
P(a:b, 1) = ii;
P(a:b, 2:n) = t;
a = b + 1;
end
end
function CR = combs_rep(N,K)
% Subfunction multichoose: combinations with replacement.
% cr = @(N,K) prod((N):(N+K-1))/(prod(1:K)); Number of rows.
M = double(N); % Single will give us trouble on indexing.
WV = ones(1,K,class(N)); % This is the working vector.
mch = prod((M:(M+K-1)) ./ (1:K)); % Pre-allocation.
CR = ones(round(mch),K,class(N));
for ii = 2:mch
if WV(K) == N
cnt = K-1; % Work backwards in WV.
while WV(cnt) == N
cnt = cnt-1; % Work backwards in WV.
end
WV(cnt:K) = WV(cnt) + 1; % Fill forward.
else
WV(K) = WV(K)+1; % Keep working in this group.
end
CR(ii,:) = WV;
end
function CN = combs_no_rep(N,K)
% Subfunction choose: combinations w/o replacement.
% cn = @(N,K) prod(N-K+1:N)/(prod(1:K)); Number of rows.
% Same output as the MATLAB function nchoosek(1:N,K), but often faster for
% larger N.
% For example:
%
% tic,Tn = nchoosek(1:17,8);toc
% %Elapsed time is 0.430216 seconds. Allow Ctrl+T+C+R on block
% tic,Tc = combinator(17,8,'c');toc
% %Elapsed time is 0.024438 seconds.
% isequal(Tc,Tn) % Yes
if K>N
error(['When no repetitions are allowed, '...
'K must be less than or equal to N'])
end
M = double(N); % Single will give us trouble on indexing.
if K == 1
CN =(1:N).'; % These are simple cases.
return
elseif K == N
CN = (1:N);
return
elseif K==2 && N>2 % This is an easy case to do quickly.
BC = (M-1)*M / 2;
id1 = cumsum2((M-1):-1:2)+1;
CN = zeros(BC,2,class(N));
CN(:,2) = 1;
CN(1,:) = [1 2];
CN(id1,1) = 1;
CN(id1,2) = -((N-3):-1:0);
CN = cumsum2(CN);
return
end
WV = 1:K; % Working vector.
lim = K; % Sets the limit for working index.
inc = 1; % Controls which element of WV is being worked on.
BC = prod(M-K+1:M) / (prod(1:K)); % Pre-allocation.
CN = zeros(round(BC),K,class(N));
CN(1,:) = WV; % The first row.
for ii = 2:(BC - 1);
if logical((inc+lim)-N) % The logical is nec. for class single(?)
stp = inc; % This is where the for loop below stops.
flg = 0; % Used for resetting inc.
else
stp = 1;
flg = 1;
end
for jj = 1:stp
WV(K + jj - inc) = lim + jj; % Faster than a vector assignment.
end
CN(ii,:) = WV; % Make assignment.
inc = inc*flg + 1; % Increment the counter.
lim = WV(K - inc + 1 ); % lim for next run.
end
CN(ii+1,:) = (N-K+1):N;
function A = cumsum2(A)
%CUMSUM2, works with integer classes.
% Duplicates the action of cumsum, but for integer classes.
% If Matlab ever allows cumsum to work for integer classes, we can remove
% this.
if isfloat(A)
A = cumsum(A); % For single and double, use built-in.
return
else
try
A = cumsumall(A); % User has the MEX-File ready?
catch
warning('Cumsumming by loop. MEX cumsumall.cpp for speed.') %#ok
for ii = 2:size(A,1)
A(ii,:) = A(ii,:) + A(ii-1,:); % User likes it slow.
end
end
end
|
github
|
erlichlab/elutils-master
|
MakeSpectrumNoise.m
|
.m
|
elutils-master/+sound/MakeSpectrumNoise.m
| 2,511 |
utf_8
|
1ad790feb7a4eab9a9dd378d9caba9ef
|
% function [snd] = MakeSpectrumNoise(SRate, F1, F2, Duration, Kontrast, ...
% CRatio, varargin)
%
% This function generates a sound whose power spectrum is white except for
% two Gaussian peaks at F1 and F2 (each with std = sigma). The contrast of
% each peak is defined as C_i = (P_i - b)/b, where P is the height of the peak
% and b (baseline) is the baseline power of every other (non-peak) frequency.
%
% In order to adjust the relative contributions of the peaks at F1 and F2
% in a continuous way along one dimension, we specify the sum of contrasts
% Kontrast = C1 + C2
% and the log ratio of contrasts
% CRatio = log(C1/C2).
% In this way, we can keep Kontrast at some constant and adjust CRatio so
% that when CRatio > 0, there is more power around F1 and when CRatio < 0,
% there is more power around F2.
%
% ARGUMENTS
% ---------
% Makes a sound such that:
%
% Srate sampling rate, in samples/sec
% F1 frequency of first peak above white noise
% F2 frequency of second peak above white noise
% Duration duration of sound, in milliseconds
% Kontrast C1 + C2 (see above)
% CRatio log(C1/C2), as described above
% OPTIONAL ARGUMENTS
% ------------------
% sigma stdev of Gaussian distributions around F1 and F2 in
% frequency space of the final sound
% baseline power of every other frequency not around F1 or F2
% written by Bing, October 2008
function [snd] = MakeSpectrumNoise(SRate, F1, F2, Duration, Kontrast, CRatio, varargin)
pairs = {
'stdev' 100 ; ...
'baseline' 0.01 ; ...
}; parseargs(varargin, pairs);
Duration = Duration/1000; % to sec
% make white noise
t = linspace(0, Duration, SRate*Duration);
wnoise = randn(size(t));
C1 = Kontrast/(exp(-CRatio)+1);
C2 = Kontrast - C1;
% transform white noise to frequency space
fwnoise = fft(wnoise)/Duration; % scale magnitude of the fft corresponding to duration ot sound
omega = SRate*linspace(0, 1, length(fwnoise)); % corresponding frequency dimension
G1 = exp(-(omega - F1) .^2 /(2*stdev^2));
G2 = exp(-(omega - F2) .^2 /(2*stdev^2));
% enhance frequencies around F1 and F2, then recover sound
fsnd = fwnoise .* (G1*baseline*C1+baseline + G2*baseline*C2+baseline);
% normalize the volume so that snd is as loud (psychoacoustics aside) as
% the original generating white noise
fsnd = fsnd * sqrt((sum(fwnoise.*conj(fwnoise)) / sum(fsnd.*conj(fsnd))));
snd = real(ifft(fsnd));
|
github
|
erlichlab/elutils-master
|
cosyne_ramp.m
|
.m
|
elutils-master/+sound/cosyne_ramp.m
| 887 |
utf_8
|
94b4e864d3b54de9f7a28cca9a9bfcb4
|
% [snd] = cosyne_ramp(snd, srate, ramp_ms)
%
% Takes a sound in the 1-dimensional vector snd, and assuming that the
% samplerate for it is srate samples/sec, multiplies it by a cosyne ramp of
% ramp_ms milliseconds (i.e., the cosyne function goes from min to max in
% ramp_ms, meaning it has a whole-cycle a period of 2*ramp_ms)
%
function [snd] = cosyne_ramp(snd, srate, ramp_ms)
if isempty(snd), return; end;
len = ceil(srate*ramp_ms/1000)+1;
if ~isvector(snd),
error('COSYNE_RAMP:Invalid', 'snd must be an n-by-1 or 1-by-n vector');
end;
if length(snd) < len,
error('COSYNE_RAMP:Invalid', 'snd must be at least ramp_ms plus one sample long');
end;
cos_period = 2*ramp_ms/1000;
cosyne = cos(2*pi*(1/cos_period)*(0:len-1)/srate);
snd(1:len) = snd(1:len).*cosyne(end:-1:1);
snd(end-len+1:end) = snd(end-len+1:end).*cosyne;
|
github
|
erlichlab/elutils-master
|
MakeBupperSwoop.m
|
.m
|
elutils-master/+sound/MakeBupperSwoop.m
| 6,598 |
utf_8
|
08ef1f9c6e0298e251130dfbe2ca6e26
|
%MakeBupperSwoop.m [monosound]=MakeBupperSwoop(SRate, Att, StartFreq, ...
% EndFreq, BeforeBreakDuration, AfterBreakDuration,...
% Breaklen, Tau)
%
% Makes a sound:
%
% SRate: sampling rate, in samples/sec
% Attenuation
% StartFreq starting frequency of the sound, in Hz
% EndFreq ending frequency of the sound, in Hz
% BeforeBreakDuration duration of the first nonzero amplitude
% parts of the sound (excluding breaks), in ms
% AfterBreakDuration duration of the second nonzero amplitude
% parts of the sound (excluding breaks), in ms
% Breaklen number of ms of silence inserted into the middle of the tone
% Tau Tau of frequency sigmoid, in ms
%
% OPTIONAL ARGS:
% --------------
%
% F1_volume_factor default 1; How much to multiply StartFreq part
% of signal by.
%
% F2_volume_factor default 1; How much to multiply EndFreq part
% of signal by.
%
% Stereo default 0; returns a mono sound. If 1, returns a
% a stereo sound
%
% F1_loc_factor Only relevant if Stereo==1. Default is 0,
% meaning no bias to Left or Right. A value of 1
% means bias completely to the left; a value of -1
% means bias completely to the right.
%
% F2_loc_factor As F1_loc_factor, but for sound F2.
%
% F1_lead_time Only relevant if Stereo==1. This is a time
% advance, in ms, with which the Left signal is generated
% compared to the Right signal. For a rat's head
% size, 0.1 ms should be good. If this is left
% empty, then it will be set equal to 0.1*F1_loc_factor.
%
% F2_lead_time As F1_lead_time, but for sound F1. If this is left
% empty, then it will be set equal to 0.1*F2_loc_factor.
%
% The transitions from F1 to F2 in _volume_factor, _loc_factor, and
% _lead_time all follow the sigmoid used for everything else.
%
% Carlos Brody Apr 06; _loc_factor and _lead_time added May 06
function [Beep]=MakeBupperSwoop(SRate, Att, StartFreq, EndFreq, ...
BeforeDuration, AfterDuration, Breaklen, ...
Tau, varargin)
if nargin<=8, varargin = {}; end;
pairs = { ...
'F1_volume_factor' 1 ; ...
'F2_volume_factor' 1 ; ...
'Stereo' 0 ; ...
'F1_loc_factor' 0 ; ...
'F2_loc_factor' 0 ; ...
'F1_lead_time' [] ; ...
'F2_lead_time' [] ; ...
'PPfilter_fname' '' ; ...
'bup_width' 5 ; ...
}; utils.parseargs(varargin, pairs);
if isempty(F1_lead_time), F1_lead_time = -0.1*F1_loc_factor; end;
if isempty(F2_lead_time), F2_lead_time = -0.1*F2_loc_factor; end;
if BeforeDuration==0 & AfterDuration==0, Beep = []; return; end;
BeforeDuration = BeforeDuration/1000; % Turn everything into seconds
AfterDuration = AfterDuration/1000;
Duration = BeforeDuration + AfterDuration;
BreakFraction = BeforeDuration/Duration;
Breaklen = Breaklen/1000;
F1_lead_time = F1_lead_time/1000;
F2_lead_time = F2_lead_time/1000;
Tau = Tau/(1000*Duration); % This is in relative units of zero2one vector
% Create a time vector.
t=0:(1/SRate):Duration;
t=t(1:(end-1));
zero2one = (0:length(t)-1) / (length(t)-1);
zero2one = tanh((zero2one - BreakFraction)/Tau);
volume_factor = (F2_volume_factor - F1_volume_factor)*(zero2one+1)/2 + ...
F1_volume_factor;
loc_factor = (F2_loc_factor - F1_loc_factor) *(zero2one+1)/2 + ...
F1_loc_factor;
lead_time = (F2_lead_time - F1_lead_time) *(zero2one+1)/2 + ...
F1_lead_time;
zero2one = zero2one - min(zero2one); zero2one = zero2one/max(zero2one);
logFrequency = log(StartFreq) + zero2one*(log(EndFreq) - log(StartFreq));
Frequency = exp(logFrequency);
Phi = 2*pi*(cumsum(Frequency)-Frequency(1))*mean(diff(t));
if Stereo,
Left_Phi = 2*pi*cumsum(Frequency)*mean(diff(t+lead_time));
Right_Phi = Phi;
left_loc_factor = min(1+loc_factor, 1);
right_loc_factor = min(1-loc_factor, 1);
Left_Beep = MakeSound(Left_Phi, SRate, Att, Breaklen, BreakFraction, ...
left_loc_factor.*volume_factor, PPfilter_fname, ...
zero2one);
Right_Beep = MakeSound(Right_Phi, SRate, Att, Breaklen, BreakFraction, ...
right_loc_factor.*volume_factor, PPfilter_fname, ...
zero2one);
ldiff = length(Left_Beep) - length(Right_Beep);
if ldiff < 0, Left_Beep = [Left_Beep zeros(1, -ldiff)];
elseif ldiff > 0, Right_Beep = [Right_Beep zeros(1, ldiff)];
end;
Beep = [Left_Beep ; Right_Beep];
else
Beep = MakeSound(Phi, SRate, Att, Breaklen, BreakFraction, ...
volume_factor, PPfilter_fname, ...
zero2one, bup_width);
end;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [Beep] = MakeSound(Phi, SRate, Att, Breaklen, BreakFraction, ...
volume_factor, PPfilter_fname, zero2one, bup_width)
Timer = sin(Phi);
Beep = zeros(size(Phi));
u = find(diff(sign(Timer)) > 0); u = [1 u];
bup = sound.singlebup(SRate, Att, 'PPfilter_fname', PPfilter_fname, 'width', bup_width);
lbup = length(bup);
for i=1:length(u),
Beep(u(i):u(i)+lbup-1) = bup;
end;
Beep(1:length(volume_factor)) = Beep(1:length(volume_factor)).*volume_factor;
if length(Beep)>length(volume_factor),
Beep(length(volume_factor)+1:end) = ...
Beep(length(volume_factor)+1:end).*volume_factor(end);
end;
Edge=MakeEdge(SRate, 0.003);
LEdge=length(Edge);
Breaklen = round(Breaklen*SRate);
if Breaklen>0,
[trash, u] = min(abs(zero2one-BreakFraction));
Beep1 = Beep(1:u);
Beep2 = Beep(u+1:end);
if length(Beep1) > LEdge;
Beep1(end-LEdge+1:end) = Beep1(end-LEdge+1:end) .* Edge;
end;
if length(Beep2) > LEdge,
Beep2(1:LEdge) = Beep2(1:LEdge) .* fliplr(Edge);
end;
Beep = [Beep1 ones(1, Breaklen)*Beep1(end) Beep2];
end;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = (cos(t)).^2;
return;
|
github
|
erlichlab/elutils-master
|
MakeSwoop.m
|
.m
|
elutils-master/+sound/MakeSwoop.m
| 2,192 |
utf_8
|
09ee5917bcea33f5d8c9b389ce7ef88d
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeSwoop
% Generate the individual tone pips as an accessory to PrepareSweep.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeSwoop
% Usage:
% Beep=MakeSwoop( SRate, Attenuation, Frequency, Duration, [RiseFall] )
% Create a sinusoidal beep at frequency Frequency in Hz of duration
% SRate is the sample rate in Hz.
% Attenuation is a scalar (0 dB is an amplitude 1 sinusoid.)
% If a Attenuation is a vector, a harmonic stack is created with these attenuations.
% Frequency in Hz
% Duration in milliseconds
% A fifth optional parameter RiseFall specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
function Beep=MakeSwoop( SRate, Attenuation, FrequencyStart, FrequencyEnd, Duration, varargin )
% Create a time vector.
t=0:(1/SRate):(Duration/1000);
t=t(1:(end-1));
% Make harmonic frequencies.
FreqStart=FrequencyStart*(1:length(Attenuation));
FreqEnd =FrequencyEnd *(1:length(Attenuation));
% Create the frequencies in the beep.
%Beep = 10 * 10.^(-Attens./20) .* sin( 2*pi* Freqs .* t );
if FrequencyStart < 0
Beep = 1*(10.^(-Attenuation./20)) .* randn(size(t));
else
Beep=zeros(length(Attenuation), length(t)); zero2one = (0:length(t)-1) / (length(t)-1);
for i=1:length(Attenuation),
logFrequency = log(FreqStart(i)) + zero2one*(log(FreqEnd(i)) - log(FreqStart(i)));
Frequency = exp(logFrequency);
Beep(i,:) = 1*(10.^(-Attenuation(i)./20)) .* sin( 2*pi* Frequency .* t );
end;
end
if FrequencyStart ~= FrequencyEnd,
gu=10;
end;
% Add harmonic components together.
Beep=sum(Beep,1);
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeSwoop : End of function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
erlichlab/elutils-master
|
MakeBeep.m
|
.m
|
elutils-master/+sound/MakeBeep.m
| 1,862 |
utf_8
|
e6730035baf6efe94fb226b17bff9e9e
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeBeep
% Generate the individual tone pips as an accessory to PrepareSweep.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeBeep
% Usage:
% Beep=MakeBeep( SRate, Attenuation, Frequency, Duration, [RiseFall] )
% Create a sinusoidal beep at frequency Frequency in Hz of duration
% SRate is the sample rate in Hz.
% Attenuation is a scalar (0 dB is an amplitude 1 sinusoid.)
% If a Attenuation is a vector, a harmonic stack is created with these attenuations.
% Frequency in Hz
% Duration in milliseconds
% A fifth optional parameter RiseFall specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
function Beep=MakeBeep( SRate, Attenuation, Frequency, Duration, varargin )
% Create a time vector.
t=0:(1/SRate):(Duration/1000);
t=t(1:(end-1));
% Make harmonic frequencies.
Freqs=Frequency*(1:length(Attenuation));
Attens=meshgrid(Attenuation,t);
Attens=Attens';
[Freqs,t]=meshgrid(Freqs,t);
Freqs=Freqs';
t=t';
% Create the frequencies in the beep.
%Beep = 10 * 10.^(-Attens./20) .* sin( 2*pi* Freqs .* t );
if Frequency < 0
Beep = 1*(10.^(-Attens./20)) .* randn(size(t));
else
Beep = 1*(10.^(-Attens./20)) .* sin( 2*pi* Freqs .* t );
end
% Add harmonic components together.
Beep=sum(Beep,1);
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeBeep : End of function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
erlichlab/elutils-master
|
MakeChord2.m
|
.m
|
elutils-master/+sound/MakeChord2.m
| 2,265 |
utf_8
|
d4e4da484d1e93df77d03709404f2dcf
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeChord2
% Generate Chord.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Usage:
% Beep=MakeChord( SRate, Attenuation, BaseFreq, NTones, Duration, [RiseFall] )
% Create a chord with base frequency 'BaseFreq' and with 'NTones' tones.
% 'SRate' is the sample rate in Hz.
% 'Attenuation' is a scalar (0 dB is an amplitude 1 sinusoid.)
% 'BaseFreq' in Hz
% 'Duration' in milliseconds
%
% Unlike MakeChord, MakeChord2 uses key-value pairs for varargin.
% To specify 'RiseFall', for example, you would do:
% MakeChord(srate, att, basefreq, ntones, dur, 'RiseFall', 0.05)
% instead of tacking RiseFall as the fifth parameter.
%
% Also allows volume to be scaled up or down using a linear factor
% 'volume_factor'
function Beep=MakeChord2( SRate, Attenuation, BaseFreq, NTones, Duration, varargin )
pairs = { ...
'RiseFall', 0 ; ...
'volume_factor', 1 ; ...
};
parse_knownargs(varargin, pairs);
FilterPath=[GetParam('rpbox','protocol_path') '\PPfilter.mat'];
if ( size(dir(FilterPath),1) == 1 )
PP=load(FilterPath);
PP=PP.PP;
% message(me,'Generating Calibrated Tones');
else
PP=[];
% message(me,'Generating Non-calibrated Tones');
end
% Create a time vector.
t=0:(1/(SRate)):(Duration/1000);
t=t(1:(end-1));
finterv = sqrt(sqrt(2)); %this stepping yields a diminished minor chord + 13
freq = BaseFreq;
snd = zeros(1,length(t));
for k=1:NTones
if isempty(PP)
ToneAttenuation_adj(k) = Attenuation;
else
ToneAttenuation_adj(k) = Attenuation - ppval(PP, log10( freq ));
% Remove any negative attenuations and replace with zero attenuation.
ToneAttenuation_adj(k) = ToneAttenuation_adj(k) .* (ToneAttenuation_adj(k) > 0);
end
snd = snd + 10^(-ToneAttenuation_adj(k)/20) * ( sin( 2*pi*freq.*t )/NTones ); %IS THIS CORRECT???
freq = freq * finterv;
end
Beep = snd;
% If the user specifies, add edge smoothing.
if ( RiseFall > 0)
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
end
Beep = Beep.*volume_factor;
|
github
|
erlichlab/elutils-master
|
MakeSwoop2.m
|
.m
|
elutils-master/+sound/MakeSwoop2.m
| 1,742 |
utf_8
|
06d44b69c6c79cd89c41fb2f3d72696b
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeSwoop2
% Generate the individual tone pips as an accessory to PrepareSweep.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeSwoop2
% Usage:
% Beep=MakeSwoop( SRate, Attenuation, Frequency, Duration, [RiseFall] )
% Create a sinusoidal beep at frequency Frequency in Hz of duration
% SRate is the sample rate in Hz.
% Attenuation is a scalar (0 dB is an amplitude 1 sinusoid.)
% If a Attenuation is a vector, a harmonic stack is created with these attenuations.
% Frequency in Hz
% Duration in milliseconds
% A fifth optional parameter RiseFall specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
function Beep=MakeSwoop2( SRate, Attenuation, LoFreq, HiFreq, Sweepdir, Duration, varargin )
% Create a time vector.
t=0:(1/SRate):(Duration/1000);
t=t(1:(end-1));
% Make harmonic frequencies.
% Create the frequencies in the beep.
%Beep = 10 * 10.^(-Attens./20) .* sin( 2*pi* Freqs .* t );
zero2one = (0:length(t)-1) / (length(t)-1);
logFrequency = log(LoFreq) + zero2one*(log(HiFreq) - log(LoFreq));
Frequency = exp(logFrequency);
Beep = 1*(10.^(-Attenuation./20)) .* sin( 2*pi* Frequency .* t );
switch Sweepdir,
case 'up',
case 'down',
Beep = Beep(end:-1:1);
otherwise,
error('Sweepdir can only be ''up'' or ''down''');
end;
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
end
|
github
|
erlichlab/elutils-master
|
MakeSigmoidSwoop3.m
|
.m
|
elutils-master/+sound/MakeSigmoidSwoop3.m
| 4,319 |
utf_8
|
4b75bae0f81f56a8e851319eef4dccf6
|
%MakeSigmoidSwoop3.m [monosound]=MakeSigmoidSwoop3(SRate, Att, StartFreq, ...
% EndFreq, BeforeBreakDuration, AfterBreakDuration,...
% Breaklen, Tau, [RiseFall=3] )
%
% Makes a sound:
%
% SRate: sampling rate, in samples/sec
% Attenuation
% StartFreq starting frequency of the sound, in Hz
% EndFreq ending frequency of the sound, in Hz
% BeforeBreakDuration duration of the first nonzero amplitude
% parts of the sound (excluding breaks), in ms
% AfterBreakDuration duration of the second nonzero amplitude
% parts of the sound (excluding breaks), in ms
% Breaklen number of ms of silence inserted into the middle of the tone
% Tau Tau of frequency sigmoid, in ms
% RiseFall width of half-cosine squared edge window, in ms
%
% OPTIONAL ARGS:
% --------------
%
% F1_volume_factor default 1; How much to multiply StartFreq part
% of signal by.
%
% F2_volume_factor default 1; How much to multiply EndFreq part
% of signal by.
%
% PPfilter_fname full path and filename, including .mat, of a
% file containing filter parameters from speaker
% calibration. If this parameter is left empty, the
% location is drawn from exper's rpbox protocol_path.
%
% The transition from F1_volume_factor to F2_volume_factor follows the
% sigmoid used for everything else.
%
% Carlos Brody 28 Mar 06
function [Beep]=MakeSigmoidSwoop3(SRate, Att, StartFreq, EndFreq, ...
BeforeDuration, AfterDuration, Breaklen, ...
Tau, RiseFall, varargin)
if nargin<=9, varargin = {}; end;
pairs = { ...
'F1_volume_factor' 1 ; ...
'F2_volume_factor' 1 ; ...
'PPfilter_fname' '' ; ...
}; parseargs(varargin, pairs);
if BeforeDuration==0 & AfterDuration==0, Beep = []; return; end;
if isempty(PPfilter_fname)
FilterPath=['Protocols' filesep 'PPfilter.mat'];
else
FilterPath = PPfilter_fname;
end;
PP = load(FilterPath);
PP=PP.PP;
BeforeDuration = BeforeDuration/1000; % Turn everything into seconds
AfterDuration = AfterDuration/1000;
Duration = BeforeDuration + AfterDuration;
BreakFraction = BeforeDuration/Duration;
Breaklen = Breaklen/1000;
if nargin < 9, RiseFall = 0.003; else RiseFall = RiseFall/1000; end;
Tau = Tau/(1000*Duration); % This is in relative units of zero2one vector
% Create a time vector.
t=0:(1/SRate):Duration;
t=t(1:(end-1));
zero2one = (0:length(t)-1) / (length(t)-1);
zero2one = tanh((zero2one - BreakFraction)/Tau);
volume_factor = (F2_volume_factor - F1_volume_factor)*(zero2one+1)/2 + ...
F1_volume_factor;
zero2one = zero2one - min(zero2one); zero2one = zero2one/max(zero2one);
logFrequency = log(StartFreq) + zero2one*(log(EndFreq) - log(StartFreq));
Frequency = exp(logFrequency);
Phi = 2*pi*cumsum(Frequency)*mean(diff(t));
% Attenuation = Att - ppval(PP, log10(Frequency));
% plot(Frequency, Attenuation);
% Attenuation = 5;
[U, I, J] = unique(Frequency);
Attenuation = Att - ppval(PP, log10(U));
Attenuation(Attenuation<0) = 0;
Beep = 10.^(-Attenuation./20);
Beep = Beep(row(J)).* sin(Phi);
Beep = Beep.*volume_factor;
% Edge ramp
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
% Is there a break in the middle of the swoop?
Breaklen = round(Breaklen*SRate);
if Breaklen>0,
[trash, u] = min(abs(zero2one-BreakFraction));
Beep1 = Beep(1:u);
Beep2 = Beep(u+1:end);
if length(Beep1) > LEdge;
Beep1(end-LEdge+1:end) = Beep1(end-LEdge+1:end) .* Edge;
end;
if length(Beep2) > LEdge,
Beep2(1:LEdge) = Beep2(1:LEdge) .* fliplr(Edge);
end;
Beep = [Beep1 ones(1, Breaklen)*Beep1(end) Beep2];
end;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = (cos(t)).^2;
return;
function x=row(x)
x=x(:)';
|
github
|
erlichlab/elutils-master
|
MakeChord.m
|
.m
|
elutils-master/+sound/MakeChord.m
| 2,135 |
utf_8
|
00364a0eb3f67051ad1e59e125a86d24
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeChord
% Generate Chord.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Usage:
% Beep=MakeChord( SRate, Attenuation, BaseFreq, NTones, Duration, [RiseFall] )
% Create a chord with base frequency 'BaseFreq' and with 'NTones' tones.
% 'SRate' is the sample rate in Hz.
% 'Attenuation' is a scalar (0 dB is an amplitude 1 sinusoid.)
% 'BaseFreq' in Hz
% 'Duration' in milliseconds
% A fifth optional parameter 'RiseFall' specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
% added try-catch so that this would work in dispatcher. JCE July 2007
%
function Beep=MakeChord( SRate, Attenuation, BaseFreq, NTones, Duration, varargin )
try
FilterPath=[GetParam('rpbox','protocol_path') '\PPfilter.mat'];
if ( size(dir(FilterPath),1) == 1 )
PP=load(FilterPath);
PP=PP.PP;
else
PP=[];
end
% message(me,'Generating Calibrated Tones');
catch
PP=[];
% message(me,'Generating Non-calibrated Tones');
end
% Create a time vector.
t=0:(1/(SRate)):(Duration/1000);
t=t(1:(end-1));
finterv = sqrt(sqrt(2)); %this stepping yields a diminished minor chord + 13
freq = BaseFreq;
snd = zeros(1,length(t));
for k=1:NTones
if isempty(PP)
ToneAttenuation_adj(k) = Attenuation;
else
ToneAttenuation_adj(k) = Attenuation - ppval(PP, log10( freq ));
% Remove any negative attenuations and replace with zero attenuation.
ToneAttenuation_adj(k) = ToneAttenuation_adj(k) .* (ToneAttenuation_adj(k) > 0);
end
snd = snd + 10^(-ToneAttenuation_adj(k)/20) * ( sin( 2*pi*freq.*t )/NTones ); %IS THIS CORRECT???
freq = freq * finterv;
end
Beep = snd;
% If the user specifies, add edge smoothing.
% This was changed to >=6 to correspond with the actual input variable list
% JCE, July 2007
if ( nargin >= 6 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
end
|
github
|
erlichlab/elutils-master
|
MakeSigmoidSwoop2.m
|
.m
|
elutils-master/+sound/MakeSigmoidSwoop2.m
| 2,507 |
utf_8
|
db64fa6d40a96528a57c83acd4ae8d39
|
%MakeSigmoidSwoop2.m [Beep]=MakeSigmoidSwoop(SRate, SPL, StartFreq, EndFreq, Duration, Tau, Breaklen, [RiseFall=5] )
%
% Makes a sound:
%
% SRate: sampling rate, in samples/sec
% Attenuation
% StartFreq starting frequency of the sound, in Hz
% EndFreq ending frequency of the sound, in Hz
% Duration duration of the nonzero amplitude parts of the sound (excluding breaks), in ms
% Tau Tau of frequency sigmoid, in ms
% Breaklen number of ms of silence inserted into the middle of the tone
% RiseFall width of half-cosine squared edge window, in ms
%
% Carlos Brody 25 Apr 05
function [Beep]=MakeSigmoidSwoop2(SRate, Att, StartFreq, EndFreq, Duration, Tau, Breaklen, RiseFall )
if Duration==0, Beep = []; return; end;
FilterPath=[GetParam('rpbox','protocol_path') filesep 'PPfilter.mat'];
PP = load(FilterPath);
PP=PP.PP;
Tau = Tau/Duration; % This is in relative units for zero2one vector below
Duration = Duration/1000; % Turn everything into seconds
Breaklen = Breaklen/1000;
if nargin < 8, RiseFall = 0.005; else RiseFall = RiseFall/1000; end;
% Create a time vector.
t=0:(1/SRate):Duration;
t=t(1:(end-1));
zero2one = (0:length(t)-1) / (length(t)-1); zero2one = tanh((zero2one - 0.5)/Tau);
zero2one = zero2one - min(zero2one); zero2one = zero2one/max(zero2one);
logFrequency = log(StartFreq) + zero2one*(log(EndFreq) - log(StartFreq));
Frequency = exp(logFrequency);
Phi = 2*pi*cumsum(Frequency)*mean(diff(t));
Attenuation = Att - ppval(PP, log10(Frequency));
Attenuation(find(Attenuation<0)) = 0;
% plot(Frequency, Attenuation);
% Attenuation = 5;
Beep = 1*(10.^(-Attenuation./20) .* sin(Phi));
% Edge ramp
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
% Is there a break in the middle of the swoop?
Breaklen = round(Breaklen*SRate);
if Breaklen>0,
[trash, u] = min(abs(zero2one-0.5));
Beep1 = Beep(1:u);
Beep2 = Beep(u+1:end);
Beep1(end-LEdge+1:end) = Beep1(end-LEdge+1:end) .* Edge;
Beep2(1:LEdge) = Beep2(1:LEdge) .* fliplr(Edge);
Beep = [Beep1 ones(1, Breaklen)*Beep1(end) Beep2];
end;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = (cos(t)).^2;
return;
|
github
|
erlichlab/elutils-master
|
MakeClick.m
|
.m
|
elutils-master/+sound/MakeClick.m
| 1,391 |
utf_8
|
6e51c9a71deabd3dacbf01b3c4d7b57e
|
% [click] = MakeClick({'sigma', 0.0001}, {'power', 1.2})
%
% Makes a single, sharp, brief, broad-band "click!" of amplitude 0.7.
%
% Gets the sampling rate from protocolobj; then makes a
% Gaussian-like function, exp(-|t|^power / (2*sigma^power)) : a
% Guassian would have power=2; then takes the derivative of this
% function. This is returned, with a length from -5*sigma to +5*sigma.
%
% If you want two settings that are different, clearly discriminable to
% the human ear, audible to the rat ear, most likely clearly discriminable
% to the rat ear, and playable at a 50KHz sampling rate, try: sigma=0.0002
% and power=1.5; versus sigma=0.00004, power=1.5. (That is, power 1.5 for
% both cases, and sigma 200 microseconds in case one, 40 microseconds in
% case two.) Case one has peak power at 1KHz and 2KHz; case two has peak
% power at 5kHz and 10kHz.
%
%
% OBLIGATORY PARAMETERS:
% ----------------------
%
% None
%
% OPTIONAL PARAMETERS:
% --------------------
%
% sigma, in milliseconds
%
% power
%
% CDB Feb 06
function [click] = MakeClick(varargin)
sigma = [];
power = [];
pairs = { ...
'sigma' 0.0001 ; ...
'power' 1.2 ; ...
}; parseargs(varargin, pairs);
srate = get_generic('sampling_rate');
t = 0:(1/srate):10*sigma;
click = diff(exp(-abs(t-5*sigma).^power / (2*sigma.^power)));
click = 0.7*click/max(abs(click));
|
github
|
erlichlab/elutils-master
|
MakeBeep4Winsound.m
|
.m
|
elutils-master/+sound/MakeBeep4Winsound.m
| 1,818 |
utf_8
|
83fd71b44c3e6b281395e603e3add516
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeBeep4Winsound
% Generate the individual tone pips as an accessory to PlayTones.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Beep=MakeBeep4Winsound( SRate, Attenuation, Frequency, Duration, varargin )
% MakeBeep
% Usage:
% Beep=MakeBeep( SRate, Attenuation, Frequency, Duration, [RiseFall] )
% Create a sinusoidal beep at frequency Frequency in Hz of duration
% SRate is the sample rate in Hz.
% Attenuation is a scalar.
% If a Attenuation is a vector, a harmonic stack is created with these attenuations.
% Frequency in Hz
% Duration in milliseconds
% A fifth optional parameter RiseFall specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
% Create a time vector.
t=0:(floor(Duration/1000*SRate)-1);
t=t/SRate;
% Make harmonic frequencies.
Freqs=Frequency*(1:length(Attenuation));
Attens=meshgrid(Attenuation,t);
Attens=Attens';
[Freqs,t]=meshgrid(Freqs,t);
Freqs=Freqs';
t=t';
% Create the frequencies in the beep.
%Beep = 10 * (10.^(-Attens./20));
if Frequency < 0
Beep = 1*(10.^(-Attens./20)) .* randn(size(t));
else
Beep = 1*(10.^(-Attens./20)) .* sin( 2*pi* Freqs .* t );
end
% Add harmonic components together.
Beep=sum(Beep,1);
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep(end-LEdge+1:end)=Beep(end-LEdge+1:end) .* Edge;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeBeep : End of function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
erlichlab/elutils-master
|
Make2Sines.m
|
.m
|
elutils-master/+sound/Make2Sines.m
| 2,539 |
utf_8
|
492ef41bbfe84d1b25ae431055ed018e
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make2Sines
% Generate two sine tones with delay.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Usage:
% Beep=Make2Sines( SRate, Attenuation, F1, F2, ToneDuration, Delay, [RiseFall] )
% Create sine tone with frequency f1, delay, and sine tone with freq f2
% 'SRate' is the sample rate in Hz.
% 'Attenuation' is a scalar (0 dB is an amplitude 1 sinusoid.)
% 'F1' and 'F2' in Hz
% 'ToneDuration' and 'Delay' in milliseconds
% A fifth optional parameter 'RiseFall' specifies the 10%-90%
% rise and fall times in milliseconds using a cos^2 edge.
function Beep=Make2Sines( SRate, Attenuation, F1, F2, ToneDuration, Delay, varargin )
FilterPath=[GetParam('rpbox','protocol_path') '\PPfilter.mat'];
if ( size(dir(FilterPath),1) == 1 )
PP=load(FilterPath);
PP=PP.PP;
% message(me,'Generating Calibrated Tones');
else
PP=[];
% message(me,'Generating Non-calibrated Tones');
end
% Create a time vector.
t = 0:(1/SRate):(ToneDuration/1000);
t = t(1:end-1);
%Create F1
if isempty(PP)
ToneAttenuation_adj = Attenuation;
else
ToneAttenuation_adj = Attenuation - ppval(PP, log10( F1 ));
% Remove any negative attenuations and replace with zero attenuation.
ToneAttenuation_adj = ToneAttenuation_adj * (ToneAttenuation_adj > 0);
end
snd = 10^(-ToneAttenuation_adj/20) * sin( 2*pi*F1*t );
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
snd(1:LEdge)=snd(1:LEdge) .* fliplr(Edge);
snd((end-LEdge+1):end)=snd((end-LEdge+1):end) .* Edge;
end
%Create Delay
tmp = 0:(1/SRate):(Delay/1000);
snd2 = zeros(1,length(tmp)-1);
%Create F2
if isempty(PP)
ToneAttenuation_adj = Attenuation;
else
ToneAttenuation_adj = Attenuation - ppval(PP, log10( F2 ));
% Remove any negative attenuations and replace with zero attenuation.
ToneAttenuation_adj = ToneAttenuation_adj * (ToneAttenuation_adj > 0);
end
snd3 = 10^(-ToneAttenuation_adj/20) * sin( 2*pi*F2*t );
% If the user specifies, add edge smoothing.
if ( nargin >= 5 )
RiseFall=varargin{1};
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
% Put a cos^2 gate on the leading and trailing edges.
snd3(1:LEdge)=snd3(1:LEdge) .* fliplr(Edge);
snd3((end-LEdge+1):end)=snd3((end-LEdge+1):end) .* Edge;
end
Beep = [snd, snd2, snd3];
|
github
|
erlichlab/elutils-master
|
MakeSigmoidSwoop.m
|
.m
|
elutils-master/+sound/MakeSigmoidSwoop.m
| 2,211 |
utf_8
|
3f9b0adbb2823476b55a5c7f9523c9bb
|
%MakeSigmoidSwoopm.m [Beep]=MakeSigmoidSwoop(SRate, Attenuation, StartFreq, EndFreq, Duration, Tau, Breaklen, [RiseFall=5] )
%
% Makes a sound:
%
% SRate: sampling rate, in samples/sec
% Attenuation
% StartFreq starting frequency of the sound, in Hz
% EndFreq ending frequency of the sound, in Hz
% Duration duration of the nonzero amplitude parts of the sound (excluding breaks), in ms
% Tau Tau of frequency sigmoid, in ms
% Breaklen number of ms of silence inserted into the middle of the tone
% RiseFall width of half-cosine edge window, in ms
%
% Carlos Brody 21 Apr 05
function [Beep]=MakeSigmoidSwoop(SRate, Attenuation, StartFreq, EndFreq, Duration, Tau, Breaklen, RiseFall )
Tau = Tau/Duration; % This is in relative units for zero2one vector below
Duration = Duration/1000; % Turn everything into seconds
Breaklen = Breaklen/1000;
if nargin < 8, RiseFall = 0.005; else RiseFall = RiseFall/1000; end;
% Create a time vector.
t=0:(1/SRate):Duration;
t=t(1:(end-1));
zero2one = (0:length(t)-1) / (length(t)-1); zero2one = tanh((zero2one - 0.5)/Tau);
zero2one = zero2one - min(zero2one); zero2one = zero2one/max(zero2one);
logFrequency = log(StartFreq) + zero2one*(log(EndFreq) - log(StartFreq));
Frequency = exp(logFrequency);
Phi = 2*pi*cumsum(Frequency)*mean(diff(t));
Beep = 1*(10.^(-Attenuation./20) .* sin(Phi));
% Edge ramp
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
% Is there a break in the middle of the swoop?
Breaklen = round(Breaklen*SRate);
if Breaklen>0,
[trash, u] = min(abs(zero2one-0.5));
Beep1 = Beep(1:u);
Beep2 = Beep(u+1:end);
Beep1(end-LEdge+1:end) = Beep(end-LEdge+1:end) .* Edge;
Beep2(1:LEdge) = Beep2(1:LEdge) .* fliplr(Edge);
Beep = [Beep1 ones(1, Breaklen)*Beep1(end) Beep2];
end;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = cos(t);
return;
|
github
|
erlichlab/elutils-master
|
MakeFMWiggle.m
|
.m
|
elutils-master/+sound/MakeFMWiggle.m
| 2,621 |
utf_8
|
14f4272f26b69bb9edcbd12b347726ad
|
%MakeFMWiggle.m [monosound]=MakeFMWiggle(SRate, Att, Duration, CarrierFreq, ...
% FMFreq, FMAmp, [RiseFall=3] {'volume_factor', 1, 'PPfilter_name', ''})
%
% Makes a sinusoidally wiggling frequency pure tone (i.e., a sinusoidally frequency modulated sine wave):
%
% SRate: sampling rate, in samples/sec
% Attenuation
% Duration length of sound, in secs
% CarrierFreq mean frequency of the sound, in Hz
% FMFreq frequency at which the Carrier frequency will be modulated, in Hz
% FMAmp amplitude of the FM modulation, in Hz.
% RiseFall width of half-cosine squared edge window, in ms
%
% OPTIONAL ARGS:
% --------------
%
% volume_factor default 1; How much to multiply the signal amplitude by
%
% PPfilter_fname full path and filename, including .mat, of a
% file containing filter parameters from speaker
% calibration. If this parameter is left empty, the
% location is drawn from exper's rpbox protocol_path.
%
% Carlos Brody Aug 07
function [Beep]=MakeFMWiggle(SRate, Att, Duration, CarrierFreq, FMFreq, ...
FMAmp, RiseFall, varargin)
if nargin<=7, varargin = {}; end;
pairs = { ...
'volume_factor' 1 ; ...
'PPfilter_fname' '' ; ...
}; parseargs(varargin, pairs);
if Duration==0, Beep = []; return; end;
if isempty(PPfilter_fname) FilterPath=['Protocols' filesep 'PPfilter.mat'];
else FilterPath = PPfilter_fname;
end;
PP = load(FilterPath); PP=PP.PP;
if nargin < 7, RiseFall = 0.003; else RiseFall = RiseFall/1000; end;
% Create a time vector.
t=0:(1/SRate):Duration;
t=t(1:(end-1));
Frequency = CarrierFreq + FMAmp*sin(2*pi*FMFreq*t);
Phi = 2*pi*cumsum(Frequency)*mean(diff(t));
% Attenuation = Att - ppval(PP, log10(Frequency));
% plot(Frequency, Attenuation);
% Attenuation = 5;
[U, I, J] = unique(Frequency);
% Attenuation = Att - ppval(PP, log10(U));
Attenuation = Att - 30*ones(size(U));
Attenuation(find(Attenuation<0)) = 0;
Beep = 10.^(-Attenuation./20);
Beep = Beep(J).* sin(Phi);
Beep = Beep.*volume_factor;
% Edge ramp
Edge=MakeEdge( SRate, RiseFall );
LEdge=length(Edge);
Beep(1:LEdge)=Beep(1:LEdge) .* fliplr(Edge);
Beep((end-LEdge+1):end)=Beep((end-LEdge+1):end) .* Edge;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = (cos(t)).^2;
return;
|
github
|
erlichlab/elutils-master
|
make_pbup.m
|
.m
|
elutils-master/+sound/make_pbup.m
| 8,806 |
utf_8
|
87fd9aa4ca3b776517cfe0782df11b6d
|
% [snd lrate rrate data] = make_pbup(R, g, srate, T, varargin)
%
% Makes Poisson bups
% bup events from the left and right speakers are independent Poisson
% events
%
% =======
% inputs:
%
% R total rate (in clicks/sec) of bups from both left and right
% speakers (r_L + r_R). Note that if distractor_rate > 0, then R
% includes these stereo distractor bups as well.
%
% g the natural log ratio of right and left rates: log(r_R/r_L)
%
% srate sample rate
%
% T total time (in sec) of Poisson bup trains to be generated
%
% =========
% varargin:
%
% bup_width
% width of a bup in msec (Default 3)
% base_freq
% base frequency of an individual bup, in Hz. The individual bup
% consists of this in combination with ntones-1 octaves above the
% base frequency. (Default 2000)
%
% ntones
% number of tones comprising each individual bup. The bup is the
% basefreq combined with ntones-1 higher octaves. (Default 5)
%
% bup_ramp
% the duration in msec of the upwards and downwards volume ramps
% for individual bups. The bup volume ramps up following a cos^2
% function over this duration and it ramps down in an inverse
% fashion.
%
% first_bup_stereo
% if 1, then the first bup to occur is forced to be stereo
%
% distractor_rate
% if >0, then this is the rate of stereo distractors (bups that
% are played on both speakers). These stereo bups are generated
% as Poisson events and then combined with those generated for
% left and right sides.
% note that this value affects the R used to compute independent
% Poisson rates for left and right sides, such that
% R = R - 2*distractor_rate
%
% generate_sound
% if 1, then generate the snd vector
% if 0, the snd vector will be empty; data will still contain the
% bups times
%
% fixed_sound
% if [], then generate new pbups sound
% if not empty, then should contain a struct D with fields:
% D.left = [left bup times]
% D.right = [right bup times]
% D.lrate
% D.rrate
% these two vectors should be at least as long as T, so there's
% no gap in the sound that's generated
%
% crosstalk
% [left_crosstalk right_crosstalk]
% between 0 and 1, determines volume of left clicks that are
% heard in the right channel, and vice versa.
% if only number is provided, the crosstalk is assumed to be
% symmetric (i.e., left_crosstalk = right_crosstalk)
%
% avoid_collisions
% produces a pseudo-poisson clicks train where no clicks are
% allowed to overlap. If the click rate is so high that
% collisions are unavoidable a warning will be displayed
% added: Chuck 2010-10-05
%
% force_count
% produces a pseudo-poisson click train where the precise number
% of clicks is predetermined. The rate variables are interpreted
% as counts.
% added: Chuck 2010-10-05
%
% ========
% outputs:
%
% snd a vector representing the sound generated
%
% lrate rate of Poisson events generated only on the left
%
% rrate rate of Poisson events generated only on the right
%
% data a struct containing the actual bup times (in sec, centered in
% middle of every bup) in snd.
% data.left and data.right
%
function [snd lrate rrate data] = make_pbup(R, g, srate, T, varargin)
pairs = {...
'bup_width', 3; ...
'base_freq', 2000; ...
'ntones', 5; ...
'bup_ramp', 2; ...
'first_bup_stereo' 0; ...
'distractor_rate' 0; ...
'generate_sound' 1; ...
'fixed_sound' []; ...
'crosstalk' [0 0]; ...
'avoid_collisions' 0; ...
'force_count' 0; ...
}; parseargs(varargin, pairs);
if isempty(crosstalk), crosstalk = [0 0]; end; %#ok<NODEF>
if numel(crosstalk) < 2, crosstalk = crosstalk*[1 1]; end;
if isempty(fixed_sound),
if distractor_rate > 0,
R = R - distractor_rate*2;
end;
% rates of Poisson events on left and right
rrate = R/(exp(-g)+1);
lrate = R - rrate;
if force_count == 1
%rates are interpreted as counts and therefore must be integers
rrate = round(rrate);
lrate = round(lrate);
end
%t = linspace(0, T, srate*T);
lT = srate*T; %the length of what previously was the t vector
if avoid_collisions == 1
lT2 = ceil(T * 1e3 / bup_width);
if force_count == 1
if ~isnan(lrate); temp = randperm(lT2); tp1 = temp(1:lrate); tp1 = sortrows(tp1')'; else tp1 = []; end
if ~isnan(rrate); temp = randperm(lT2); tp2 = temp(1:rrate); tp2 = sortrows(tp2')'; else tp2 = []; end
else
if ~isnan(lrate); tp1 = find(rand(1,lT2) < lrate/(1e3/bup_width)); else tp1 = []; end
if ~isnan(rrate); tp2 = find(rand(1,lT2) < rrate/(1e3/bup_width)); else tp2 = []; end
end
if first_bup_stereo,
first_bup = min([tp1 tp2]);
bupwidth = 1;
if first_bup <= bupwidth, extra_bup = first_bup;
else extra_bup = ceil(rand(1)*(first_bup-bupwidth));
end;
tp1 = union(extra_bup, tp1);
tp2 = union(extra_bup, tp2);
end
if distractor_rate > 0,
if force_count == 1
temp = randperm(lT2); td = temp(1:round(distractor_rate)); td = sortrows(td')';
else
td = find(rand(1,lT2) < distractor_rate/(1e3/bup_width));
end
tp1 = union(td, tp1);
tp2 = union(td, tp2);
end
if (lrate + distractor_rate) * bup_width > 200 || (rrate + distractor_rate) * bup_width > 200
disp('Warning: Click rate is set to high to ensure Poisson train with avoid_collisions on');
end
tp1 = tp1 * (srate / (1e3 / bup_width));
tp2 = tp2 * (srate / (1e3 / bup_width));
else
% times of the bups are Poisson events
if force_count == 1
if ~isnan(lrate); temp = randperm(lT); tp1 = temp(1:lrate); tp1 = sortrows(tp1')'; else tp1 = []; end
if ~isnan(rrate); temp = randperm(lT); tp2 = temp(1:rrate); tp2 = sortrows(tp2')'; else tp2 = []; end
else
if ~isnan(lrate); tp1 = find(rand(1,lT) < lrate/srate); else tp1 = []; end
if ~isnan(rrate); tp2 = find(rand(1,lT) < rrate/srate); else tp2 = []; end
end
% in order not to alter the difference in bup numbers between left and
% right, the extra stereo bup is placed randomly somewhere between 0 and
% the earliest bup on either side
if first_bup_stereo,
first_bup = min([tp1 tp2]);
bupwidth = bup_width*srate/2;
if first_bup <= bupwidth,
extra_bup = first_bup;
else
extra_bup = ceil(rand(1)*(first_bup-bupwidth) + bupwidth);
end;
tp1 = union(extra_bup, tp1);
tp2 = union(extra_bup, tp2);
end;
if distractor_rate > 0,
if force_count == 1
temp = randperm(lT); td = temp(1:round(distractor_rate)); td = sortrows(td')';
else
td = find(rand(1,lT) < distractor_rate/srate);
end
tp1 = union(td, tp1);
tp2 = union(td, tp2);
end;
end
data.left = tp1/srate;
data.right = tp2/srate;
else % if we've provided bupstimes for which a sound will be made
lrate = fixed_sound.lrate;
rrate = fixed_sound.rrate;
data.left = fixed_sound.left;
data.right = fixed_sound.right;
tp1 = round(fixed_sound.left*srate);
tp2 = round(fixed_sound.right*srate);
%t = linspace(0, T, srate*T);
lT = srate*T;
end;
if generate_sound,
bup = singlebup(srate, 0, 'ntones', ntones, 'width', bup_width, 'basefreq', base_freq, 'ntones', ntones, 'ramp', bup_ramp);
w = floor(length(bup)/2);
snd = zeros(2, lT);
for i = 1:length(tp1), % place left bups
if tp1(i) > w && tp1(i) < lT-w,
snd(1,tp1(i)-w:tp1(i)+w) = snd(1,tp1(i)-w:tp1(i)+w)+bup;
end;
end;
for i = 1:length(tp2), % place right bups
if tp2(i) > w && tp2(i) < lT-w,
snd(2,tp2(i)-w:tp2(i)+w) = snd(2,tp2(i)-w:tp2(i)+w)+bup;
end;
end;
if sum(crosstalk) > 0, % implement crosstalk
temp_snd(1,:) = snd(1,:) + crosstalk(2)*snd(2,:);
temp_snd(2,:) = snd(2,:) + crosstalk(1)*snd(1,:);
% normalize the sound so that the volume (summed across both
% speakers) is the same as the original snd before crosstalk
ftemp_snd = fft(temp_snd,2);
fsnd = fft(snd,2);
Ptemp_snd = ftemp_snd .* conj(ftemp_snd);
Psnd = fsnd .* conj(fsnd);
vol_scaling = sqrt(sum(Psnd(:))/sum(Ptemp_snd(:)));
snd = real(ifft(ftemp_snd * vol_scaling));
end;
snd(snd>1) = 1;
snd(snd<-1) = -1;
else
snd = [];
end;
|
github
|
erlichlab/elutils-master
|
MakeEdge.m
|
.m
|
elutils-master/+sound/MakeEdge.m
| 783 |
utf_8
|
8536b947788790f936e5ead9be58a078
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeEdge
% Generate the rising/falling edge as an accessory to MakeBeep.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Edge=MakeEdge( SRate, RiseFall )
% Usage:
% Edge=MakeEdge( SRate, RiseFall )
% Calculate a cos^2 gate for the trailing edge that has a 10%-90%
% fall time of RiseFall in milliseconds given sample rate SRate in Hz.
omega=(1e3/RiseFall)*(acos(sqrt(0.1))-acos(sqrt(0.9)));
t=0 : (1/SRate) : pi/2/omega;
t=t(1:(end-1));
Edge= ( cos(omega*t) ).^2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MakeEdge : End of function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
erlichlab/elutils-master
|
singlebup.m
|
.m
|
elutils-master/+sound/singlebup.m
| 1,377 |
utf_8
|
0be7b1a1e09b4be4290028c14fac66ae
|
% [snd] = singlebup(srate, att, { 'width', 5}, {'ramp', 2}, {'basefreq', 2000}, ...
% {'ntones' 5}, {'PPfilter_fname', ''}); ...
function [snd] = singlebup(srate, att, varargin)
width=5 ;
ramp = 2 ;
basefreq = 2000 ;
ntones = 5 ;
PPfilter_fname= '' ;
utils.overridedefaults(who, varargin);
width = width/1000;
ramp = ramp/1000;
if isempty(PPfilter_fname)
FilterPath=['Protocols' filesep 'PPfilter.mat'];
else
FilterPath = PPfilter_fname;
end;
PP = load(FilterPath);
PP=PP.PP;
t = 0:(1/srate):width;
snd = zeros(size(t));
for i=1:ntones,
f = basefreq*(2.^(i-1));
attenuation = att - ppval(PP, log10(f));
snd = snd + (10.^(-attenuation./20)) .* sin(2*pi*f*t);
end;
if max(abs(snd)) >= 1, snd = snd/(1.01*max(abs(snd))); end;
rampedge=MakeEdge(srate, ramp); ramplen = length(rampedge);
snd(1:ramplen) = snd(1:ramplen) .* fliplr(rampedge);
snd(end-ramplen+1:end) = snd(end-ramplen+1:end) .* rampedge;
return;
% -------------------------------------------------------------
%
%
%
% -------------------------------------------------------------
function [envelope] = MakeEdge(srate, coslen)
t = (0:(1/srate):coslen)*pi/(2*coslen);
envelope = (cos(t)).^2;
return;
|
github
|
virati/SGView-master
|
SG_view.m
|
.m
|
SGView-master/SG_view.m
| 78,170 |
utf_8
|
012bb7c3e7682c1678c29a1f1369c165
|
%%
%Written by: Vineet Tiruvadi 2013-2016
%SG Viewer
%Main Gui for rapid viewing and spectral figures of BrainRadio and hdEEG
%data for MaybergLab.
function varargout = SG_view(varargin)
% SG_VIEW MATLAB code for SG_view.fig
% SG_VIEW, by itself, creates a new SG_VIEW or raises the existing
% singleton*.DBS901-Chronic-5day_perday.fig
%
% H = SG_VIEW returns the handle to a new SG_VIEW or the handle to
% the existing singleton*.
%
% SG_VIEW('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SG_VIEW.M with the given input arguments.
%
% SG_VIEW('Property','Value',...) creates a new SG_VIEW or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before SG_view_OpeningFcn gets called. Anhttp://proxy.library.emory.edu/login?url=
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to SG_view_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help SG_view
% Last Modified by GUIDE v2.5 06-Jun-2017 18:02:40
addpath(genpath('lib'))
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @SG_view_OpeningFcn, ...
'gui_OutputFcn', @SG_view_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before SG_view is made visible.
function SG_view_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to SG_view (see VARARGIN)
% Choose default command line output for SG_view
handles.output = hObject;
handles.svInts.num = 1;
handles.interval_colors = {'k','b','m','c','r','g','y','k'};
%Hardload settings
handles.LFP_HardLoad = '';
handles.EEG_HardLoad = '';
%General directory settings
handles.LFP_dir = '~/local_data/BR';
handles.EEG_dir = '~/local_data/hdEEG';
handles.LFP_curr_dir = handles.LFP_dir;
handles.welchPSD = [];
handles.welchBounds = [];
handles.welchColor = {};
handles.pmap = colormap('lines');
colormap('default');
%Figure variables
handles.tdFig = 0;
%What should every modality be sampled to? This INTERPOLATES, need to make
%sure at every step that this is ok
handles.DATA.common_Fs = 422;
handles.BLP_pow = [];
handles.brLFP.Fs = str2num(get(handles.edtLFP_Fs,'String'));
%% NEW STRUCTURES
%Assume 260 channels, set up the UI channel list
for ii = 1:260
handles.DATA.UI_TS_List{ii} = [num2str(ii) ': Empty'];
end
handles.DATA.TS_List = zeros(260,1);
%variable for address of current active channel
%Start at 0, so throws exception if not properly handled after
%initialization
handles.UI.active_chann = 0;
%%
%Analysis tracking
handles.SG.SG_Labels = {};
handles.SG.Done = zeros(260,1);
handles.ANALYSIS.ds_factor = 1;
%Bigger one for the bar plots across files/patients
handles.ANALYSIS.Aggr.idx = 0;
%%
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes SG_view wait for user response (see UIRESUME)
% uiwait(handles.figure1);
function LoadEEG(hObject,eventdata,handles,eeg_fname,eeg_dir)
handles.RAW.EEG = [];
disp('Loading EEG...');
%Linux
handles.DATA.EEG.locs = readlocs('~/Dropbox/projects/Research/MDD-DBS/Ephys/hdEEG/GSN257.sfp');
%Windows
%handles.DATA.EEG.locs = readlocs('C:\Users\Vineet\Dropbox\projects\Research\MDD-DBS\Ephys\hdEEG\GSN257.sfp');
handles.RAW.EEG.rawdata = load([eeg_dir eeg_fname{1}]);
handles.RAW.EEG.Fs = handles.RAW.EEG.rawdata.EEGSamplingRate;
%Display information in UI
set(handles.edtEEGfname,'String',eeg_fname{1});
set(handles.edtEEG_Fs,'String',num2str(handles.RAW.EEG.Fs));
%Find the fieldnames
list_fields = fieldnames(handles.RAW.EEG.rawdata);
handles.DATA.EEG.ts = handles.RAW.EEG.rawdata.(list_fields{1});
ts_size = size(handles.DATA.EEG.ts);
avg_idx = ts_size(1)+1;
%This will be expanded and incorporate a configuration file/viewer so
%can quickly switch between configs/montages
%channel_list = {[32],[37],[25],[18],[241],[244],[238],[234],[89],[88],[130],[142],[136],[135],[148],[157],[9],[45],[186],[132]};
%Differential channels
% Subset indeed
handles.DATA.EEG.SubSet = {[32,37],[25,18],[241,244],[238,234],[89,88],[130,142],[136,135],[148,157],[9,45],[186,132]};
%handles.DATA.EEG.SubSetLabels = {};
%Single channels
%handles.DATA.EEG.SubSet = {[32],[37],[25],[18],[241],[244],[238],[234],[89],[88],[130],[142],[136],[135],[148],[157],[9],[45],[186],[132]};
%Avg Reference
%handles.DATA.EEG.SubSet = {[32,avg_idx],[37,avg_idx],[25,avg_idx],[18,avg_idx],[241,avg_idx],[244,avg_idx],[238,avg_idx],[234,avg_idx],[89,avg_idx],[88,avg_idx],[130,avg_idx],[142,avg_idx],[136,avg_idx],[135,avg_idx],[148,avg_idx],[157,avg_idx],[9,avg_idx],[45,avg_idx],[186,avg_idx],[132,avg_idx]};
%Just load all
% for ii = 1:257
% handles.DATA.EEG.SubSet{ii} = [ii];
% end
%Compute the channel average reference
handles.DATA.EEG.ts(end+1,:) = mean(handles.DATA.EEG.ts,1);
%Load in the EEG channels from the Subset variable
for ii = 1:length(handles.DATA.EEG.SubSet)
eeg_chann = cell2mat(handles.DATA.EEG.SubSet(ii));
if numel(eeg_chann) == 1
handles.DATA.chann{ii+2}.ts = detrend(handles.DATA.EEG.ts(eeg_chann,:));
handles.DATA.chann{ii+2}.label = ['EEG Channel ' num2str(eeg_chann)];
else
handles.DATA.chann{ii+2}.ts = detrend(handles.DATA.EEG.ts(eeg_chann(1),:) - handles.DATA.EEG.ts(eeg_chann(2),:));
handles.DATA.chann{ii+2}.label = ['EEG Diff Channel ' num2str(eeg_chann(1)) ' : ' num2str(eeg_chann(2))];
end
handles.DATA.chann{ii+2}.Fs = handles.RAW.EEG.Fs;
handles.DATA.chann{ii+2}.num = ii+2;
%Setup all EEG channels to be shifted when choosing windows
handles.DATA.chann{ii+2}.doShift = 1;
end
add_channs = length(handles.DATA.EEG.SubSet)-1
handles.DATA.TS_List(3:3+add_channs) = 1;
%Now do UI stuff, like populating the channel popdown for timedomain
for ii = 1:length(handles.DATA.EEG.SubSet)
handles.DATA.UI_TS_List{ii+2} = [num2str(ii+2) ':' handles.DATA.chann{ii+2}.label];
end
set(handles.popChannTs,'String',handles.DATA.UI_TS_List);
disp('...EEG File Loaded');
guidata(hObject,handles);
%Loading of data function, this is for the brainradio LFP,
%SINGLE FILES ONLY/EXPERIMENTS
function LoadLFP(hObject, eventdata, handles, data_loc)
handles.RAW.LFP = [];
disp('Loading LFP...');
%Load in data from data_loc(ation) structure argument
raw_data = dlmread([data_loc.data_path data_loc.data_file]);
handles.RAW.LFP.rawdata = raw_data(:,[1,3]);
handles.RAW.LFP.file = data_loc;
%!!CHANGEBACK TO 422
handles.RAW.LFP.rawFs = str2num(get(handles.edtLFP_Fs,'String'));
%Reflect changes in UI
set(handles.editFname,'String',data_loc.data_file);
set(handles.cmdAvgSpectr,'Enable','off');
handles.LFP_curr_dir = data_loc.data_path;
%Interpolation and channel timeseries structures
%handles.CHANN.ts will ALWAYS sampled at 1000Hz; though, here, the sizes
%may not be consistent...
for ii = 1:2
handles.DATA.chann{ii}.ts = resample(handles.RAW.LFP.rawdata(:,ii),handles.DATA.common_Fs,handles.RAW.LFP.rawFs);
handles.DATA.chann{ii}.Fs = handles.RAW.LFP.rawFs * handles.DATA.common_Fs / handles.RAW.LFP.rawFs;
handles.DATA.chann{ii}.doShift = 0;
handles.DATA.chann{ii}.num = ii;
end
handles.DATA.TS_List(1:2) = [1 1];
handles.DATA.chann{1}.label = ['LFP Channel Left'];
handles.DATA.chann{2}.label = ['LFP Channel Right'];
handles.DATA.UI_TS_List{1} = [num2str(1) ':' handles.DATA.chann{1}.label];
handles.DATA.UI_TS_List{2} = [num2str(2) ':' handles.DATA.chann{2}.label];
set(handles.popChannTs,'String',handles.DATA.UI_TS_List);
disp('...Raw LFP loaded');
handles.UI.active_chann = 1;
guidata(hObject,handles);
% --- Outputs from this function are returned to the command line.
function varargout = SG_view_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%This function is for LOADING THE CURRENT DATA
%Includes BR and (aspirationally) hdEEG data
% --- Executes on button press in cmdLoad.
function cmdLoad_Callback(hObject, eventdata, handles)
% hObject handle to cmdLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB30816
% handles structure with handles and user data (see GUIDATA)
[data_file data_path] = uigetfile({'*.txt'},'Pick BR Data File',handles.LFP_curr_dir,'MultiSelect','On')
data_info.data_file = data_file;
data_info.data_path = data_path;
LoadLFP(hObject,eventdata,handles,data_info);
%This button ALWAYS redoes analysis on all channels
%And resets analysis sets (display sets)
% --- Executes on button press in cmdLFP_TF.
% function cmdLFP_TF_Callback(hObject, eventdata, handles)
% % hObject handle to cmdLFP_TF (see GCBO)
% % eventdata reserved - to be defined in a future version of MATLAB
% % handles structure with handles and user data (see GUIDATA)
%
% disp('Generating [Spectrograms] for all channels...');
%
% ds_fact = str2num(get(handles.edtDownsample,'String'));
% %Preprocessing steps here
%
% %Clear current downsampled signals and spectrograms
% handles.brLFP.ds = [];
% handles.SG = [];
%
% handles.brLFP.ds(:,1) = decimate(handles.brLFP.rawdata{1}(1,:),ds_fact);
% handles.brLFP.ds(:,2) = decimate(handles.brLFP.rawdata{1}(2,:),ds_fact);
% handles.brLFP.aFs = handles.brLFP.Fs/ds_fact;
%
% handles.anls.data = {};
%
% if (get(handles.cbFilter,'Value'))
% disp('Filtering...');
% lpf_50 = lowpass_gen(handles.brLFP.aFs);
% handles.anls.data{end}(1,:) = filtfilthd(lpf_50,handles.anls.data{end}(1,:));
% handles.anls.data{end}(2,:) = filtfilthd(lpf_50,handles.anls.data{end}(2,:));
% end
%
% sgWin = str2num(get(handles.edSgWin,'String'));
% sgDispl = str2num(get(handles.edSgDispl,'String'));
% sgNfft = str2num(get(handles.edSgNFFT,'String'));
%
% %Does the spectrogram analysis
% for c_num = 1:2
% [handles.CHANN.SG{c_num}.S handles.CHANN.SG{c_num}.F handles.CHANN.SG{c_num}.T] = spectrogram(handles.brLFP.ds(:,c_num),blackmanharris(sgWin),sgDispl,sgNfft,handles.brLFP.aFs);
% end
%
% handles.SG.Method = 'PWelch STFT';
%
% %Which channel to plot here
% colormap('jet');
% achann = handles.UI.active_chann;
% imagesc(handles.CHANN.SG{achann}.T, handles.CHANN.SG{achann}.F, 10*log10(abs(handles.CHANN.SG{achann}.S)),[-50 0]);set(gca,'YDir','normal');colorbar();
% title(['Channel ' num2str(achann)]);
%
% disp('...Done [Spectrograms]');
%
% handles.run_mean = [];
% handles.run_length = 0;
% handles.run_mean_color = {};
%
% guidata(hObject,handles);
%
% --- Executes during object creation, after setting all properties.
function editFname_CreateFcn(hObject, eventdata, handles)
% hObject handle to editFname (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edSgWin_CreateFcn(hObject, eventdata, handles)
% hObject handle to edSgWin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edSgDispl_CreateFcn(hObject, eventdata, handles)
% hObject handle to edSgDispl (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edSgNFFT_CreateFcn(hObject, eventdata, handles)
% hObject handle to edSgNFFT (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edtIStart_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtIStart (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edtIEnd_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtIEnd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edtI2Start_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtI2Start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function edtI2End_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtI2End (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%MAIN 1-D PLOTTING FUNCTION BELOW
% --- Executes on button press in cmdSelect.
%OLDOLDOLD
% function cmdSelect_Callback(hObject, eventdata, handles)
% % hObject handle to cmdSelect (see GCBO)
% % eventdata reserved - to be defined in a future version of MATLAB
% % handles structure with handles and user data (see GUIDATA)
%
% sig_cont = select_window(hObject,eventdata,handles);
%
% PSD_estimate(handles,handles.UI.active_chann,sig_cont);
%
%
% colormap('jet');
%
% axes(handles.axes1);
% iv_rect = getrect();
%
% use_welch = 1;
%
% clear l_hpsd r_hpsd;
% [itv,t_vect] = iv_to_ts(handles,iv_rect);
%
% if use_welch
% %Uses the Welch Estimate
% [l_hpsd] = intrv_spectra(hObject,eventdata,handles,itv,'left');
% [r_hpsd] = intrv_spectra(hObject,eventdata,handles,itv,'right');
% end
%
% rectangle('Position',[iv_rect(1), 0, iv_rect(3), 100],'LineWidth',4,'EdgeColor',handles.pmap(handles.svInts.num+1,:));
%
% PSD_plotting(hObject,eventdata,handles,l_hpsd,'Left');
function PSD_plotting(hObject,eventdata,handles,PSD,fig_title)
handles.svInts.num = handles.svInts.num + 1;
figure(handles.ag_spect);
%suptitle(fig_title);
% %Display spectrogram for each interval
% subplot(3,2,1);
% imagesc(PSD.sgT,PSD.sgF,10*log10(abs(PSD.sg)));
% set(gca,'YDir','normal');
%pwelch estimate
subplot(3,2,2:4);
hold on;
for ii = 1:2
b(:,1,ii) = abs(10*log10(PSD.P(:,ii)) - 10*log10(PSD.PC(:,1,ii)));
b(:,2,ii) = abs(10*log10(PSD.P(:,ii)) - 10*log10(PSD.PC(:,2,ii)));
end
%Need to do running matrix of all PSDs being plotted and all bs
handles.runPSD = [handles.runPSD, PSD.P];
handles.runBounds = cat(3,handles.runBounds,b);
handles.runColor{handles.svInts.num} = handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1};
pmap = handles.pmap;
boundedline(PSD.welchF,10*log10(handles.welchPSD),handles.welchBounds,'cmap',pmap,'alpha');
%boundedline(PSD.welchF,10*log10(PSD.welch),b,handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1},'alpha');
title('Welch Estimate');
xlabel('Freq (Hz)');ylabel('Power (dB)');
xlim([0 25]);
%Save to handles.spectra{associated index}
handles.PSD_estimates{handles.svInts.num}.LEFT = PSD.welch;
handles.PSD_estimates{handles.svInts.num}.Freqs = PSD.welchF;
% subplot(3,1,2);
% boundedline(PSD.sgF,10*log10(PSD.sg_m),1.96 * (10*log10(PSD.sg_s))/sqrt(PSD.sg_n),handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1},'alpha');hold on;
%
% xlim([0 25]);
% xlabel('Frequency (Hz)');
% ylabel('Power (dB)');
% title('Spectrogram Average Estimate');
% subplot(3,1,3);
% b_mts(:,1) = abs(10*log10(LEFT.l_mts) - 10*log10(LEFT.l_mts_ci(1,:)'));
% b_mts(:,2) = abs(10*log10(LEFT.l_mts) - 10*log10(LEFT.l_mts_ci(1,:)'));
%
% boundedline(LEFT.l_mts_f,10*log10(LEFT.l_mts),b_mts,handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1},'alpha');
% xlabel('Frequency (Hz)');
% ylabel('Power (dB)');
% xlim([0 50]);s
% title('Multitaper Estimate');
plot_ratio = 0;
subplot(3,2,5:6);
if plot_ratio
%subplot(3,2,5:6);
if handles.svInts.num >= 2
plot(handles.PSD_estimates{1}.Freqs,10*log10(handles.PSD_estimates{2}.LEFT ./ handles.PSD_estimates{1}.LEFT));hold on;
end
xlim([0 25]);
title('Log Power Ratio')
else
%Plot band limited power
alphalim = [8,14];
thetalim = [4,8];
alpha_mask = find(PSD.welchF > alphalim(1) & PSD.welchF < alphalim(2));
theta_mask = find(PSD.welchF > thetalim(1) & PSD.welchF < thetalim(2));
alpha_pow = mean(PSD.welch(alpha_mask));
theta_pow = mean(PSD.welch(theta_mask));
handles.Alpha_pow = [handles.Alpha_pow,alpha_pow];
handles.Theta_pow = [handles.Theta_pow,theta_pow];
bar_h = bar([handles.Alpha_pow;handles.Theta_pow]);
for kk = 1:length(bar_h)
set(bar_h(kk),'FaceColor',pmap(kk,:));
end
set(gca,'XTickLabel',{'Alpha','Theta'});
end
set(findall(gcf,'-property','FontSize'),'FontSize',24);
guidata(hObject,handles);
function [nbounds,tvect] = iv_to_ts(handles,iv_rect,lim_time)
iv_start = iv_rect(1);
if lim_time == 0
iv_end = iv_rect(1)+iv_rect(3);
else
iv_end = iv_rect(1)+lim_time;
end
if iv_start < 0
iv_start = 0;
end
if iv_end > (length(handles.DATA.chann{handles.UI.active_chann}.ts) / handles.DATA.chann{handles.UI.active_chann}.Fs)
iv_end = length(handles.DATA.chann{handles.UI.active_chann}.ts) / handles.DATA.chann{handles.UI.active_chann}.Fs;
end
nbounds = [iv_start iv_end] * handles.DATA.chann{handles.UI.active_chann}.Fs + 1; %+1 to account for no 0 index
tvect = linspace(iv_start,iv_end,(iv_end - iv_start) * handles.DATA.chann{handles.UI.active_chann}.Fs);
% --- Executes on button press in cmdSvInt.
function cmdSvInt_Callback(hObject, eventdata, handles)
% hObject handle to cmdSvInt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.svInts.num = handles.svInts.num + 1;
handles.svInts.Int{handles.svInts.num}.file = get(handles.editFname,'String');
handles.svInts.Int{handles.svInts.num}.tInt = handles.curr_Int.t_Int;
handles.svInts.Int{handles.svInts.num}.label = get(handles.edtIntLabel,'String');
handles.svInts.Int{handles.svInts.num}.l_psd = handles.curr_Int.l_hpsd;
handles.svInts.Int{handles.svInts.num}.r_psd = handles.curr_Int.r_hpsd;
base_list = get(handles.lsbIvs,'String');
base_list = strvcat(char(base_list),handles.svInts.Int{handles.svInts.num}.label);
set(handles.lsbIvs,'String',cellstr(base_list));
guidata(hObject,handles);
% --- Executes on selection change in lsbIvs.
function lsbIvs_Callback(hObject, eventdata, handles)
% hObject handle to lsbIvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns lsbIvs contents as cell array
% contents{get(hObject,'Value')} returns selected item from lsbIvs
% --- Executes during object creation, after setting all properties.
function lsbIvs_CreateFcn(hObject, eventdata, handles)
% hObject handle to lsbIvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cmdLoadInt.
function cmdLoadInt_Callback(hObject, eventdata, handles)
% hObject handle to cmdLoadInt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.ANALYSIS.active_figure = figure();
%Refresh SG main axes
%Plot the active chann
SG_Plot_Chann(hObject,handles,handles.UI.active_chann);
%Reset the interval count
handles.ANALYSIS.active_interval = 0;
handles.ANALYSIS.intv = {};
handles.ANALYSIS.Aggr.idx = handles.ANALYSIS.Aggr.idx + 1;
%
%handles.ag_spect = figure;
% handles.svInts.num = 0;
% handles.sel = 0;
% handles.freq_means = [];
%
% handles.welchPSD = [];
% handles.welchBounds = [];
% handles.Alpha_pow = [];
% handles.Theta_pow = [];
guidata(hObject,handles);
function edtIntLabel_Callback(hObject, eventdata, handles)
% hObject handle to edtIntLabel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtIntabel as text
% str2double(get(hObject,'String')) returns contents of edtIntLabel as a double
% --- Executes during object creation, after setting all properties.
function edtIntLabel_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtIntLabel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cbFilter.
function cbFilter_Callback(hObject, eventdata, handles)
% hObject handle to cbFilter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cbFilter
% --- Executes on button press in cmdTime.
%Displays the time series for the rectangle chosen
function cmdTime_Callback(hObject, eventdata, handles)
% hObject handle to cmdTime (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1);
iv_rect = getrect();
iv_start = iv_rect(1);
iv_end = iv_rect(1)+iv_rect(3);
if iv_start < 0
iv_start = 0;
end
if iv_end > (length(handles.brLFP.ds(:,1)) / handles.brLFP.aFs)
iv_end = length(handles.brLFP.ds(:,1)) / handles.brLFP.aFs;
end
iv = [iv_start iv_end] * handles.brLFP.aFs + 1;
t_vect = linspace(iv_start,iv_end,(iv_end - iv_start) * handles.brLFP.aFs + 1);
t_sig = handles.brLFP.ds(iv(1):iv(2),:);
figure;
subplot(3,1,1);
plot(t_vect,t_sig(:,1)); hold on;
plot(t_vect,t_sig(:,2),'r');
set(findall(gcf,'-property','FontSize'),'FontSize',24);
%set(findall(gcf,'-property','FontName'), 'Helvetica');
subplot(3,1,3);
[acor, lag] = xcorr(t_sig(:,1),t_sig(:,2),'coeff');
plot(lag,acor);
write_file = 1;
if write_file
dlmwrite('/tmp/left_time_sig.txt',[t_vect;t_sig(:,1)'],'delimiter',',');
dlmwrite('/tmp/right_time_sig.txt',[t_vect;t_sig(:,2)'],'delimiter',',');
end
% --- Executes on button press in cmdSvBL.
function cmdSvBL_Callback(hObject, eventdata, handles)
% hObject handle to cmdSvBL (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.baselineInt.left = handles.curr_Int.left;
handles.baselineInt.right = handles.curr_Int.right;
guidata(hObject,handles);
function edtIntLength_Callback(hObject, eventdata, handles)
% hObject handle to edtIntLength (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtIntLength as text
% str2double(get(hObject,'String')) returns contents of edtIntLength as a double
% --- Executes during object creation, after setting all properties.
function edtIntLength_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtIntLength (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edtDownsample_Callback(hObject, eventdata, handles)
% hObject handle to edtDownsample (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtDownsample as text
% str2double(get(hObject,'String')) returns contents of edtDownsample as a double
% --- Executes during object creation, after setting all properties.
function edtDownsample_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtDownsample (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cmdAvgSpectr.
function cmdAvgSpectr_Callback(hObject, eventdata, handles)
% hObject handle to cmdAvgSpectr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.svInts.num = handles.svInts.num + 1;
%Periodogram
for ii = 1:length(handles.anls.multi_data)
%precondition signal
sig_n = detrend(handles.anls.multi_data{ii}(1,:),'constant');
%Take just the last part of sig_n, minus the initial transient
sig_n = sig_n(end - 5*handles.brLFP.aFs:end);
%[Lpxx(ii,:),Lf] = periodogram(handles.anls.multi_data{ii}(1,:),blackmanharris(length(handles.anls.multi_data{ii}(1,:))),1024*2,handles.brLFP.aFs);
[Lpxx(ii,:),Lf] = pwelch(sig_n,blackmanharris(5 * handles.brLFP.aFs),[],2056,handles.brLFP.aFs);
disp(num2str(size(sig_n)));
end
if ~isfield(handles,'avgSpect')
handles.avgSpect = figure();
end
avgLp = mean(Lpxx,1);
%stdLp = std(10*log10(Lpxx),[],1);
stdLp = std(Lpxx,[],1);
rngLp = range(Lpxx,1);
figure(handles.avgSpect);
subplot(4,1,1);
plot(Lf,10*log10(avgLp),handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1});hold on;
xlim([0 50]);
subplot(4,1,2);
boundedline(Lf,10*log10(avgLp),2*(10*log10(stdLp))/sqrt(length(handles.anls.multi_data)),handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1},'alpha')%,handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1},'alpha');hold on;
xlim([0 50]);
%Subplot for theta, alpha, beta band limited
theta_mask = (Lf > 4 ) & (Lf < 8);
theta_band_spectr = avgLp .* theta_mask';
theta_mean = mean(theta_band_spectr(theta_mask ~= 0));
alpha_mask = (Lf > 8 ) & (Lf < 14);
alpha_band_spectr = avgLp .* alpha_mask';
alpha_mean = mean(alpha_band_spectr(alpha_mask ~= 0));
handles.run_length = handles.run_length + 1;
handles.run_mean(:,handles.run_length) = [theta_mean,alpha_mean]';
%handles.run_mean = [handles.run_mean';theta_mean,alpha_mean]';
handles.run_mean_color = [handles.run_mean_color,handles.interval_colors{mod(handles.svInts.num,length(handles.interval_colors))+1}];
set(findall(gcf,'-property','FontSize'),'FontSize',24);
guidata(hObject,handles);
% --- Executes on button press in cmdReload.
function cmdReload_Callback(hObject, eventdata, handles)
% hObject handle to cmdReload (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LoadLFP(hObject,eventdata,handles);
guidata(hObject,handles);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over cmdSelect.
function cmdSelect_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to cmdSelect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on cmdSelect and none of its controls.
function cmdSelect_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to cmdSelect (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) https://docs.google.com/presentation/d/1F5ppNZjxxtwawCghksNKbVTURH4TyB8eCgRIxSMwlfs/edit?usp=sharingof the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in SaveSGCmd.
function SaveSGCmd_Callback(hObject, eventdata, handles)
% hObject handle to SaveSGCmd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Fig2 = figure;
copyobj(handles.axes1,Fig2);colormap('jet');
data_file = get(handles.editFname,'String');
%hgsave(Fig2, ['/tmp/' handles.data_file '_spectrogram.fig']);
pause(2);
print(Fig2,'-dpng',['/tmp/' data_file '_Chann' num2str(handles.UI.active_chann) '_spectrogram.png']);
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: place code in OpeningFcn to populate axes1
% --- Executes on button press in cmdClearSG.
function cmdClearSG_Callback(hObject, eventdata, handles)
% hObject handle to cmdClearSG (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1)
cla;
% --- Executes on button press in cmdMeta.
function cmdMeta_Callback(hObject, eventdata, handles)
% hObject handle to cmdMeta (see GCBO)%
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Textprompts for ease
pt = input('What patient is this?')
exp = input('What experiment is this?')
timept = input('What timepoint is this?')
condit = input('What condition is this?')
trial = input('What trial is this?')
base_dir = '/tmp/Results/SysID/';
out_dir = [base_dir '/' exp '/' timept '/' pt '/']
mkdir(out_dir)
output_file = [out_dir condit '_T' trial '.xml']
% --- Executes on button press in cmdPathClip.
function cmdPathClip_Callback(hObject, eventdata, handles)
% hObject handle to cmdPathClip (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clipboard('copy',[handles.RAW.LFP.file.data_path handles.RAW.LFP.file.data_file]);
function SG_Plot_Chann(hObject,handles,achann)
axes(handles.axes1);cla;
colormap('jet');
%achann = handles.UI.active_chann;
colormap('jet');
imagesc(handles.TF.chann{achann}.T, handles.TF.chann{achann}.F, 10*log10(abs(handles.TF.chann{achann}.S)));
%caxis [-20,20] on the z-scored input signal seems like a great
%VISUALIZATION technique; keep this for the main window spectrogram/view
%But might need to be tweaked for the EEG data
set(gca,'YDir','normal');colorbar();ylim([0 handles.TF.Fs / 2]);caxis([-20,20]);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
title(['Channel ' num2str(achann) ' - ' handles.DATA.chann{achann}.label]);
% --- Executes during object creation, after setting all properties.
function popChann_CreateFcn(hObject, eventdata, handles)
% hObject handle to popChann (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popTFMethod.
function popTFMethod_Callback(hObject, eventdata, handles)
% hObject handle to popTFMethod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popTFMethod contents as cell array
% contents{get(hObject,'Value')} returns selected item from popTFMethod
handles.TF_Method.idx = get(hObject,'Value');
temp_string = get(hObject,'String');
handles.TF_Method.name = temp_string{handles.TF_Method.idx};
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function popTFMethod_CreateFcn(hObject, eventdata, handles)
% hObject handle to popTFMethod (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cmdEEGLoad.
function cmdEEGLoad_Callback(hObject, eventdata, handles)
% hObject handle to cmdEEGLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[handles.EEG_file handles.EEG_path] = uigetfile({'*.mat'},'Pick EEG Data File',handles.EEG_dir,'MultiSelect','Off')
handles.EEG_file = cellstr(handles.EEG_file);
handles.EEG_dir = handles.EEG_path;
eeg_fname = handles.EEG_file;eeg_dir = handles.EEG_path;
guidata(hObject,handles);
LoadEEG(hObject,eventdata,handles,eeg_fname,eeg_dir);
function edtEEGfname_Callback(hObject, eventdata, handles)
% hObject handle to edtEEGfname (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtEEGfname as text
% str2double(get(hObject,'String')) returns contents of edtEEGfname as a double
% --- Executes during object creation, after setting all properties.
function edtEEGfname_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtEEGfname (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cmdPAC.
function cmdPAC_Callback(hObject, eventdata, handles)
% hObject handle to cmdPAC (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Interval return function
axes(handles.axes1);
iv_rect = getrect();
if get(handles.chkLimIntv,'Value')
lim_time = str2num(get(handles.edtIntLength,'String'));
else
lim_time = 0;
end
[itv,t_vect] = iv_to_ts(handles,iv_rect,lim_time);
disp('Starting PAC');
PAC.sig = handles.brLFP.ds(itv(1):itv(2),:);
disp('Running PAC...');
%Do PAC Calculation
%CFC Section
a_range = 1:1:100;
p_range = 1:1:25;
bw = 2; pbr = 0.02;
n = 36; Fb = 2; Fc = 1;
% %GPU version
% %GPU VERSION
% s1c = reshape(repmat(PAC.sig(:,1)',100,1),10,10,[]);
% s2c = reshape(repmat(PAC.sig(:,2)',100,1),10,10,[]);
%
% S1 = gpuArray(PAC.sig(:,1)');
% S2 = gpuArray(PAC.sig(:,2)');
%Non-GPU version
CFC.MI{1}.MIs = GLMcomodulogram(PAC.sig(:,1)',PAC.sig(:,2)',a_range,p_range,handles.brLFP.aFs,bw,pbr,'No');
CFC.MI{2}.MIs = GLMcomodulogram(PAC.sig(:,2)',PAC.sig(:,1)',a_range,p_range,handles.brLFP.aFs,bw,pbr,'No');
CFC.MI{3}.MIs = GLMcomodulogram(PAC.sig(:,1)',PAC.sig(:,1)',a_range,p_range,handles.brLFP.aFs,bw,pbr,'No');
CFC.MI{4}.MIs = GLMcomodulogram(PAC.sig(:,2)',PAC.sig(:,2)',a_range,p_range,handles.brLFP.aFs,bw,pbr,'No');
handles.CFC = CFC;
guidata(hObject,handles);
figure;
colormap('jet');
subplot(2,2,1);
imagesc(p_range,a_range,handles.CFC.MI{1}.MIs',[0 0.8]);set(gca,'ydir','Normal');colorbar();
subplot(2,2,2);
imagesc(p_range,a_range,handles.CFC.MI{2}.MIs',[0 0.8]);set(gca,'ydir','Normal');colorbar();
subplot(2,2,3);
imagesc(p_range,a_range,handles.CFC.MI{3}.MIs',[0 0.8]);set(gca,'ydir','Normal');colorbar();
subplot(2,2,4);
imagesc(p_range,a_range,handles.CFC.MI{4}.MIs',[0 0.8]);set(gca,'ydir','Normal');colorbar();
disp('DONE PAC');
% --- Executes on selection change in popPSDEst.
function popPSDEst_Callback(hObject, eventdata, handles)
% hObject handle to popPSDEst (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popPSDEst contents as cell array
% contents{get(hObject,'Value')} returns selected item from popPSDEst
handles.PSD_Method.idx = get(hObject,'Value');
temp_string = get(hObject,'String');
handles.PSD_Method.name = temp_string{handles.PSD_Method.idx};
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function popPSDEst_CreateFcn(hObject, eventdata, handles)
% hObject handle to popPSDEst (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edtLFP_Fs_Callback(hObject, eventdata, handles)
% hObject handle to edtLFP_Fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtLFP_Fs as text
% str2double(get(hObject,'String')) returns contents of edtLFP_Fs as a double
handles.brLFP.Fs = str2num(get(hObject,'String'));
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function edtLFP_Fs_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtLFP_Fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edtEEG_Fs_Callback(hObject, eventdata, handles)
% hObject handle to edtEEG_Fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtEEG_Fs as text
% str2double(get(hObject,'String')) returns contents of edtEEG_Fs as a double
handles.hdEEG.Fs = str2num(get(hObject,'String'));
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function edtEEG_Fs_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtEEG_Fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popPACc1.
function popPACc1_Callback(hObject, eventdata, handles)
% hObject handle to popPACc1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popPACc1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popPACc1
% --- Executes during object creation, after setting all properties.
function popPACc1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popPACc1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popPACc2.
function popPACc2_Callback(hObject, eventdata, handles)
% hObject handle to popPACc2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popPACc2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popPACc2
% --- Executes during object creation, after setting all properties.
function popPACc2_CreateFcn(hObject, eventdata, handles)
% hObject handle to popPACc2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in chkLimIntv.
function chkLimIntv_Callback(hObject, eventdata, handles)
% hObject handle to chkLimIntv (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of chkLimIntv
% --- Executes on button press in cmdTimeFile.
function cmdTimeFile_Callback(hObject, eventdata, handles)
% hObject handle to cmdTimeFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%time_file = dlmread('/tmp/Andrea_imagined_movement/DBS906_emoLFPpilot_11092015.txt');
%time_file = dlmread('/tmp/Andrea_imagined_movement/DBS905_motorLFPpilot_11102015.txt');
meta_file = [handles.RAW.LFP.file.data_path handles.RAW.LFP.file.data_file(1:end-3) '.xml']
meta_data = dlmread(meta_file);
timings = time_file(:,2);
stim_art = time_file(:,3);
disp('Timings Loaded...');
% --- Executes on button press in boxResamp1K.
stim_art = time_file(:,3);
disp('Timings Loaded...');
% --- Executes on button press in boxResamp1K.
function boxResamp1K_Callback(hObject, eventdata, handles)
% hObject handle to boxResamp1K (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of boxResamp1K
% --- Executes on selection change in popChannTs.
function popChannTs_Callback(hObject, eventdata, handles)
% hObject handle to popChannTs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popChannTs contents as cell array
% contents{get(hObject,'Value')} returns selected item from popChannTs
%When this value changes, update the current active channel
handles.UI.active_chann = get(hObject,'Value');
disp(['Changing Active Channel to ' num2str(handles.UI.active_chann)]);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function popChannTs_CreateFcn(hObject, eventdata, handles)
% hObject handle to popChannTs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in cmdTsShow.
function cmdTsShow_Callback(hObject, eventdata, handles)
% hObject handle to cmdTsShow (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
curr_chann = get(handles.popChannTs,'Value');
figure(100);
subplot(3,1,1);
plot(handles.DATA.chann{curr_chann}.ts);hold on;
title(['Channel ' num2str(curr_chann) ' :: Time Domain']);legend();
subplot(3,1,2);
plot(handles.RAW.LFP.rawdata(:,curr_chann));hold on;
title(['Raw Channel ' num2str(curr_chann) ' at ' num2str(handles.RAW.LFP.rawFs) ' :: T Domain']);
%subplot(3,1,3);
%spectrogram(handles.RAW.LFP.rawdata(:,curr_chann),blackmanharris(512),500,2^10,handles.RAW.LFP.rawFs);
%title(['Spectrogram of RAW Channel ' num2str(curr_chann) ' :: TF Domain']);legend();
guidata(hObject,handles);
% --- Executes on button press in cmdTFPlot.
function cmdTFPlot_Callback(hObject, eventdata, handles)
% hObject handle to cmdTFPlot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a = find(handles.DATA.TS_List == 1)';
disp('Computing T-F for Loaded Channels...');
handles.SG.Done = [];
handles.SG.SG_Labels = {};
%Make a local container for the raw data
chann_ts{1} = [];
chann_fs = handles.DATA.chann{min(a)}.Fs;
ds_fact = 1;
for ii = a
dummy_chann = handles.DATA.chann{ii};
chann_ts{ii}.ts = decimate(dummy_chann.ts,ds_fact);
end
chann_fs = chann_fs ./ ds_fact;
%Without downsampling ahead of time
for ii = a
[handles.TF.chann{ii}.S, handles.TF.chann{ii}.F, handles.TF.chann{ii}.T] = spectrogram(chann_ts{ii}.ts,blackmanharris(512),500,2^10,422)%chann_fs);
end
%Update the decimated Fs
handles.TF.Fs = chann_fs;
%Set UI active channel to lowest available channel
handles.UI.active_chann = min(a);
%Plot the active chann
SG_Plot_Chann(hObject,handles,handles.UI.active_chann);
%Update the popdown text
for ii = a
SG_Labels{ii} = ['Channel ' num2str(ii)];
handles.SG.SG_Labels = SG_Labels;
handles.SG.Done = [handles.SG.Done ii];
end
set(handles.popChann,'String',SG_Labels);
disp('...Done computing T-F for Channel Set');
guidata(hObject,handles);
% --- Executes on button press in cmdCoher.
function cmdCoher_Callback(hObject, eventdata, handles)
% hObject handle to cmdCoher (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on selection change in popChann.
function popChann_Callback(hObject, eventdata, handles)
% hObject handle to popChann (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popChann contents as cell array
% contents{get(hObject,'Value')} returns selected item from popChann
handles.UI.active_chann = get(hObject,'Value');
%Is value gotten in the current list of SG'ed channels?
guidata(hObject, handles);
if handles.SG.Done(handles.UI.active_chann)
SG_Plot_Chann(hObject,handles,handles.UI.active_chann);
else
disp('That Channel Was Not Computed');
end
%Function that finds the stim periods in ALL CHANNELS, and aligns them
%Do this on raw data, sampled at highest Fs
% --- Executes on button press in cmdStimAlign.
function cmdStimAlign_Callback(hObject, eventdata, handles)
% hObject handle to cmdStimAlign (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Filter all channels at 130 Hz
loaded_channs = find(handles.DATA.TS_List == 1)';
d = fdesign.bandpass('N,F3dB1,F3dB2',20,129,131,1000);
Hd = design(d,'butter');
fvtool(Hd);
for ii = loaded_channs
%filted_sig{ii}.stim_sig = eegfilt(handles.DATA.chann{ii}.ts,handles.DATA.chann{ii}.Fs,129,130);
a{ii}.ts = filtfilthd(Hd,handles.DATA.chann{ii}.ts);
end
disp('...Done Aligning');
function intv = select_window(hObject,eventdata,handles)
axes(handles.axes1);
iv_rect = getrect();
%Bounds should be the boundary TIMES
[intv.nbounds,intv.tvect] = iv_to_ts(handles,iv_rect,0); %0 is for the lim time ability, to keep fixed window length
intv.fromChannel = handles.UI.active_chann;
% --- Executes on button press in cmdChannPCA.
function cmdChannPCA_Callback(hObject, eventdata, handles)
% hObject handle to cmdChannPCA (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Do PCA on all channels
%Choose your epoch
curr_epoch = select_window(hObject,eventdata,handles)
epoch_data = extractEpoch(handles,curr_epoch);
ChannBand(handles,epoch_data);
%Do a banding out
%Just do raw PCA
[coeff,score,latent] = pca(epoch_data,'Algorithm','eig');
%or do PCA on banded data
%
% figure;
% subplot(3,2,1);
% plot(score);
% subplot(3,2,2);
% scatter(epoch_data(:,1),epoch_data(:,2),'.');
%
% subplot(3,2,3);
% hist(epoch_data(:,1));
% subplot(3,2,4);
% hist(epoch_data(:,2));
%
% subplot(3,2,5);
% [s,f,t] = spectrogram(score(:,1),blackmanharris(512),500,2^10,1000);
% imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
% subplot(3,2,6);
% [s,f,t] = spectrogram(score(:,2),blackmanharris(512),500,2^10,1000);
% imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
%
% disp('Done with time-series PCA');
function ChannBand(handles,epoch_data)
%Break into bands
band_epoch_data = extractBands(handles,epoch_data);
%find timepoints
bed_size = size(band_epoch_data);
%Reshape so it's timex(channelxbands)
PCA_input = reshape(permute(band_epoch_data,[2,3,1]),[],bed_size(1))'; %YES! this reshapes this matrix properly, as you would expect
PCA_input = abs(PCA_input)
[coeff,score,latent] = pca(PCA_input,'Algorithm','eig');
score = real(score)
figure;
subplot(2,2,1);
%plot(abs(PCA_input));
imagesc(abs(coeff))
subplot(2,2,2);
%plot(abs(score));
plot(latent)
subplot(2,2,3);
scatter3(abs(PCA_input(:,1)),abs(PCA_input(:,2)),abs(PCA_input(:,3)),'.');
subplot(2,2,4);
scatter3(score(:,1),score(:,2),score(:,3),'.');
%subplot(3,2,3);
%hist(PCA_input(:,1));
%subplot(3,2,4);
%hist(PCA_input(:,2));
%this stuff is a bit meaningless when banded out; why take spectrogram of
%banded power; ehh, there are reasons, but not right now
%subplot(3,2,5);
%[s,f,t] = spectrogram(score(:,1),blackmanharris(512),500,2^10,422);
%imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
%subplot(3,2,6);
%[s,f,t] = spectrogram(score(:,2),blackmanharris(512),500,2^10,422);
%imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
disp('Done with time-series PCA');
% figure;
% subplot(3,1,1);
% imagesc(abs(coeff));
% subplot(3,1,2);
% plot(score);
% %Do covariance matrix
%
% %Plotting, bullshit right now
% figure;
% subplot(4,2,1);plot(epoch_data);
% subplot(4,2,3);imagesc(coeff);
% subplot(4,2,5);plot(latent);
% topovect = linspace(1,260,260);
% subplot(4,2,7);topoplot(topovect,handles.DATA.EEG.locs);
%
% %Plot the head and EEG channels
% %figure;
% %topoplot([],handles.DATA.EEG.locs,'style','blank','electrodes','labelpoint');
% %disp('PCA Analysis Done...');
%
% %Blindly plot the first channel theta power vs third channel theta power
% figure;title('Theta Power Space');
% %scatter3(PCA_input(:,5*(1-1) + 2),PCA_input(:,5*(3-1) + 2),PCA_input(:,5*(5-1) + 2));hold on;
% line(PCA_input(:,5*(1-1) + 2),PCA_input(:,5*(3-1) + 4),PCA_input(:,5*(5-1) + 4));
% xlabel('Channel 1 Theta');
% ylabel('Channel 3 Theta');
function banded_data = extractSGBands(handles,epoch_data)
%Break into traditional bands
osc_bands.F = {[1,4],[4,8],[8,14],[15,30],[30,50],[1,20]};
osc_bands.name = {'Delta','Theta','Alpha','Beta','Broad Gamma','Norm'};
%Dimensionality of the data
%Row is going to be observation, column is channel
data_dim = size(epoch_data);
for ii = 1:data_dim(2)
%For each channel in the above
%Do multitaper for spectrogram
%Do pwelch spectrogram
[S,F,T] = spectrogram(epoch_data(:,ii),blackmanharris(256),250,2^10,1000); %!!! Fs hardcoded here, change this
for jj = 1:length(osc_bands.name)
%For each band
%banded_data;
bandlims = osc_bands.F{jj};
%Log transform HERE
%banded_data(:,jj,ii) = mean(10*log10(abs(S(F > bandlims(1) & F < bandlims(2),:))));
%OR Save log transform for viz
banded_data(:,jj,ii) = sum(abs(S(F > bandlims(1) & F < bandlims(2),:)));
end
end
function hilb_data = extractBands(handles,epoch_data)
%Break into traditional bands
osc_bands.F = {[1,4],[4,8],[8,14],[15,30],[30,50],[1,20]};
osc_bands.name = {'Delta','Theta','Alpha','Beta','Broad Gamma','Norm'};
%Dimensionality of the data
%Row is going to be observation, column is channel
data_dim = size(epoch_data);
for ii = 1:length(osc_bands.name)
f(ii) = fdesign.bandpass('N,Fc1,Fc2',100,osc_bands.F{ii}(1),osc_bands.F{ii}(2),1000);
Fd(ii) = design(f(ii),'butter');
end
for ii = 1:data_dim(2)
%For each channel in the above
%Do multitaper for spectrogram
%Do FILTERING approach
for jj = 1:length(osc_bands.name)
%Make the filter
fsig(:,jj,ii) = filtfilthd(Fd(jj),epoch_data(:,ii));
%banded_data(:,jj,ii) = fsig(:,jj,ii).^2;
hilb_data(:,jj,ii) = hilbert(fsig(:,jj,ii));
end
end
%Do any band normalization here
disp('Done Banding...');
function epochts = extractEpoch(handles,curr_epoch)
%Go through all loaded channels and extract the needed epoch
for ii = 1:length(handles.DATA.chann)
[aligned_epoch,achann] = align_epoch(handles,curr_epoch, handles.DATA.chann{ii});
achann.ds = decimate(achann.ts,handles.ANALYSIS.ds_factor);
%Now take the the interval chunk we wanted
achann.intv{1}.ds = achann.ds(round(aligned_epoch.ivn));
achann.intv{1}.tvect = linspace(aligned_epoch.tvect(1),aligned_epoch.tvect(end),length(achann.intv{1}.ds));
epochts(:,ii) = achann.intv{1}.ds;
end
function [out_epoch,achann] = align_epoch(handles,in_epoch,achann)
%Grab active channel and decimate it
achann.dsFs = achann.Fs ./ handles.ANALYSIS.ds_factor;
out_epoch = in_epoch;
out_epoch.ivn = (in_epoch.tvect(1)*achann.dsFs) : (in_epoch.tvect(end)*achann.dsFs);
if in_epoch.fromChannel <= 2
%window is in the reference of the LFPs
if achann.num > 2
out_epoch.ivn = (in_epoch.tvect(1)*achann.dsFs - handles.DATA.lag_val) : (in_epoch.tvect(end)*achann.dsFs - handles.DATA.lag_val);
end
else
%Window is in the reference of the EEGs
if achann.num <= 2
out_epoch.ivn = (in_epoch.tvect(1)*achann.dsFs + handles.DATA.lag_val) : (in_epoch.tvect(end)*achann.dsFs + handles.DATA.lag_val);
end
end
% --- Executes on button press in cmdOscModel.
function cmdOscModel_Callback(hObject, eventdata, handles)
% hObject handle to cmdOscModel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Do PCA on all channels
%Choose your epoch
curr_epoch = select_window(hObject,eventdata,handles)
channel_Ts = extractEpoch(handles,curr_epoch);
band_Ts = extractBands(handles,channel_Ts);
%F(round(length(band_Ts(:,1,1))./10)) = struct('cdata',[],'colormap',[]);
iband = 2;
%Compute PLV for all pairwise channels
figure();
nchann = length(band_Ts(1,1,:));
PLV = zeros(length(band_Ts(:,1,1)),nchann,nchann);
for ii = 1:length(band_Ts(1,1,:))
for jj = 1:ii-1
subplot(4,1,1);plot(real(band_Ts(:,iband,ii)));hold on;plot(real(band_Ts(:,iband,jj)),'r');
phasediff = phase(band_Ts(:,iband,ii)) - phase(band_Ts(:,iband,jj));
PLV(:,ii,jj) = sin(phasediff);
subplot(4,1,2);plot(phasediff);hold on;title('Phase Difference In Theta');
subplot(4,1,3);plot(diff(PLV(:,ii,jj)));hold on;title('Derivative of Phase Difference');
end
end
PLV2 = sin(phase(band_Ts(:,iband,1)) - phase(band_Ts(:,iband,2)));
pval = angle(band_Ts(:,iband,:));
subplot(4,1,4);plot(PLV2);ylim([-2,2]);title('Sin Phase Difference');
% figure(81);
% plot(channel_Ts);
%figure();
%plot(PLV);title('Left and Right PLV');
%ylim([-2,2]);
% Animation for phase offset
% for kk = 1:50:length(band_Ts(:,1,1));
% figure(82);
% clf;
% for jj = iband;
% subplot(3,1,1);
% %plot(channel_Ts);
% line([kk,kk],[0,2]);
%
% subplot(2,1,1);
% %plot(imag(PLV));
% plot(PLV);
% %plot(angle(band_Ts(:,jj,1)) - angle(band_Ts(:,jj,2)));
% %plot([diff(sin(phase(band_Ts(:,jj,1)) - phase(band_Ts(:,jj,2))));0],'r');
% line([kk,kk],[-pi,pi]);
%
% subplot(2,1,2);
%
% for ss = 1:length(band_Ts(1,1,:))
% polar(pval(kk,ss),1,'o');hold on;
% end
% end
% pause(0.001);
% %F(kk) = getframe(gcf);
% end
disp('Done with osc model');
function [delta,theta,alpha,beta,bbgamma] = breakBands(ts)
disp('Band Analysis...');
%bp.delta = fdesign.bandpass('',)
function edtDSFactor_Callback(hObject, eventdata, handles)
% hObject handle to edtDSFactor (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtDSFactor as text
% str2double(get(hObject,'String')) returns contents of edtDSFactor as a double
handles.ANALYSIS.ds_factor = str2double(get(hObject,'String'));
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function edtDSFactor_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtDSFactor (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%MAIN 1-D PLOTTING FUNCTION BELOW
% --- Executes on button press in cmdSelect.
function cmdSelect_Callback(hObject, eventdata, handles)
% hObject handle to cmdSelect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
sig_cont = select_window(hObject,eventdata,handles);
solo_chann = 0;
%Increment the current interval
handles.ANALYSIS.active_interval = handles.ANALYSIS.active_interval + 1;
%Get channel data for the interval of interest
if solo_chann
%if you want a single channel (the active one)
achann = get_intv(handles,handles.UI.active_chann,sig_cont);
else
%if you want all the loaded channels
achann = get_intv(handles,find(handles.DATA.TS_List==1)',sig_cont);
end
handles.ANALYSIS.intv{handles.ANALYSIS.active_interval}.achann = calc_Oscil(handles,achann);
%Plot oscillatory data
band_bars = plot_Oscil(handles);
handles.ANALYSIS.Aggr.blp{handles.ANALYSIS.Aggr.idx} = band_bars;
%Paint the window onto the SGview
axes(handles.axes1);
hold on;
c = lines;
for ii = 1:length(handles.ANALYSIS.intv)
line([handles.ANALYSIS.intv{ii}.achann{1}.tvect(1),handles.ANALYSIS.intv{ii}.achann{1}.tvect(end)],[0,0],'LineWidth',10,'Color',c(ii,:));
end
guidata(hObject,handles);
%Calculate the PSD and also oscillatory bands; these will go hand in hand
%for these analyses
function achann = calc_Oscil(handles,achann)
for ii = 1:length(achann)
%Now calculate the PSD using pwelch
%[P,F,B] = pwelch(achann.intv{1}.ds,512,500,2^10,achann.dsFs,'ConfidenceLevel',0.95);
%Or with multitaper
[achann{ii}.P,achann{ii}.F,achann{ii}.B] = pmtm(achann{ii}.ds,10,2^10,achann{ii}.dsFs,'ConfidenceLevel',0.95);
%Extract the slope of the PSD
achann{ii}.soi = achann{ii}.F > 1 & achann{ii}.F < 20;
achann{ii}.slop = (10*log10(achann{ii}.P)) \ (10 * log10(achann{ii}.F));
achann{ii}.slop20 = (10*log10(achann{ii}.P(achann{ii}.soi))) \ (10 * log10(achann{ii}.F(achann{ii}.soi)));
%Now calculate the oscillatory power in each band
%achann{cidx}.intv{1}.bands =
achann{ii}.bandData = extractSGBands(handles,achann{ii}.ds);
achann{ii}.oscData = extractBands(handles,achann{ii}.ds);
end
function band_bars = plot_Oscil(handles,achann)
%Start plotting
figure(handles.ANALYSIS.active_figure);
clf;
numints = length(handles.ANALYSIS.intv);
cmap = [];
for jj = 1:numints
achann = handles.ANALYSIS.intv{jj}.achann;
for ii = 1:length(achann)
subplot(3,length(achann),ii);
colormap('lines');
h = plot(achann{ii}.tvect,achann{ii}.ds);hold on;
xlabel('Time (s)');ylabel('Voltage (mV)');
title(['Raw Downsampled Signal - Channel ' num2str(ii)]);
%set up color scheme properly
%c = get(h,'Color');
cmap = colormap;
subplot(3,length(achann),2+ii);
bplot(achann{ii}.F,achann{ii}.P,achann{ii}.B,cmap(jj,:));hold on;
title('PSD Plots');
%plot(achann{ii}.F(achann{ii}.soi),achann{ii}.slop20 * achann{ii}.F(achann{ii}.soi),zeros(size(achann{ii}.F,1),2),[1 0 0]);
end
end
figure(handles.ANALYSIS.active_figure);
achann = handles.ANALYSIS.intv{1}.achann;
for ii = 1:length(achann)
for jj = 1:numints
%Normalize the bands
handles.ANALYSIS.osc_bands(:,jj,ii) = 10*log10(mean(handles.ANALYSIS.intv{jj}.achann{ii}.bandData ./ mean(handles.ANALYSIS.intv{jj}.achann{ii}.bandData(:,6),1)));
%Don't normalize the bands
handles.ANALYSIS.osc_bands(:,jj,ii) = mean(abs(handles.ANALYSIS.intv{jj}.achann{ii}.bandData));
handles.ANALYSIS.psd.P(:,:,jj,ii) = handles.ANALYSIS.intv{jj}.achann{ii}.P;
handles.ANALYSIS.psd.F(:,:,jj,ii) = handles.ANALYSIS.intv{jj}.achann{ii}.F;
handles.ANALYSIS.psd.B(:,:,jj,ii) = handles.ANALYSIS.intv{jj}.achann{ii}.B;
end
%subplot(1,length(achann),ii)
%bplot(handles.ANALYSIS.psd.F,handles.ANALYSIS.psd.P,handles.ANALYSIS.psd.B,colormap('jet'));
%title('PSD Plots');
subplot(3,length(achann),4+ii)
b = bar(handles.ANALYSIS.osc_bands(:,:,ii));
for kk = 1:length(b)
b(kk).FaceColor = cmap(kk,:);
end
set(gca,'XTickLabels',{'Delta','Theta','Alpha','Beta','Gamma','NORM'});
title('Banded Power');
end
%Store banded data and colors into larger array
band_bars = handles.ANALYSIS.osc_bands;
function achann = get_intv(handles,onchanns,epoch)
%Check if we want to downsample the data
ds_fact = handles.ANALYSIS.ds_factor;
cidx = 0;
for activec = onchanns
cidx = cidx + 1;
disp(['Calculating PSD for chann ' num2str(activec)]);
%Grab active channel and decimate it
achann{cidx}.ts = handles.DATA.chann{activec}.ts;
achann{cidx}.dsFs = handles.DATA.chann{activec}.Fs ./ ds_fact;
set(handles.txtDSFs,'String',['Fs: ' num2str(achann{cidx}.dsFs)]);
%Decimate the signal
achann{cidx}.ds = decimate(achann{cidx}.ts,ds_fact);
%IF WE'RE DEALING WITH AN EEG SIGNAL, we need to shift it
epoch.ivn = (epoch.tvect(1)*achann{cidx}.dsFs) : (epoch.tvect(end)*achann{cidx}.dsFs);
if epoch.fromChannel <= 2
%window is in the reference of the LFPs
if activec > 2
epoch.ivn = (epoch.tvect(1)*achann{cidx}.dsFs - handles.DATA.lag_val) : (epoch.tvect(end)*achann{cidx}.dsFs - handles.DATA.lag_val);
end
else
%Window is in the reference of the EEGs
if activec <= 2
epoch.ivn = (epoch.tvect(1)*achann{cidx}.dsFs + handles.DATA.lag_val) : (epoch.tvect(end)*achann{cidx}.dsFs + handles.DATA.lag_val);
end
end
%Ignoring doShift in this implementation
%Now take the the interval chunk we wanted
achann{cidx}.ds = achann{cidx}.ds(round(epoch.ivn));
achann{cidx}.tvect = linspace(epoch.tvect(1),epoch.tvect(end),length(achann{cidx}.ds));
end
%figure;
%pwelch(achann.intv{1}.ds,512,500,2^10,achann.dsFs,'ConfidenceLevel',0.95);
%subplot(2,1,2);
%plot(b,10*log10(abs(a)));hold on;
function bplot(F,P,B,c)
%B comes directly from the computation functions
b(:,1) = abs(10*log10(abs(squeeze(P))) - 10*log10(abs(B(:,1))));
b(:,2) = abs(10*log10(abs(squeeze(P))) - 10*log10(abs(B(:,2))));
h = boundedline(F,10*log10(abs(P)),b,'alpha','cmap',c);
xlabel('Frequency (Hz)');ylabel('Power (dB)');
%set(h,'Colormap',c);
xlim([0 100]);
% --- Executes on button press in cmdAChannTF.
function cmdAChannTF_Callback(hObject, eventdata, handles)
% hObject handle to cmdAChannTF (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a = handles.UI.active_chann;
disp('Computing T-F for Active Channel...');
%Make a local container for the raw data
chann_ts = [];
chann_fs = handles.DATA.chann{min(a)}.Fs;
ds_fact = 1; %Purely for display reasons; need not be put on front-UI
for ii = a
dummy_chann = handles.DATA.chann{ii};
chann_ts{ii}.ts = decimate(dummy_chann.ts,ds_fact);
end
chann_fs = chann_fs ./ ds_fact;
%Without downsampling ahead of time??
%z-score the input signals
for ii = a
chann_ts{ii}.ts = zscore(chann_ts{ii}.ts);
[handles.TF.chann{ii}.S, handles.TF.chann{ii}.F, handles.TF.chann{ii}.T] = spectrogram(chann_ts{ii}.ts,blackmanharris(512),500,2^10,chann_fs);
end
%Update the decimated Fs
handles.TF.Fs = chann_fs;
%Plot the active chann
SG_Plot_Chann(hObject,handles,handles.UI.active_chann);
%Update that the SG for the active channel has been done
handles.SG.Done(a) = 1;
handles.SG.SGLabels{a} = ['Channel ' num2str(a)];
set(handles.popChann,'String',handles.SG.SGLabels);
set(handles.popChann,'Value',a);
disp(['...Done computing T-F for Channel ' num2str(handles.UI.active_chann)]);
guidata(hObject,handles);
function update_UI_SG_Pop(handles)
%check the handles SG tracking variables and populate the list
%appropriately
% --- Executes on button press in cmdAutoAlignStims.
function cmdAutoAlignStims_Callback(hObject, eventdata, handles)
% hObject handle to cmdAutoAlignStims (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Automated version here; move to other button when ready
disp('Aligning channels');
d = fdesign.bandpass('N,F3dB1,F3dB2',20,129,131,1000);
Hd = design(d,'butter');
%Compare the LFP signal with an EEG signal
%I added the intrinsic differential signal for common mode rejection of
%noise
%This was more robust for SINGLE channels from the EEG
%And seemed to stay the same for DIFFERENTIAL channels from the EEG
c1 = zscore(filtfilthd(Hd,handles.DATA.chann{1}.ts));
c2 = zscore(filtfilthd(Hd,handles.DATA.chann{3}.ts - handles.DATA.chann{4}.ts));
%Try a cross correlation approach
[cc,lags] = xcorr(c1,c2);
[~,max_cc_idx] = max(cc);
%We know that the lag should be limited, it's not going to be >
max_cc_loc = lags(max_cc_idx)
% Other way of doing it, trying to find the first point of large overlap;
% this is shit
% %find max region
% %first z-score
ccz = zscore(cc);
%Try plotting the aligned signals;
figure;
subplot(3,1,1);
c1t = 1:length(handles.DATA.chann{1}.ts);
c2t = 1:length(handles.DATA.chann{3}.ts);
c2ts = c2t + max_cc_loc;
plot(c1t,zscore(handles.DATA.chann{1}.ts));hold on;
plot(c2ts,zscore(handles.DATA.chann{3}.ts));
%Plot filtered stim artifact one
subplot(3,1,2);
plot(c1);hold on;plot(c2);
subplot(3,1,3);
plot(lags,ccz);
%Store lag value for EEG channel set
handles.DATA.lag_val = max_cc_loc;
disp('Done Aligning');
guidata(hObject,handles);
% --- Executes on button press in cmdDiffChann.
function cmdDiffChann_Callback(hObject, eventdata, handles)
% hObject handle to cmdDiffChann (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in cmdCmpLoad.
function cmdCmpLoad_Callback(hObject, eventdata, handles)
% hObject handle to cmdCmpLoad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in cmdSGSett.
function cmdSGSett_Callback(hObject, eventdata, handles)
% hObject handle to cmdSGSett (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function chann_sig = extract_window(handles,sig_cont)
%get channel data
chann_sig = handles.DATA.chann{sig_cont.fromChannel}.ts(sig_cont.nbounds(1):sig_cont.nbounds(2));
% --- Executes on button press in cmdMedFilt.
function cmdMedFilt_Callback(hObject, eventdata, handles)
% hObject handle to cmdMedFilt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
sig_cont = select_window(hObject,eventdata,handles);
sig_oi = extract_window(handles,sig_cont);
figure;
subplot(2,2,1);
plot(sig_oi);title('Unfiltered interval of interest on channel');
%Filter the data
for ii = 1:length(sig_cont.fromChannel)
%filted(:,ii) = medfilt1(handles.DATA.chann{ii}.ts,50);
hampeled(:,ii) = hampel(1:length(sig_oi),sig_oi,1,3,'Adaptive',0.1);
end
subplot(2,2,2);
plot(hampeled);title('Filtered signal');
subplot(2,2,3);
[s,f,t] = spectrogram(sig_oi,blackmanharris(512),500,2^10,1000);
imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
subplot(2,2,4);
[s,f,t] = spectrogram(hampeled,blackmanharris(512),500,2^10,1000);
imagesc(t,f,10*log10(abs(s)));colormap('jet');set(gca,'YDir','normal');
% --- Executes on button press in cmdBreak.
function cmdBreak_Callback(hObject, eventdata, handles)
% hObject handle to cmdBreak (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in cmdPlotAggrBands.
function cmdPlotAggrBands_Callback(hObject, eventdata, handles)
% hObject handle to cmdPlotAggrBands (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
figure;
cmap = colormap('colorcube');
%Plot the left signals first (channel 1)
for ii = 1:2 %channel number
subplot(1,2,ii);
for jj = 2 %band number
for ll = 1:length(handles.ANALYSIS.Aggr.blp)
dummysize = size(handles.ANALYSIS.Aggr.blp{ll});
intvs = dummysize(2);
for kk = 1:intvs %interval number
%plot all patients next to each other
osc(ll,:,:,:) = handles.ANALYSIS.Aggr.blp{ll};
b = bar(squeeze(osc(:,jj,:,ii))');
xlabel('Interval Number');ylabel('Power');
leg_end{kk} = ['Patient #' num2str(kk)];
end
for pp = 1:length(b)
b(pp).FaceColor = cmap(pp,:);
end
end
end
title(['Channel ' num2str(ii) ' Theta power']);
legend(leg_end);
end
suptitle('TurnOn Powers');
% --- Executes on button press in cmdLowPassExtr.
function cmdLowPassExtr_Callback(hObject, eventdata, handles)
% hObject handle to cmdLowPassExtr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Just take channel 1
chann = 1;
raw_sig = handles.DATA.chann{chann}.ts;
%Band it below
lph = fdesign.lowpass('N,F3dB',20,20,handles.DATA.chann{chann}.Fs);
lpf = design(lph);
filted_sig = filtfilthd(lpf,raw_sig);
disp('Filtered...');
% --- Executes on button press in cmdSelectInfo.
function cmdSelectInfo_Callback(hObject, eventdata, handles)
% hObject handle to cmdSelectInfo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
sig_cont = select_window(hObject,eventdata,handles);
disp('Interval Info:');
if sig_cont.tvect(end) - sig_cont.tvect(1) > 15
str_ok = 'OK!';
else
str_ok = 'SMALL!!';
end
disp(['Length of this interval is: ' num2str(sig_cont.tvect(end) - sig_cont.tvect(1)) ' which is ' str_ok]);
disp([num2str(sig_cont.tvect(1)) ' to ' num2str(sig_cont.tvect(end))]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.