text:
function [varargout]=triSurfRemoveThreeConnect(varargin)

% function [Ft,Vt,Ct,L]=triSurfRemoveThreeConnect(Fd,Vd,Cd)
% ------------------------------------------------------------------------
% In a surface triangulation "3-connected" locations often contain poor
% quality triangles of a locally smaller area then the rest of the surface.
% Smoothening does not resolve this issue since the quality is not great
% improved even after vertex is at the centre of its neighbouring nodes.
% Hence the function triSurfRemoveThreeConnect instead removes the central
% nodes and groups the affected triangles into a single triangle.
% The input sets Fd, Vd and Cd represent the input faces, vertices and face
% colours respectively. The output sets Ft, Vt and Ct represent the fixed
% faces, vertices and face colours respectively. In addition a logic L can
% be output which defines the affected vertices in Vd. The output may
% consist of [Ft,Vt] or [Ft,Vt,Ct] or [Ft,Vt,Ct,L].
% The last nnz(L)/3 faces in Ft represent the fixed faces.
%
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2014/06/03 Created
% 2015/05/01 Updated with varagin type input
%------------------------------------------------------------------------

%% Parse input
Fd=varargin{1};
Vd=varargin{2};

if nargin==3
    Cd=varargin{3};
else
    Cd=[];
end

if isempty(Cd)
    Cd=(1:1:size(Fd,1))';
end

%%

%Get patch face/vertex connectivity matrices
[IND_F,IND_V]=patchIND(Fd,Vd,1);

%Count point connectivity
numFriends=sum(IND_V>0,2); %Number of vertex neighbours
logicThree=numFriends==3; %Logic for vertices with only three connected neighbours

%Remove boundary points from list
TR=triangulation(Fd,Vd);
indFree=freeBoundary(TR);
indFree=unique(indFree(:));
if ~isempty(indFree)
    logicThree(indFree)=0;
end

if nnz(logicThree)>0

    %IND_V subset
    IND_V_three=IND_V(logicThree,:);

    %Snap vertices to mean of neighbours such that vertex normal should
    %coincide with new surface normal
    logicValid=IND_V_three>0;
    Xp=NaN(size(IND_V_three));
    Yp=NaN(size(IND_V_three));
    Zp=NaN(size(IND_V_three));
    Xp(logicValid)=Vd(IND_V_three(logicValid),1);
    Yp(logicValid)=Vd(IND_V_three(logicValid),2);
    Zp(logicValid)=Vd(IND_V_three(logicValid),3);
    Vp=[gnanmean(Xp,2) gnanmean(Yp,2) gnanmean(Zp,2)];
    Vd(logicThree,:)=Vp; %Replace points

    %Get new faces
    IND_F_three=IND_F(logicThree,:);
    indFacesThree=IND_F_three(IND_F_three>0);
    logicFacesThree=false(size(Fd,1),1);
    logicFacesThree(indFacesThree)=1;
    IND_V_three=sort(IND_V_three,2);
    if size(IND_V_three,2)>3
        IND_V_three=IND_V_three(:,end-2:end);
    end
    F_new=IND_V_three;

    %Fix face orientation based on normals
    indUsed=unique(F_new(:));
    V_new=Vd(indUsed,:);
    indFix=zeros(size(Vd,1),1);
    indFix(indUsed)=1:numel(indUsed);
    F_new_fix=indFix(F_new);
    if size(F_new,1)==1
        F_new_fix=F_new_fix';
    end
    [~,~,Nd]=patchNormal(Fd,Vd);
    [N_new]=patchNormal(F_new_fix,V_new);
    N_sum_mag=sqrt(sum((Nd(logicThree,:)+N_new).^2,2));
    logicFlip=N_sum_mag<1;
    F_new(logicFlip,:)=fliplr(F_new(logicFlip,:));

    %Get color information for new faces
    logicValid=IND_F_three>0;

    C_F_three=nan(size(IND_F_three));
    C_F_three(logicValid)=Cd(IND_F_three(logicValid));
    C_new=gnanmean(C_F_three,2);

    %Faces to keep
    F_keep=Fd(~logicFacesThree,:);
    C_keep=Cd(~logicFacesThree,:);

    %Join and create vertex/face/color sets
    Ft=[F_keep;F_new];
    Ct=[C_keep;C_new];

    indUsed=unique(Ft(:));
    Vt=Vd(indUsed,:);
    indFix=zeros(size(Vd,1),1);
    indFix(indUsed)=1:numel(indUsed);
    Ft=indFix(Ft);

else
    Ft=Fd;
    Vt=Vd;
    Ct=Cd;
    logicFacesThree=false(size(Ft,1),1);
end

switch nargout
    case 2
        varargout{1}=Ft;
        varargout{2}=Vt;
    case 3
        varargout{1}=Ft;
        varargout{2}=Vt;
        varargout{3}=Ct;
    case 4
        varargout{1}=Ft;
        varargout{2}=Vt;
        varargout{3}=Ct;
        varargout{4}=logicFacesThree;
    otherwise
        error('Wrong number of output arguments');
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function K = rbfwhiteXrbfwhiteKernCompute(rbfKern1, rbfKern2, t1, t2)

% RBFWHITEXRBFWHITEKERNCOMPUTE Compute a cross kernel between two RBF-WHITE
% kernels.
% FORMAT
% DESC computes cross kernel terms between two RBF-WHITE kernels for
% the multiple output kernel.
% ARG lfmKern1 : the kernel structure associated with the first RBF-WHITE
% kernel.
% ARG lfmKern2 : the kernel structure associated with the second RBF-WHITE
% kernel.
% ARG t1 : inputs for which kernel is to be computed.
% RETURN K : block of values from kernel matrix.
%
% FORMAT
% DESC computes cross kernel terms between two RBF-WHITE kernels for
% the multiple output kernel.
% ARG rbfKern1 : the kernel structure associated with the first RBF-WHITE
% kernel.
% ARG rbfKern2 : the kernel structure associated with the second RBF-WHITE
% kernel.
% ARG t1 : row inputs for which kernel is to be computed.
% ARG t2 : column inputs for which kernel is to be computed.
% RETURN K : block of values from kernel matrix.
%
% SEEALSO : multiKernParamInit, multiKernCompute, rbfwhiteKernParamInit
%
% COPYRIGHT : David Luengo, 2009

% KERN

if nargin < 4
  t2 = t1;
end
if size(t1, 2) > 1 | size(t2, 2) > 1
  error('Input can only have one column');
end
if rbfKern1.variance ~= rbfKern2.variance
  error('Kernels cannot be cross combined if they have different variances.')
end
if rbfKern1.isStationary ~= rbfKern2.isStationary
  error('Stationary and non-stationary kernels cannot be cross combined.')
end

isStationary = rbfKern1.isStationary;

T1 = repmat(t1, 1, size(t2, 1));
T2 = repmat(t2.', size(t1, 1), 1);
deltaT = T1-T2;
indT = double(deltaT >= 0);

variance = rbfKern1.variance;
inverseWidth1 = rbfKern1.inverseWidth;
inverseWidth2 = rbfKern2.inverseWidth;
statInvWidth = inverseWidth2 + (inverseWidth1-inverseWidth2)*indT;

c = variance / sqrt(8*pi);
K = 1 - erf(sqrt(0.5*inverseWidth1*inverseWidth2) * statInvWidth ...
    .* abs(deltaT) / (inverseWidth1+inverseWidth2));
if (isStationary == false)
    K = K + erf(sqrt(0.5*inverseWidth1*inverseWidth2) * (inverseWidth1*T1 ...
        + inverseWidth2*T2) / (inverseWidth1+inverseWidth2)) - 1;
end
K = c * K ...
    .* exp((-0.5*inverseWidth1*inverseWidth2/(inverseWidth1+inverseWidth2))*(deltaT.^2));

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
%Set parameters: k and threshold of lof
k = 10;
threshold = 2;

%Test data1
test = load('TestData1.mat');
[suspicious_index lof] = LOF(test.data, k);
target = test.data(lof>=threshold, :);
normal = test.data(lof<threshold, :);

%Visualization

%Plot result, red x: outlier, blue circle: normal point
figure(2);
cla;
hold on;
scatter(normal(:, 1), normal(:, 2), 'b');
scatter(target(:, 1), target(:, 2), 'rx')
hold off;

disp('Demo LOF for test data1')
disp('Press Enter for continuing...')
pause
disp('Demo LOF for test data2')

%Test data2
test = load('TestData2.mat');
[suspicious_index lof] = LOF(test.data, k);
target = test.data(lof>=threshold, :);
normal = test.data(lof<threshold, :);

%Visualization

%Plot result, red x: outlier, blue circle: normal point
figure(2);
cla;
hold on;
scatter(normal(:, 1), normal(:, 2), 'b');
scatter(target(:, 1), target(:, 2), 'rx')
hold off;

author: dsmi-lab-ntust

repo: AnomalyDetectionToolbox


text:
function [xUpdate, SUpdate,innov,Szz,W]=sqrtKalmanUpdateWithPred(z,SR,zPred,otherInfo)
%%SQRTKALMANUPDATEWITHPRED Given the output of the measurement prediction
%           step from sqrtKalmanMeasPred and a measurement, complete the
%           measurement update step of the square-root Kalman filter.
%           Separating the measurement prediction step from the rest of the
%           update step can make the creation of multiple measurement
%           association hypotheses from a single target prediction more
%           efficient. The full measurement update function is
%           sqrtKalmanUpdate.
%
%INPUTS: z The zDimX1 measurement vector.
%       SR The zDimXzDim lower-triangular square root of the measurement
%          covariance matrix in the native coordinate system of the
%          measurement.
%    zPred The zDimXnumComp measurement predictions from the filter.
%   PzPred The zDimXzDimXnumComp covariance matrices associated with zPred.
% otherInfo The intermediate results returned in the otherInfo output of
%          the sqrtKalmanMeasPred function.
%
%OUTPUTS: xUpdate The xDimXnumComp updated state vectors.
%         SUpdate The updated xDimXxDimXnumComp lower-triangular square-
%                 root state covariance matrices.
%      innov, Szz The zDimXnumComp innovations and the zDimXzDimXnumComp
%                 square-root innovation covariance matrix are returned in
%                 case one wishes to analyze the consistency of the
%                 estimator or use those values in gating or likelihood
%                 evaluation.
%               W The xDimXzDimXnumComp gain used in the update. This can
%                 be useful when gating and using the function
%                 calcMissedGateCov.
%
%See the comments to the function sqrtKalmanMeasPred for an example of
%usage of this function. See the comments to sqrtKalmanUpdate for more
%information on the algorithm.
%
%June 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

xPred=otherInfo.xPred;
SPred=otherInfo.SPred;
Pxz=otherInfo.Pxz;
H=otherInfo.H;

xDim=size(xPred,1);
numComp=size(xPred,2);
zDim=size(z,1);

xUpdate=zeros(xDim,numComp);
SUpdate=zeros(xDim,xDim,numComp);
innov=zeros(zDim,numComp);
Szz=zeros(zDim,zDim,numComp);
W=zeros(xDim,zDim,numComp);

for k=1:numComp
    Szz(:,:,k)=tria([H*SPred(:,:,k),SR]);
    W=(Pxz(:,:,k)/Szz(:,:,k)')/Szz(:,:,k);
    innov(:,k)=z-zPred(:,k);
    xUpdate(:,k)=xPred(:,k)+W(:,:,k)*innov(:,k);
    temp=W(:,:,k)*H;
    SUpdate(:,:,k)=tria([(eye(size(temp))-temp)*SPred,W(:,:,k)*SR]);
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
% NANMAX Maximum value, ignoring NaNs.
%    M = NANMAX(A) returns the maximum of A with NaNs treated as missing.
%    For vectors, M is the largest non-NaN element in A.  For matrices, M is
%    a row vector containing the maximum non-NaN element from each column.
%    For N-D arrays, NANMAX operates along the first non-singleton
%    dimension.
%
%    [M,NDX] = NANMAX(A) returns the indices of the maximum values in A.  If
%    the values along the first non-singleton dimension contain more than
%    one maximal element, the index of the first one is returned.
%
%    M = NANMAX(A,B) returns an array the same size as A and B with the
%    largest elements taken from A or B.  Either one can be a scalar.
%
%    [M,NDX] = NANMAX(A,[],DIM) operates along the dimension DIM.
%
%    See also MAX, NANMIN, NANMEAN, NANMEDIAN, NANMIN, NANVAR, NANSTD.
%
%    Reference page in Doc Center
%       doc stats/nanmax
%
%    Other functions named nanmax
%
%       distributed/nanmax    fints/nanmax
%

author: jmaih


text:
% Wrapper for pca_apply that allows for application to large X.
%
% Wrapper for pca_apply that splits and processes X in parts, this may be
% useful if processing cannot be done fully in parallel because of memory
% constraints. See pca_apply for usage.
%
% USAGE
%  same as pca_apply
%
% INPUTS
%  same as pca_apply
%
% OUTPUTS
%  same as pca_apply
%
% EXAMPLE
%
% See also PCA, PCA_APPLY, PCA_VISUALIZE

% Piotr's Image&Video Toolbox      Version 1.5
% Written and maintained by Piotr Dollar    pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!

function [ Yk, Xhat, avsq ] = pca_apply_large( X, U, mu, vars, k )

siz = size(X); nd = ndims(X);  [N,r]  = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));

% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
  warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
  k=r;
end

% Will run out of memory if X has too many elements.  Hence, run
% pca_apply on parts of X and recombine.
maxwidth = ceil( (10^7) / d );
if(maxwidth > siz(end))
  if (nargout==1)
    Yk = pca_apply( X, U, mu, vars, k );
  elseif (nargout==2)
    [Yk, Xhat] = pca_apply( X, U, mu, vars, k );
  else
    [ Yk, Xhat, avsq ] = pca_apply( X, U, mu, vars, k );
  end
else
  Yk = zeros( k, siz(end) );  Xhat = zeros( siz );
  avsq = 0;  avsqOrig = 0;  last = 0;
  while(last < siz(end))
    first=last+1;  last=min(first+maxwidth-1,siz(end));
    Xi = X(inds{:}, first:last);
    if( nargout==1 )
      Yki = pca_apply( Xi, U, mu, vars, k );
    else
      if( nargout==2 )
        [Yki,Xhati] = pca_apply( Xi, U, mu, vars, k );
      else
        [Yki,Xhati,avsqi,avsqOrigi] = pca_apply( Xi, U, mu, vars, k );
        avsq = avsq + avsqi;  avsqOrig = avsqOrig + avsqOrigi;
      end;
      Xhat(inds{:}, first:last ) = Xhati;
    end
    Yk( :, first:last ) = Yki;
  end;
  if( nargout==3); avsq = avsq / avsqOrig; end
end

author: pdollar

repo: toolbox

save_path: github-repos/MATLAB/pdollar-toolbox


text:
function [dy] = dmodel2D(t,y,a)
dy = zeros(2,1);
dy(1) = y(2);
dy(2) = (1 - a(2)*y(2)-a(1)*y(1))/a(3);
%

author: Sable

repo: mcbench-benchmarks


text:
function R = xyz2R(xyz)
%DESCRIPTION: given a point on earth retrun the rotation matrix with:
%           - fist lien directed to loacal east
%           - second line directed  as north
%           - third line directed as local up
[phi, lam] = cart2geod(xyz(1), xyz(2), xyz(3));

    %rotation matrix from global to local reference system
    R = [-sin(lam) cos(lam) 0;
         -sin(phi)*cos(lam) -sin(phi)*sin(lam) cos(phi);
         +cos(phi)*cos(lam) +cos(phi)*sin(lam) sin(phi)];
end

author: goGPS-Project


text:
function [P L U Q]=GaElCoPi(A)

%Gaussian Elimination with Complete Pivoting
%version 1.0

%P*A*Q=L*U
%Alvaro Moraes
%KAUST 2009

%Example of usage:
%A=randn(40);
%[P L U Q]=GaElCoPi(A);
%norm(P*A*Q-L*U)

% or this (it takes some time)
% choose the size of A and
% the number of simulations
% for k=1:1000
%  k
%  A=randn(128);
%  [P L U Q]=GaElCoPi(A);
%  N1(k) =norm(P*A*Q-L*U);
%  %compute the growth factor
%  %rho(k)=max(max(abs(U)))/max(max(abs(A)))
% end
% plot(N1)
% max(abs(N1)) %must be small xxe-014

%and also check the worst scenario for the Partial Pivoting:
% m=128; %(matrix 22.4 from Trefethen and Baum)
% A=-1*tril(ones(m))+2*eye(m);
% A(:,m)=ones(m,1);
%[P L U Q]=GaElCoPi(A);
%norm(P*A*Q-L*U)

[n n]=size(A);
L=zeros(n);
%v and w record the permutations
%of the rows and cols respect.
v=1:n; w=1:n;

for k=1:n-1
     %in the next three lines
     %we obtain  the max of abs(A(v(k:n),w(k:n)))
     %and its coordinates (imr,imc)
     [m,mc]=max(abs(A(v(k:n),w(k:n))));
     [m,c]=max(m);
     imc=c; imr=mc(c);
     %next we transform this coordinates to the
     %coordinates of A
     imr=imr+k-1;
     imc=imc+k-1;
     %now, we perform the permutations
     v([k imr])=v([imr k]);
     w([k imc])=w([imc k]);
     %next, the gaussian elimination step
    for i=k+1:n
        L(v(i),w(k))=A(v(i),w(k))/A(v(k),w(k));
        A(v(i),:)=A(v(i),:)-L(v(i),w(k))*A(v(k),:);
    end
end
%by last, we use v and w to define P, Q, L and U
P=eye(n);P=P(v,:);
Q=eye(n);Q=Q(:,w);
L=L(v,w)+ eye(n);
U=A(v,w);


text:
%%
%nested cross validation for testing the logistic rMTFL model
%The stratified cv are integrated into method to handle
%"not_enough_data_sample" problems and privide more accurate estimator
%Han Cao
%24.02.2017
%%

clear;
clc;
close;

addpath('../MALSAR/functions/rMTFL/'); % load function
addpath('../MALSAR/utils/'); % load utilities
addpath('./train_and_test/');

% simulate the data
n = 50;
d = 300;
T = 10;

X = cell(T, 1);
Y = cell(T, 1);
W = randn(d, T);
W_mask = abs(randn(d, T))<1;
W(W_mask) = 0;
for i = 1: T
    X{i} = randn(n, d);
    Y{i} = sign(X{i} * W(:, i) + rand(n, 1) * 0.01);
end

%optimization options
opts.init = 2;
opts.tFlag = 1;
opts.tol = 10^-5;
opts.maxIter = 60000;

% lambda range
lambda1_range = [1:-0.01:0.01];
lambda2_range = [2:-0.05:0.05];

%container for holding the results
r_acc=cell(1,3);
r_inCvAcc=cell(1,3); %
r_S=cell(1,3);

%nested cross validation
out_cv_fold=3;
in_cv_fold=5;
for i = 1: out_cv_fold
    Xtr = cell(T, 1);
    Ytr = cell(T, 1);
    Xte = cell(T, 1);
    Yte = cell(T, 1);

    %stratified cross validation
    for t = 1: T
        task_sample_size = length(Y{t});
        ct = find(Y{t}<0);
        cs = find(Y{t}>0);
        ct_idx = i : out_cv_fold : length(ct);
        cs_idx = i : out_cv_fold : length(cs);
        te_idx = [ct(ct_idx); cs(cs_idx)];
        tr_idx = setdiff(1:task_sample_size, te_idx);

        Xtr{t} = X{t}(tr_idx, :);
        Ytr{t} = Y{t}(tr_idx, :);
        Xte{t} = X{t}(te_idx, :);
        Yte{t} = Y{t}(te_idx, :);
    end

    %inner cv
    fprintf('inner CV started\n')
    [best_lambda1 best_lambda2 accuracy_mat] = CrossValidationDirty( Xtr, Ytr, ...
        'Logistic_rMTFL', opts, lambda1_range,lambda2_range, in_cv_fold, ...
        'eval_MTL_accuracy');

    %train
    %warm start for one turn
    [W C P Q L F] = Logistic_rMTFL(Xtr, Ytr, best_lambda1, best_lambda2, opts);
    opts2=opts;
    opts2.init=1;
    opts2.C0=C;
    opts2.P0=P;
    opts2.Q0=Q;
    opts2.tol = 10^-10;
    [W2 C2 P2 Q2 L2 F2] = Logistic_rMTFL(Xtr, Ytr, best_lambda1, best_lambda2, opts2);

     %test
    final_performance = eval_MTL_accuracy(Yte, Xte, W2, C2);

    %collect results
    r_acc{i}=final_performance;
    r_inCvAcc{i}=accuracy_mat;
    r_S{i}=nnz((sum(P2,2)==0))/size(P2,1);

end

 fprintf('the average accuracy is \n')
 disp(mean(cell2mat(r_acc)))

 %cv accuracy cross lambda
for i=1:out_cv_fold
    surf(lambda1_range', lambda2_range,r_inCvAcc{i}' );
    xlabel('Parameter for P');
    ylabel('parameter for Q');
    hold on;
end
hold off;
title('cross validation accuracy over different lambda');
set(gca,'FontSize',12);
print('-dpdf', '-r100', 'LogisticDirty');

author: jiayuzhou

repo: MALSAR

save_path: github-repos/MATLAB/jiayuzhou-MALSAR


text:
% Compute null space vanilla
function [qd_null] = null_space_7dof(robot, q)
%compute nil-space!!
J = manipulator_jacobian(robot, q);
I = eye(robot.DOF);
Jp=pinv(J);
%null space projector
%n_space_projector = (I-Jp*J);
%for an arbitrary vector
%do not use [1 1 1 1]
qd3 = [0 0 1 0 0 0 0]';
%qd3 = q;
qd_null = project(J, Jp, I, qd3);

function qd_null = project(J, Jp, I, qd)
%q2 est� calculado a trav�s de un proyector (I-Jp*J),
%, de tal manera que q2 pertenece al null space de J
qd_null = (I-Jp*J)*qd;

repo: ARTE


text:
function varargout = rmEditStimParams(varargin)
% RMEDITSTIMPARAMS M-file for rmEditStimParams.fig
%      RMEDITSTIMPARAMS, by itself, creates a new RMEDITSTIMPARAMS or raises the existing
%      singleton*.
%
%      H = RMEDITSTIMPARAMS returns the handle to a new RMEDITSTIMPARAMS or the handle to
%      the existing singleton*.
%
%      RMEDITSTIMPARAMS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RMEDITSTIMPARAMS.M with the given input arguments.
%
%      RMEDITSTIMPARAMS('Property','Value',...) creates a new RMEDITSTIMPARAMS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before rmEditStimParams_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to rmEditStimParams_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% NOTE: You can also pass in a view structure as the first option:
%	rmEditStimParams(view, [options...]).   (ras, 01/09)
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help rmEditStimParams

% Last Modified by GUIDE v2.5 16-Jan-2009 16:56:08

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @rmEditStimParams_OpeningFcn, ...
                   'gui_OutputFcn',  @rmEditStimParams_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
return;

% --- Executes just before rmEditStimParams is made visible.
function rmEditStimParams_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
%
% The key subroutines are:
% 1. rmEditStimParams_OpeningFcn (this one), which initializes values in
% the UI window
% 2. paramsToWindow: writes values from the parameters to the UI window
% 3. paramsFromWindow: writes values from the UI window to the parameters
% 4. btnDone_Callback: writes values to parameters and then to vista view

% Choose default command line output for rmEditStimParams
handles.output = hObject;

%% get the view associated with these parameters
% (ras, 01/09, change from original): does not require that you're using a
% global VOLUME view. Should allow inplanes and hidden view structures. So,
% we allow you to pass the view in as the first argument, if it's a hidden
% view. Otherwise, finds the currently-selected view.
if ~isempty(varargin) & isstruct(varargin{1}) & isfield(varargin{1}, 'viewType')
	handles.vw = varargin{1};
else
	handles.vw = getCurView; % does not always get current view because it is order dependent
end

handles.dt = viewGet(handles.vw, 'currentdatatypestructure');

% Put values into the window.  We first check the stimulus
% parameterization for the currently loaded rm model.
sParams = viewGet(handles.vw,'rmStimParams');

%  If there is no currently loaded model, we try to get the values from the
%  dataTYPES.
if isempty(sParams), sParams = dtGet(handles.dt, 'rmParams'); end

% We enforce the stimulus parameters organization. If no values were found
% in a current model or in the dataTYPES, we put in defaults. If values
% were found, we check that all necessary fields are present, and that
% unrecognized fields are removed. Older computed data such as 'images' and
% 'images_org' are deleted here.  We create the new images and related
% fields when we push the Done button.
sParams = rmCreateStim(handles.vw,sParams);

% Store the current stimulus parameters
handles.sParams = sParams;

% Initialize the scan slider
nScans = length(sParams);
setScanSlider(hObject, nScans);

% We need to a separate variable which will tell us the previous scan after
% the slider or edit box are changed clicked. Since we always initialize at
% scan 1, we set prior scan to 1 when we open the GUI.
handles.priorScan = 1;

% Identify the number of scans in the session
% set(handles.txtScanNum,'String',sprintf('Scan (%d)',nScans));
set(handles.editNumScans,'String',num2str(nScans));
guidata(hObject,handles);

% Refresh the UI using the fields in the stimulus parameters (sParams)
whichScan = 1; paramsToWindow(hObject,whichScan);

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes rmEditStimParams wait for user response (see UIRESUME)
% uiwait(handles.rmEditStimParams);
return;

% --- Outputs from this function are returned to the command line.
function varargout = rmEditStimParams_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;
return;

% - Refresh the window using current values of stimulus parameters
function paramsToWindow(hObject,whichScan)
% Copy parameters from the view structure into the window

% Get current state of handles and stimulus parameters
handles = guidata(hObject);
thisParams = handles.sParams(whichScan);

% The popupClass must be set before calling this routine
refreshImagePopups(hObject,whichScan);

% Set the edit boxes
set(handles.editRadius,'String',num2str(thisParams.stimSize));
set(handles.editWidth,'String',num2str(thisParams.stimWidth));
set(handles.editStartPhase,'String',num2str(thisParams.stimStart));
set(handles.editCycles,'String',num2str(thisParams.nCycles));
set(handles.editMeanBlocks,'String',num2str(thisParams.nStimOnOff));
set(handles.editRep,'String',num2str(thisParams.nUniqueRep));
set(handles.editDetrend,'String',num2str(thisParams.nDCT));
set(handles.editRemoved,'String',num2str(thisParams.prescanDuration));
set(handles.editFrames,'String',num2str(thisParams.nFrames));
set(handles.editInterval,'String',num2str(thisParams.framePeriod));

% Check boxes
if ~checkfields(thisParams, 'fliprotate'), thisParams.fliprotate = [0 0 0]; end
flip = thisParams.fliprotate;
if length(flip) < 3, thisParams.fliprotate = padarray(flip,3-length(flip), 'post'); end
set(handles.cboxLR,'Value',thisParams.fliprotate(1));
set(handles.cboxUD,'Value',thisParams.fliprotate(2));
set(handles.cboxCCW,'Value',thisParams.fliprotate(3));

guidata(hObject,handles);

return;

% - Should be a separate utility function
function ii = getPopupValue(h,target)
% Given a handle to a popup, h, find the value

str = get(h,'String');
if ~iscell(str)  % Only one term
    if strcmpi(str,target), ii = 1; return; end
else
    for ii=1:length(str)
        if strcmpi(str{ii},target)
            return;
        end
    end
end

% Returns a safe value, but maybe it should be null?
ii = 1;

% if strcmpi(target,'none'), return;
% else fprintf('Target string [%s] not found\n',target);
% end

return;

% - Refresh the parameters using current values window objects
function paramsFromWindow(hObject,handles,whichScan)

% Current parameter values
thisParams = handles.sParams(whichScan);

% Update the values from the handles
% Copy parameters from the view structure into the window

% Spatial grouping
%
classes = get(handles.popupClass,'String');
thisParams.stimType = classes{get(handles.popupClass,'value')};

thisParams.stimSize = str2double(get(handles.editRadius,'String'));
thisParams.stimWidth = str2double(get(handles.editWidth,'String'));
thisParams.stimStart = str2double(get(handles.editStartPhase,'String'));

% An integer that defines in/out or cw/ccw
thisParams.stimDir = get(handles.popupDirection,'value') - 1;

thisParams.nCycles         = str2double(get(handles.editCycles,'String'));
thisParams.nStimOnOff      = str2double(get(handles.editMeanBlocks,'String'));
thisParams.nUniqueRep      = str2double(get(handles.editRep,'String'));
thisParams.nDCT            = str2double(get(handles.editDetrend,'String'));

% Timing grouping
thisParams.prescanDuration = str2double(get(handles.editRemoved,'String'));
thisParams.nFrames         = str2double(get(handles.editFrames,'String'));
thisParams.framePeriod     = str2double(get(handles.editInterval,'String'));

% Timing grouping
classes = get(handles.popupHRFModel,'String');
v = get(handles.popupHRFModel,'value');
thisParams.hrfType = classes{v};

% These are the Boynton and SPM HRF parameters and now an impulse HRF
% We are guessing that the hrfType field is used to choose between these
% two (now three) parameter sets
%
% hrfModelParams = {[1.68,3 ,2.05],[5.4,5.2 ,10.8,7.35,0.35], [1]};
% thisParams.hrfParams = hrfModelParams{v};

% Image Grouping
thisParams.fliprotate(1) = get(handles.cboxLR, 'Value');
thisParams.fliprotate(2) = get(handles.cboxUD, 'Value');
thisParams.fliprotate(3) = get(handles.cboxCCW,'Value');

classes = get(handles.popupImageFile,'String');
thisParams.imFile = classes;
if iscell(classes)
    thisParams.imFile = classes{get(handles.popupImageFile,'value')};
end

classes = get(handles.popupParamsFile,'String');
thisParams.paramsFile = classes;
if iscell(classes)
    thisParams.paramsFile = classes{get(handles.popupParamsFile,'value')};
end

classes = get(handles.popupImageFilter,'String');
thisParams.imFilter = classes;
if iscell(classes)
    thisParams.imFilter = classes{get(handles.popupImageFilter,'value')};
end

classes = get(handles.popupJitter,'String');
thisParams.jitterFile = classes;
if iscell(classes)
    thisParams.jitterFile = classes{get(handles.popupJitter,'value')};
end

% Put them back in the handles structure
handles.sParams(whichScan) = thisParams;

guidata(hObject,handles);

return;

% --- Executes on slider movement.
function sliderScan_Callback(hObject, eventdata, handles)
% We copy the data in the window to the handles.sParams entries.

% The user clicked on the slider and changed the scan to this new value
v = get(handles.sliderScan,'Value');

% make sure the value is an integer.
v = round(v);

% We update the edit box as well.
set(handles.editScan,'String',num2str(v));

% Before we clicked, we were operating on a prior scan.
% We take the parameters in the window and copy them into the parameter
% fields of that scan.
whichScan = handles.priorScan;
paramsFromWindow(hObject,handles,whichScan);
handles = guidata(hObject);

% Copy the parameters in thisParams from the new scan into the window
whichScan = v;
paramsToWindow(hObject,whichScan);

% The present becomes past
handles.priorScan=v;

guidata(hObject,handles);

return;

% --- Executes during object creation, after setting all properties.
function sliderScan_CreateFcn(hObject, eventdata, handles)
% hObject    handle to sliderScan (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

return;

function editScan_Callback(hObject, eventdata, handles)
% When the edit box for scan number is changed

% Make sure we are in range
nScans = length(handles.sParams);
v = str2double(get(handles.editScan,'string')); v = min(v,nScans); v = max(1,v);

% Adjust the slider
set(handles.sliderScan,'value',v);
set(handles.editScan,'string',num2str(v));

% Move the stimulus parameter data from the window
whichScan = handles.priorScan;
paramsFromWindow(hObject,handles,whichScan);
handles = guidata(hObject);

% Copy the new parameters to the window
whichScan = v;
paramsToWindow(hObject,whichScan);

% The present becomes past
handles.priorScan=v;

guidata(hObject,handles);
return;

% --- Executes during object creation, after setting all properties.
function editScan_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editScan (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
return;

% --- Executes on selection change in popupClass.
function popupClass_Callback(hObject, eventdata, handles)
% Must update the popups because we may choose stimFromScan clas

whichScan = get(handles.sliderScan,'value');
paramsFromWindow(hObject,handles,whichScan)
refreshImagePopups(hObject,whichScan);

return;

% --- Executes during object creation, after setting all properties.
function popupClass_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editRadius_Callback(hObject, eventdata, handles)
return;

% --- Executes during object creation, after setting all properties.
function editRadius_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editWidth_Callback(hObject, eventdata, handles)
return;

% --- Executes during object creation, after setting all properties.
function editWidth_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
return;

function editStartPhase_Callback(hObject, eventdata, handles)
% hObject    handle to editStartPhase (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 editStartPhase as text
%        str2double(get(hObject,'String')) returns contents of editStartPhase as a double

return;

% --- Executes during object creation, after setting all properties.
function editStartPhase_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editStartPhase (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
return;

% --- Executes on selection change in popupDirection.
function popupDirection_Callback(hObject, eventdata, handles)
% hObject    handle to popupDirection (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 popupDirection contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupDirection
return;

% --- Executes during object creation, after setting all properties.
function popupDirection_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupDirection (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
return;

function editCycles_Callback(hObject, eventdata, handles)
% hObject    handle to editCycles (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 editCycles as text
%        str2double(get(hObject,'String')) returns contents of editCycles as a double

return;
% --- Executes during object creation, after setting all properties.
function editCycles_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editCycles (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
return;

function editMeanBlocks_Callback(hObject, eventdata, handles)
% hObject    handle to editMeanBlocks (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 editMeanBlocks as text
%        str2double(get(hObject,'String')) returns contents of editMeanBlocks as a double
return;

% --- Executes during object creation, after setting all properties.
function editMeanBlocks_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMeanBlocks (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
return;

function editRep_Callback(hObject, eventdata, handles)
% hObject    handle to editRep (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 editRep as text
%        str2double(get(hObject,'String')) returns contents of editRep as a double
return;

% --- Executes during object creation, after setting all properties.
function editRep_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editRep (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
return;

function editDetrend_Callback(hObject, eventdata, handles)
% hObject    handle to editDetrend (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 editDetrend as text
%        str2double(get(hObject,'String')) returns contents of editDetrend as a double
return;

% --- Executes during object creation, after setting all properties.
function editDetrend_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editDetrend (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
return;

function editRemoved_Callback(hObject, eventdata, handles)
% hObject    handle to editRemoved (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 editRemoved as text
%        str2double(get(hObject,'String')) returns contents of editRemoved as a double
return;

% --- Executes during object creation, after setting all properties.
function editRemoved_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editRemoved (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
return;

% --- Executes on button press in cboxLR.
function cboxLR_Callback(hObject, eventdata, handles)
% hObject    handle to cboxLR (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 cboxLR

return;

% --- Executes on selection change in popupImageFile.
function popupImageFile_Callback(hObject, eventdata, handles)
% hObject    handle to popupImageFile (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 popupImageFile contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupImageFile
return;

% --- Executes during object creation, after setting all properties.
function popupImageFile_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupImageFile (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
return;

% --- Executes on selection change in popupParamsFile.
function popupParamsFile_Callback(hObject, eventdata, handles)
% hObject    handle to popupParamsFile (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 popupParamsFile contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupParamsFile
return;

% --- Executes during object creation, after setting all properties.
function popupParamsFile_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupParamsFile (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
return;

% --- Executes on selection change in popupImageFilter.
function popupImageFilter_Callback(hObject, eventdata, handles)
% hObject    handle to popupImageFilter (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 popupImageFilter contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupImageFilter
return;

% --- Executes during object creation, after setting all properties.
function popupImageFilter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupImageFilter (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
return;

% --- Executes on button press in cboxJitter.
function cboxJitter_Callback(hObject, eventdata, handles)
% hObject    handle to cboxJitter (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 cboxJitter
return;
% --- Executes on selection change in popupHRFModel.
function popupHRFModel_Callback(hObject, eventdata, handles)
% hObject    handle to popupHRFModel (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 popupHRFModel contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupHRFModel
return;

% --- Executes during object creation, after setting all properties.
function popupHRFModel_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupHRFModel (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
return;

function editFrames_Callback(hObject, eventdata, handles)
% hObject    handle to editFrames (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 editFrames as text
%        str2double(get(hObject,'String')) returns contents of editFrames as a double
return;

% --- Executes during object creation, after setting all properties.
function editFrames_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editFrames (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

return;

function editInterval_Callback(hObject, eventdata, handles)
% hObject    handle to editInterval (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 editInterval as text
%        str2double(get(hObject,'String')) returns contents of editInterval as a double
return;

% --- Executes during object creation, after setting all properties.
function editInterval_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editInterval (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
return;

% --- Executes on button press in btnCancel.
function btnCancel_Callback(hObject, eventdata, handles)
% hObject    handle to btnCancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close;
return;

% --- Executes on button press in btnDone.
function btnDone_Callback(hObject, eventdata, handles)
% User is finished.  Parameters from window to sParams
% Then we attach it do dataTypes and view.

whichScan  = get(handles.sliderScan,'Value');
paramsFromWindow(hObject,handles,whichScan);
handles = guidata(hObject);
paramsToVista(hObject,handles);

closereq

return;

% Copy the final set of stimulus parameters into the view and dataTypes
function paramsToVista(hObject,handles)
% Assign the new values to the view structure and dataType

% Make the current view variable (INPLANE, VOLUME) and dataTYPE accessible
mrGlobals;

handles = guidata(hObject);
handles = fileFullPath(handles);

handles.vw = viewSet(handles.vw, 'rmStimParams',handles.sParams);

% save to data types if selected
% (see discussion in the change log for this file)
hSave = findobj('Tag', 'cbox_saveToDataTYPES');
hSaveValue = get(hSave, 'Value');
if iscell(hSaveValue) % hSaveValue is a cell struct.
    hSaveValue = hSaveValue{1};
end
if hSaveValue==1
	dtNum = viewGet(handles.vw,'dtNumber');
	handles.dt = dtSet(handles.dt,'retinotopyModelParams',handles.sParams);
	dataTYPES(dtNum).retinotopyModelParams = [];
    dataTYPES(dtNum) = handles.dt;
	fprintf('Updated stored stimulus parameters in dataTYPES.\n');
	saveSession;
end

% rmLoadParameters builds the stimuli (images) and computes various things
% and puts them into the view.
handles.vw = rmLoadParameters(handles.vw);

% if this is a global variable (INPLANE, VOLUME), update the global
% variable to match this view
if strncmp(handles.vw.name, 'INPL', 4) | strncmp(handles.vw.name, 'VOLU', 4)
	updateGlobal(handles.vw);
end

return

function h = fileFullPath(h)
% Convert the file names to full paths for this session.

nScans  = length(h.sParams);
homeDir = viewGet(h.vw,'homeDir');

for ii=1:nScans

    [p,n,e] = fileparts(h.sParams(ii).imFile);
    h.sParams(ii).imFile = fullfile(homeDir,'Stimuli',[n,e]);

    [p,n,e] = fileparts(h.sParams(ii).jitterFile);
    h.sParams(ii).jitterFile = fullfile(homeDir,'Stimuli',[n,e]);

    [p,n,e] = fileparts(h.sParams(ii).paramsFile);
    h.sParams(ii).paramsFile = fullfile(homeDir,'Stimuli',[n,e]);
end

return;

function setScanSlider(hObject, nScans)

handles = guidata(hObject);

% get the current scan number
scanNum = str2num(get(handles.editScan, 'String'));

% check that it is not greater than the number of scans being set
if scanNum > nScans,
    error('Number of scans is less than the current scan number');
end

% The user clicked on the slider and changed the scan to this new value

if nScans > 1
    % Multiple scans - possibility of changing
    set(handles.sliderScan,'min',1);
    set(handles.sliderScan,'max',nScans);
    set(handles.sliderScan,'sliderStep',[1/(nScans-1) 1/(nScans-1)])
    set(handles.sliderScan,'Value',scanNum);
    set(handles.editScan,'String',num2str(scanNum));
    set(handles.sliderScan,'Visible','on');
    set(handles.editScan,'Visible','on');
else
    % Only one scan - so no possibility of changing
    set(handles.sliderScan,'min',1);
    set(handles.sliderScan,'max',1);
    set(handles.sliderScan,'Value',1);
    set(handles.sliderScan,'Visible','off');
    set(handles.editScan,'Visible','off');
end
guidata(hObject,handles);
return

% --- Executes on selection change in popupJitter.
function popupJitter_Callback(hObject, eventdata, handles)
% hObject    handle to popupJitter (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 popupJitter contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupJitter
return;

% --- Executes during object creation, after setting all properties.
function popupJitter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupJitter (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
return;

%  --- Manage the image popup strings depending on context
function refreshImagePopups(hObject,whichScan)
% Fill fields when StimFromScan field in class
% Gray out the text when popups are irrelevant

handles = guidata(hObject);
thisParams = handles.sParams(whichScan);

% Set Class poup
switch thisParams.stimType
    case '8Bars',        v = 1;
    case 'Ring',         v = 2;
    case 'RoughBars',    v = 3;
    case 'Wedge',        v = 4;
    case 'StimFromScan', v = 5;
    case 'StimFromScan1D', v = 6;
    otherwise,
        warndlg('Unknown stimulus type')
        v = 1;
end
set(handles.popupClass,'value',v);

% Set stimulus direction popup
switch thisParams.stimDir
    case 0,  v = 1;
    case 1,  v = 2;
    otherwise,
        warndlg('Unknown direction')
        v = 1;
end
set(handles.popupDirection,'value',v);

% HRF type
switch thisParams.hrfType
    case 'one gamma (Boynton style)', v = 1;
    case 'two gammas (SPM style)',    v = 2;
    case 'impulse',                   v = 3;
    otherwise,
        warndlg('Unknown HRF model %s',thisParams.hrfType)
        v = 1;
end
set(handles.popupHRFModel,'value',v);

% Define the Stimuli directory for finding local files
sDir = fullfile(viewGet(handles.vw,'homeDir'),'Stimuli');

% Populate the pulldown strings
switch lower(thisParams.stimType)
    case {'stimfromscan','stimfromscan1d'}
        grayEditText(handles,whichScan);  % Stim from scan

        % If stimfromscan, we populate with files in the Stimuli
        % directory.

        if exist(sDir,'dir')
            % Image pulldown
            f = dir(fullfile(sDir,'*image*.mat'));
            str = cell(length(f),1);
            if ~isempty(f)
                for ii=1:length(f)
                    str{ii} = f(ii).name;
                end
                set(handles.popupImageFile,'String',str);
            end
            set(handles.txtImgFile,'foregroundcolor',[0 0 0]);

            % Image pulldown
            f = dir(fullfile(sDir,'*params*.mat'));
            str = cell(length(f),1);
            if ~isempty(f)
                for ii=1:length(f)
                    str{ii} = f(ii).name;
                end
                set(handles.popupParamsFile,'String',str);
            end
            set(handles.txtPFile,'foregroundcolor',[0 0 0]);

            % Filter definitions
            d = fullfile(mrvRootPath,'Analysis',...
                'retinotopyModel',...
                'FilterDefinitions','*.m');
            f = dir(d);
            str = cell(length(f)+1,1);
            str{1} = 'none';
            for ii=1:length(f)
                s = findstr(f(ii).name,'_');
                [p,str{ii+1},e] = fileparts(f(ii).name((s+1):end));
            end
            set(handles.popupImageFilter,'String',str);
            set(handles.txtIFilter,'foregroundcolor',[0 0 0]);
        end

    otherwise
        grayEditText(handles,whichScan);  % Not stim from scan

        % For most cases, these are not options so we gray them out
        set(handles.popupImageFile,'String','none');
        set(handles.popupImageFile,'Value',1);
        set(handles.popupParamsFile,'String','none');
        set(handles.popupParamsFile,'Value',1);
        set(handles.popupImageFilter,'String','none');
        set(handles.popupImageFilter,'Value',1);

end

% Populate the pulldown Jitter files
f = dir(fullfile(sDir,'*jitter*.mat'));
str = cell(length(f)+1,1); str{1} = 'none';
if ~isempty(f)
    for ii=1:length(f)
        str{ii+1} = f(ii).name;
    end
end
set(handles.popupJitter,'String',str);

% We set the pulldown values
bName = mrvFileNameExt(thisParams.imFile);
v = getPopupValue(handles.popupImageFile,bName);
set(handles.popupImageFile,'Value',v);

bName = mrvFileNameExt(thisParams.paramsFile);
v = getPopupValue(handles.popupParamsFile,bName);
set(handles.popupParamsFile,'Value',v);

bName = mrvFileNameExt(thisParams.imFilter);
v = getPopupValue(handles.popupImageFilter,bName);
set(handles.popupImageFilter,'Value',v);

% jitter file popup
if ~checkfields(thisParams,'jitterFile'), return;
else
    bName = mrvFileNameExt(thisParams.jitterFile);
    v = getPopupValue(handles.popupJitter,bName);
    set(handles.popupJitter,'Value',v);
end

guidata(hObject,handles);

return;

% Gray out irrelevant text edit boxes
function grayEditText(handles,whichScan)

thisParams = handles.sParams(whichScan);
switch lower(thisParams.stimType)
    case {'stimfromscan','stimfromscan1d'}
        val1 = [.5 .5 .5]; val2 = [ 0 0 0];
    otherwise
        val1 = [ 0 0 0]; val2 = [.5 .5 .5];
end

set(handles.txtImgFile,'foregroundcolor', val2);
set(handles.txtPFile,'foregroundcolor',val2);
set(handles.txtIFilter,'foregroundcolor',val2);

set(handles.txtCycles,'foregroundcolor',val1);
set(handles.txtDirection,'foregroundcolor',val1);
set(handles.txtFrames,'foregroundcolor',val1);
set(handles.txtFrameInt,'foregroundcolor',val1);
set(handles.txtMeanLumBlk,'foregroundcolor',val1);
set(handles.txtRemoved,'foregroundcolor',val1);
set(handles.txtReps,'foregroundcolor',val1);
set(handles.txtPhase,'foregroundcolor',val1);
set(handles.txtWidth,'foregroundcolor',val1);

return;

% --- Executes on button press in cboxUD.
function cboxUD_Callback(hObject, eventdata, handles)
% hObject    handle to cboxUD (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 cboxUD
return;

% --- Executes on button press in cboxCCW.
function cboxCCW_Callback(hObject, eventdata, handles)
% hObject    handle to cboxCCW (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 cboxCCW
return;

function editNumScans_Callback(hObject, eventdata, handles)
% hObject    handle to editNumScans (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 editNumScans as text
%        str2double(get(hObject,'String')) returns contents of editNumScans as a double

nScans = str2double(get(hObject,'String'));
n = length(handles.sParams);
setScanSlider(hObject, nScans)

if     nScans > n, handles.sParams(n+1:nScans) = handles.sParams(n);
elseif nScans < n, handles.sParams(nScans+1:n) = [];
end

guidata(hObject,handles);

return

% --- Executes during object creation, after setting all properties.
function editNumScans_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editNumScans (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
return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function r = isnan(a)
%ISNAN        Array of 1's for NaN components
%
%   r = isnan(a)
%

% written  10/16/98     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 02/17/06     S.M. Rump  huge arrays and a.rad=0
%

  if a.complex
    if isequal(a.rad,0)
      r = isnan(a.mid);
    else
      r = isnan(a.mid) | isnan(a.rad) ;
    end
  else
    r = isnan(a.inf) | isnan(a.sup) ;
  end

repo: OpenMAS


text:
function x = p16_start ( option, nvar )

%*****************************************************************************80
%
%% P16_START returns a starting point for problem 16.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Input, integer NVAR, the number of variables.
%
%    Output, real X(NVAR), the starting point.
%
  x = zeros ( nvar, 1 );

  x(1:nvar-1) = 1.0;
  x(nvar) = 0.0;

  return
end

author: johannesgerer

repo: jburkardt-m


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
% ##2
%==============================================================================
%
%   - data                 MRI (head), level=7, m=[128,128]
%   - viewer               viewImage2D
%   - interpolation        splineInter
%   - distance             MI
%   - pre-registration     affine2D
%   - regularizer          mbElastic
%   - optimization         lBFGS
% ===============================================================================

close all, help(mfilename);

setup2DMRIData
imgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-2);
distance('reset','distance','MI','nT',8,'nR',8);
trafo('reset','trafo','affine2D');
regularizer('reset','regularizer','mbElastic','alpha',1e-3,'mu',1,'lambda',0);

level = 7; omega = ML{level}.omega; m = ML{level}.m;

% initialize the interpolation scheme and coefficients
imgModel('reset','imgModel','splineInter');
[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega,'out',0);
xc    = getCellCenteredGrid(omega,m);
Rc    = imgModel(R,omega,xc);

% initialize distance measure
distance('set','distance','MI','nT',8,'nR',8);

% initialize regularization, note: yc-yRef is regularized, elastic is staggered
regularizer('reset','regularizer','mbElastic','alpha',1e-2,'mu',1,'lambda',0);
y0   = getStaggeredGrid(omega,m); yRef = y0; yStop = y0;

% setup and initialize plots
FAIRplots('set','mode','lBFGS','omega',omega,'m',m,'fig',1,'plots',1);
FAIRplots('init',struct('Tc',T,'Rc',R,'omega',omega,'m',m));

% build objective function, note: T coefficients of template, Rc sampled reference
fctn = @(yc) NPIRBFGSobjFctn(T,Rc,omega,m,yRef,yc); fctn([]); % report status

% -- solve the optimization problem -------------------------------------------
[yc,his] = lBFGS(fctn,y0,'maxIter',500,'Plots',@FAIRplots,'yStop',yStop,'tolJ',1e-4);
iter = size(his.his,1)-2; reduction = 100*fctn(yc)/fctn(getStaggeredGrid(omega,m)); yOpt = yc;
fprintf('reduction = %s%% after %d iterations\n',num2str(reduction),iter);
[yc,wc,his] = MLIR(ML,'minLevel',4,'maxLevel',6,'parametric',1,'plotMLiter',0,'plotIter',1);

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


text:
% MatrixUser, a multi-dimensional matrix analysis software package
% https://sourceforge.net/projects/matrixuser/
%
% The MatrixUser is a matrix analysis software package developed under Matlab
% Graphical User Interface Developing Environment (GUIDE). It features
% functions that are designed and optimized for working with multi-dimensional
% matrix under Matlab. These functions typically includes functions for
% multi-dimensional matrix display, matrix (image stack) analysis and matrix
% processing.
%
% Author:
%   Fang Liu <leoliuf@gmail.com>
%   University of Wisconsin-Madison
%   Aug-30-2014

% load image matrix from system screenshot

function MU_load_screenshot(handles)

try
    import java.awt.*;
    rob=Robot;
    t=java.awt.Toolkit.getDefaultToolkit();
    rec=java.awt.Rectangle(t.getScreenSize());
    img=rob.createScreenCapture(rec);
    filehandle=java.io.File('__scrnsht_temp.bmp');
    javax.imageio.ImageIO.write(img,'bmp',filehandle);
    imdata = imread('__scrnsht_temp.bmp','bmp'); % temporary file
    delete('__scrnsht_temp.bmp'); % temp file removed
    if ~MU_load_matrix('sns', imdata, 1)
        error('Loading image from screenshot failed!');
    end

catch me
    error_msg{1,1}='Error!!! Getting image information from system screenshot aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);
    return;
end

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function varargout = drawCylinder(varargin)
%DRAWCYLINDER Draw a cylinder.
%
%   drawCylinder(CYL)
%   Draws the cylinder CYL on the current axis.
%   CYL is a 1-by-7 row vector in the form [x1 y1 z1 x2 y2 z2 r] where:
%   * [x1 y1 z1] are the coordinates of starting point,
%   * [x2 y2 z2] are the coordinates of ending point,
%   * R is the radius of the cylinder
%
%   drawCylinder(CYL, N)
%   Uses N points for discretizating the circles of the cylinder. Default
%   value is 32.
%
%   drawCylinder(..., OPT)
%   with OPT = 'open' (default) or 'closed', specify if the bases of the
%   cylinder should be drawn.
%
%   drawCylinder(..., 'FaceColor', COLOR)
%   Specifies the color of the cylinder. Any couple of parameters name and
%   value can be given as argument, and will be transfered to the 'surf'
%   matlab function
%
%   drawCylinder(..., 'FaceAlpha', ALPHA)
%   Specifies the transparency of the cylinder and of the optionnal caps.
%
%   drawCylinder(AX, ...)
%   Specifies the axis to draw on. AX should be a valid axis handle.
%
%   H = drawCylinder(...)
%   Returns a handle to the patch representing the cylinder.
%
%
%   Examples:
%   % basic example
%     figure; drawCylinder([0 0 0 10 20 30 5]);
%
%   % draw hollow cylinders
%     figure; drawCylinder([0 0 0 10 20 30 5], 'open');
%
%   % change cylinder color
%     figure; drawCylinder([0 0 0 10 20 30 5], 'FaceColor', 'r');
%
%   % change cylinder color using graphical handle
%     figure;
%     h = drawCylinder([0 0 0 10 20 30 5]);
%     set(h, 'facecolor', 'b');
%
%   % Draw three mutually intersecting cylinders
%     p0 = [10 10 10];
%     p1 = p0 + 80 * [1 0 0];
%     p2 = p0 + 80 * [0 1 0];
%     p3 = p0 + 80 * [0 0 1];
%     figure; axis equal; axis([0 100 0 100 0 100]); hold on
%     drawCylinder([p0 p1 10], 'FaceColor', 'r');
%     drawCylinder([p0 p2 10], 'FaceColor', 'g');
%     drawCylinder([p0 p3 10], 'FaceColor', 'b');
%     axis equal
%     set(gcf, 'renderer', 'opengl')
%     view([60 30]); light;
%
%   % draw cube skeleton
%     [v, e, f] = createCube;
%     figure; axis equal; axis([-0.2 1.2 -0.2 1.2 -0.2 1.2]); hold on; view(3);
%     cyls = [v(e(:,1), :) v(e(:,2),:) repmat(0.1, size(e, 1), 1)];
%     drawCylinder(cyls);
%     light
%
%   See also
%     cylinderMesh, drawEllipseCylinder, drawSphere, drawLine3d, surf
%     intersectLineCylinder, cylinderSurfaceArea
%

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2005-09-17
% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE

%% Input argument processing

% parse axis handle
if isAxisHandle(varargin{1})
    hAx = varargin{1};
    varargin(1) = [];
else
    hAx = gca;
end

% input argument representing cylinders
cyl = varargin{1};
varargin(1) = [];

% process the case of multiple cylinders
if iscell(cyl)
    hCyls = gobjects(length(cyl), 1);
    for i = 1:length(cyl)
        hCyls(i) = drawCylinder(hAx, cyl{i}, varargin{:});
    end
    if nargout > 0
        varargout{1} = hCyls;
    end
    return;
elseif size(cyl, 1) > 1
    hCyls = gobjects(size(cyl, 1), 1);
    for i = 1:size(cyl, 1)
        hCyls(i) = drawCylinder(hAx, cyl(i, :), varargin{:});
    end

    if nargout > 0
        varargout{1} = hCyls;
    end
    return;
end

% default values
N = 32;
closed = true;

% check number of discretization steps
if ~isempty(varargin)
    var = varargin{1};
    if isnumeric(var)
        N = var;
        varargin = varargin(2:end);
    end
end

% check if cylinder must be closed or open
if ~isempty(varargin)
    var = varargin{1};
    if ischar(var)
        if strncmpi(var, 'open', 4)
            closed = false;
            varargin = varargin(2:end);
        elseif strncmpi(var, 'closed', 5)
            closed = true;
            varargin = varargin(2:end);
        end
    end
end

faceColor = 'g';
ind = find(strcmpi(varargin, 'FaceColor'), 1, 'last');
if ~isempty(ind)
    faceColor = varargin{ind+1};
    varargin(ind:ind+1) = [];
end

% extract transparency
alpha = 1;
ind = find(strcmpi(varargin, 'FaceAlpha'), 1, 'last');
if ~isempty(ind)
    alpha = varargin{ind+1};
    varargin(ind:ind+1) = [];
end

% add default drawing options
varargin = [{'FaceColor', faceColor, 'edgeColor', 'none', 'FaceAlpha', alpha} varargin];

%% Computation of mesh coordinates

% extreme points of cylinder
p1 = cyl(1:3);
p2 = cyl(4:6);

% radius of cylinder
r = cyl(7);

% compute orientation angle of cylinder
[theta, phi, rho] = cart2sph2d(p2 - p1);
dphi = linspace(0, 2*pi, N+1);

% generate a cylinder oriented upwards
x = repmat(cos(dphi) * r, [2 1]);
y = repmat(sin(dphi) * r, [2 1]);
z = repmat([0 ; rho], [1 length(dphi)]);

% transform points
trans   = localToGlobal3d(p1, theta, phi, 0);
pts     = transformPoint3d([x(:) y(:) z(:)], trans);

% reshape transformed points
x2 = reshape(pts(:,1), size(x));
y2 = reshape(pts(:,2), size(x));
z2 = reshape(pts(:,3), size(x));

%% Display cylinder mesh

% plot the cylinder as a surface
hCyl(1) = surf(hAx, x2, y2, z2, varargin{:});

% eventually plot the ends of the cylinder
if closed
    hCyl(2)=patch(hAx, x2(1,:)', y2(1,:)', z2(1,:)', faceColor, 'edgeColor', 'none', 'FaceAlpha', alpha);
    hCyl(3)=patch(hAx, x2(2,:)', y2(2,:)', z2(2,:)', faceColor, 'edgeColor', 'none', 'FaceAlpha', alpha);
    gh = hggroup(hAx);
    set(hCyl,'Parent',gh)
    hCyl = gh;
end

% format ouptut
if nargout == 1
    varargout{1} = hCyl;
end

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function fcn_Plot_StationaryLeader(p_all_time, v_all_time, a_all_time, error_all, aDiff_all)
close all

global nodenum edgenum neighborMat dim simTime leaderNum kp kv
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot a subset of the data, because too much data
delta=50;
time_all=v_all_time.time(1:delta:end);
p_all=p_all_time.signals.values(1:delta:end,:);
v_all=v_all_time.signals.values(1:delta:end,:);
a_all=a_all_time.signals.values(1:delta:end,:);
error_all=error_all.signals.values(1:delta:end,:);
aDiff_all=aDiff_all.signals.values(1:delta:end,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
linewidth=0.5;
dotsize=7;
fontsize=7;%15;
formationColor=0*[0 0 1];
% edgeColorList=zeros(nodenum,3);
faceColorList=zeros(nodenum,3);
for i=1:nodenum
    if i<=leaderNum
        faceColorList(i,:)=[1,0,0];
    else
        faceColorList(i,:)=[0,0,1];
    end
end
for i=1:nodenum
    if i<=leaderNum
        markerList(i)={'o'};
    else
        markerList(i)={'o'};
    end
end
for i=1:nodenum
    if i<=leaderNum
        linestyleList(i)={'-'};
    else
        linestyleList(i)={'--'};
    end
end
%% plot trajectory
figure;
subplot(4,1,[1,2,3]); % to make the axis short
hold on; box on;
set(gca, 'fontSize', fontsize)
set(get(gca, 'xlabel'), 'String', 'x (m)', 'fontSize', fontsize);
set(get(gca, 'ylabel'), 'String', 'y (m)', 'fontSize', fontsize);
%set(get(gca, 'zlabel'), 'String', 'z (m)', 'fontSize', fontsize);
axis equal
set(gca, 'fontsize', fontsize);
%plot trajectory
for i=1:nodenum
    if dim==2
        xi_all=p_all(:,2*i-1);
        yi_all=p_all(:,2*i);
        plot(xi_all, yi_all, ':', 'linewidth', linewidth, 'color', faceColorList(i,:));
    else
        xi_all=p_all(:,3*i-2);
        yi_all=p_all(:,3*i-1);
        zi_all=p_all(:,3*i);
        plot3(xi_all, yi_all, zi_all, ':', 'linewidth', linewidth, 'color', faceColorList(i,:));
    end
end
% plot obstacle
leftx=18;
width=5;
h=rectangle('Position', [leftx, 1.8, width, 15]);
set(h, 'faceColor', 0.4*ones(1,3))
h=rectangle('Position', [leftx, -16.5, width, 14.5]);
set(h, 'faceColor', 0.4*ones(1,3))
h=rectangle('Position', [leftx, -25, width, 6.5]);
set(h, 'faceColor', 0.4*ones(1,3))
text(20.5, -9, 'Obstacle','color', 'w', 'FontSize', 8, 'horizontalAlignment', 'center', 'FontWeight', 'normal', 'Rotation', 0, 'fontname', 'Times');

axis tight
xlim=get(gca,'xlim');
set(gca,'xlim', xlim+[-5,5]);
ylim=get(gca,'ylim');
set(gca,'ylim', ylim+[-4,3]);
% title
%set(get(gca, 'title'), 'String', 'Trajectory', 'fontsize', fontsize);

%% plot intermediate formations
dataNum=size(p_all,1);
hMarkerAll=zeros(nodenum,1);
index=[1,floor(dataNum/10*1.4),floor(dataNum/10*2.2),floor(dataNum/10*3.2),floor(dataNum/10*4.47),...
    floor(dataNum/10*5.3),floor(dataNum/10*6.45),floor(dataNum/10*7.2),floor(dataNum/10*8),floor(dataNum/10*9),floor(dataNum/10*10)]; % for 2D scale big example
% index=[1,floor(dataNum/10*10)];
for k=1:size(index,2)
    idx=index(k);
    for i=1:nodenum
        for j=1:nodenum
            if neighborMat(i,j)==1
                if dim==2
                    pi=p_all(idx,2*i-1:2*i)';
                    pj=p_all(idx,2*j-1:2*j)';
                    line([pi(1),pj(1)], [pi(2),pj(2)], 'linewidth', 0.5, 'color', formationColor);
                    %fcn_plotArrow((pi+pj)/2, (pj-pi)/norm(pj-pi), initialColor, linewidth)
                else
                    pi=p_all(idx,3*i-2:3*i)';
                    pj=p_all(idx,3*j-2:3*j)';
                    line([pi(1),pj(1)], [pi(2),pj(2)], [pi(3),pj(3)], 'linewidth', 0.5, 'color', formationColor);
                    %fcn_plotArrow((pi+pj)/2, (pj-pi)/norm(pj-pi),
                    %initialColor, linewidth)
                end
            end
        end
    end
    for i=1:nodenum
        if dim==2
            xi=p_all(idx,2*i-1);
            yi=p_all(idx,2*i);
            hMarkerAll(i)=plot(xi, yi, char(markerList(i)), 'MarkerEdgeColor', 'k', 'MarkerFaceColor', faceColorList(i,:), 'markersize', dotsize, 'linewidth', 0.5);
            text(xi, yi, num2str(i),'color', 'w', 'FontSize', 5, 'horizontalAlignment', 'center', 'FontWeight', 'bold');
        else
            xi=p_all(idx,3*i-2);
            yi=p_all(idx,3*i-1);
            zi=p_all(idx,3*i);
            hMarkerAll(i)=plot3(xi, yi, zi, char(markerList(i)), 'MarkerEdgeColor', 'k', 'MarkerFaceColor', faceColorList(i,:), 'markersize', dotsize, 'linewidth', 1);
        end
    end
end
hLegendTraj=legend([hMarkerAll(1),hMarkerAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'West');
%set(hLegendTraj, 'pos', [0.14, 0.72, 0.2375, 0.1333]);
% axis tight
% margin=1;
% xlim=get(gca,'xlim');
% set(gca,'xlim', xlim+[-margin,margin]);
% ylim=get(gca,'ylim');
% set(gca,'ylim', ylim+[-margin,margin]);

% plot time for corresponding formation
text(0, 5, strcat('t=',num2str(time_all(index(1)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(10, 5, strcat('t=',num2str(time_all(index(2)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(33, 5, strcat('t=',num2str(time_all(index(4)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(45, 5, strcat('t=',num2str(time_all(index(5)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(50, -7, strcat('t=',num2str(time_all(index(6)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(50, -17, strcat('t=',num2str(time_all(index(7)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(38, -22, strcat('t=',num2str(time_all(index(8)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(28, -22, strcat('t=',num2str(time_all(index(9)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(14, -22, strcat('t=',num2str(time_all(index(10)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');
text(3, -22, strcat('t=',num2str(time_all(index(11)),'%.1f'),'s'),'color', 'k', 'FontSize', fontsize+1, 'horizontalAlignment', 'center', 'FontName', 'times');

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot error
figure
subplot(5,1,1) % to make the axis short
hold on; box on
% set the format of the axis
set(gca, 'fontSize', fontsize)
% set(get(gca, 'xlabel'), 'String', 'Time (s)', 'fontSize', fontsize);
set(get(gca, 'ylabel'), 'String', 'Tracking error', 'fontSize', fontsize);
set(gca, 'xlim', [0,simTime])
% set(gca, 'ylim', [0,10])
plot(time_all, error_all, 'color', 'm', 'linewidth', 1)
% set(get(gca, 'title'), 'String', strcat('Tracking error: kp=',num2str(kp),', kv=',num2str(kv)), 'fontsize', fontsize);

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot velocity
% figure
hLineAll=zeros(nodenum,1);
if dim==2
    % x velocity
    subplot(5,1,2)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, v_all(:,2*i-1), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'x-velocity (m/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    set(gca, 'ylim', [-3,3])
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
    % y velocity
    subplot(5,1,3)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, v_all(:,2*i), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'y-velocity (m/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    set(gca, 'ylim', [-3,3])
%     set(get(gca, 'xlabel'), 'String', 'Time (s)', 'fontSize', fontsize);
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
elseif dim==3 % plot vx and vy
    % x velocity
    subplot(3,1,1)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, v_all(:,3*i-2), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'x-velocity (m/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
    % title
    set(get(gca, 'title'), 'String', 'Velocity', 'fontsize', fontsize);
    % y velocity
    subplot(3,1,2)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, v_all(:,3*i-1), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'y-velocity (m/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(3)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
    % z velocity
    subplot(3,1,3)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, v_all(:,3*i), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'xlabel'), 'String', 'Time (sec)', 'fontSize', fontsize);
    set(get(gca, 'ylabel'), 'String', 'z-velocity (m/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(3)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
end

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot acceleration
% figure
hLineAll=zeros(nodenum,1);
if dim==2
    % x velocity
    subplot(5,1,4)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, a_all(:,2*i-1), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'x-acceleration (m^2/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
    % title
%     set(get(gca, 'title'), 'String', 'Acceleration', 'fontsize', fontsize);
    % y velocity
    subplot(5,1,5)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, a_all(:,2*i), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'y-acceleration (m^2/s)', 'fontSize', fontsize);
    set(get(gca, 'xlabel'), 'String', 'Time (s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
end

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot acceleration error
figure
hLineAll=zeros(nodenum,1);
if dim==2
    % x velocity
    subplot(5,1,1)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, aDiff_all(:,2*i-1), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'x-aDiff (m^2/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    % y velocity
    subplot(5,1,2)
    hold on; box on;
    for i=1:nodenum
        hLineAll(i)=plot(time_all, aDiff_all(:,2*i), 'color', faceColorList(i,:), 'linestyle', char(linestyleList(i)), 'linewidth', 1);
    end
    set(gca, 'fontSize', fontsize)
    set(get(gca, 'ylabel'), 'String', 'y-aDiff (m^2/s)', 'fontSize', fontsize);
    set(gca, 'xlim', [0,simTime])
    set(get(gca, 'xlabel'), 'String', 'Time (s)', 'fontSize', fontsize);
    hLegend=legend([hLineAll(1),hLineAll(leaderNum+1)], 'Leader', 'Follower', 'location', 'southwest');
    set(hLegend, 'fontsize', fontsize);
end

repo: paper-simulation


text:
% SLAVEHOOK installs a 'hook' into the slave structure which overrides
% function calls made to the named hook.
%
% slave.hook(hookName, func, userData, noDeref) inserts a hook into the
% slave structure which will be called whenever the slave receives a request
% to call the function with name hookName.  func is the function handle to
% be called and userData is an optional argument whose value is passed as
% the first argument of func, followed by the arguments from the server.
%
% This can be used to override matlab functions or other functions that
% might be called by the server and replace them with more RPC-friendly
% semantics, etc.  For instance, by default, all slaves include an 'exit'
% hook that allows the server to call the 'exit' function as usual, but
% which cleanly destroys the slave state before closing (whereas calling
% MATLAB's exit() directly would quit the slave without cleaning up).
% if
%
function hook(slave, hookName, func, userData, noDeref)

  slave.hooks.(hookName).func = func;

  if ((nargin > 3) & (~isempty(userData)))
    slave.hooks.(hookName).userData = userData;
  end

  if (nargin < 5)
    noDeref = 0;
  end
  slave.hooks.(hookName).noDereference = noDeref;

author: huashiyiqike

repo: LSTM-MATLAB


text:
function J = convBox( I, r, s, nomex )
% Extremely fast 2D image convolution with a box filter.
%
% Convolves an image by a F=ones(2*r+1,2*r+1)/(2*r+1)^2 filter. The
% convolution can be performed in constant time per-pixel, independent of
% the radius r. In fact the implementation is nearly optimal, with the
% convolution taking only slightly more time than creating a copy of the
% input array. Boundary effects are handled as if the image were padded
% symmetrically prior to performing the convolution. An optional integer
% downsampling parameter "s" can be specified, in which case the output is
% downsampled by s (the implementation is efficient with downsampling
% occurring simultaneously with smoothing, saving additional time).
%
% The output is exactly equivalent to the following Matlab operations:
%  f = ones(1,2*r+1); f=f/sum(f);
%  J = padarray(I,[r r],'symmetric','both');
%  J = convn(convn(J,f,'valid'),f','valid');
%  if(s>1), t=floor(s/2)+1; J=J(t:s:end-s+t,t:s:end-s+t,:); end
% The computation, however, is an order of magnitude faster than the above.
%
% When used as a smoothing filter, the standard deviation (sigma) of a box
% filter with radius r can be computed using [sigma=sqrt(r*(r+1)/3)]. For
% the first few values of r this translates to: r=1: sigma=sqrt(2/3), r=2:
% sigma=sqrt(2), r=3: sigma=2. Given sigma, the equivalent value of r can
% be computed via [r=sqrt(12*sigma*sigma+1)/2-.5].
%
% The related function convTri performs convolution with a triangle filter,
% which has nicer properties if used for smoothing, but is slightly slower.
%
% This code requires SSE2 to compile and run (most modern Intel and AMD
% processors support SSE2). Please see: http://en.wikipedia.org/wiki/SSE2.
%
% USAGE
%  J = convBox( I, r, [s], [nomex] )
%
% INPUTS
%  I      - [hxwxk] input k channel single image
%  r      - integer filter radius
%  s      - [1] integer downsampling amount after convolving
%  nomex  - [0] if true perform computation in matlab (for testing/timing)
%
% OUTPUTS
%  J      - [hxwxk] smoothed image
%
% EXAMPLE
%  I = single(imResample(imread('cameraman.tif'),[480 640]))/255;
%  r = 5; s = 2; % set parameters as desired
%  tic, J1=convBox(I,r,s); toc % mex version (fast)
%  tic, J2=convBox(I,r,s,1); toc % matlab version (slow)
%  figure(1); im(J1); figure(2); im(abs(J2-J1));
%
% See also conv2, convTri
%
% Piotr's Computer Vision Matlab Toolbox      Version 3.02
% Copyright 2014 Piotr Dollar & Ron Appel.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

assert( r>=0 );
if( nargin<3 ), s=1; end
if( nargin<4 ), nomex=0; end
if( isempty(I) || (r==0 && s==1) ), J = I; return; end
m=min(size(I,1),size(I,2)); if( m<4 || 2*r+1>=m ), nomex=1; end

if( nomex==0 )
  if( r==1 && s<=2 )
    J = convConst('convTri1',I,1,s);
  else
    J = convConst('convBox',I,r,s);
  end
else
  f = ones(1,2*r+1); f=f/sum(f);
  J = padarray(I,[r r],'symmetric','both');
  J = convn(convn(J,f,'valid'),f','valid');
  if(s>1), t=floor(s/2)+1; J=J(t:s:end-s+t,t:s:end-s+t,:); end
end


text:
function anal = er_chopTSeriesraw(view,coords,scans,varargin);

% anal = er_chopTSerieskgs(view,[roi],[scans],varargin);
%
% Concatenates tSeries from the selected scans together,
% chops up according to the assigned parfiles, and returns
% an analysis struct with the following fields:
%
%   allTcs:
%   meanTcs:
%   sems:
%   amps:
%   relamps:
%   hMat:
%   pMat:
%
%
% 06/17/04 ras: wrote it.
% 07/08/04 kgs modified
global dataTYPES;

if ieNotDefined('coords')
    rois = viewGet(view,'rois');
    selRoi = viewGet(view,'selectedroi');
    coords = rois(selRoi).coords;
end

dt = viewGet(view,'curdt');

if ieNotDefined('scans')
    [scans dt] = er_getScanGroup(view);
    view = viewSet(view,'curdt',dt);
end

%%%%% params/defaults %%%%%
normBsl = 1;            % flag to zero baseline or not 0 does not removed baseline
alpha = 0.05;           % threshold for significant activations
TR = dataTYPES(dt).scanParams(scans(1)).framePeriod;
bslPeriod = [-4:0 ];  % period to use as baseline in t-tests, in seconds
peakPeriod = 8:12; % 6:12      % period to look for peaks in t-tests, in seconds
timeWindow = -4:20;            % seconds relative to trial onset to take for each trial
onsetDelta = -4;               % # secs to shift onsets in parfiles, relative to time course
prestim=-4;                    % secs before stim onset for which the window is calculated

%%%%% parse the options %%%%%
for i = 1:length(varargin)
    if ischar(varargin{i})
        switch lower(varargin{i})
        case 'normbsl', normBsl = varargin{i+1};
        case 'alpha', alpha = varargin{i+1};
        case 'peakperiod', peakPeriod = varargin{i+1};
        case 'timewindow', timeWindow = varargin{i+1};
        case 'scans', scans = varargin{i+1};
        case 'dt', dt = varargin{i+1};
        case 'onsetdelta', onsetDelta = varargin{i+1};
        otherwise, % ignore
        end
    end
end

%%%%% concatenate tSeries from selected scans
allt = [];
fprintf('Loading tSeries from selected scans ... \t');
for s = scans
%   subt = meanTSeries(view,s,coords);
     subt = meanTSeriesraw(view,s,coords);

 % get raw detrended TC without % siganl

 %   another option is to use rory;s code
 %    tS = getTseriesOneROI(view,coords,s,1);
 %    get raw time series
 %    subt = mean(tS{1},2);
   allt = [allt subt'];
   fprintf('%i ',s);
end
fprintf('\n');

%%%%% get parfile info, if it's not passed in in varargin
trials = er_concatParfiles(view,scans);
trials.onsetSecs = trials.onsetSecs + onsetDelta;
trials.onsetFrames = trials.onsetFrames + onsetDelta/TR;

%%%%% get nConds from trials struct
nConds = max(trials.cond);
nTrials = length(scans); % current operating assumption

%%%%% get a set of label names, if they were specified in the parfiles
for i = 1:nConds
    ind = find(trials.cond==i);
    labels{i} = trials.label{ind(1)};
end

%%%%% convert params expressed in secs into frames
frameWindow = unique(round(timeWindow./TR));
prestim = -1 * frameWindow(1);
peakFrames = unique(round(peakPeriod./TR))
bslFrames = unique(round(bslPeriod./TR));
peakFrames = find(ismember(frameWindow,peakFrames))
bslFrames = find(ismember(frameWindow,bslFrames));

%%%%% build tc matrix of trials x time points x conditions
%%%%% take (frameWindow) secs from each trial
tc = zeros(length(scans),length(frameWindow),nConds);

for i = 1:nConds
   ind = find(trials.cond==i);
   for j = 1:length(scans)
       tstart = trials.onsetFrames(ind(j));
       tend = min([tstart+frameWindow(end),length(allt)]);
       rng = tstart:tend;

       % add prestim
       if ind(j)==1
           % for 1st trial, no baseline available -- set to 0
           tc(j,:,i) = [zeros(1,prestim) allt(rng)];
       else
           % augment the range by previous [prestim] frames
           fullrng = rng(1)-prestim:rng(end);
           tc(j,1:length(fullrng),i) = allt(fullrng);
       end

       % remove baseline estimate, if selected
       if normBsl
           % estimate DC offset by prestim baseline vals
           DC = mean(tc(j,bslFrames,i));
           tc(j,:,i) = tc(j,:,i) - DC;
       end
   end
end

%%%%% get tcs, sems for each condition
tcs = zeros(length(frameWindow),nConds);
sems = zeros(length(frameWindow),nConds);

for i = 1:nConds
    tcs(:,i) = mean(tc(:,:,i))';
    sems(:,i) = std(tc(:,:,i))' ./ sqrt(nTrials);
end

%%%%% do t-tests of post-baseline v. baseline
Hs = NaN*ones(1,nConds);

for i = 1:nConds
    bsl = tc(:,bslFrames,i);
    peak = tc(:,peakFrames,i);
    [Hs(i) ps(i)] = ttest2(bsl(:),peak(:),alpha,-1);
    amps(:,i) = (mean(peak,2) - mean(bsl,2))/100+1;
end
size(amps)
size(peakFrames)
size(peak)
size(bsl)
%%%%% compute Signal-to-Noise Ratio
allBsl = tcs(bslFrames,:,:);
allPk = tcs(peakFrames,:,:);
SNR = abs(mean(allPk(:)) - mean(allBsl(:))) / std(allBsl(:));

%%%%% compute relamps
% the resulting matrix will be of size
% nTrials x nConds (have to shuffle things around)
relamps = fmri_relamps(permute(tc,[2 3 1]));

%%%%% assign everything to the output struct
anal.meanTcs = tcs;
anal.sems = sems;
anal.Hs = Hs;
anal.ps = ps;
anal.labels = labels;
anal.timeWindow = TR .* frameWindow;
anal.peakPeriod = [min(peakPeriod):TR:max(peakPeriod)];
anal.peakFrames=peakFrames;
anal.bslPeriod = TR .* bslFrames;
anal.amps = amps;
anal.relamps = relamps;
anal.SNR = SNR;
anal.SNRdb = 20 * log10(SNR);

% assign all time courses, but
% shuffle it into column former -- it's nicer
anal.allTcs = permute(tc,[2 1 3]);

return


text:
function [G] = uGal2G(uGal)
% Convert acceleration from microgals to average acceleration due to
% Earth's gravity.
% Chad A. Greene 2012
G = uGal/(9.80665e+8);
end


text:
function varargout=enframe(varargin)
%
% For calling details please see v_enframe.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_enframe.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: enframe.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_enframe(varargin{:});
else
    v_enframe(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function K = covGaboriso(hyp, x, z, i)

% Gabor covariance function with length scale ell and period p. The
% covariance function is parameterized as:
%
% k(x,z) = h(x-z) with h(t) = exp(-t'*t/(2*ell^2))*cos(2*pi*sum(t)/p).
%
% The hyperparameters are:
%
% hyp = [ log(ell)
%         log(p)   ]
%
% Note that covSM implements a weighted sum of Gabor covariance functions, but
% using an alternative (spectral) parameterization.
%
% For more help on design of covariance functions, try "help covFunctions".
%
% Copyright (c) by Hannes Nickisch, 2014-09-26.
%
% See also COVFUNCTIONS.M, COVGABORARD.M, COVSM.M.

if nargin<2, K = '2'; return; end                          % report no of params
if nargin<3, z = []; end                                   % make sure, z exists
xeqz = isempty(z); dg = strcmp(z,'diag');                       % determine mode

[n,D] = size(x);                                                % dimensionality
ell = exp(hyp(1));                                                % length scale
p = exp(hyp(2));                                                        % period

if dg                                              % compute squared distance d2
  d2 = zeros(n,1);
else
  if xeqz                                                 % symmetric matrix Kxx
    d2 = sq_dist(x'/ell);
  else                                                   % cross covariances Kxz
    d2 = sq_dist(x'/ell,z'/ell);
  end
end

dp = zeros(size(d2));                                % init sum(t)/p computation
if ~dg
  if xeqz                                                 % symmetric matrix Kxx
    for d=1:D, dp = dp + (x(:,d)*ones(1,size(x,1))-ones(n,1)*x(:,d)')/p; end
  else                                                   % cross covariances Kxz
    for d=1:D, dp = dp + (x(:,d)*ones(1,size(z,1))-ones(n,1)*z(:,d)')/p; end
  end
end

K = exp(-d2/2);
if nargin<4                                                        % covariances
  K = cos(2*pi*dp).*K;
else                                                               % derivatives
  if i==1                                                         % length scale
    K = d2.*cos(2*pi*dp).*K;
  elseif i==2                                                           % period
    K = 2*pi*dp.*sin(2*pi*dp).*K;
  else
    error('Unknown hyperparameter')
  end
end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function y = spm_detrend(x,p)
% Polynomial detrending over columns
% FORMAT y = spm_detrend(x,p)
% x   - data matrix
% p   - order of polynomial [default: 0]
%
% y   - detrended data matrix
%__________________________________________________________________________
%
% spm_detrend removes linear and nonlinear trends from column-wise data
% matrices.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_detrend.m 7271 2018-03-04 13:11:54Z karl $

% Check for cell arrays
%-------------------------------------------------------------------------
if iscell(x)
    if nargin == 1
        p = 0;
    end
    y     = x;
    for i = 1:numel(x)
        y{i} = spm_detrend(x{i},p);
    end
    return
end

% defaults
%--------------------------------------------------------------------------
[m,n] = size(x);
if ~m || ~n
    y = [];
    return
end
if nargin == 1
    p = 0;
end

% centre columns
%--------------------------------------------------------------------------
if ~p
    y = x - ones(m,1)*mean(x);
    return
end

% polynomial adjustment
%--------------------------------------------------------------------------
G     = zeros(m,p + 1);
for i = 0:p
    d = (1:m).^i;
    G(:,i+1) = d(:);
end
y     = x - G*(pinv(full(G))*x);

author: spm