plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
uncledickHe/FastICA-1-master
|
pcamat.m
|
.m
|
FastICA-1-master/pcamat.m
| 12,075 |
utf_8
|
bcb1117d4132558d0d54d8b7b616a902
|
function [E, D] = pcamat(vectors, firstEig, lastEig, s_interactive, ...
s_verbose);
%PCAMAT - Calculates the pca for data
%
% [E, D] = pcamat(vectors, firstEig, lastEig, ...
% interactive, verbose);
%
% Calculates the PCA matrices for given data (row) vectors. Returns
% the eigenvector (E) and diagonal eigenvalue (D) matrices containing the
% selected subspaces. Dimensionality reduction is controlled with
% the parameters 'firstEig' and 'lastEig' - but it can also be done
% interactively by setting parameter 'interactive' to 'on' or 'gui'.
%
% ARGUMENTS
%
% vectors Data in row vectors.
% firstEig Index of the largest eigenvalue to keep.
% Default is 1.
% lastEig Index of the smallest eigenvalue to keep.
% Default is equal to dimension of vectors.
% interactive Specify eigenvalues to keep interactively. Note that if
% you set 'interactive' to 'on' or 'gui' then the values
% for 'firstEig' and 'lastEig' will be ignored, but they
% still have to be entered. If the value is 'gui' then the
% same graphical user interface as in FASTICAG will be
% used. Default is 'off'.
% verbose Default is 'on'.
%
%
% EXAMPLE
% [E, D] = pcamat(vectors);
%
% Note
% The eigenvalues and eigenvectors returned by PCAMAT are not sorted.
%
% This function is needed by FASTICA and FASTICAG
% For historical reasons this version does not sort the eigenvalues or
% the eigen vectors in any ways. Therefore neither does the FASTICA or
% FASTICAG. Generally it seams that the components returned from
% whitening is almost in reversed order. (That means, they usually are,
% but sometime they are not - depends on the EIG-command of matlab.)
% @(#)$Id: pcamat.m,v 1.5 2003/12/15 18:24:32 jarmo Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default values:
if nargin < 5, s_verbose = 'on'; end
if nargin < 4, s_interactive = 'off'; end
if nargin < 3, lastEig = size(vectors, 1); end
if nargin < 2, firstEig = 1; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check the optional parameters;
switch lower(s_verbose)
case 'on'
b_verbose = 1;
case 'off'
b_verbose = 0;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
end
switch lower(s_interactive)
case 'on'
b_interactive = 1;
case 'off'
b_interactive = 0;
case 'gui'
b_interactive = 2;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''interactive''\n', ...
s_interactive));
end
oldDimension = size (vectors, 1);
if ~(b_interactive)
if lastEig < 1 | lastEig > oldDimension
error(sprintf('Illegal value [ %d ] for parameter: ''lastEig''\n', lastEig));
end
if firstEig < 1 | firstEig > lastEig
error(sprintf('Illegal value [ %d ] for parameter: ''firstEig''\n', firstEig));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate PCA
% Calculate the covariance matrix.
if b_verbose, fprintf ('Calculating covariance...\n'); end
covarianceMatrix = cov(vectors', 1);
% Calculate the eigenvalues and eigenvectors of covariance
% matrix.
[E, D] = eig (covarianceMatrix);
% The rank is determined from the eigenvalues - and not directly by
% using the function rank - because function rank uses svd, which
% in some cases gives a higher dimensionality than what can be used
% with eig later on (eig then gives negative eigenvalues).
rankTolerance = 1e-7;
maxLastEig = sum (diag (D) > rankTolerance);
if maxLastEig == 0,
fprintf (['Eigenvalues of the covariance matrix are' ...
' all smaller than tolerance [ %g ].\n' ...
'Please make sure that your data matrix contains' ...
' nonzero values.\nIf the values are very small,' ...
' try rescaling the data matrix.\n'], rankTolerance);
error ('Unable to continue, aborting.');
end
% Sort the eigenvalues - decending.
eigenvalues = flipud(sort(diag(D)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - command-line
if b_interactive == 1
% Show the eigenvalues to the user
hndl_win=figure;
bar(eigenvalues);
title('Eigenvalues');
% ask the range from the user...
% ... and keep on asking until the range is valid :-)
areValuesOK=0;
while areValuesOK == 0
firstEig = input('The index of the largest eigenvalue to keep? (1) ');
lastEig = input(['The index of the smallest eigenvalue to keep? (' ...
int2str(oldDimension) ') ']);
% Check the new values...
% if they are empty then use default values
if isempty(firstEig), firstEig = 1;end
if isempty(lastEig), lastEig = oldDimension;end
% Check that the entered values are within the range
areValuesOK = 1;
if lastEig < 1 | lastEig > oldDimension
fprintf('Illegal number for the last eigenvalue.\n');
areValuesOK = 0;
end
if firstEig < 1 | firstEig > lastEig
fprintf('Illegal number for the first eigenvalue.\n');
areValuesOK = 0;
end
end
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - GUI
if b_interactive == 2
% Show the eigenvalues to the user
hndl_win = figure('Color',[0.8 0.8 0.8], ...
'PaperType','a4letter', ...
'Units', 'normalized', ...
'Name', 'FastICA: Reduce dimension', ...
'NumberTitle','off', ...
'Tag', 'f_eig');
h_frame = uicontrol('Parent', hndl_win, ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'Units', 'normalized', ...
'Position',[0.13 0.05 0.775 0.17], ...
'Style','frame', ...
'Tag','f_frame');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0949436 0.712077 0.108507], ...
'String','Give the indices of the largest and smallest eigenvalues of the covariance matrix to be included in the reduced data.', ...
'Style','text', ...
'Tag','StaticText1');
e_first = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'f=round(str2num(get(gcbo, ''String'')));' ...
'if (f < 1), f=1; end;' ...
'l=str2num(get(findobj(''Tag'',''e_last''), ''String''));' ...
'if (f > l), f=l; end;' ...
'set(gcbo, ''String'', int2str(f));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.284831 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', '1', ...
'Tag','e_first');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0678168 0.12207 0.0542535], ...
'String','Range from', ...
'Style','text', ...
'Tag','StaticText2');
e_last = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'l=round(str2num(get(gcbo, ''String'')));' ...
'lmax = get(gcbo, ''UserData'');' ...
'if (l > lmax), l=lmax; fprintf([''The selected value was too large, or the selected eigenvalues were close to zero\n'']); end;' ...
'f=str2num(get(findobj(''Tag'',''e_first''), ''String''));' ...
'if (l < f), l=f; end;' ...
'set(gcbo, ''String'', int2str(l));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.467936 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', int2str(maxLastEig), ...
'UserData', maxLastEig, ...
'Tag','e_last');
% in the first version oldDimension was used instead of
% maxLastEig, but since the program would automatically
% drop the eigenvalues afte maxLastEig...
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.427246 0.0678168 0.0406901 0.0542535], ...
'String','to', ...
'Style','text', ...
'Tag','StaticText3');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback','uiresume(gcbf)', ...
'Position',[0.630697 0.0678168 0.12207 0.0542535], ...
'String','OK', ...
'Tag','Pushbutton1');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'gui_help(''pcamat'');' ...
], ...
'Position',[0.767008 0.0678168 0.12207 0.0542535], ...
'String','Help', ...
'Tag','Pushbutton2');
h_axes = axes('Position' ,[0.13 0.3 0.775 0.6]);
set(hndl_win, 'currentaxes',h_axes);
bar(eigenvalues);
title('Eigenvalues');
uiwait(hndl_win);
firstEig = str2num(get(e_first, 'String'));
lastEig = str2num(get(e_last, 'String'));
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% See if the user has reduced the dimension enought
if lastEig > maxLastEig
lastEig = maxLastEig;
if b_verbose
fprintf('Dimension reduced to %d due to the singularity of covariance matrix\n',...
lastEig-firstEig+1);
end
else
% Reduce the dimensionality of the problem.
if b_verbose
if oldDimension == (lastEig - firstEig + 1)
fprintf ('Dimension not reduced.\n');
else
fprintf ('Reducing dimension...\n');
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the smaller eigenvalues
if lastEig < oldDimension
lowerLimitValue = (eigenvalues(lastEig) + eigenvalues(lastEig + 1)) / 2;
else
lowerLimitValue = eigenvalues(oldDimension) - 1;
end
lowerColumns = diag(D) > lowerLimitValue;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the larger eigenvalues
if firstEig > 1
higherLimitValue = (eigenvalues(firstEig - 1) + eigenvalues(firstEig)) / 2;
else
higherLimitValue = eigenvalues(1) + 1;
end
higherColumns = diag(D) < higherLimitValue;
% Combine the results from above
selectedColumns = lowerColumns & higherColumns;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% print some info for the user
if b_verbose
fprintf ('Selected [ %d ] dimensions.\n', sum (selectedColumns));
end
if sum (selectedColumns) ~= (lastEig - firstEig + 1),
error ('Selected a wrong number of dimensions.');
end
if b_verbose
fprintf ('Smallest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(lastEig));
fprintf ('Largest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(firstEig));
fprintf ('Sum of removed eigenvalues [ %g ]\n', sum(diag(D) .* ...
(~selectedColumns)));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Select the colums which correspond to the desired range
% of eigenvalues.
E = selcol(E, selectedColumns);
D = selcol(selcol(D, selectedColumns)', selectedColumns);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some more information
if b_verbose
sumAll=sum(eigenvalues);
sumUsed=sum(diag(D));
retained = (sumUsed / sumAll) * 100;
fprintf('[ %g ] %% of (non-zero) eigenvalues retained.\n', retained);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newMatrix = selcol(oldMatrix, maskVector);
% newMatrix = selcol(oldMatrix, maskVector);
%
% Selects the columns of the matrix that marked by one in the given vector.
% The maskVector is a column vector.
% 15.3.1998
if size(maskVector, 1) ~= size(oldMatrix, 2),
error ('The mask vector and matrix are of uncompatible size.');
end
numTaken = 0;
for i = 1 : size (maskVector, 1),
if maskVector(i, 1) == 1,
takingMask(1, numTaken + 1) = i;
numTaken = numTaken + 1;
end
end
newMatrix = oldMatrix(:, takingMask);
|
github
|
uncledickHe/FastICA-1-master
|
icaplot.m
|
.m
|
FastICA-1-master/icaplot.m
| 13,259 |
utf_8
|
dde3e6d852f657a3c1eaacbd03f5dcc7
|
function icaplot(mode, varargin);
%ICAPLOT - plot signals in various ways
%
% ICAPLOT is mainly for plottinf and comparing the mixed signals and
% separated ica-signals.
%
% ICAPLOT has many different modes. The first parameter of the function
% defines the mode. Other parameters and their order depends on the
% mode. The explanation for the more common parameters is in the end.
%
% Classic
% icaplot('classic', s1, n1, range, xrange, titlestr)
%
% Plots the signals in the same manner as the FASTICA and FASTICAG
% programs do. All the signals are plotted in their own axis.
%
% Complot
% icaplot('complot', s1, n1, range, xrange, titlestr)
%
% The signals are plotted on the same axis. This is good for
% visualization of the shape of the signals. The scale of the signals
% has been altered so that they all fit nicely.
%
% Histogram
% icaplot('histogram', s1, n1, range, bins, style)
%
% The histogram of the signals is plotted. The number of bins can be
% specified with 'bins'-parameter. The style for the histograms can
% be either 'bar' (default) of 'line'.
%
% Scatter
% icaplot('scatter', s1, n1, s2, n2, range, titlestr, s1label,
% s2label, markerstr)
%
% A scatterplot is plotted so that the signal 1 is the 'X'-variable
% and the signal 2 is the 'Y'-variable. The 'markerstr' can be used
% to specify the maker used in the plot. The format for 'markerstr'
% is the same as for Matlab's PLOT.
%
% Compare
% icaplot('compare', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% This for for comparing two signals. The main used in this context
% would probably be to see how well the separated ICA-signals explain
% the observed mixed signals. The s2 signals are first scaled with
% REGRESS function.
%
% Compare - Sum
% icaplot('sum', s1, n1, s2, n2, range, xrange, titlestr, s1label,
% s2label)
%
% The same as Compare, but this time the signals in s2 (specified by
% n2) are summed together.
%
% Compare - Sumerror
% icaplot('sumerror', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% The same as Compare - Sum, but also the 'error' between the signal
% 1 and the summed IC's is plotted.
%
%
% More common parameters
% The signals to be plotted are in matrices s1 and s2. The n1 and n2
% are used to tell the index of the signal or signals to be plotted
% from s1 or s2. If n1 or n2 has a value of 0, then all the signals
% from corresponding matrix will be plotted. The values for n1 and n2
% can also be vectors (like: [1 3 4]) In some casee if there are more
% than 1 signal to be plotted from s1 or s2 then the plot will
% contain as many subplots as are needed.
%
% The range of the signals to be plotted can be limited with
% 'range'-parameter. It's value is a vector ( 10000:15000 ). If range
% is 0, then the whole range will be plotted.
%
% The 'xrange' is used to specify only the labels used on the
% x-axis. The value of 'xrange' is a vector containing the x-values
% for the plots or [start end] for begin and end of the range
% ( 10000:15000 or [10 15] ). If xrange is 0, then value of range
% will be used for x-labels.
%
% You can give a title for the plot with 'titlestr'. Also the
% 's1label' and 's2label' are used to give more meaningfull label for
% the signals.
%
% Lastly, you can omit some of the arguments from the and. You will
% have to give values for the signal matrices (s1, s2) and the
% indexes (n1, n2)
% @(#)$Id: icaplot.m,v 1.2 2003/04/05 14:23:58 jarmo Exp $
switch mode
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 'dispsig' is to replace the old DISPSIG
% '' & 'classic' are just another names - '' quite short one :-)
case {'', 'classic', 'dispsig'}
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
clf;
numSignals = size(n1, 2);
for i = 1:numSignals,
subplot(numSignals, 1, i);
plot(xrange, s1(n1(i), range));
end
subplot(numSignals,1, 1);
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'complot'
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = remmean(varargin{1});
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
for i = 1:size(n1, 2)
S1(i, :) = s1(n1(i), range);
end
alpha = mean(max(S1')-min(S1'));
for i = 1:size(n1,2)
S2(i,:) = S1(i,:) - alpha*(i-1)*ones(size(S1(1,:)));
end
plot(xrange, S2');
axis([min(xrange) max(xrange) min(min(S2)) max(max(S2)) ]);
set(gca,'YTick',(-size(S1,1)+1)*alpha:alpha:0);
set(gca,'YTicklabel',fliplr(n1));
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'histogram'
% icaplot(mode, s1, n1, range, bins, style)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, style = 'bar';else style = varargin{5}; end
if length(varargin) < 4, bins = 10;else bins = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
numSignals = size(n1, 2);
rows = floor(sqrt(numSignals));
columns = ceil(sqrt(numSignals));
while (rows * columns < numSignals)
columns = columns + 1;
end
switch style
case {'', 'bar'}
for i = 1:numSignals,
subplot(rows, columns, i);
hist(s1(n1(i), range), bins);
title(int2str(n1(i)));
drawnow;
end
case 'line'
for i = 1:numSignals,
subplot(rows, columns, i);
[Y, X]=hist(s1(n1(i), range), bins);
plot(X, Y);
title(int2str(n1(i)));
drawnow;
end
otherwise
fprintf('Unknown style.\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'scatter'
% icaplot(mode, s1, n1, s2, n2, range, titlestr, xlabelstr, ylabelstr, markerstr)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, markerstr = '.';else markerstr = varargin{9}; end
if length(varargin) < 8, ylabelstr = 'Signal 2';else ylabelstr = varargin{8}; end
if length(varargin) < 7, xlabelstr = 'Signal 1';else xlabelstr = varargin{7}; end
if length(varargin) < 6, titlestr = '';else titlestr = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
n2 = varargin{4};
s2 = varargin{3};
n1 = varargin{2};
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
rows = size(n1, 2);
columns = size(n2, 2);
for r = 1:rows
for c = 1:columns
subplot(rows, columns, (r-1)*columns + c);
plot(s1(n1(r), range),s2(n2(c), range),markerstr);
if (~isempty(titlestr))
title(titlestr);
end
if (rows*columns == 1)
xlabel(xlabelstr);
ylabel(ylabelstr);
else
xlabel([xlabelstr ' (' int2str(n1(r)) ')']);
ylabel([ylabelstr ' (' int2str(n2(c)) ')']);
end
drawnow;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case {'compare', 'sum', 'sumerror'}
% icaplot(mode, s1, n1, s2, n2, range, xrange, titlestr, s1label, s2label)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, s2label = 'IC';else s2label = varargin{9}; end
if length(varargin) < 8, s1label = 'Mix';else s1label = varargin{8}; end
if length(varargin) < 7, titlestr = '';else titlestr = varargin{7}; end
if length(varargin) < 6, xrange = 0;else xrange = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
s1 = varargin{1};
n1 = varargin{2};
s2 = varargin{3};
n2 = varargin{4};
range = chkrange(range, s1);
xrange = chkxrange(xrange, range);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
numSignals = size(n1, 2);
if (numSignals > 1)
externalLegend = 1;
else
externalLegend = 0;
end
rows = floor(sqrt(numSignals+externalLegend));
columns = ceil(sqrt(numSignals+externalLegend));
while (rows * columns < (numSignals+externalLegend))
columns = columns + 1;
end
clf;
for j = 1:numSignals
subplot(rows, columns, j);
switch mode
case 'compare'
plotcompare(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendcompare(n1(j),n2,s1label,s2label,externalLegend);
case 'sum'
plotsum(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsum(n1(j),n2,s1label,s2label,externalLegend);
case 'sumerror'
plotsumerror(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsumerror(n1(j),n2,s1label,s2label,externalLegend);
end
if externalLegend
title([titlestr ' (' s1label ' ' int2str(n1(j)) ')']);
else
legend(char(legendtext));
if (~isempty(titlestr))
title(titlestr);
end
end
end
if (externalLegend)
subplot(rows, columns, numSignals+1);
legendsize = size(legendtext, 2);
hold on;
for i=1:legendsize
plot([0 1],[legendsize-i legendsize-i], char(legendstyle(i)));
text(1.5, legendsize-i, char(legendtext(i)));
end
hold off;
axis([0 6 -1 legendsize]);
axis off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotcompare(s1, n1, s2, n2, range, xrange);
style=getStyles;
K = regress(s1(n1,:)',s2');
plot(xrange, s1(n1,range), char(style(1)));
hold on
for i=1:size(n2,2)
plotstyle=char(style(i+1));
plot(xrange, K(n2(i))*s2(n2(i),range), plotstyle);
end
hold off
function [legendText, legendStyle]=legendcompare(n1, n2, s1l, s2l, externalLegend);
style=getStyles;
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendStyle(1)=style(1);
for i=1:size(n2, 2)
legendText(i+1) = {[s2l ' ' int2str(n2(i))]};
legendStyle(i+1) = style(i+1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsum(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-');
function [legendText, legendStyle]=legendsum(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendStyle={'k-';'b-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsumerror(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-', ...
xrange, s1(n1, range)-sigsum(range), 'r-');
function [legendText, legendStyle]=legendsumerror(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendText(3)={'"Error"'};
legendStyle={'k-';'b-';'r-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function style=getStyles;
color = {'k','r','g','b','m','c','y'};
line = {'-',':','-.','--'};
for i = 0:size(line,2)-1
for j = 1:size(color, 2)
style(j + i*size(color, 2)) = strcat(color(j), line(i+1));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function range=chkrange(r, s)
if r == 0
range = 1:size(s, 2);
else
range = r;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xrange=chkxrange(xr,r);
if xr == 0
xrange = r;
elseif size(xr, 2) == 2
xrange = xr(1):(xr(2)-xr(1))/(size(r,2)-1):xr(2);
elseif size(xr, 2)~=size(r, 2)
error('Xrange and range have different sizes.');
else
xrange = xr;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n=chkn(n,s)
if n == 0
n = 1:size(s, 1);
end
|
github
|
ECNURoboLab/nimbro_picking-master
|
getColorFromID.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/getColorFromID.m
| 2,097 |
utf_8
|
dcfebcc07c95fb5a9cd79bfd1f991086
|
function col=getColorFromID(id)
% get rgb [0 1] values from id
%
if id==0, col=zeros(1, 3); return; end
colors=getIDColors;
col=colors((mod(id, size(colors, 1)))+1, :);
end
function colors=getIDColors()
colors=[
128 255 255; %
255 0 0; % red 1
0 255 0; % green 2
0 0 255; % blue 3
0 255 255; % cyan 4
255 0 255; % magenta 5
212 212 0; % yellow 6
25 25 25; % black 7
34 139 34; % forestgreen 8
0 191 255; % deepskyblue 9
139 0 0 ; % darkred 10
218 112 214; % orchid 11
244 164 96; % sandybrown 12
245 245 245; % white smoke 13
139 119 101; % peach puff 4 14
105 105 105; % dim gray 15
25 25 112; % midnight blue 16
70 130 180; % steel blue 17
64 224 208; % turqoise 18
95 158 160; % cadet blue 19
106 19 205; % slate blue 20
102 205 170; % Medium Aquamarine 21
152 251 152; % Pale Green 22
240 230 140; % Khaki 23
255 215 0; % Gold 24
184 134 11; % Dark Goldenrod 25
188 143 143; % Rosy Brown 26
160 82 45; % Sienna 27
245 245 220; % Beige 28
210 180 140; % Tan 29
178 34 34; % Firebrick 30
233 150 122; % Dark Salmon 31
255 165 0; % Orange 32
255 99 71; % Tomato 33
240 128 128; % Light Coral 34
255 105 180; % Hot Pink 35
255 192 203; % Pink 36
221 160 221; % Plum 37
245 222 179; % Wheat 38
255 250 205; % Lemon Chiffon 39
160 32 240; % Purple 40
210 105 30; % Chocolate 41
127 255 0; % Chartreuse 42
153 50 204; % Dark Orchid 43
216 191 216;]; % Thistle 44
colors = colors / 255;
end
|
github
|
ECNURoboLab/nimbro_picking-master
|
pclviewer.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/external/pcd/matpcl/pclviewer.m
| 1,291 |
utf_8
|
f58f1e96b93686f38351e26b2c2db93f
|
%PCLVIEWER View a point cloud using PCL
%
% PCLVIEWER(P) writes the point cloud P (MxN) to a temporary file and invokes
% the PCL point cloud viewer for fast display and visualization. The columns of P
% represent the 3D points.
%
% If M=3 then the rows are x, y, z.
% If M=6 then the rows are x, y, z, R, G, B where R,G,B are in the range 0
% to 1.
%
% PCLVIEWER(P, ARGS) as above but the optional arguments ARGS are passed to the
% PCL viewer. For example:
%
% pclviewer( rand(3,1000), '-ps 2 -ax 1' )
%
% Notes::
% - Only the "x y z" and "x y z rgb" field formats are currently supported.
% - The file is written in ascii format.
% - When viewing colored point clouds in pcl_viewer remember to toggle to
%
% See also savepcd, lspcd, readpcd.
%
% Copyright (C) 2013, by Peter I. Corke
% TODO
% - add color
function pclviewer(points, args)
% change the next line to suit your operating system
viewer = '/usr/local/bin/pcl_viewer.app/Contents/MacOS/pcl_viewer';
pointfile = [tempname '.pcd'];
if nargin < 2
args = '';
end
savepcd(pointfile, points);
system(sprintf('head -20 %s', pointfile));
system(sprintf('%s %s %s &', ...
viewer, pointfile, args));
pause(1)
delete(pointfile);
|
github
|
ECNURoboLab/nimbro_picking-master
|
loadpcd.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/external/pcd/matpcl/loadpcd.m
| 8,507 |
utf_8
|
bc2b81bf77de6a881efb122b16176a1f
|
%LOADPCD Load a point cloud from a PCD format file
%
% P = LOADPCD(FNAME) is a set of points loaded from the PCD format
% file FNAME.
%
% For an unorganized point cloud the columns of P represent the 3D points,
% and the rows are: x, y, z, r, g, b, a depending on the FIELDS in the file.
%
% For an organized point cloud P is a 3-dimensional matrix (HxWxN) where the
% N planes are: x, y, z, r, g, b, a depending on the FIELDS in the file. This
% format is useful since the planes z, r, g, b, a can be considered as images.
%
% Notes::
% - Only the x y z field format are currently supported
% - The file can be in ascii or binary format, binary_compressed is not
% supported
%
% See also pclviewer, lspcd, loadpcd.
%
% Copyright (C) 2013, by Peter I. Corke
% TODO
% - handle binary_compressed
function points = loadpcd(fname)
verbose = true;
fp = fopen(fname, 'r');
while true
line = fgetl(fp);
if line(1) == '#'
continue;
end
[field,remain] = strtok(line, ' \t');
remain = strtrim(remain);
switch field
case 'VERSION'
continue;
case 'FIELDS'
FIELDS = remain;
case 'TYPE'
TYPE = remain;
case 'SIZE'
sizes = str2num(remain);
case 'WIDTH'
width = str2num(remain);
case 'HEIGHT'
height = str2num(remain);
case 'POINTS'
npoints = str2num(remain);
case 'COUNT'
count = str2num(remain);
case 'VIEWPOINT'
% WHAT IS THAT?
case 'DATA'
mode = remain;
break;
otherwise
warning('unknown field %s\n', field);
end
end
% parse out details of the fields
% numFields the number of fields
% sizes vector of field sizes (in bytes)
% types vector of type identifiers (I U F)
% fields vector of field names (x y z rgb rgba etc)
numFields = numel(sizes);
types = cell2mat(regexp(TYPE,'\s+','split'));
fields = regexp(FIELDS,'\s+','split');
if verbose
% the doco says height > 1 means organized, but some old files have
% height = 1 and width > 1
if height > 1 && width > 1
organized = true;
org = 'organized';
else
organized = false;
org = 'unorganized';
end
fprintf('%s: %s, %s, <%s> %dx%d\n', ...
fname, mode, org, FIELDS, width, height);
fprintf(' %s; %s\n', TYPE, num2str(sizes));
end
if any(count > 1)
error('can only handle 1 element per dimension');
end
switch mode
case 'ascii'
format = '';
for j=1:numFields
switch types(j)
case 'I', typ = 'd';
case 'U', typ = 'u';
case 'F', typ = 'f';
end
format = [format '%' typ num2str(sizes(j)*8)];
end
c = textscan(fp, format, npoints);
points = [];
for j=1:length(c)
points = [points; c{j}'];
end
if size(points,2) ~= npoints
error('incorrect number of points in file: was %d, should be %d', ...
size(points,2), npoints);
end
case 'binary'
format = '';
if true || all(types == types(1)) && all(sizes == sizes(1))
% simple case where all fields have the same length and type
% map IUF -> int, uint, float
switch types(1)
case 'I'
fmt = 'int';
case 'U'
fmt = 'uint';
case 'F'
fmt = 'float';
end
format = [format '*' fmt num2str(sizes(1)*8)];
points = fread(fp, [numFields npoints], format);
else
% more complex case where fields have different length and type
% code contributed by Will
startPos_fp = ftell(fp);
% Just initialize the xyz portion for now
points = zeros(3, npoints);
for i=1:numFields
% map each field sequentially, using fread() skip functionality,
% essentially interleaved reading of the file
% map IUF -> int, uint, float
switch types(i)
case 'I'
fmt = 'int';
case 'U'
fmt = 'uint';
case 'F'
fmt = 'float';
end
format = ['*' fmt num2str(sizes(i)*8)];
fseek(fp, startPos_fp + sum(sizes(1:i-1)), 'bof');
data = fread(fp, [1 npoints], format, sum(sizes)-sizes(i));
switch fields{i}
case 'x'
points(1,:) = data;
case 'y'
points(2,:) = data;
case 'z'
points(3,:) = data;
case {'rgb', 'rgba'}
points(4,:) = data;
end
end
end
case 'binary_compressed'
% binary part of the file contains:
% compressed size of data (uint32)
% uncompressed size of data (uint32)
% compressed data
% junk
compressed_size = fread(fp, 1, 'uint32');
uncompressed_size = fread(fp, 1, 'uint32');
compressed_data = fread(fp, compressed_size, 'uint8')';
uncompressed_data = lzfd(compressed_data);
if length(uncompressed_data) ~= uncompressed_size
error('decompression error');
end
% the data is stored unpacked, that is one field for all points,
% then the next field for all points, etc.
start = 1;
for i=1:numFields
len = sizes(i)*npoints;
switch types(1)
case 'I'
fmt = 'int32';
case 'U'
fmt = 'uint32';
case 'F'
fmt = 'single';
end
field = typecast(uncompressed_data(start:start+len-1), fmt);
start = start + len;
switch fields{i}
case 'x'
points(1,:) = field;
case 'y'
points(2,:) = field;
case 'z'
points(3,:) = field;
case {'rgb', 'rgba'}
points(4,:) = field;
end
end
otherwise
error('unknown DATA mode: %s', mode);
end
if size(points,1) > 3
% convert RGB from float to rgb
rgb = typecast(points(4,:), 'uint32');
switch FIELDS
case 'x y z rgb'
R = double(bitand(255, bitshift(rgb, 16))) /255;
G = double(bitand(255, bitshift(rgb, 8))) /255;
B = double(bitand(255, rgb)) /255;
points = [points(1:3,:); R; G; B];
case 'x y z rgba'
R = double(bitand(255, bitshift(rgb, 24))) /255;
G = double(bitand(255, bitshift(rgb, 16))) /255;
B = double(bitand(255, bitshift(rgb, 8))) /255;
A = double(bitand(255, rgb)) /255;
points = [points(1:3,:); R; G; B; A];
end
end
if organized
% data is an organized point cloud, rearrange it into planes
points = permute( reshape( shiftdim(points, 1), width, height, []), [2 1 3]);
end
fclose(fp);
|
github
|
ECNURoboLab/nimbro_picking-master
|
lzfd.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/external/pcd/matpcl/lzfd.m
| 2,169 |
utf_8
|
1280ce0a291d2c9d98b06a4673a98535
|
%LZFD LZF decompression
%
% OUT = LZFD(IN) is the decompressed version of the uint8 array IN.
%
% OUT = LZFD(IN, LEN) as above but sets the internal working buffer to length
% LEN which should exceed the expected uncompressed data size.
%
% Notes::
% - LZF is an algorithm that is efficient and gives reasonable compression ratios
% - If LEN is not specified 2*length(IN) is used. Better to overestimate to save
% MATLAB continually extending the array.
%
% Reference::
% - C source code lizf_d.c from liblzf available from http://software.schmorp.de/pkg/liblzf
%
% Author::
% - Peter Corke
% Copyright (C) 2013 Peter Corke
function out = lzfd(in, outlen)
if nargin < 2
outlen = 2 * length(in);
end
ip = 1; % input pointer, range 1 to length(in)
op = 1; % output pointer, range 1 to outlen
% preallocate decompressed data storage
out = zeros(1, outlen, 'uint8');
while (1)
ctrl = cast(in(ip), 'uint32'); ip = ip + 1;
if ctrl < 32
% literal run
ctrl = ctrl+1;
% lzf_movsb(op, ip, ctrl)
out(op:op+ctrl-1) = in(ip:ip+ctrl-1);
ip = ip + ctrl;
op = op + ctrl;
else
% back reference
len = bitshift(ctrl, -5);
ref = op - bitshift(bitand(ctrl, 31), 8) - 1;
if len == 7
len = len + cast(in(ip), 'uint32'); ip = ip + 1;
end
ref = ref - cast(in(ip), 'uint32'); ip = ip + 1;
% lzf_movsb(op, ref, len)
len = len + 2;
try
out(op:op+len-1) = out(ref:ref+len-1);
catch
% extend the buffer used for decompression
out = [out zeros(1, length(in), 'uint8')];
outlen = length(out);
out(op:op+len-1) = out(ref:ref+len-1);
end
op = op + len;
end
if ip >= length(in) % are we done yet?
break
end
end
out = out(1:op-1); % return the valid data
end
|
github
|
ECNURoboLab/nimbro_picking-master
|
lspcd.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/external/pcd/matpcl/lspcd.m
| 2,071 |
utf_8
|
e67de9778584a673b9569720ea4c72f9
|
%LSPCD List attributes of PCD format files
%
% LSPCD() list the attributes of all .PCD files in the current folder.
%
% LSPCD(FILESPEC) as above but list only files that match FILESPEC which
% might contain a directory name and/or a wildcard.
%
%
% See also pclviewer, loadpcd.
%
% Copyright (C) 2013, by Peter I. Corke
function lspcd(name)
% default to .pcd files in current dir
if nargin < 1
name = '*.pcd';
end
path = fileparts(name); % get the common path
files = dir(name); % get all the matching files
for file=files'
header(path, file.name);
end
end
function header(dir, file)
% build the full path to the file
fname = fullfile(dir, file);
fp = fopen(fname, 'r');
version = [];
while true
line = fgetl(fp);
if line(1) == '#'
continue;
end
[field,remain] = strtok(line, ' \t');
remain = strtrim(remain);
switch field
case 'VERSION'
version = remain;
case 'FIELDS'
fields = remain;
case 'TYPE'
type = remain;
case 'WIDTH'
width = str2num(remain);
case 'HEIGHT'
height = str2num(remain);
case 'POINTS'
npoints = str2num(remain);
case 'SIZE'
siz = str2num(remain);
case 'COUNT'
count = str2num(remain);
case 'DATA'
mode = remain;
break;
otherwise
fprintf('unknown field %s\n', field);
end
end
% if no version field we'll assume it's not a PCD file
if isempty(version)
return;
end
if height == 1
org = 'unorganized';
else
org = 'organized';
end
fprintf('%s: %s, %s, <%s> %dx%d\n', ...
fname, mode, org, fields, width, height);
fprintf(' %s; %s\n', type, num2str(siz));
fclose(fp);
end
|
github
|
ECNURoboLab/nimbro_picking-master
|
savepcd.m
|
.m
|
nimbro_picking-master/apc_object_perception/apc_segmentation/matlab/external/pcd/matpcl/savepcd.m
| 4,547 |
utf_8
|
b6fc9de72f9c31f773ed98eb76072db1
|
%SAVEPCD Write a point cloud to file in PCD format
%
% SAVEPCD(FNAME, P) writes the point cloud P to the file FNAME as an
% as a PCD format file.
%
% SAVEPCD(FNAME, P, 'binary') as above but save in binary format. Default
% is ascii format.
%
% If P is a 2-dimensional matrix (MxN) then the columns of P represent the
% 3D points and an unorganized point cloud is generated.
%
% If M=3 then the rows of P are x, y, z.
% If M=6 then the rows of P are x, y, z, R, G, B where R,G,B are in the
% range 0 to 1.
% If M=7 then the rows of P are x, y, z, R, G, B, A where R,G,B,A are in
% the range 0 to 1.
%
% If P is a 3-dimensional matrix (HxWxM) then an organized point cloud is
% generated.
%
% If M=3 then the planes of P are x, y, z.
% If M=6 then the planes of P are x, y, z, R, G, B where R,G,B are in the
% range 0 to 1.
% If M=7 then the planes of P are x, y, z, R, G, B, A where R,G,B,A are in
% the range 0 to 1.
%
% Notes::
% - Only the "x y z", "x y z rgb" and "x y z rgba" field formats are currently
% supported.
% - Cannot write binary_compressed format files
% See also pclviewer, lspcd, loaddpcd.
%
% Copyright (C) 2013, by Peter I. Corke
% TODO
% - option for binary write
function savepcd(fname, points, binmode)
% save points in xyz format
% TODO
% binary format, RGB
ascii = true;
if nargin < 3
ascii = true;
else
switch binmode
case 'binary'
ascii = false;
case 'ascii'
ascii = true;
otherwise
error('specify ascii or binary');
end
end
fp = fopen(fname, 'w');
% find the attributes of the point cloud
if ndims(points) == 2
% unorganized point cloud
npoints = size(points, 2);
width = npoints;
height = 1;
nfields = size(points, 1);
else
width = size(points, 2);
height = size(points, 1);
npoints = width*height;
nfields = size(points, 3);
% put the data in order with one column per point
points = permute(points, [2 1 3]);
points = reshape(points, [], size(points,3))';
end
switch nfields
case 3
fields = 'x y z';
count = '1 1 1';
typ = 'F F F';
siz = '4 4 4';
case 6
fields = 'x y z rgb';
count = '1 1 1 1';
if ascii
typ = 'F F F I';
else
typ = 'F F F F';
end
siz = '4 4 4 4';
case 7
fields = 'x y z rgba';
fields = 'x y z rgb';
count = '1 1 1 1';
if ascii
typ = 'F F F I';
else
typ = 'F F F F';
end
siz = '4 4 4 4';
end
% write the PCD file header
fprintf(fp, '# .PCD v.7 - Point Cloud Data file format\n');
fprintf(fp, 'VERSION .7\n');
fprintf(fp, 'FIELDS %s\n', fields);
fprintf(fp, 'SIZE %s\n', siz);
fprintf(fp, 'TYPE %s\n', typ);
fprintf(fp, 'COUNT %s\n', count);
fprintf(fp, 'WIDTH %d\n', width);
fprintf(fp, 'HEIGHT %d\n', height);
fprintf(fp, 'POINTS %d\n', npoints);
switch nfields
case 3
case 6
% RGB data
RGB = uint32(points(4:6,:)*255);
rgb = (RGB(1,:)*256+RGB(2,:))*256+RGB(3,:);
points = [ points(1:3,:); double(rgb)];
case 7
% RGBA data
RGBA = uint32(points(4:7,:)*255);
rgba = ((RGBA(1,:)*256+RGBA(2,:))*256+RGBA(3,:))*256+RGBA(4,:);
points = [ points(1:3,:); double(rgba)];
end
if ascii
% Write ASCII format data
fprintf(fp, 'DATA ascii\n');
if nfields == 3
% uncolored points
fprintf(fp, '%f %f %f\n', points);
else
% colored points
fprintf(fp, '%f %f %f %d\n', points);
end
else
% Write binary format data
fprintf(fp, 'DATA binary\n');
% for a full color point cloud the colors are not quite right in pclviewer,
% color as a float has only 23 bits of mantissa precision, not enough for
% RGB as 8 bits each
% write color as a float not an int
fwrite(fp, points, 'float32');
end
fclose(fp);
end
|
github
|
nevaehRen/Yeastbow_Cluster-master
|
Step3_1_Training_Process_Movie.m
|
.m
|
Yeastbow_Cluster-master/Step3_1_Training_Process_Movie.m
| 1,290 |
utf_8
|
adc1e429b4c409f3bee79aa0fd4038c1
|
function Step3_1_Training_Process_Movie()
clear;clc;
File=dir('process*.mat');
for m=1:length(File)
load([File(m).name]);
Image = reshape(Image,PatchSize,PatchSize,[]);
Prediction = double(reshape(Prediction,PatchSize,PatchSize,[]));
close all;
figure(1);set(1,'Position',[100,100,800,400],'Color','w')
for i=1:size(Prediction,3)
i
subplot(1,2,1)
imagesc(Image); axis off; colormap(gray);title('Input','fontsize',20,'Fontname','Comic sans ms')
subplot(1,2,2)
imagesc(Prediction(:,:,i)'); axis off; colormap(gray);title('Output','fontsize',20,'Fontname','Comic sans ms')
text(59,243,strcat('Epochs:', num2str(i),' (x100) steps '),'fontsize',15,'Fontname','Comic sans ms','color','w')
figure(1)
Gif([File(m).name(1:end-4),'.gif'],i)
end
M=getframe(gcf);
% M.cdata=imresize(M.cdata(:,:,:),[400,400]);
nn=frame2im(M);
[nn,cm]=rgb2ind(nn,256);
imwrite(nn,cm,[File(m).name(1:end-4),'.gif'],'gif','WriteMode','append','DelayTime',10)
close all;
end
end
function Gif(Name,i)
M=getframe(gcf);
% M.cdata=imresize(M.cdata(:,:,:),[400,400]);
nn=frame2im(M);
[nn,cm]=rgb2ind(nn,256);
if i==1
imwrite(nn,cm,Name,'gif','LoopCount',inf,'DelayTime',0.002);
else
imwrite(nn,cm,Name,'gif','WriteMode','append','DelayTime',0.002)
end
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyTJM.m
|
.m
|
AmazingTransferLearning-master/code/MyTJM.m
| 3,517 |
utf_8
|
ce3d34bcb6ed86fc570f1f4f818ff2aa
|
function [acc,acc_list,A] = MyTJM(X_src,Y_src,X_tar,Y_tar,options)
% Inputs:
%%% X_src :source feature matrix, ns * m
%%% Y_src :source label vector, ns * 1
%%% X_tar :target feature matrix, nt * m
%%% Y_tar :target label vector, nt * 1
%%% options:option struct
% Outputs:
%%% acc :final accuracy using knn, float
%%% acc_list:list of all accuracies during iterations
%%% A :final adaptation matrix, (ns + nt) * (ns + nt)
%% Set options
lambda = options.lambda; %% lambda for the regularization
dim = options.dim; %% dim is the dimension after adaptation, dim <= m
kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf
gamma = options.gamma; %% gamma is the bandwidth of rbf kernel
T = options.T; %% iteration number
fprintf('TJM: dim=%d lambda=%f\n',dim,lambda);
% Set predefined variables
X = [X_src',X_tar'];
X = X*diag(sparse(1./sqrt(sum(X.^2))));
ns = size(X_src,1);
nt = size(X_tar,1);
n = ns+nt;
% Construct kernel matrix
K = kernel_tjm(kernel_type,X,[],gamma);
% Construct centering matrix
H = eye(n)-1/(n)*ones(n,n);
% Construct MMD matrix
e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)];
C = length(unique(Y_src));
M = e*e' * C;
Cls = [];
% Transfer Joint Matching: JTM
G = speye(n);
acc_list = [];
for t = 1:T
%%% Mc [If want to add conditional distribution]
N = 0;
if ~isempty(Cls) && length(Cls)==nt
for c = reshape(unique(Y_src),1,C)
e = zeros(n,1);
e(Y_src==c) = 1 / length(find(Y_src==c));
e(ns+find(Cls==c)) = -1 / length(find(Cls==c));
e(isinf(e)) = 0;
N = N + e*e';
end
end
M = (1 - mu) * M + mu * N;
M = M/norm(M,'fro');
[A,~] = eigs(K*M*K'+lambda*G,K*H*K',dim,'SM');
% [A,~] = eigs(X*M*X'+lambda*G,X*H*X',k,'SM');
G(1:ns,1:ns) = diag(sparse(1./(sqrt(sum(A(1:ns,:).^2,2)+eps))));
Z = A'*K;
Z = Z*diag(sparse(1./sqrt(sum(Z.^2))));
Zs = Z(:,1:ns)';
Zt = Z(:,ns+1:n)';
knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1);
Cls = knn_model.predict(Zt);
acc = sum(Cls==Y_tar)/nt;
acc_list = [acc_list;acc(1)];
fprintf('[%d] acc=%f\n',t,full(acc(1)));
end
fprintf('Algorithm JTM terminated!!!\n\n');
end
% With Fast Computation of the RBF kernel matrix
% To speed up the computation, we exploit a decomposition of the Euclidean distance (norm)
%
% Inputs:
% ker: 'linear','rbf','sam'
% X: data matrix (features * samples)
% gamma: bandwidth of the RBF/SAM kernel
% Output:
% K: kernel matrix
function K = kernel_tjm(ker,X,X2,gamma)
switch ker
case 'linear'
if isempty(X2)
K = X'*X;
else
K = X'*X2;
end
case 'rbf'
n1sq = sum(X.^2,1);
n1 = size(X,2);
if isempty(X2)
D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X;
else
n2sq = sum(X2.^2,1);
n2 = size(X2,2);
D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2;
end
K = exp(-gamma*D);
case 'sam'
if isempty(X2)
D = X'*X;
else
D = X'*X2;
end
K = exp(-gamma*acos(D).^2);
otherwise
error(['Unsupported kernel ' ker])
end
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyJGSA.m
|
.m
|
AmazingTransferLearning-master/code/MyJGSA.m
| 6,642 |
utf_8
|
09a8f009556a3e0b09d10483558976ec
|
function [acc,acc_list,A,B] = MyJGSA(X_src,Y_src,X_tar,Y_tar,options)
%% Joint Geometrical and Statistic Adaptation
% Inputs:
%%% X_src :source feature matrix, ns * m
%%% Y_src :source label vector, ns * 1
%%% X_tar :target feature matrix, nt * m
%%% Y_tar :target label vector, nt * 1
%%% options:option struct
% Outputs:
%%% acc :final accuracy using knn, float
%%% acc_list:list of all accuracies during iterations
%%% A :final adaptation matrix for source domain, m * dim
%%% B :final adaptation matrix for target domain, m * dim
alpha = options.alpha;
mu = options.mu;
beta = options.beta;
gamma = options.gamma;
kernel_type = options.kernel_type;
dim = options.dim;
T = options.T;
X_src = X_src';
X_tar = X_tar';
m = size(X_src,1);
ns = size(X_src,2);
nt = size(X_tar,2);
class_set = unique(Y_src);
C = length(class_set);
acc_list = [];
Y_tar_pseudo = [];
if strcmp(kernel_type,'primal')
[Sw, Sb] = scatter_matrix(X_src',Y_src);
P = zeros(2 * m,2 * m);
P(1:m,1:m) = Sb;
Q = Sw;
for t = 1 : T
[Ms,Mt,Mst,Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C);
Ts = X_src * Ms * X_src';
Tt = X_tar * Mt * X_tar';
Tst = X_src * Mst * X_tar';
Tts = X_tar * Mts * X_src';
Ht = eye(nt) - 1 / nt * ones(nt,nt);
X = [zeros(m,ns),zeros(m,nt);zeros(m,ns),X_tar];
H = [zeros(ns,ns),zeros(ns,nt);zeros(nt,ns),Ht];
Smax = mu * X * H * X' + beta * P;
Smin = [Ts+alpha*eye(m)+beta*Q, Tst-alpha*eye(m) ; ...
Tts-alpha*eye(m), Tt+(alpha+mu)*eye(m)];
mm = 1e-9*eye(2*m);
[W,~] = eigs(Smax,Smin + mm,dim,'LM');
As = W(1:m,:);
At = W(m+1:end,:);
Zs = (As' * X_src)';
Zt = (At' * X_tar)';
if T > 1
knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1);
Y_tar_pseudo = knn_model.predict(Zt);
acc = length(find(Y_tar_pseudo == Y_tar)) / length(Y_tar);
fprintf('acc of iter %d: %0.4f\n',t, acc);
acc_list = [acc_list;acc];
end
end
else
Xst = [X_src,X_tar];
nst = size(Xst,2);
[Ks, Kt, Kst] = constructKernel(X_src,X_tar,kernel_type,gamma);
[Sw, Sb] = scatter_matrix(Ks,Y_src);
P = zeros(2 * nst,2 * nst);
P(1:nst,1:nst) = Sb;
Q = Sw;
for t = 1:T
% Construct MMD matrix
[Ms, Mt, Mst, Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C);
Ts = Ks'*Ms*Ks;
Tt = Kt'*Mt*Kt;
Tst = Ks'*Mst*Kt;
Tts = Kt'*Mts*Ks;
K = [zeros(ns,nst), zeros(ns,nst); zeros(nt,nst), Kt];
Smax = mu*K'*K+beta*P;
Smin = [Ts+alpha*Kst+beta*Q, Tst-alpha*Kst;...
Tts-alpha*Kst, Tt+mu*Kst+alpha*Kst];
[W,~] = eigs(Smax, Smin+1e-9*eye(2*nst), dim, 'LM');
W = real(W);
As = W(1:nst, :);
At = W(nst+1:end, :);
Zs = (As'*Ks')';
Zt = (At'*Kt')';
if T > 1
knn_model = fitcknn(Zs,Y_src,'NumNeighbors',1);
Y_tar_pseudo = knn_model.predict(Zt);
acc = length(find(Y_tar_pseudo == Y_tar)) / length(Y_tar);
fprintf('acc of iter %d: %0.4f\n',t, full(acc));
acc_list = [acc_list;acc];
end
end
end
A = As;
B = At;
end
function [Sw,Sb] = scatter_matrix(X,Y)
%% Within and between class Scatter matrix
%% Inputs:
%%% X: data matrix, length * dim
%%% Y: label vector, length * 1
% Outputs:
%%% Sw: With-in class matrix, dim * dim
%%% Sb: Between class matrix, dim * dim
X = X';
dim = size(X,1);
class_set = unique(Y);
C = length(class_set);
mean_total = mean(X,2);
Sw = zeros(dim,dim);
Sb = zeros(dim,dim);
for i = 1 : C
Xi = X(:,Y == class_set(i));
mean_class_i = mean(Xi,2);
Hi = eye(size(Xi,2)) - 1/(size(Xi,2)) * ones(size(Xi,2),size(Xi,2));
Sw = Sw + Xi * Hi * Xi';
Sb = Sb + size(Xi,2) * (mean_class_i - mean_total) * (mean_class_i - mean_total)';
end
end
function [Ms,Mt,Mst,Mts] = construct_mmd(ns,nt,Y_src,Y_tar_pseudo,C)
es = 1 / ns * ones(ns,1);
et = -1 / nt * ones(nt,1);
e = [es;et];
M = e * e' * C;
Ms = es * es' * C;
Mt = et * et' * C;
Mst = es * et' * C;
Mts = et * es' * C;
if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo) == nt
for c = reshape(unique(Y_src),1,C)
es = zeros(ns,1);
et = zeros(nt,1);
es(Y_src == c) = 1 / length(find(Y_src == c));
et(Y_tar_pseudo == c) = -1 / length(find(Y_tar_pseudo == c));
es(isinf(es)) = 0;
et(isinf(et)) = 0;
Ms = Ms + es * es';
Mt = Mt + et * et';
Mst = Mst + es * et';
Mts = Mts + et * es';
end
end
Ms = Ms / norm(M,'fro');
Mt = Mt / norm(M,'fro');
Mst = Mst / norm(M,'fro');
Mts = Mts / norm(M,'fro');
end
function [Ks, Kt, Kst] = constructKernel(Xs,Xt,ker,gamma)
Xst = [Xs, Xt];
ns = size(Xs,2);
nt = size(Xt,2);
nst = size(Xst,2);
Kst0 = km_kernel(Xst',Xst',ker,gamma);
Ks0 = km_kernel(Xs',Xst',ker,gamma);
Kt0 = km_kernel(Xt',Xst',ker,gamma);
oneNst = ones(nst,nst)/nst;
oneN=ones(ns,nst)/nst;
oneMtrN=ones(nt,nst)/nst;
Ks=Ks0-oneN*Kst0-Ks0*oneNst+oneN*Kst0*oneNst;
Kt=Kt0-oneMtrN*Kst0-Kt0*oneNst+oneMtrN*Kst0*oneNst;
Kst=Kst0-oneNst*Kst0-Kst0*oneNst+oneNst*Kst0*oneNst;
end
function K = km_kernel(X1,X2,ktype,kpar)
% KM_KERNEL calculates the kernel matrix between two data sets.
% Input: - X1, X2: data matrices in row format (data as rows)
% - ktype: string representing kernel type
% - kpar: vector containing the kernel parameters
% Output: - K: kernel matrix
% USAGE: K = km_kernel(X1,X2,ktype,kpar)
%
% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2012.
%
% This file is part of the Kernel Methods Toolbox for MATLAB.
% https://github.com/steven2358/kmbox
switch ktype
case 'gauss' % Gaussian kernel
sgm = kpar; % kernel width
dim1 = size(X1,1);
dim2 = size(X2,1);
norms1 = sum(X1.^2,2);
norms2 = sum(X2.^2,2);
mat1 = repmat(norms1,1,dim2);
mat2 = repmat(norms2',dim1,1);
distmat = mat1 + mat2 - 2*X1*X2'; % full distance matrix
sgm = sgm / mean(mean(distmat)); % added by jing 24/09/2016, median-distance
K = exp(-distmat/(2*sgm^2));
case 'gauss-diag' % only diagonal of Gaussian kernel
sgm = kpar; % kernel width
K = exp(-sum((X1-X2).^2,2)/(2*sgm^2));
case 'poly' % polynomial kernel
% p = kpar(1); % polynome order
% c = kpar(2); % additive constant
p = kpar; % jing
c = 1; % jing
K = (X1*X2' + c).^p;
case 'linear' % linear kernel
K = X1*X2';
otherwise % default case
error ('unknown kernel type')
end
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyJDA.m
|
.m
|
AmazingTransferLearning-master/code/MyJDA.m
| 4,118 |
utf_8
|
54f4173e19b0dbf7b2572a964a6a3277
|
function [acc,acc_ite,A] = MyJDA(X_src,Y_src,X_tar,Y_tar,options)
% Inputs:
%%% X_src :source feature matrix, ns * m
%%% Y_src :source label vector, ns * 1
%%% X_tar :target feature matrix, nt * m
%%% Y_tar :target label vector, nt * 1
%%% options:option struct
% Outputs:
%%% acc :final accuracy using knn, float
%%% acc_ite:list of all accuracies during iterations
%%% A :final adaptation matrix, (ns + nt) * (ns + nt)
%% Set options
lambda = options.lambda; %% lambda for the regularization
dim = options.dim; %% dim is the dimension after adaptation, dim <= m
kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf
gamma = options.gamma; %% gamma is the bandwidth of rbf kernel
T = options.T; %% iteration number
acc_ite = [];
Y_tar_pseudo = [];
%% Iteration
for i = 1 : T
[Z,A] = JDA_core(X_src,Y_src,X_tar,Y_tar_pseudo,options);
%normalization for better classification performance
Z = Z*diag(sparse(1./sqrt(sum(Z.^2))));
Zs = Z(:,1:size(X_src,1));
Zt = Z(:,size(X_src,1)+1:end);
knn_model = fitcknn(Zs',Y_src,'NumNeighbors',1);
Y_tar_pseudo = knn_model.predict(Zt');
acc = length(find(Y_tar_pseudo==Y_tar))/length(Y_tar);
fprintf('JDA+NN=%0.4f\n',acc);
acc_ite = [acc_ite;acc];
end
end
function [Z,A] = JDA_core(X_src,Y_src,X_tar,Y_tar_pseudo,options)
%% Set options
lambda = options.lambda; %% lambda for the regularization
dim = options.dim; %% dim is the dimension after adaptation, dim <= m
kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf
gamma = options.gamma; %% gamma is the bandwidth of rbf kernel
%% Construct MMD matrix
X = [X_src',X_tar'];
X = X*diag(sparse(1./sqrt(sum(X.^2))));
[m,n] = size(X);
ns = size(X_src,1);
nt = size(X_tar,1);
e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)];
C = length(unique(Y_src));
%%% M0
M = e * e' * C; %multiply C for better normalization
%%% Mc
N = 0;
if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo)==nt
for c = reshape(unique(Y_src),1,C)
e = zeros(n,1);
e(Y_src==c) = 1 / length(find(Y_src==c));
e(ns+find(Y_tar_pseudo==c)) = -1 / length(find(Y_tar_pseudo==c));
e(isinf(e)) = 0;
N = N + e*e';
end
end
M = M + N;
M = M / norm(M,'fro');
%% Centering matrix H
H = eye(n) - 1/n * ones(n,n);
%% Calculation
if strcmp(kernel_type,'primal')
[A,~] = eigs(X*M*X'+lambda*eye(m),X*H*X',dim,'SM');
Z = A'*X;
else
K = kernel_jda(kernel_type,X,[],gamma);
[A,~] = eigs(K*M*K'+lambda*eye(n),K*H*K',dim,'SM');
Z = A'*K;
end
end
% With Fast Computation of the RBF kernel matrix
% To speed up the computation, we exploit a decomposition of the Euclidean distance (norm)
%
% Inputs:
% ker: 'linear','rbf','sam'
% X: data matrix (features * samples)
% gamma: bandwidth of the RBF/SAM kernel
% Output:
% K: kernel matrix
%
% Gustavo Camps-Valls
% 2006(c)
% Jordi ([email protected]), 2007
% 2007-11: if/then -> switch, and fixed RBF kernel
% Modified by Mingsheng Long
% 2013(c)
% Mingsheng Long ([email protected]), 2013
function K = kernel_jda(ker,X,X2,gamma)
switch ker
case 'linear'
if isempty(X2)
K = X'*X;
else
K = X'*X2;
end
case 'rbf'
n1sq = sum(X.^2,1);
n1 = size(X,2);
if isempty(X2)
D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X;
else
n2sq = sum(X2.^2,1);
n2 = size(X2,2);
D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2;
end
K = exp(-gamma*D);
case 'sam'
if isempty(X2)
D = X'*X;
else
D = X'*X2;
end
K = exp(-gamma*acos(D).^2);
otherwise
error(['Unsupported kernel ' ker])
end
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyGFK.m
|
.m
|
AmazingTransferLearning-master/code/MyGFK.m
| 2,152 |
utf_8
|
a01af2b801cc7b96695684ce8e803547
|
function [acc,G] = MyGFK(X_src,Y_src,X_tar,Y_tar,dim)
% Inputs:
%%% X_src :source feature matrix, ns * m
%%% Y_src :source label vector, ns * 1
%%% X_tar :target feature matrix, nt * m
%%% Y_tar :target label vector, nt * 1
% Outputs:
%%% acc :accuracy after GFK and 1NN
%%% G :geodesic flow kernel matrix
Ps = pca(X_src);
Pt = pca(X_tar);
G = GFK_core([Ps,null(Ps')], Pt(:,1:dim));
[~, acc] = my_kernel_knn(G, X_src, Y_src, X_tar, Y_tar);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [prediction,accuracy] = my_kernel_knn(M, Xr, Yr, Xt, Yt)
dist = repmat(diag(Xr*M*Xr'),1,length(Yt)) ...
+ repmat(diag(Xt*M*Xt')',length(Yr),1)...
- 2*Xr*M*Xt';
[~, minIDX] = min(dist);
prediction = Yr(minIDX);
accuracy = sum( prediction==Yt ) / length(Yt);
end
function G = GFK_core(Q,Pt)
% Input: Q = [Ps, null(Ps')], where Ps is the source subspace, column-wise orthonormal
% Pt: target subsapce, column-wise orthonormal, D-by-d, d < 0.5*D
% Output: G = \int_{0}^1 \Phi(t)\Phi(t)' dt
% ref: Geodesic Flow Kernel for Unsupervised Domain Adaptation.
% B. Gong, Y. Shi, F. Sha, and K. Grauman.
% Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), Providence, RI, June 2012.
% Contact: Boqing Gong ([email protected])
N = size(Q,2); %
dim = size(Pt,2);
% compute the principal angles
QPt = Q' * Pt;
[V1,V2,V,Gam,Sig] = gsvd(QPt(1:dim,:), QPt(dim+1:end,:));
V2 = -V2;
theta = real(acos(diag(Gam))); % theta is real in theory. Imaginary part is due to the computation issue.
% compute the geodesic flow kernel
eps = 1e-20;
B1 = 0.5.*diag(1+sin(2*theta)./2./max(theta,eps));
B2 = 0.5.*diag((-1+cos(2*theta))./2./max(theta,eps));
B3 = B2;
B4 = 0.5.*diag(1-sin(2*theta)./2./max(theta,eps));
G = Q * [V1, zeros(dim,N-dim); zeros(N-dim,dim), V2] ...
* [B1,B2,zeros(dim,N-2*dim);B3,B4,zeros(dim,N-2*dim);zeros(N-2*dim,N)]...
* [V1, zeros(dim,N-dim); zeros(N-dim,dim), V2]' * Q';
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyTCA.m
|
.m
|
AmazingTransferLearning-master/code/MyTCA.m
| 2,818 |
utf_8
|
7aee1d32ebfb97f5974be024ce450ce1
|
function [X_src_new,X_tar_new,A] = MyTCA(X_src,X_tar,options)
% Inputs: [dim is the dimension of features]
%%% X_src:source feature matrix, ns * dim
%%% X_tar:target feature matrix, nt * dim
%%% options:option struct
% Outputs:
%%% X_src_new:transformed source feature matrix, ns * dim_new
%%% X_tar_new:transformed target feature matrix, nt * dim_new
%%% A: adaptation matrix, (ns + nt) * (ns + nt)
%% Set options
lambda = options.lambda; %% lambda for the regularization
dim = options.dim; %% dim is the dimension after adaptation
kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf
gamma = options.gamma; %% gamma is the bandwidth of rbf kernel
%% Calculate
X = [X_src',X_tar'];
X = X*diag(sparse(1./sqrt(sum(X.^2))));
[m,n] = size(X);
ns = size(X_src,1);
nt = size(X_tar,1);
e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)];
M = e * e';
M = M / norm(M,'fro');
H = eye(n)-1/(n)*ones(n,n);
if strcmp(kernel_type,'primal')
[A,~] = eigs(X*M*X'+lambda*eye(m),X*H*X',dim,'SM');
Z = A' * X;
Z = Z * diag(sparse(1./sqrt(sum(Z.^2))));
X_src_new = Z(:,1:ns)';
X_tar_new = Z(:,ns+1:end)';
else
K = TCA_kernel(kernel_type,X,[],gamma);
[A,~] = eigs(K*M*K'+lambda*eye(n),K*H*K',dim,'SM');
Z = A' * K;
Z = Z*diag(sparse(1./sqrt(sum(Z.^2))));
X_src_new = Z(:,1:ns)';
X_tar_new = Z(:,ns+1:end)';
end
end
% With Fast Computation of the RBF kernel matrix
% To speed up the computation, we exploit a decomposition of the Euclidean distance (norm)
%
% Inputs:
% ker: 'linear','rbf','sam'
% X: data matrix (features * samples)
% gamma: bandwidth of the RBF/SAM kernel
% Output:
% K: kernel matrix
%
% Gustavo Camps-Valls
% 2006(c)
% Jordi ([email protected]), 2007
% 2007-11: if/then -> switch, and fixed RBF kernel
% Modified by Mingsheng Long
% 2013(c)
% Mingsheng Long ([email protected]), 2013
function K = TCA_kernel(ker,X,X2,gamma)
switch ker
case 'linear'
if isempty(X2)
K = X'*X;
else
K = X'*X2;
end
case 'rbf'
n1sq = sum(X.^2,1);
n1 = size(X,2);
if isempty(X2)
D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X;
else
n2sq = sum(X2.^2,1);
n2 = size(X2,2);
D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq -2*X'*X2;
end
K = exp(-gamma*D);
case 'sam'
if isempty(X2)
D = X'*X;
else
D = X'*X2;
end
K = exp(-gamma*acos(D).^2);
otherwise
error(['Unsupported kernel ' ker])
end
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
lapgraph.m
|
.m
|
AmazingTransferLearning-master/code/MyARTL/lapgraph.m
| 20,244 |
utf_8
|
cfed436191fe6a863089f6da80644260
|
function [W, elapse] = lapgraph(fea,options)
% Usage:
% W = graph(fea,options)
%
% fea: Rows of vectors of data points. Each row is x_i
% options: Struct value in Matlab. The fields in options that can be set:
% Metric - Choices are:
% 'Euclidean' - Will use the Euclidean distance of two data
% points to evaluate the "closeness" between
% them. [Default One]
% 'Cosine' - Will use the cosine value of two vectors
% to evaluate the "closeness" between them.
% A popular similarity measure used in
% Information Retrieval.
%
% NeighborMode - Indicates how to construct the graph. Choices
% are: [Default 'KNN']
% 'KNN' - k = 0
% Complete graph
% k > 0
% Put an edge between two nodes if and
% only if they are among the k nearst
% neighbors of each other. You are
% required to provide the parameter k in
% the options. Default k=5.
% 'Supervised' - k = 0
% Put an edge between two nodes if and
% only if they belong to same class.
% k > 0
% Put an edge between two nodes if
% they belong to same class and they
% are among the k nearst neighbors of
% each other.
% Default: k=0
% You are required to provide the label
% information gnd in the options.
%
% WeightMode - Indicates how to assign weights for each edge
% in the graph. Choices are:
% 'Binary' - 0-1 weighting. Every edge receiveds weight
% of 1. [Default One]
% 'HeatKernel' - If nodes i and j are connected, put weight
% W_ij = exp(-norm(x_i - x_j)/2t^2). This
% weight mode can only be used under
% 'Euclidean' metric and you are required to
% provide the parameter t.
% 'Cosine' - If nodes i and j are connected, put weight
% cosine(x_i,x_j). Can only be used under
% 'Cosine' metric.
%
% k - The parameter needed under 'KNN' NeighborMode.
% Default will be 5.
% gnd - The parameter needed under 'Supervised'
% NeighborMode. Colunm vector of the label
% information for each data point.
% bLDA - 0 or 1. Only effective under 'Supervised'
% NeighborMode. If 1, the graph will be constructed
% to make LPP exactly same as LDA. Default will be
% 0.
% t - The parameter needed under 'HeatKernel'
% WeightMode. Default will be 1
% bNormalized - 0 or 1. Only effective under 'Cosine' metric.
% Indicates whether the fea are already be
% normalized to 1. Default will be 0
% bSelfConnected - 0 or 1. Indicates whether W(i,i) == 1. Default 1
% if 'Supervised' NeighborMode & bLDA == 1,
% bSelfConnected will always be 1. Default 1.
%
%
% Examples:
%
% fea = rand(50,15);
% options = [];
% options.Metric = 'Euclidean';
% options.NeighborMode = 'KNN';
% options.k = 5;
% options.WeightMode = 'HeatKernel';
% options.t = 1;
% W = constructW(fea,options);
%
%
% fea = rand(50,15);
% gnd = [ones(10,1);ones(15,1)*2;ones(10,1)*3;ones(15,1)*4];
% options = [];
% options.Metric = 'Euclidean';
% options.NeighborMode = 'Supervised';
% options.gnd = gnd;
% options.WeightMode = 'HeatKernel';
% options.t = 1;
% W = constructW(fea,options);
%
%
% fea = rand(50,15);
% gnd = [ones(10,1);ones(15,1)*2;ones(10,1)*3;ones(15,1)*4];
% options = [];
% options.Metric = 'Euclidean';
% options.NeighborMode = 'Supervised';
% options.gnd = gnd;
% options.bLDA = 1;
% W = constructW(fea,options);
%
%
% For more details about the different ways to construct the W, please
% refer:
% Deng Cai, Xiaofei He and Jiawei Han, "Document Clustering Using
% Locality Preserving Indexing" IEEE TKDE, Dec. 2005.
%
%
% Written by Deng Cai (dengcai2 AT cs.uiuc.edu), April/2004, Feb/2006,
% May/2007
%
if (~exist('options','var'))
options = [];
else
if ~isstruct(options)
error('parameter error!');
end
end
%=================================================
if ~isfield(options,'Metric')
options.Metric = 'Cosine';
end
switch lower(options.Metric)
case {lower('Euclidean')}
case {lower('Cosine')}
if ~isfield(options,'bNormalized')
options.bNormalized = 0;
end
otherwise
error('Metric does not exist!');
end
%=================================================
if ~isfield(options,'NeighborMode')
options.NeighborMode = 'KNN';
end
switch lower(options.NeighborMode)
case {lower('KNN')} %For simplicity, we include the data point itself in the kNN
if ~isfield(options,'k')
options.k = 5;
end
case {lower('Supervised')}
if ~isfield(options,'bLDA')
options.bLDA = 0;
end
if options.bLDA
options.bSelfConnected = 1;
end
if ~isfield(options,'k')
options.k = 0;
end
if ~isfield(options,'gnd')
error('Label(gnd) should be provided under ''Supervised'' NeighborMode!');
end
if ~isempty(fea) && length(options.gnd) ~= size(fea,1)
error('gnd doesn''t match with fea!');
end
otherwise
error('NeighborMode does not exist!');
end
%=================================================
if ~isfield(options,'WeightMode')
options.WeightMode = 'Binary';
end
bBinary = 0;
switch lower(options.WeightMode)
case {lower('Binary')}
bBinary = 1;
case {lower('HeatKernel')}
if ~strcmpi(options.Metric,'Euclidean')
warning('''HeatKernel'' WeightMode should be used under ''Euclidean'' Metric!');
options.Metric = 'Euclidean';
end
if ~isfield(options,'t')
options.t = 1;
end
case {lower('Cosine')}
if ~strcmpi(options.Metric,'Cosine')
warning('''Cosine'' WeightMode should be used under ''Cosine'' Metric!');
options.Metric = 'Cosine';
end
if ~isfield(options,'bNormalized')
options.bNormalized = 0;
end
otherwise
error('WeightMode does not exist!');
end
%=================================================
if ~isfield(options,'bSelfConnected')
options.bSelfConnected = 1;
end
%=================================================
tmp_T = cputime;
if isfield(options,'gnd')
nSmp = length(options.gnd);
else
nSmp = size(fea,1);
end
maxM = 62500000; %500M
BlockSize = floor(maxM/(nSmp*3));
if strcmpi(options.NeighborMode,'Supervised')
Label = unique(options.gnd);
nLabel = length(Label);
if options.bLDA
G = zeros(nSmp,nSmp);
for idx=1:nLabel
classIdx = options.gnd==Label(idx);
G(classIdx,classIdx) = 1/sum(classIdx);
end
W = sparse(G);
elapse = cputime - tmp_T;
return;
end
switch lower(options.WeightMode)
case {lower('Binary')}
if options.k > 0
G = zeros(nSmp*(options.k+1),3);
idNow = 0;
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
D = EuDist2(fea(classIdx,:),[],0);
[dump idx] = sort(D,2); % sort each row
clear D dump;
idx = idx(:,1:options.k+1);
nSmpClass = length(classIdx)*(options.k+1);
G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]);
G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:));
G(idNow+1:nSmpClass+idNow,3) = 1;
idNow = idNow+nSmpClass;
clear idx
end
G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp);
G = max(G,G');
else
G = zeros(nSmp,nSmp);
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
G(classIdx,classIdx) = 1;
end
end
if ~options.bSelfConnected
for i=1:size(G,1)
G(i,i) = 0;
end
end
W = sparse(G);
case {lower('HeatKernel')}
if options.k > 0
G = zeros(nSmp*(options.k+1),3);
idNow = 0;
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
D = EuDist2(fea(classIdx,:),[],0);
[dump idx] = sort(D,2); % sort each row
clear D;
idx = idx(:,1:options.k+1);
dump = dump(:,1:options.k+1);
dump = exp(-dump/(2*options.t^2));
nSmpClass = length(classIdx)*(options.k+1);
G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]);
G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:));
G(idNow+1:nSmpClass+idNow,3) = dump(:);
idNow = idNow+nSmpClass;
clear dump idx
end
G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp);
else
G = zeros(nSmp,nSmp);
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
D = EuDist2(fea(classIdx,:),[],0);
D = exp(-D/(2*options.t^2));
G(classIdx,classIdx) = D;
end
end
if ~options.bSelfConnected
for i=1:size(G,1)
G(i,i) = 0;
end
end
W = sparse(max(G,G'));
case {lower('Cosine')}
if ~options.bNormalized
[nSmp, nFea] = size(fea);
if issparse(fea)
fea2 = fea';
feaNorm = sum(fea2.^2,1).^.5;
for i = 1:nSmp
fea2(:,i) = fea2(:,i) ./ max(1e-10,feaNorm(i));
end
fea = fea2';
clear fea2;
else
feaNorm = sum(fea.^2,2).^.5;
for i = 1:nSmp
fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i));
end
end
end
if options.k > 0
G = zeros(nSmp*(options.k+1),3);
idNow = 0;
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
D = fea(classIdx,:)*fea(classIdx,:)';
[dump idx] = sort(-D,2); % sort each row
clear D;
idx = idx(:,1:options.k+1);
dump = -dump(:,1:options.k+1);
nSmpClass = length(classIdx)*(options.k+1);
G(idNow+1:nSmpClass+idNow,1) = repmat(classIdx,[options.k+1,1]);
G(idNow+1:nSmpClass+idNow,2) = classIdx(idx(:));
G(idNow+1:nSmpClass+idNow,3) = dump(:);
idNow = idNow+nSmpClass;
clear dump idx
end
G = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp);
else
G = zeros(nSmp,nSmp);
for i=1:nLabel
classIdx = find(options.gnd==Label(i));
G(classIdx,classIdx) = fea(classIdx,:)*fea(classIdx,:)';
end
end
if ~options.bSelfConnected
for i=1:size(G,1)
G(i,i) = 0;
end
end
W = sparse(max(G,G'));
otherwise
error('WeightMode does not exist!');
end
elapse = cputime - tmp_T;
return;
end
if strcmpi(options.NeighborMode,'KNN') && (options.k > 0)
if strcmpi(options.Metric,'Euclidean')
G = zeros(nSmp*(options.k+1),3);
for i = 1:ceil(nSmp/BlockSize)
if i == ceil(nSmp/BlockSize)
smpIdx = (i-1)*BlockSize+1:nSmp;
dist = EuDist2(fea(smpIdx,:),fea,0);
dist = full(dist);
[dump idx] = sort(dist,2); % sort each row
idx = idx(:,1:options.k+1);
dump = dump(:,1:options.k+1);
if ~bBinary
dump = exp(-dump/(2*options.t^2));
end
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]);
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),2) = idx(:);
if ~bBinary
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = dump(:);
else
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = 1;
end
else
smpIdx = (i-1)*BlockSize+1:i*BlockSize;
dist = EuDist2(fea(smpIdx,:),fea,0);
dist = full(dist);
[dump idx] = sort(dist,2); % sort each row
idx = idx(:,1:options.k+1);
dump = dump(:,1:options.k+1);
if ~bBinary
dump = exp(-dump/(2*options.t^2));
end
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]);
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),2) = idx(:);
if ~bBinary
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = dump(:);
else
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = 1;
end
end
end
W = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp);
else
if ~options.bNormalized
[nSmp, nFea] = size(fea);
if issparse(fea)
fea2 = fea';
clear fea;
for i = 1:nSmp
fea2(:,i) = fea2(:,i) ./ max(1e-10,sum(fea2(:,i).^2,1).^.5);
end
fea = fea2';
clear fea2;
else
feaNorm = sum(fea.^2,2).^.5;
for i = 1:nSmp
fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i));
end
end
end
G = zeros(nSmp*(options.k+1),3);
for i = 1:ceil(nSmp/BlockSize)
if i == ceil(nSmp/BlockSize)
smpIdx = (i-1)*BlockSize+1:nSmp;
dist = fea(smpIdx,:)*fea';
dist = full(dist);
[dump idx] = sort(-dist,2); % sort each row
idx = idx(:,1:options.k+1);
dump = -dump(:,1:options.k+1);
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]);
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),2) = idx(:);
G((i-1)*BlockSize*(options.k+1)+1:nSmp*(options.k+1),3) = dump(:);
else
smpIdx = (i-1)*BlockSize+1:i*BlockSize;
dist = fea(smpIdx,:)*fea';
dist = full(dist);
[dump idx] = sort(-dist,2); % sort each row
idx = idx(:,1:options.k+1);
dump = -dump(:,1:options.k+1);
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),1) = repmat(smpIdx',[options.k+1,1]);
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),2) = idx(:);
G((i-1)*BlockSize*(options.k+1)+1:i*BlockSize*(options.k+1),3) = dump(:);
end
end
W = sparse(G(:,1),G(:,2),G(:,3),nSmp,nSmp);
end
if strcmpi(options.WeightMode,'Binary')
W(find(W)) = 1;
end
if isfield(options,'bSemiSupervised') && options.bSemiSupervised
tmpgnd = options.gnd(options.semiSplit);
Label = unique(tmpgnd);
nLabel = length(Label);
G = zeros(sum(options.semiSplit),sum(options.semiSplit));
for idx=1:nLabel
classIdx = tmpgnd==Label(idx);
G(classIdx,classIdx) = 1;
end
Wsup = sparse(G);
if ~isfield(options,'SameCategoryWeight')
options.SameCategoryWeight = 1;
end
W(options.semiSplit,options.semiSplit) = (Wsup>0)*options.SameCategoryWeight;
end
if ~options.bSelfConnected
for i=1:size(W,1)
W(i,i) = 0;
end
end
W = max(W,W');
elapse = cputime - tmp_T;
return;
end
% strcmpi(options.NeighborMode,'KNN') & (options.k == 0)
% Complete Graph
if strcmpi(options.Metric,'Euclidean')
W = EuDist2(fea,[],0);
W = exp(-W/(2*options.t^2));
else
if ~options.bNormalized
% feaNorm = sum(fea.^2,2).^.5;
% fea = fea ./ repmat(max(1e-10,feaNorm),1,size(fea,2));
[nSmp, nFea] = size(fea);
if issparse(fea)
fea2 = fea';
feaNorm = sum(fea2.^2,1).^.5;
for i = 1:nSmp
fea2(:,i) = fea2(:,i) ./ max(1e-10,feaNorm(i));
end
fea = fea2';
clear fea2;
else
feaNorm = sum(fea.^2,2).^.5;
for i = 1:nSmp
fea(i,:) = fea(i,:) ./ max(1e-12,feaNorm(i));
end
end
end
% W = full(fea*fea');
W = fea*fea';
end
if ~options.bSelfConnected
for i=1:size(W,1)
W(i,i) = 0;
end
end
W = max(W,W');
elapse = cputime - tmp_T;
function D = EuDist2(fea_a,fea_b,bSqrt)
% Euclidean Distance matrix
% D = EuDist(fea_a,fea_b)
% fea_a: nSample_a * nFeature
% fea_b: nSample_b * nFeature
% D: nSample_a * nSample_a
% or nSample_a * nSample_b
if ~exist('bSqrt','var')
bSqrt = 1;
end
if (~exist('fea_b','var')) | isempty(fea_b)
[nSmp, nFea] = size(fea_a);
aa = sum(fea_a.*fea_a,2);
ab = fea_a*fea_a';
aa = full(aa);
ab = full(ab);
if bSqrt
D = sqrt(repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab);
D = real(D);
else
D = repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab;
end
D = max(D,D');
D = D - diag(diag(D));
D = abs(D);
else
[nSmp_a, nFea] = size(fea_a);
[nSmp_b, nFea] = size(fea_b);
aa = sum(fea_a.*fea_a,2);
bb = sum(fea_b.*fea_b,2);
ab = fea_a*fea_b';
aa = full(aa);
bb = full(bb);
ab = full(ab);
if bSqrt
D = sqrt(repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab);
D = real(D);
else
D = repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab;
end
D = abs(D);
end
|
github
|
mengchuangji/AmazingTransferLearning-master
|
MyARTL.m
|
.m
|
AmazingTransferLearning-master/code/MyARTL/MyARTL.m
| 3,503 |
utf_8
|
91802921f23d322f2ffca0e311f9372a
|
function [acc,acc_ite,Alpha] = MyARTL(X_src,Y_src,X_tar,Y_tar,options)
% Inputs:
%%% X_src :source feature matrix, ns * m
%%% Y_src :source label vector, ns * 1
%%% X_tar :target feature matrix, nt * m
%%% Y_tar :target label vector, nt * 1
%%% options:option struct
% Outputs:
%%% acc :final accuracy using knn, float
%%% acc_ite:list of all accuracies during iterations
%%% A :final adaptation matrix, (ns + nt) * (ns + nt)
%% Set options
lambda = options.lambda; %% lambda for the regularization
kernel_type = options.kernel_type; %% kernel_type is the kernel name, primal|linear|rbf
T = options.T; %% iteration number
n_neighbor = options.n_neighbor;
sigma = options.sigma;
gamma = options.gamma;
X = [X_src',X_tar'];
Y = [Y_src;Y_tar];
X = X*diag(sparse(1./sqrt(sum(X.^2))));
ns = size(X_src,1);
nt = size(X_tar,1);
nm = ns + nt;
e = [1/ns*ones(ns,1);-1/nt*ones(nt,1)];
C = length(unique(Y_src));
E = diag(sparse([ones(ns,1);zeros(nt,1)]));
YY = [];
for c = reshape(unique(Y),1,length(unique(Y)))
YY = [YY,Y==c];
end
%% Construct graph laplacian
manifold.k = options.n_neighbor;
manifold.Metric = 'Cosine';
manifold.NeighborMode = 'KNN';
manifold.WeightMode = 'Cosine';
[W,Dw,L] = construct_lapgraph(X',manifold);
%%% M0
M = e * e' * C; %multiply C for better normalization
acc_ite = [];
Y_tar_pseudo = [];
% If want to include conditional distribution in iteration 1, then open
% this
% if ~isfield(options,'Yt0')
% % model = train(Y(1:ns),sparse(X(:,1:ns)'),'-s 0 -c 1 -q 1');
% % [Y_tar_pseudo,~] = predict(Y(ns+1:end),sparse(X(:,ns+1:end)'),model);
% knn_model = fitcknn(X_src,Y_src,'NumNeighbors',1);
% Y_tar_pseudo = knn_model.predict(X_tar);
% else
% Y_tar_pseudo = options.Yt0;
% end
%% Iteration
for i = 1 : T
%%% Mc
N = 0;
if ~isempty(Y_tar_pseudo) && length(Y_tar_pseudo)==nt
for c = reshape(unique(Y_src),1,C)
e = zeros(nm,1);
e(Y_src==c) = 1 / length(find(Y_src==c));
e(ns+find(Y_tar_pseudo==c)) = -1 / length(find(Y_tar_pseudo==c));
e(isinf(e)) = 0;
N = N + e*e';
end
end
M = M + N;
M = M / norm(M,'fro');
%% Calculation
K = kernel_artl(kernel_type,X,sqrt(sum(sum(X.^2).^0.5)/nm));
Alpha = ((E + lambda * M + gamma * L) * K + sigma * speye(nm,nm)) \ (E * YY);
F = K * Alpha;
[~,Cls] = max(F,[],2);
Acc = numel(find(Cls(ns+1:end)==Y(ns+1:end)))/nt;
Y_tar_pseudo = Cls(ns+1:end);
fprintf('Iteration [%2d]:ARTL=%0.4f\n',i,Acc);
acc_ite = [acc_ite;Acc];
end
end
function [W,Dw,L] = construct_lapgraph(X,options)
W = lapgraph(X,options);
Dw = diag(sparse(sqrt(1./sum(W))));
L = speye(size(X,1)) - Dw * W * Dw;
end
function K = kernel_artl(ker,X,sigma)
switch ker
case 'linear'
K = X' * X;
case 'rbf'
n1sq = sum(X.^2,1);
n1 = size(X,2);
D = (ones(n1,1)*n1sq)' + ones(n1,1)*n1sq -2*X'*X;
K = exp(-D/(2*sigma^2));
case 'sam'
D = X'*X;
K = exp(-acos(D).^2/(2*sigma^2));
otherwise
error(['Unsupported kernel ' ker])
end
end
|
github
|
xhwang/joint_image_restoration-master
|
cross_field_re.m
|
.m
|
joint_image_restoration-master/cross_field_re.m
| 4,606 |
utf_8
|
d7f02c729db2a411acad86d5f23b7ce0
|
function I = cross_field_re(I0, G, lambda, beta, eps, eta_sqr, phi_alpha, phi_eps, iternum)
show = 0;
S = ones(size(I0));
I = I0;
[m, n] = size(I);
Cx = get_Cx(m, n); Cy = get_Cy(m, n);
Cxt = get_Cxt(m, n); Cyt = get_Cyt(m, n);
Gx = cal(Cx, G); Gy = cal(Cy, G);
Px = 1 ./ (msign(Gx) .* max(abs(Gx), eps));
Py = 1 ./ (msign(Gy) .* max(abs(Gy), eps));
G2 = Gx .* Gx + Gy .* Gy;
S1 = eta_sqr ./ (G2 + 2 * eta_sqr);
S2 = (G2 + eta_sqr) ./ (G2 + 2 * eta_sqr);
Gs = sqrt(G2);
Vx = Gx ./ max(abs(Gs), eps);
Vy = Gy ./ max(abs(Gs), eps);
if show
figure;
subplot(221); mesh(S1); view(2); colorbar;
subplot(222); mesh(S2); view(2); colorbar;
subplot(223); mesh(Vx); view(2); colorbar;
subplot(224); mesh(Vy); view(2); colorbar;
end
ls1 = zeros(1, iternum);
ls2 = zeros(1, iternum);
li1 = zeros(1, iternum);
li2 = zeros(1, iternum);
for i = 1:iternum
Ix = cal(Cx, I); Iy = cal(Cy, I);
Ax = phi(S - Px .* Ix, phi_alpha, phi_eps);
Ay = phi(S - Py .* Iy, phi_alpha, phi_eps);
lhs = S_func(Cx, Cxt, Cy, Cyt, S1, S2, Vx, Vy, beta, Ax, Ay);
rhs = Ax .* Px .* Ix + Ay .* Py .* Iy;
rhs = reshape(rhs, [m*n, 1]);
tol = 0; max_iter = 100; display_id = 10;
Sinit = reshape(S, [m*n, 1]);
S = cg(lhs, rhs, Sinit, tol, max_iter, show, num2str(i), display_id);
S = reshape(S, [m, n]);
% TODO:
S(Gs<0.005) = 0;
ls1(i) = sum(sum((S - Px .* Ix).^2 .* Ax))...
+ sum(sum((S - Py .* Iy).^2 .* Ay));
L = L_func(Cx, Cxt, Cy, Cyt, S1, S2, Vx, Vy);
St = reshape(S, [m*n, 1]);
ls2(i) = beta * sum(sum(St' * L * St));
Ax = phi(S - Px .* Ix, phi_alpha, phi_eps);
Ay = phi(S - Py .* Iy, phi_alpha, phi_eps);
B = phi(I - I0, phi_alpha, phi_eps);
lhs = I_func(Cx, Cxt, Cy, Cyt, Px, Py, Ax, Ay, lambda, B);
rhs = cal(Cxt, Px .* Ax .* S) + cal(Cyt, Py .* Ay .* S) + lambda * B .* I0;
rhs = reshape(rhs, [m*n, 1]);
tol = 0; max_iter = 100; display_id = 11;
Iinit = reshape(I, [m*n, 1]);
I = cg(lhs, rhs, Iinit, tol, max_iter, show, num2str(i), display_id);
I = reshape(I, [m, n]);
I(I<0) = 0;
I(I>1) = 1;
li1(i) = sum(sum((S - Px .* Ix).^2 .* Ax))...
+ sum(sum((S - Py .* Iy).^2 .* Ay));
li2(i) = lambda * sum(sum((I-I0).^2 .* B));
if show
figure(1); clf;
plot(1:iternum, ls1, '--o', 'DisplayName', 'ls1');
hold on;
plot(1:iternum, ls2, '--*', 'DisplayName', 'ls2');
hold on;
plot(1:iternum, li1, 'r', 'DisplayName', 'li1');
hold on;
plot(1:iternum, li2, 'b', 'DisplayName', 'li2');
legend('show');
figure(2); clf;
Sa = abs(S);
Sn = (Sa - min(Sa(:))) ./ (max(Sa(:)) - min(Sa(:)));
subplot(211); imshow(Sn, []); title(num2str(i));
subplot(212); imshow(I); title(num2str(i));
drawnow;
end
end
end
function y = S_func(Cx, Cxt, Cy, Cyt, S1, S2, Vx, Vy, beta, Ax, Ay)
num = numel(S1);
y = sparse(1:num, 1:num, Ax(:), num, num) + ...
sparse(1:num, 1:num, Ay(:), num, num) + ...
beta * L_func(Cx, Cxt, Cy, Cyt, S1, S2, Vx, Vy);
end
function y = L_func(Cx, Cxt, Cy, Cyt, S1, S2, Vx, Vy)
num = numel(S1);
t = S1 .* Vx.^2 + S2 .* Vy.^2;
t = sparse(1:num, 1:num, t(:), num, num);
first = Cxt * t * Cx;
t = S2 .* Vx.^2 + S1 .* Vy.^2;
t = sparse(1:num, 1:num, t(:), num, num);
second = Cyt * t * Cy;
t = (S1 - S2) .* Vx .* Vy;
t = sparse(1:num, 1:num, t(:), num, num);
third = 2 * Cyt * t * Cx;
y = first + second + third;
end
function y = I_func(Cx, Cxt, Cy, Cyt, Px, Py, Ax, Ay, lambda, B)
num = numel(Px);
t = Px.^2 .* Ax;
t = sparse(1:num, 1:num, t(:), num, num);
first = Cxt * t * Cx;
t = Py.^2 .* Ay;
t = sparse(1:num, 1:num, t(:), num, num);
second = Cyt * t * Cy;
t = lambda * B;
third = sparse(1:num, 1:num, t(:), num, num);
y = first + second + third;
end
function y = phi(x, alpha, eps)
y = 1 ./ (abs(x).^(2-alpha) + eps);
end
function y = msign(x)
y = sign(x);
y(y==0) = 1;
end
function Tc = get_Cx(m, n)
dx = [1, -1];
T = convmtx2(dx, m, n);
Tc = T(m+1:end, :);
Tc(end-m:end, :) = 0;
end
function Tc = get_Cxt(m, n)
dx = [1, -1];
T = convmtx2(dx, m, n);
Tc = T(m+1:end, :);
Tc = Tc';
Tc(1:m, :) = 0;
end
function Tc = get_Cy(m, n)
dy = [1; -1];
T = convmtx2(dy, m, n);
Tc = T;
Tc(1:m+1:end, :) = [];
Tc(m:m:end, :) = 0;
end
function Tc = get_Cyt(m, n)
dy = [1; -1];
T = convmtx2(dy, m, n);
Tc = T;
Tc(1:m+1:end, :) = [];
Tc = Tc';
Tc(1:m:end, :) = 0;
end
function y = cal(Cm, x)
y = reshape(Cm*x(:), size(x));
end
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
newton_v2.m
|
.m
|
ffr-MetodeNumerik-master/AkarPersamaan/octave/newton_v2.m
| 1,424 |
utf_8
|
0f526d7022f022cf086ae470328d0273
|
% newtons.m to solve a set of nonlinear eqs f1(x)=0, f2(x)=0,..
function [x,fx,xx]= newton_v2(f, x0, TolX, MaxIter, varargin)
%input: f = a 1st-order vector ftn equivalent to a set of equations
% x0 = the initial guess of the solution
% TolX = the upper limit of |x(k)-x(k-1)|
% MaxIter= the maximum # of iteration
%output: x = the point which the algorithm has reached
% fx = f(x(last))
% xx = the history of x
h = 1e-5;
TolFun = eps;
EPS = 1e-6;
fx = feval(f,x0,varargin{:});
Nf = length(fx);
Nx = length(x0);
if Nf ~= Nx
error('Incompatible dimensions of f and x0!');
end
if nargin < 4
MaxIter=100;
end
if nargin < 3
TolX=EPS;
end
xx(1,:) = x0(:).';
%fx0= norm(fx);
for k = 1:MaxIter
J = jacob_v2( f, xx(k,:), h ,varargin{:} );
if rank(J) < Nx
k = k-1;
fprintf('Warning: Jacobian singular! with det(J) = %12.6e\n',det(J));
break;
else
dx = -J\fx(:); %-[dfdx]^-1*fx;
end
%for l=1: 3 %damping to avoid divergence %(2)
%dx= dx/2; %(3)
xx(k+1,:) = xx(k,:) + dx.';
fx = feval(f,xx(k+1,:),varargin{:}); fxn=norm(fx);
% if fxn<fx0, break; end
%end
if fxn < TolFun | norm(dx) < TolX
break;
end
%fx0= fxn;
end
x = xx(k+1,:);
if k == MaxIter
fprintf('newton_v2 does not converge after %d iterations\n',MaxIter)
end
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
lagranp.m
|
.m
|
ffr-MetodeNumerik-master/InterpolasiFitting/octave/lagranp.m
| 434 |
utf_8
|
51f9232e1569f01f4b4d6d44bb88a0ae
|
%Program 3.1
function [l,L]=lagranp(x,y)
%Input : x=[x0 x1 ... xN], y=[y0 y1 ... yN]
%Output: l=Lagrange polynomial coefficients of order N
% L=Lagrange coefficient polynomial
N= length(x)-1; %the order of polynomial
l=0;
for m=1:N+1
P=1;
for k=1:N+1
if k~=m
P=conv(P,poly(x(k)))/(x(m)-x(k));
end
end
L(m,:)=P; %Lagrange coefficient polynomial
l =l+y(m)*P; %Lagrange polynomial
end
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
stdDev.m
|
.m
|
ffr-MetodeNumerik-master/InterpolasiFitting/octave/stdDev.m
| 661 |
utf_8
|
498d95cf79725fd2973f08e380188268
|
function sigma = stdDev(coeff,xData,yData)
% Returns the standard deviation between data points and the polynomial
% a(1)*x^(m-1) + a(2)*x^(m-2) + ... + a(m)
% USAGE: sigma = stdDev(coeff,xData,yData)
% coeff = coefficients of the polynomial.
% xData = x-coordinates of data points.
% yData = y-coordinates of data points.
m = length(coeff);
n = length(xData);
sigma = 0;
for i =1:n
y = polyEval(coeff,xData(i));
sigma = sigma + (yData(i) - y)^2;
end
sigma =sqrt(sigma/(n - m));
endfunction
function y = polyEval(coeff,x)
% Returns the value of the polynomial at x.
m = length(coeff);
y = coeff(1);
for j = 1:m-1
y = y*x + coeff(j+1);
end
endfunction
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
splineEval.m
|
.m
|
ffr-MetodeNumerik-master/InterpolasiFitting/octave/splineEval.m
| 831 |
utf_8
|
ae95c918e043b4c17f6e25114a27f407
|
function y = splineEval(xData,yData,k,x)
% Returns value of cubic spline interpolant at x.
% USAGE: y = splineEval(xData,yData,k,x)
% xData = x-coordinates of data points.
% yData = y-coordinates of data points.
% k = curvatures of spline at the knots;
% returned by the function splineCurv.
i = findSeg(xData,x);
h = xData(i) - xData(i+1);
y = ((x - xData(i+1))^3/h - (x - xData(i+1))*h)*k(i)/6.0 ...
- ((x - xData(i))^3/h - (x - xData(i))*h)*k(i+1)/6.0 ...
+ yData(i)*(x - xData(i+1))/h - yData(i+1)*(x - xData(i))/h;
endfunction
function i = findSeg(xData,x)
% Returns index of segment containing x.
iLeft = 1;
iRight = length(xData);
while 1
if(iRight - iLeft) <= 1
i = iLeft;
return
end
i = fix((iLeft + iRight)/2);
if x < xData(i)
iRight = i;
else
iLeft = i;
end
end
endfunction
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
shoot2.m
|
.m
|
ffr-MetodeNumerik-master/BVP/octave/shoot2.m
| 845 |
utf_8
|
31b78e74f29b92c8d8c1c1181218dead
|
addpath('../../AkarPersamaan/octave')
addpath('../../IVP/octave')
function F = dEqs(x,y)
% First-order differential
F = [y(2), -3*y(1)*y(2)]; % equations.
endfunction
function y = inCond(u) % Initial conditions (u is
y = [0 u]; % the unknown condition).
endfunction
%function shoot2
% Shooting method for 2nd-order boundary value problem in Example 8.1.
xStart = 0;
xStop = 2; % Range of integration.
h = 0.1; % Step size.
freq = 2; % Frequency of printout.
u1 = 1;
u2 = 2; % Trial values of unknown
% initial condition u.
x = xStart;
function r = residual(u)
% Boundary residual.
x = 0;
xStop = 2;
h = 0.1;
[xSol,ySol] = runKut4(@dEqs,x,inCond(u),xStop,h);
r = ySol(size(ySol,1),1) - 1;
endfunction
u = ridder(@residual,u1,u2);
[xSol,ySol] = runKut4(@dEqs,x,inCond(u),xStop,h);
printSol(xSol,ySol,freq)
%endfunction
|
github
|
f-fathurrahman/ffr-MetodeNumerik-master
|
powell.m
|
.m
|
ffr-MetodeNumerik-master/Optimisasi/octave/powell.m
| 1,713 |
utf_8
|
a11ec775a54d5dd44174a17ab2300ff0
|
function [xMin,fMin,nCyc] = powell(func,x,h,tol)
% Powell’s method for minimizing f(x1,x2,...,xn).
% USAGE: [xMin,fMin,nCyc] = powell(h,tol)
% INPUT:
% func = handle of function that returns f.
% x = starting point
% h = initial search increment (default = 0.1).
% tol = error tolerance (default = 1.0e-6).
% OUTPUT:
% xMin = minimum point
% fMin = minimum value of f
% nCyc = number of cycles to convergence
if nargin < 4
tol = 1.0e-6;
end
if nargin < 3
h = 0.1;
end
% x must be column vector
if size(x,2) > 1
x = x';
end
% Number of design variables
n = length(x);
df = zeros(n,1); % Decreases of f stored here
u = eye(n); % Columns of u store search directions v
MaxIter = 30;
for j = 1:MaxIter
xOld = x;
fOld = feval(func,xOld);
% First n line searches record the decrease of f
for i = 1:n
v = u(1:n,i);
fLine = @(s) fLine_full(func, x, v, s);
[a,b] = goldBracket(fLine,0.0,h);
[s,fMin] = goldSearch(fLine,a,b);
df(i) = fOld - fMin;
fOld = fMin;
x = x + s*v;
end
% Last line search in the cycle
v = x - xOld;
fLine = @(s) fLine_full(func, x, v, s);
[a,b] = goldBracket(fLine,0.0,h);
[s,fMin] = goldSearch(fLine,a,b);
x = x + s*v;
% Check for convergence
if sqrt(dot(x-xOld,x-xOld)/n) < tol
xMin = x;
nCyc = j;
return
end
% Identify biggest decrease of f & update search directions
iMax = 1; dfMax = df(1);
for i = 2:n
if df(i) > dfMax
iMax = i; dfMax = df(i);
end
end
for i = iMax:n-1
u(1:n,i) = u(1:n,i+1);
end
u(1:n,n) = v;
end
error('Powell method did not converge')
endfunction
function z = fLine_full(func,x,v,s) % F in the search direction v
z = feval(func, x + s*v);
endfunction
|
github
|
taodeng/Top-down-based-traffic-driving-saliency-model-master
|
convolve_gLoG.m
|
.m
|
Top-down-based-traffic-driving-saliency-model-master/vanishing point detection/convolve_gLoG.m
| 1,193 |
utf_8
|
229fb14b4020504281e6a1e6f1458577
|
%%%%%%%% convoluation of an image with gLoG filters of the same
%%%%%%%% orientation
function [responseMap] = convolve_gLoG(img, smallestSigma, largestSigma, theta)
imgH = size(img,1);
imgW = size(img,2);
responseMap = zeros(imgH,imgW);
sigmaStep = -1;
newKerSize = 3*largestSigma;
hsize2 = newKerSize/2;
alpha = 1;
for sigmaX = largestSigma : sigmaStep: smallestSigma;
for sigmaY = sigmaX : sigmaStep: smallestSigma;
if sigmaX~=sigmaY
[h] = -elipLog([newKerSize+1,newKerSize+1], sigmaX, sigmaY, theta);
filteredImg = real(ifft2(fft2(img) .* fft2(h,imgH,imgW)));
tmpMap = filteredImg;
tmpMap(1:imgH-hsize2, 1:imgW-hsize2) = filteredImg(1+hsize2:imgH, 1+hsize2:imgW);
tmpMap(1:imgH-hsize2,imgW-hsize2+1:imgW) = filteredImg(hsize2+1:imgH,1:hsize2);
tmpMap(imgH-hsize2+1:imgH,1:imgW-hsize2) = filteredImg(1:hsize2,hsize2+1:imgW);
tmpMap(imgH-hsize2+1:imgH, imgW-hsize2+1:imgW) = filteredImg(1:hsize2,1:hsize2);
tmpMap = (1+log(sigmaX^alpha))*(1+log(sigmaY^alpha))*tmpMap;
responseMap = responseMap+tmpMap;
end
end
end
|
github
|
mehryaragha/NoseBiometrics-master
|
compute_mid_points.m
|
.m
|
NoseBiometrics-master/compute_mid_points.m
| 1,086 |
utf_8
|
022157866ed49903cde7725ca6881ee6
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function found_points = compute_mid_points(starting_pnt, end_pnt, number_of_divisions, rotated_nose);
% This function computes middle points to create the set of nasal landmarks
% according to the PAMI paper.
dividing_vector = (end_pnt - starting_pnt)/ number_of_divisions;
found_points = [];
curr_point = starting_pnt;
for land_cnt = 1: (number_of_divisions - 1)
curr_point = curr_point + dividing_vector;
% Map to the found landmark to the nose surface
curr_dist = ...
((curr_point(1) - rotated_nose(:, :, 1)).^ 2) + (curr_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
found_points(land_cnt, :) = new_point;
end
end
|
github
|
mehryaragha/NoseBiometrics-master
|
curve_cropper.m
|
.m
|
NoseBiometrics-master/curve_cropper.m
| 878 |
utf_8
|
ffa95181dbba13a6e79e968f5b086978
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 31 December 2018
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function cropped_out = curve_cropper(pnt1, pnt2, the_curve)
% [~, pnt1_idx] = min(sum((the_curve - repmat(pnt1, [size(the_curve, 1) 1])).^2, 2));
% [~, pnt2_idx] = min(sum((the_curve - repmat(pnt2, [size(the_curve, 1) 1])).^2, 2));
[~, pnt1_idx] = min(sum((the_curve(:, 1: 2) - repmat(pnt1(1: 2), [size(the_curve, 1) 1])).^2, 2));
[~, pnt2_idx] = min(sum((the_curve(:, 1: 2) - repmat(pnt2(1: 2), [size(the_curve, 1) 1])).^2, 2));
pnt_sorted = sort([pnt1_idx pnt2_idx], 'ascend');
cropped_out = the_curve(pnt_sorted(1): pnt_sorted(2), :);
|
github
|
mehryaragha/NoseBiometrics-master
|
Gabor_wavelet_computer.m
|
.m
|
NoseBiometrics-master/Gabor_wavelet_computer.m
| 1,789 |
utf_8
|
9eb1dd59591ecdab09b928bca2af477f
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function all_layers = Gabor_wavelet_computer(rotated_nose, max_ori, max_scale)
% This function obtains the 3D nose model rotated_nose, which is an M X N X
% 3 block matrix and computes the Gabor-wavelets using in max_ori
% orientations and max_scale scales. Both max_ori and max_scale are
% scalars.
%%%%%%% First find different scales of Gabor filter.
curr_depth = rotated_nose(:, :, 3);
% Replacing the NaNs in the input by the nose's median
curr_depth(isnan(curr_depth)) = nanmedian(curr_depth(:));
curr_depth_f = fft2(curr_depth);
% max_ori = 4;
% max_scale = 4;
all_layers = zeros(size(curr_depth_f, 1), size(curr_depth_f, 2), max_scale);
for scale_cnt = 1: max_scale
curr_layer = zeros(size(curr_depth_f, 1), size(curr_depth_f, 2), max_ori);
for ori_cnt = 1: max_ori
[Gr, Gi] = gabor_by_meshgrid(size(curr_depth),...
[scale_cnt, ori_cnt], [0.05 1], [max_scale, max_ori], 0);
% find the fft of the input and put its DC freq zero
G_F = fft2(Gr + i*Gi);
G_F(1, 1) = 0;
curr_filtered_nose = abs(ifft2(curr_depth_f.* G_F));
% curr_filtered_nose = gather(curr_filtered_nose);
curr_layer(:, :, ori_cnt) = fftshift(curr_filtered_nose);
end
% all_layers(:, :, scale_cnt) = median(curr_layer, 3);
all_layers(:, :, scale_cnt) = max(curr_layer, [], 3);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
mehryaragha/NoseBiometrics-master
|
feature_extraction_spheres.m
|
.m
|
NoseBiometrics-master/feature_extraction_spheres.m
| 2,504 |
utf_8
|
6d16837470ca9308bfb3af956400be7d
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function all_feat = feature_extraction_spheres(X, Y, Z, all_landmarks, all_normal_maps, R, hist_bins, toDisplay)
% This function uses spherical patches as feature descriptors to extract
% histograms of the normal maps computed over the Gabor-wavelet images.
% X and Y and Z are the 3D point cloud of the input image.
% all_landmarks is and M X 3 matrix containing the nasal landmarks
% all_normal_maps is a cell array containing the normal maps.
% R is the radius of the spherical patches in millimeters.
% hist_bins is a vector with elements between -1 and 1, used as histogram
% bins.
% toDisplay is a binary flag to show the output.
rotated_nose(:, :, 1) = X;
rotated_nose(:, :, 2) = Y;
rotated_nose(:, :, 3) = Z;
all_feat = [];
for layercnt = 1: length(all_normal_maps)
curr_map = all_normal_maps{layercnt};
Nx = curr_map(:, :, 1);
Ny = curr_map(:, :, 2);
Nz = curr_map(:, :, 3);
all_curr_dist = false(size(Nx));
for land_cnt = 1: size(all_landmarks, 1)
curr_land = all_landmarks(land_cnt, :);
% R = 11;
% Crop a sphere around the landmark
curr_dist = (rotated_nose(:, :, 1) - curr_land(1)).^ 2 + (rotated_nose(:, :, 2) - curr_land(2)).^ 2 + ...
(rotated_nose(:, :, 3) - curr_land(3)).^ 2 < R^2;
all_curr_dist = or(curr_dist, all_curr_dist);
histx = hist(Nx(curr_dist), hist_bins); histx = histx/ max(histx);
histy = hist(Ny(curr_dist), hist_bins); histy = histy/ max(histy);
histz = hist(Nz(curr_dist), hist_bins); histz = histz/ max(histz);
curr_set = [histx, histy, histz];
all_feat = [all_feat, curr_set];
end
end
if toDisplay
[sphx, sphy, sphz] = sphere(50);
figure('Name', 'Spherical patches', 'NumberTitle','off')
surf(rotated_nose(:, :, 1), rotated_nose(:, :, 2), rotated_nose(:, :, 3), 'linestyle', 'none'),
view(0, 90)
for land_cnt = 1: size(all_landmarks, 1)
curr_land = all_landmarks(land_cnt, :);
hold on,
surf(R* sphx + curr_land(1), R* sphy + curr_land(2), R* sphz + curr_land(3))
hold off
end
end
camlight left
|
github
|
mehryaragha/NoseBiometrics-master
|
gabor_by_meshgrid.m
|
.m
|
NoseBiometrics-master/gabor_by_meshgrid.m
| 2,357 |
utf_8
|
42f358abce39be02aebaff491ab62072
|
% Modified by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
% This is a modified code from the paper:
% B. S. Manjunath and W.Y. Ma, "Texture features for browsing and retrieval of image data"
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI - Special issue on Digital Libraries),
% vol. 18, no. 8, pp. 837-42, Aug. 1996.
%, which works on meshgrid input image.
% For more info, please check:
% http://old.vision.ece.ucsb.edu/texture/software/
% access time: 21:10 on 25 June 2017
% Or check the spplementary material of the PAMI paper below:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function [Gr,Gi] = gabor_by_meshgrid(N,index,freq,partition,flag)
% get parameters
s = index(1);
n = index(2);
Ul = freq(1);
Uh = freq(2);
stage = partition(1);
orientation = partition(2);
% computer ratio a for generating wavelets
base = Uh/Ul;
C = zeros(1,stage);
C(1) = 1;
C(stage) = -base;
P = abs(roots(C));
a = P(1);
% computer best variance of gaussian envelope
u0 = Uh/(a^(stage-s));
Uvar = ((a-1)*u0)/((a+1)*sqrt(2*log(2)));
z = -2*log(2)*Uvar^2/u0;
Vvar = tan(pi/(2*orientation))*(u0+z)/sqrt(2*log(2)-z*z/(Uvar^2));
% generate the spetial domain of gabor wavelets
j = sqrt(-1);
if (rem(N,2) == 0)
side = N/2-0.5;
else
side = fix(N/2);
end;
% x = -side:1:side;
% l = length(x);
% y = x';
% X = ones(l,1)*x;
% Y = y*ones(1,l);
[X, Y] = meshgrid(1: N(2), N(1): -1: 1);
X = X - mean(X(:)); Y = Y - mean(Y(:));
t1 = cos(pi/orientation*(n-1));
t2 = sin(pi/orientation*(n-1));
XX = X*t1+Y*t2;
YY = -X*t2+Y*t1;
Xvar = 1/(2*pi*Uvar);
Yvar = 1/(2*pi*Vvar);
coef = 1/(2*pi*Xvar*Yvar);
Gr = a^(stage-s)*coef*exp(-0.5*((XX.*XX)./(Xvar^2)+(YY.*YY)./(Yvar^2))).*cos(2*pi*u0*XX);
Gi = a^(stage-s)*coef*exp(-0.5*((XX.*XX)./(Xvar^2)+(YY.*YY)./(Yvar^2))).*sin(2*pi*u0*XX);
% remove the real part mean if flag is 1
if (flag == 1)
m = sum(sum(Gr))/sum(sum(abs(Gr)));
Gr = Gr-m*abs(Gr);
end;
|
github
|
mehryaragha/NoseBiometrics-master
|
get_the_line3.m
|
.m
|
NoseBiometrics-master/get_the_line3.m
| 582 |
utf_8
|
d54cc850b64476213a09b001b8a9bc37
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 31 December 2018
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function out = get_the_line3(rotated_nose, land1, land2)
v = cross(land1 - land2, [0, 0, 1]);
out = intersectPlaneSurf(land1, v, rotated_nose(:, :, 1),...
rotated_nose(:, :, 2), rotated_nose(:, :, 3));
out = curve_cropper(land1, land2, out);
|
github
|
mehryaragha/NoseBiometrics-master
|
create_landmarks.m
|
.m
|
NoseBiometrics-master/create_landmarks.m
| 7,941 |
utf_8
|
ea1aaacee536f04bccc309b824111b54
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function my_landmarks = create_landmarks(input_data, L1, L2, E1, E2, N, TIP, SADDLE, vertical_div, horiz_div);
% Loading the nasal landmarks.
% Only to be used when the input is a cropped nasal region. It uses nasal
% alar groove (L1 and L2), nasal tip (TIP), nasal root (SADDLE), subnasale
% (N) to create the set of landmarks according to the PAMI papers, using
% the desired division assigned by vertical_div and horiz_div variables.
L3 = L1;
L6 = L2;
L1 = SADDLE;
L2 = E1;
L4 = TIP;
L5 = N;
L7 = E2;
rotated_nose = input_data;
new_point = L3(1: 2) + ((L3(1: 2) - L1(1: 2))./norm(L3(1: 2) -...
L1(1: 2)))* (norm(L3(1: 2) - L1(1: 2))/6);
% Map the new point on the nose surface
curr_dist = ...
((new_point(1) - rotated_nose(:, :, 1)).^ 2) + (new_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
AL3 = new_point;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Find the one at the bottom of L6
new_point = L6(1: 2) + ((L6(1: 2) - L1(1: 2))./norm(L1(1: 2) -...
L6(1: 2)))* (norm(L1(1: 2) - L6(1: 2))/6);
% Map the new point on the nose surface
curr_dist = ...
((new_point(1) - rotated_nose(:, :, 1)).^ 2) + (new_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
AL6 = new_point;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Find the one at the bottom of AL3
new_point = AL3(1: 2) + ((AL3(1: 2) - L1(1: 2))./norm(AL3(1: 2) -...
L1(1: 2)))* (norm(L3(1: 2) - L1(1: 2))/6);
% Map the new point on the nose surface
curr_dist = ...
((new_point(1) - rotated_nose(:, :, 1)).^ 2) + (new_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
AAL3 = new_point;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Find the one at the bottom of AL6
new_point = AL6(1: 2) + ((AL6(1: 2) - L1(1: 2))./norm(L1(1: 2) -...
AL6(1: 2)))* (norm(L1(1: 2) - L6(1: 2))/6);
% Map the new point on the nose surface
curr_dist = ...
((new_point(1) - rotated_nose(:, :, 1)).^ 2) + (new_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
AAL6 = new_point;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Finding the horizontal landmarks between L1 and L3 - L7 and
%%%%%% L6
dividing_vector = (L3 - L2)/ vertical_div;
all_between_L3_and_L2 = [];
curr_point = L2;
for vertical_land_cnt = 1: (vertical_div - 1)
curr_point = curr_point + dividing_vector;
% Map to the found landmark to the nose surface
curr_dist = ...
((curr_point(1) - rotated_nose(:, :, 1)).^ 2) + (curr_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
all_between_L3_and_L2(vertical_land_cnt, :) = new_point;
end
% figure(1), surf(rotated_nose(:, :, 1), rotated_nose(:, :, 2), rotated_nose(:, :, 3)),
% hold on, plot3(all_between_L3_and_L2(:, 1), all_between_L3_and_L2(:, 2), all_between_L3_and_L2(:, 3), '.g')
% plot3(L2(1), L2(2), L2(3), 'r.')
% plot3(L3(1), L3(2), L3(3), 'r.')
% plot3(AL3(1), AL3(2), AL3(3), 'r.')
% plot3(AAL3(1), AAL3(2), AAL3(3), 'r.')
dividing_vector = (L6 - L7)/ vertical_div;
all_between_L6_and_L7 = [];
curr_point = L7;
for vertical_land_cnt = 1: (vertical_div - 1)
curr_point = curr_point + dividing_vector;
% Map to the found landmark to the nose surface
curr_dist = ...
((curr_point(1) - rotated_nose(:, :, 1)).^ 2) + (curr_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
all_between_L6_and_L7(vertical_land_cnt, :) = new_point;
end
% plot3(all_between_L6_and_L7(:, 1), all_between_L6_and_L7(:, 2), all_between_L6_and_L7(:, 3), 'g.')
% plot3(L7(1), L7(2), L7(3), 'r.')
% plot3(L6(1), L6(2), L6(3), 'r.')
% plot3(AL6(1), AL6(2), AL6(3), 'r.')
% plot3(AAL6(1), AAL6(2), AAL6(3), 'r.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%% Find points between L1 and L4
dividing_vector = (L4 - L1)/ vertical_div;
all_between_L1_and_L4 = [];
curr_point = L1;
for vertical_land_cnt = 1: (vertical_div - 1)
curr_point = curr_point + dividing_vector;
% Map to the found landmark to the nose surface
curr_dist = ...
((curr_point(1) - rotated_nose(:, :, 1)).^ 2) + (curr_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
all_between_L1_and_L4(vertical_land_cnt, :) = new_point;
end
% plot3(all_between_L1_and_L4(:, 1), all_between_L1_and_L4(:, 2), all_between_L1_and_L4(:, 3), 'g.')
% plot3(L1(1), L1(2), L1(3), 'r.')
% plot3(L4(1), L4(2), L4(3), 'r.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% Find one point between L4 and L5
dividing_vector = (L5 - L4)/ 2;
curr_point = L4;
curr_point = curr_point + dividing_vector;
% Map to the found landmark to the nose surface
curr_dist = ...
((curr_point(1) - rotated_nose(:, :, 1)).^ 2) + (curr_point(2) - rotated_nose(:, :, 2)).^ 2;
[r, c] = find(curr_dist == min(curr_dist(:))); r = r(1); c = c(1);
new_point = rotated_nose(r, c, :); new_point = new_point(:)';
one_point_between_L4_and_L5 = new_point;
% plot3(L4(1), L4(2), L4(3), 'r.')
% plot3(L5(1), L5(2), L5(3), 'r.')
% plot3(one_point_between_L4_and_L5(1), one_point_between_L4_and_L5(2), one_point_between_L4_and_L5(3), 'g.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Save the points as left, central and right hand side
left_points = [L2; all_between_L3_and_L2; L3; AL3; AAL3];
centre_points = [L1; all_between_L1_and_L4; L4; one_point_between_L4_and_L5; L5];
right_points = [L7; all_between_L6_and_L7; L6; AL6; AAL6];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Compute the horizontal divisions
left_hand_horiz_landmarks = [];
right_hand_horiz_landmarks = [];
for vertical_pair_cnt = 1: size(centre_points, 1)
left_hand_horiz_landmarks = [left_hand_horiz_landmarks;
compute_mid_points(centre_points(vertical_pair_cnt, :), left_points(vertical_pair_cnt, :), horiz_div, rotated_nose)];
right_hand_horiz_landmarks = [right_hand_horiz_landmarks;
compute_mid_points(centre_points(vertical_pair_cnt, :), right_points(vertical_pair_cnt, :), horiz_div, rotated_nose)];
end
% plot3(left_hand_horiz_landmarks(:, 1), left_hand_horiz_landmarks(:, 2), left_hand_horiz_landmarks(:, 3), '.y')
% plot3(right_hand_horiz_landmarks(:, 1), right_hand_horiz_landmarks(:, 2), right_hand_horiz_landmarks(:, 3), '.y')
% view(0, 90)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Stacking all the landmarks
my_landmarks = [left_points; centre_points; right_points;...
left_hand_horiz_landmarks; right_hand_horiz_landmarks];
% figure(2), surf(rotated_nose(:, :, 1), rotated_nose(:, :, 2), rotated_nose(:, :, 3))
% hold on, plot3(all_landmarks(:, 1), all_landmarks(:, 2), all_landmarks(:, 3), '.g')
% view(0, 90)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
mehryaragha/NoseBiometrics-master
|
Demo_nasal_curves_patched.m
|
.m
|
NoseBiometrics-master/Demo_nasal_curves_patched.m
| 5,350 |
utf_8
|
8aa65f1b7eef94b7dd34d4f3310b9197
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 31 December 2018
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function Demo_nasal_curves_patched
% This function is a demo for the nasal cureves feature extraction from
% the Gabor-wavelet filtered normal maps. It uses an uploaded 3D model of
% the nose.
% After loading the landmarks, the function applies the Gabor-wavelets and
% computes the maximum per orientation.
% Then normal vectors are computed for each maximum scale image. And
% finally, the curves are computed over the nasal region and
% feature vectors are concatenated to form the final feature vector.
clc
close all
warning off
curves_to_plot = 1;
%%%%%%%%%%%%% Loading the 2.5 depth map
load nasal_curve_landmarks.mat
input_data = rotated_nose;
figure, surf(input_data(:, :, 1), input_data(:, :, 2), input_data(:, :, 3), 'linestyle', 'none')
view(0, 90), camlight left, title('Input data')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%% Setting up the landmarks over the depth map
%%%%%%%%% Name of curves
curves_name = {'L1 L2', 'L1 M1', 'L1 M2', 'L1 M3', 'L1 L3', 'L1 AL3', 'L1 AAL3', ...
'L1 C', 'L1 M4', 'L1 L4', 'L1 L5', 'L1 L7', 'L1 M8', 'L1 M7', 'L1 M6', 'L1 L6', ...
'L1 AL6', 'L1 AAL6', 'L1 M5', ...
'L2 L7', 'L2 C', 'L2 L4', 'L2 L3', 'L2 AAL3', 'L2 M7', 'L2 M8', ...
'L7 C', 'L7 L4', 'L7 L6', 'L7 AAL6', 'L7 M2', 'L7 M1', ...
'M1 C', 'M2 C', 'M3 C', 'L3 C', 'AL3 C', 'AAL3 C', 'L4 C', 'M8 C', 'M7 C', 'M6 C', ...
'L6 C', 'AL6 C', 'AAL6 C', ...
'L4 M1', 'L4 M2', 'L4 M3', 'L4 L3', 'L4 AL3', 'L4 AAL3', 'L4 L5', 'L4 AAL6', 'L4 AL6', ...
'L4 M6', 'L4 M7', 'L4 M8', ...
'M4 M2', 'M4 M3', 'M4 M7', ...
'M5 M7', 'M5 M6', 'M5 M2', ...
'M1 M8', 'M2 M7', 'M3 M6', 'L3 L6', 'AL3 AL6', 'AAL3 AAL6', ...
'AAL3 L5', 'AAL6 L5', ...
'M2 L6', 'M7 L3'};
%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Plotting the landmarks
figure(1)
my_landmarks = [L1; L2; L3; L4; L5; L6; L7; M1; M2; M3; M4; M5; M6; M7; M8; C; AL3; AL6; AAL3; AAL6];
hold on,
plot3(my_landmarks(:, 1), my_landmarks(:, 2), my_landmarks(:, 3), 'r.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Computing the Gabor-wavelets
max_ori = 4;
max_scale = 4;
all_layers = Gabor_wavelet_computer(input_data, max_ori, max_scale);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Plotting the Gabor-wavelet output
figure('Name', 'Maximal Gabor-wavelet outputs per orientation', 'NumberTitle','off');
subplot(2, 2, 1),
imagesc(all_layers(:, :, 1))
subplot(2, 2, 2),
imagesc(all_layers(:, :, 2))
subplot(2, 2, 3),
imagesc(all_layers(:, :, 3))
subplot(2, 2, 4),
imagesc(all_layers(:, :, 4))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Computing the normal vectors
all_normal_maps = Normal_vector_computer(input_data(:, :, 1), input_data(:, :, 2), all_layers);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% Plotting the normal maps
figure('Name', 'Normal maps plot', 'NumberTitle','off')
for map_cnt = 1: length(all_normal_maps)
curr_map = all_normal_maps{map_cnt};
subplot(2, 2, map_cnt),
imagesc(curr_map)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Computing the feature space as the histogram of the nasal
%%%%%%%%%%%%%%%% curves
all_feats = [];
hist_bins = [0: 1: 10];
subplot_cnt = 1;
for layer_cnt = 1: length(all_normal_maps)
curr_layer3D = rotated_nose;
curr_norm = all_normal_maps{layer_cnt};
N1 = curr_norm(:, :, 1);
N2 = curr_norm(:, :, 2);
N3 = curr_norm(:, :, 3);
for norm_cnt = 1: 3
curr_layer3D(:, :, 3) = eval(['N' num2str(norm_cnt)]);
if curves_to_plot == 1
figure(4), subplot(length(all_normal_maps), 3, subplot_cnt),
surf(curr_layer3D(:, :, 1), curr_layer3D(:, :, 2), curr_layer3D(:, :, 3), 'linestyle', 'none')
view(0, 90), camlight left
end
for curve_cnt = 1: length(curves_name)
curr_curve = curves_name{curve_cnt};
locs = regexp(curr_curve, ' ');
Start = curr_curve(1: locs - 1);
End = curr_curve(locs + 1: end);
out = get_the_line3(curr_layer3D, eval(Start), eval(End));
if curves_to_plot == 1
subplot(length(all_normal_maps), 3, subplot_cnt), hold on,
plot3(out(:, 1), out(:, 2), out(:, 3), '.b')
end
curr_feat = out(:, 3); curr_feat = curr_feat - min(curr_feat);
curr_feat = (curr_feat./ max(curr_feat))*10;
curr_feat = hist(curr_feat, hist_bins); curr_feat = curr_feat./ (max(curr_feat) + eps);
all_feats = [all_feats, curr_feat];
end
if curves_to_plot == 1
title(['Gabor layer = ' num2str(layer_cnt) sprintf('\n') 'Normal dimension = ' num2str(norm_cnt)])
subplot_cnt = subplot_cnt + 1;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%% Plotting the feature space
figure, plot(all_feats), ylim([0, 1.5]), title('Extracted feature vector')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
mehryaragha/NoseBiometrics-master
|
Demo_spherical_patched.m
|
.m
|
NoseBiometrics-master/Demo_spherical_patched.m
| 3,416 |
utf_8
|
291efe76e06a8168af93e4d49740eeec
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function Demo_spherical_patched
% This function is a demo for the spherical patches feature extraction from
% the Gabor-wavelet filtered normal maps. It uses an uploaded 3D model of
% the nose. It can work in two modes: (1) uniformly selected landmarks and
% (2) nasal landmarks explained in the above PAMI paper.
% After loading the landmarks, it then applies the Gabor-wavelets and
% computes the maximum per orientation.
% Then normal vectors are computed for each maximum scale image. And
% finally, the spherical patches are computed over the nasal region and
% feature vectors are concatenated to form the final feature vector.
clc
close all
clear all
warning off
%%%%%%%%%%%%% Loading the 2.5 depth map
load Sample_Nose.mat
input_data = rotated_nose;
figure, surf(input_data(:, :, 1), input_data(:, :, 2), input_data(:, :, 3), 'linestyle', 'none')
view(0, 90), camlight left, title('Input data')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%% Setting up the landmarks over the depth map
Using_uniform_landmarks = false;
if Using_uniform_landmarks
my_x_res = 5;
my_y_res = 6.5;
my_landmarks = create_uniform_landmarks(input_data, my_x_res, my_y_res);
else
vertical_div = 5;
horiz_div = 5;
my_landmarks = create_landmarks(input_data, L1, L2, E1, E2, N, TIP, SADDLE, vertical_div, horiz_div);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Plotting the landmarks
figure(1)
hold on,
plot3(my_landmarks(:, 1), my_landmarks(:, 2), my_landmarks(:, 3), 'r.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%% Computing the Gabor-wavelets
max_ori = 4;
max_scale = 4;
all_layers = Gabor_wavelet_computer(input_data, max_ori, max_scale);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Plotting the Gabor-wavelet output
figure('Name', 'Maximal Gabor-wavelet outputs per orientation', 'NumberTitle','off');
subplot(2, 2, 1),
imagesc(all_layers(:, :, 1))
subplot(2, 2, 2),
imagesc(all_layers(:, :, 2))
subplot(2, 2, 3),
imagesc(all_layers(:, :, 3))
subplot(2, 2, 4),
imagesc(all_layers(:, :, 4))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Computing the normal vectors
all_normal_maps = Normal_vector_computer(input_data(:, :, 1), input_data(:, :, 2), all_layers);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% Plotting the normal maps
figure('Name', 'Normal maps plot', 'NumberTitle','off')
for map_cnt = 1: length(all_normal_maps)
curr_map = all_normal_maps{map_cnt};
subplot(2, 2, map_cnt),
imagesc(curr_map)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% Computing the feature space as the histogram of the spherical patches
R = 11;
hist_bins = [-1: 0.1: 1];
toDisplay = 1;
all_feat = feature_extraction_spheres(input_data(:, :, 1), input_data(:, :, 2), input_data(:, :, 3), my_landmarks, all_normal_maps, R, hist_bins, toDisplay);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%% Plotting the feature space
figure, plot(all_feat), ylim([0, 1.5]), title('Extracted feature vector')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
mehryaragha/NoseBiometrics-master
|
Normal_vector_computer.m
|
.m
|
NoseBiometrics-master/Normal_vector_computer.m
| 1,013 |
utf_8
|
c4c6e10e8455301d70f5b71cec0fffa9
|
% Written by: Mehryar Emambakhsh
% Email: [email protected]
% Date: 25 June 2017
% Paper:
% M. Emambakhsh and A. Evans, “Nasal patches and curves for an expression-robust 3D face recognition,”
% IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), vol. 39, no. 5, pp. 995-1007, 2017.
function all_normal_maps = Normal_vector_computer(X, Y, all_layers);
% This function gets X and Y which are the M X N matrices, containing the
% horizontal and vertical resolution matrices, and all_layers, which is a
% block matrix in the form of O X P X max_scale, and computes the normal
% maps for each scale maps.
% The output all_normal_maps is a cell array containing the normal maps.
for layer_cnt = 1: size(all_layers, 3)
[curr_norm_x, curr_norm_y, curr_norm_z] = ...
surfnorm(X, Y, all_layers(:, :, layer_cnt));
curr_norm(:, :, 1) = curr_norm_x;
curr_norm(:, :, 2) = curr_norm_y;
curr_norm(:, :, 3) = curr_norm_z;
all_normal_maps{layer_cnt} = curr_norm;
end
|
github
|
yqueau/shape_from_shading-master
|
export_obj2.m
|
.m
|
shape_from_shading-master/Toolbox/export_obj2.m
| 11,644 |
iso_8859_1
|
9242380a00fbba473f3004c6ea2ff5d4
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Nom ............ : export_obj.m
% Version ........ : 1
%
% Description..... : Save the reconstruction OBJ format, in
% mesh.obj, mesh.mtl and mesh.png
% INPUT : XYZ, N, RHO -- nrows x ncols x 3
%
% Auteur ......... : Yvain Queau pour Toulouse Tech Transfer
%
% Date de création : 06/10/2014
% Date de modif... : 06/01/2014 par Yvain (moins de points, aussi
% precis)
%
% Licence ........ : Propriétaire
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function export_obj2(XYZ,N,rho,mask,filename)
if (~exist('rho','var')|isempty(rho)) rho=ones(size(XYZ)); end;
if (~exist('mask','var')|isempty(mask)) mask=ones(size(XYZ(:,:,1))); end;
[nrows,ncols] = size(mask);
% Switch to usual axis
%~ XYZ(:,:,2) = - XYZ(:,:,2);
%~ XYZ(:,:,3) = - XYZ(:,:,3);
%~ N(:,:,2) = - N(:,:,2);
%~ N(:,:,3) = - N(:,:,3);
%~
% Make a material structure
material(1).type='newmtl';
material(1).data='skin';
material(2).type='Ka';
material(2).data=[0.5 0.5 0.5];
material(3).type='Kd';
material(3).data=[1 1 1];
material(4).type='Ks';
material(4).data=[0.3 0.3 0.3];
material(5).type='illum';
material(5).data=2;
material(6).type='Ns';
material(6).data=10;
% Nuage de Points :
indices_mask = find(mask>0);
[Imask,Jmask]=ind2sub(size(mask),indices_mask);
indices = zeros(size(mask));
indices(indices_mask) = 1:length(indices_mask);
mask=[mask;zeros(1,size(mask,2))];
mask=[mask,zeros(size(mask,1),1)];
X = XYZ(:,:,1);
Y = XYZ(:,:,2);
Z = XYZ(:,:,3);
vertices = [X(indices_mask),Y(indices_mask),Z(indices_mask)];
clear X Y Z
NX = N(:,:,1);
NY = N(:,:,2);
NZ = N(:,:,3);
normals = [NX(indices_mask),NY(indices_mask),NZ(indices_mask)];
clear NX NY NZ
[X,Y] = meshgrid(1:size(XYZ,2),size(XYZ,1):-1:1);
X = X/max(X(:));
Y = Y/max(Y(:));
texture = [X(indices_mask),Y(indices_mask)];
clear X Y
disp('Meshing ...')
indices_lower_triangle = find(mask(1:end-1,1:end-1)>0 & mask(2:end,2:end) & mask(2:end,1:end-1));
[I_lt,J_lt] = ind2sub([nrows ncols],indices_lower_triangle);
indices_bas = sub2ind([nrows ncols],I_lt+1,J_lt);
indices_bas_droite = sub2ind([nrows ncols],I_lt+1,J_lt+1);
face_vertices = [indices(indices_lower_triangle),indices(indices_bas),indices(indices_bas_droite)];
indices_upper_triangle = find(mask(1:end-1,1:end-1)>0 & mask(2:end,2:end) & mask(1:end-1,2:end));
[I_ut,J_ut] = ind2sub([nrows ncols],indices_upper_triangle);
indices_droite = sub2ind([nrows ncols],I_ut,J_ut+1);
indices_bas_droite = sub2ind([nrows ncols],I_ut+1,J_ut+1);
face_vertices = [face_vertices;...
indices(indices_upper_triangle),indices(indices_bas_droite),indices(indices_droite)];
face_texture = face_vertices;
face_normals = face_vertices;
% Write texture
%~ imwrite(max(0,uint8(255*rho(:,:,:)./max(rho(:)))),'mesh.png');
imwrite(rho,sprintf('%s.png',filename));
material(7).type='map_Kd';
material(7).data=sprintf('%s.png',filename);
% Define OBJ structure
clear OBJ
OBJ.vertices = vertices;
OBJ.vertices_normal = normals;
OBJ.vertices_texture = texture;
OBJ.material = material;
OBJ.objects(2).type='g';
OBJ.objects(2).data='skin';
OBJ.objects(3).type='usemtl';
OBJ.objects(3).data='skin';
OBJ.objects(1).type='f';
OBJ.objects(1).data.vertices=face_vertices;
OBJ.objects(1).data.texture=face_texture;
OBJ.objects(1).data.normal=face_normals;
% Write
disp('Writing OBJ ...')
write_wobj(OBJ,sprintf('%s.obj',filename));
%~ disp('Writing PLY ...')
%~ write_ply(vertices,face_vertices,normals,'mesh.ply','binary_little_endian');
end
function write_wobj(OBJ,fullfilename)
% Write objects to a Wavefront OBJ file
%
% write_wobj(OBJ,filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% example reading/writing,
%
% OBJ=read_wobj('examples\example10.obj');
% write_wobj(OBJ,'test.obj');
%
% example isosurface to obj-file,
%
% % Load MRI scan
% load('mri','D'); D=smooth3(squeeze(D));
% % Make iso-surface (Mesh) of skin
% FV=isosurface(D,1);
% % Calculate Iso-Normals of the surface
% N=isonormals(D,FV.vertices);
% L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps;
% N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L;
% % Display the iso-surface
% figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight
% % Invert Face rotation
% FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)];
%
% % Make a material structure
% material(1).type='newmtl';
% material(1).data='skin';
% material(2).type='Ka';
% material(2).data=[0.8 0.4 0.4];
% material(3).type='Kd';
% material(3).data=[0.8 0.4 0.4];
% material(4).type='Ks';
% material(4).data=[1 1 1];
% material(5).type='illum';
% material(5).data=2;
% material(6).type='Ns';
% material(6).data=27;
%
% % Make OBJ structure
% clear OBJ
% OBJ.vertices = FV.vertices;
% OBJ.vertices_normal = N;
% OBJ.material = material;
% OBJ.objects(1).type='g';
% OBJ.objects(1).data='skin';
% OBJ.objects(2).type='usemtl';
% OBJ.objects(2).data='skin';
% OBJ.objects(3).type='f';
% OBJ.objects(3).data.vertices=FV.faces;
% OBJ.objects(3).data.normal=FV.faces;
% write_wobj(OBJ,'skinMRI.obj');
%
% Function is written by D.Kroon University of Twente (June 2010)
if(exist('fullfilename','var')==0)
[filename, filefolder] = uiputfile('*.obj', 'Write obj-file');
fullfilename = [filefolder filename];
end
[filefolder,filename] = fileparts( fullfilename);
comments=cell(1,4);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
fid = fopen(fullfilename,'w');
write_comment(fid,comments);
if(isfield(OBJ,'material')&&~isempty(OBJ.material))
filename_mtl=fullfile(filefolder,[filename '.mtl']);
fprintf(fid,'mtllib %s\n',filename_mtl);
write_MTL_file(filename_mtl,OBJ.material)
end
if(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices))
write_vertices(fid,OBJ.vertices,'v');
end
if(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point))
write_vertices(fid,OBJ.vertices_point,'vp');
end
if(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal))
write_vertices(fid,OBJ.vertices_normal,'vn');
end
if(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture))
write_vertices(fid,OBJ.vertices_texture,'vt');
end
for i=1:length(OBJ.objects)
type=OBJ.objects(i).type;
data=OBJ.objects(i).data;
switch(type)
case 'usemtl'
fprintf(fid,'usemtl %s\n',data);
case 'f'
check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture));
check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal));
if(check1&&check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1));
fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2));
fprintf(fid,' %d/%d/%d\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3));
end
elseif(check1)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1));
fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2));
fprintf(fid,' %d/%d\n', data.vertices(j,3),data.texture(j,3));
end
elseif(check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1));
fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2));
fprintf(fid,' %d//%d\n', data.vertices(j,3),data.normal(j,3));
end
else
for j=1:size(data.vertices,1)
fprintf(fid,'f %d %d %d\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3));
end
end
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
fclose(fid);
end
function write_MTL_file(filename,material)
fid = fopen(filename,'w');
comments=cell(1,2);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
write_comment(fid,comments);
for i=1:length(material)
type=material(i).type;
data=material(i).data;
switch(type)
case('newmtl')
fprintf(fid,'%s ',type);
fprintf(fid,'%s\n',data);
case{'Ka','Kd','Ks'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f %5.5f %5.5f\n',data);
case('illum')
fprintf(fid,'%s ',type);
fprintf(fid,'%d\n',data);
case {'Ns','Tr','d'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f\n',data);
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
comments=cell(1,2);
comments{1}='';
comments{2}=' EOF';
write_comment(fid,comments);
fclose(fid);
end
function write_comment(fid,comments)
for i=1:length(comments), fprintf(fid,'# %s\n',comments{i}); end
end
function write_vertices(fid,V,type)
switch size(V,2)
case 1
for i=1:size(V,1)
fprintf(fid,'%s %5.5f\n', type, V(i,1));
end
case 2
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f\n', type, V(i,1), V(i,2));
end
case 3
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f %5.5f\n', type, V(i,1), V(i,2), V(i,3));
end
otherwise
end
switch(type)
case 'v'
fprintf(fid,'# %d vertices \n', size(V,1));
case 'vt'
fprintf(fid,'# %d texture verticies \n', size(V,1));
case 'vn'
fprintf(fid,'# %d normals \n', size(V,1));
otherwise
fprintf(fid,'# %d\n', size(V,1));
end
end
|
github
|
yqueau/shape_from_shading-master
|
make_gradient.m
|
.m
|
shape_from_shading-master/Toolbox/make_gradient.m
| 3,744 |
utf_8
|
81093565d669618752ea1c3a8765a8ef
|
% Functions for computing the gradient operator on non-rectangular domains
function [M,imask] = make_gradient(mask)
% Compute forward (Dxp and Dyp) and backward (Dxm and Dym) operators
[Dyp,Dym,Dxp,Dxm,Sup,Sum,Svp,Svm,Omega,index_matrix,imask] = gradient_operators(mask);
[nrows,ncols] = size(mask);
% When there is no bottom neighbor, replace by backward (or by 0 if no top)
Dy = Dyp;
no_bottom = find(~Omega(:,:,1));
no_bottom = nonzeros(index_matrix(no_bottom));
Dy(no_bottom,:) = Dym(no_bottom,:);
% Same for the x direction (right / left)
Dx = Dxp;
no_right = find(~Omega(:,:,3));
no_right = nonzeros(index_matrix(no_right));
Dx(no_right,:) = Dxm(no_right,:);
M = sparse([],[],[],2*size(Dx,1),size(Dx,2),2*length(imask));
M(1:2:end-1,:) = Dx;
M(2:2:end,:) = Dy;
end
function [Dup,Dum,Dvp,Dvm,Sup,Sum,Svp,Svm,Omega,index_matrix,imask] = gradient_operators(mask)
[nrows,ncols] = size(mask);
Omega_padded = padarray(mask,[1 1],0);
% Pixels who have bottom neighbor in mask
Omega(:,:,1) = mask.*Omega_padded(3:end,2:end-1);
% Pixels who have top neighbor in mask
Omega(:,:,2) = mask.*Omega_padded(1:end-2,2:end-1);
% Pixels who have right neighbor in mask
Omega(:,:,3) = mask.*Omega_padded(2:end-1,3:end);
% Pixels who have left neighbor in mask
Omega(:,:,4) = mask.*Omega_padded(2:end-1,1:end-2);
imask = find(mask>0);
index_matrix = zeros(nrows,ncols);
index_matrix(imask) = 1:length(imask);
% Dv matrix
% When there is a neighbor on the right : forward differences
idx_c = find(Omega(:,:,3)>0);
[xc,yc] = ind2sub(size(mask),idx_c);
indices_centre = index_matrix(idx_c);
indices_right = index_matrix(sub2ind(size(mask),xc,yc+1));
indices_right = indices_right(:);
II = indices_centre;
JJ = indices_right;
KK = ones(length(indices_centre),1);
II = [II;indices_centre];
JJ = [JJ;indices_centre];
KK = [KK;-ones(length(indices_centre),1)];
Dvp = sparse(II,JJ,KK,length(imask),length(imask));
Svp = speye(length(imask));
Svp = Svp(index_matrix(idx_c),:);
% When there is a neighbor on the left : backward differences
idx_c = find(Omega(:,:,4)>0);
[xc,yc] = ind2sub(size(mask),idx_c);
indices_centre = index_matrix(idx_c);
indices_right = index_matrix(sub2ind(size(mask),xc,yc-1));
indices_right = indices_right(:);
II = [indices_centre];
JJ = [indices_right];
KK = [-ones(length(indices_centre),1)];
II = [II;indices_centre];
JJ = [JJ;indices_centre];
KK = [KK;ones(length(indices_centre),1)];
Dvm = sparse(II,JJ,KK,length(imask),length(imask));
Svm = speye(length(imask));
Svm = Svm(index_matrix(idx_c),:);
% Du matrix
% When there is a neighbor on the bottom : forward differences
idx_c = find(Omega(:,:,1)>0);
[xc,yc] = ind2sub(size(mask),idx_c);
indices_centre = index_matrix(idx_c);
indices_right = index_matrix(sub2ind(size(mask),xc+1,yc));
indices_right = indices_right(:);
II = indices_centre;
JJ = indices_right;
KK = ones(length(indices_centre),1);
II = [II;indices_centre];
JJ = [JJ;indices_centre];
KK = [KK;-ones(length(indices_centre),1)];
Dup = sparse(II,JJ,KK,length(imask),length(imask));
Sup = speye(length(imask));
Sup = Sup(index_matrix(idx_c),:);
% When there is a neighbor on the top : backward differences
idx_c = find(Omega(:,:,2)>0);
[xc,yc] = ind2sub(size(mask),idx_c);
indices_centre = index_matrix(idx_c);
indices_right = index_matrix(sub2ind(size(mask),xc-1,yc));
indices_right = indices_right(:);
II = [indices_centre];
JJ = [indices_right];
KK = [-ones(length(indices_centre),1)];
II = [II;indices_centre];
JJ = [JJ;indices_centre];
KK = [KK;ones(length(indices_centre),1)];
Dum = sparse(II,JJ,KK,length(imask),length(imask));
Sum = speye(length(imask));
Sum = Sum(index_matrix(idx_c),:);
end
|
github
|
yqueau/shape_from_shading-master
|
WolfeLineSearch.m
|
.m
|
shape_from_shading-master/Toolbox/minFunc/minFunc/WolfeLineSearch.m
| 10,590 |
utf_8
|
f962bc5ae0a1e9f80202a9aaab106dab
|
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...
x,t,d,f,g,gtd,c1,c2,LS_interp,LS_multi,maxLS,progTol,debug,doPlot,saveHessianComp,funObj,varargin)
%
% Bracketing Line Search to Satisfy Wolfe Conditions
%
% Inputs:
% x: starting location
% t: initial step size
% d: descent direction
% f: function value at starting location
% g: gradient at starting location
% gtd: directional derivative at starting location
% c1: sufficient decrease parameter
% c2: curvature parameter
% debug: display debugging information
% LS_interp: type of interpolation
% maxLS: maximum number of iterations
% progTol: minimum allowable step length
% doPlot: do a graphical display of interpolation
% funObj: objective function
% varargin: parameters of objective function
%
% Outputs:
% t: step length
% f_new: function value at x+t*d
% g_new: gradient value at x+t*d
% funEvals: number function evaluations performed by line search
% H: Hessian at initial guess (only computed if requested
% Evaluate the Objective and Gradient at the Initial Step
if nargout == 5
[f_new,g_new,H] = funObj(x + t*d,varargin{:});
else
[f_new,g_new] = funObj(x+t*d,varargin{:});
end
funEvals = 1;
gtd_new = g_new'*d;
% Bracket an Interval containing a point satisfying the
% Wolfe criteria
LSiter = 0;
t_prev = 0;
f_prev = f;
g_prev = g;
gtd_prev = gtd;
nrmD = max(abs(d));
done = 0;
while LSiter < maxLS
%% Bracketing Phase
if ~isLegal(f_new) || ~isLegal(g_new)
if debug
fprintf('Extrapolated into illegal region, switching to Armijo line-search\n');
end
t = (t + t_prev)/2;
% Do Armijo
if nargout == 5
[t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...
x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,...
funObj,varargin{:});
else
[t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...
x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,...
funObj,varargin{:});
end
funEvals = funEvals + armijoFunEvals;
return;
end
if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)
bracket = [t_prev t];
bracketFval = [f_prev f_new];
bracketGval = [g_prev g_new];
break;
elseif abs(gtd_new) <= -c2*gtd
bracket = t;
bracketFval = f_new;
bracketGval = g_new;
done = 1;
break;
elseif gtd_new >= 0
bracket = [t_prev t];
bracketFval = [f_prev f_new];
bracketGval = [g_prev g_new];
break;
end
temp = t_prev;
t_prev = t;
minStep = t + 0.01*(t-temp);
maxStep = t*10;
if LS_interp <= 1
if debug
fprintf('Extending Braket\n');
end
t = maxStep;
elseif LS_interp == 2
if debug
fprintf('Cubic Extrapolation\n');
end
t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);
elseif LS_interp == 3
t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);
end
f_prev = f_new;
g_prev = g_new;
gtd_prev = gtd_new;
if ~saveHessianComp && nargout == 5
[f_new,g_new,H] = funObj(x + t*d,varargin{:});
else
[f_new,g_new] = funObj(x + t*d,varargin{:});
end
funEvals = funEvals + 1;
gtd_new = g_new'*d;
LSiter = LSiter+1;
end
if LSiter == maxLS
bracket = [0 t];
bracketFval = [f f_new];
bracketGval = [g g_new];
end
%% Zoom Phase
% We now either have a point satisfying the criteria, or a bracket
% surrounding a point satisfying the criteria
% Refine the bracket until we find a point satisfying the criteria
insufProgress = 0;
Tpos = 2;
LOposRemoved = 0;
while ~done && LSiter < maxLS
% Find High and Low Points in bracket
[f_LO LOpos] = min(bracketFval);
HIpos = -LOpos + 3;
% Compute new trial value
if LS_interp <= 1 || ~isLegal(bracketFval) || ~isLegal(bracketGval)
if debug
fprintf('Bisecting\n');
end
t = mean(bracket);
elseif LS_interp == 2
if debug
fprintf('Grad-Cubic Interpolation\n');
end
t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d
bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);
else
% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nonTpos = -Tpos+3;
if LOposRemoved == 0
oldLOval = bracket(nonTpos);
oldLOFval = bracketFval(nonTpos);
oldLOGval = bracketGval(:,nonTpos);
end
t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);
end
% Test that we are making sufficient progress
if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1
if debug
fprintf('Interpolation close to boundary');
end
if insufProgress || t>=max(bracket) || t <= min(bracket)
if debug
fprintf(', Evaluating at 0.1 away from boundary\n');
end
if abs(t-max(bracket)) < abs(t-min(bracket))
t = max(bracket)-0.1*(max(bracket)-min(bracket));
else
t = min(bracket)+0.1*(max(bracket)-min(bracket));
end
insufProgress = 0;
else
if debug
fprintf('\n');
end
insufProgress = 1;
end
else
insufProgress = 0;
end
% Evaluate new point
if ~saveHessianComp && nargout == 5
[f_new,g_new,H] = funObj(x + t*d,varargin{:});
else
[f_new,g_new] = funObj(x + t*d,varargin{:});
end
funEvals = funEvals + 1;
gtd_new = g_new'*d;
LSiter = LSiter+1;
armijo = f_new < f + c1*t*gtd;
if ~armijo || f_new >= f_LO
% Armijo condition not satisfied or not lower than lowest
% point
bracket(HIpos) = t;
bracketFval(HIpos) = f_new;
bracketGval(:,HIpos) = g_new;
Tpos = HIpos;
else
if abs(gtd_new) <= - c2*gtd
% Wolfe conditions satisfied
done = 1;
elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0
% Old HI becomes new LO
bracket(HIpos) = bracket(LOpos);
bracketFval(HIpos) = bracketFval(LOpos);
bracketGval(:,HIpos) = bracketGval(:,LOpos);
if LS_interp == 3
if debug
fprintf('LO Pos is being removed!\n');
end
LOposRemoved = 1;
oldLOval = bracket(LOpos);
oldLOFval = bracketFval(LOpos);
oldLOGval = bracketGval(:,LOpos);
end
end
% New point becomes new LO
bracket(LOpos) = t;
bracketFval(LOpos) = f_new;
bracketGval(:,LOpos) = g_new;
Tpos = LOpos;
end
if ~done && abs(bracket(1)-bracket(2))*nrmD < progTol
if debug
fprintf('Line-search bracket has been reduced below progTol\n');
end
break;
end
end
%%
if LSiter == maxLS
if debug
fprintf('Line Search Exceeded Maximum Line Search Iterations\n');
end
end
[f_LO LOpos] = min(bracketFval);
t = bracket(LOpos);
f_new = bracketFval(LOpos);
g_new = bracketGval(:,LOpos);
% Evaluate Hessian at new point
if nargout == 5 && funEvals > 1 && saveHessianComp
[f_new,g_new,H] = funObj(x + t*d,varargin{:});
funEvals = funEvals + 1;
end
end
%%
function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);
alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);
alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);
if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)
if debug
fprintf('Cubic Extrapolation\n');
end
t = alpha_c;
else
if debug
fprintf('Secant Extrapolation\n');
end
t = alpha_s;
end
end
%%
function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);
% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nonTpos = -Tpos+3;
gtdT = bracketGval(:,Tpos)'*d;
gtdNonT = bracketGval(:,nonTpos)'*d;
oldLOgtd = oldLOGval'*d;
if bracketFval(Tpos) > oldLOFval
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);
if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)
if debug
fprintf('Cubic Interpolation\n');
end
t = alpha_c;
else
if debug
fprintf('Mixed Quad/Cubic Interpolation\n');
end
t = (alpha_q + alpha_c)/2;
end
elseif gtdT'*oldLOgtd < 0
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) sqrt(-1) gtdT],doPlot);
if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))
if debug
fprintf('Cubic Interpolation\n');
end
t = alpha_c;
else
if debug
fprintf('Quad Interpolation\n');
end
t = alpha_s;
end
elseif abs(gtdT) <= abs(oldLOgtd)
alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],...
doPlot,min(bracket),max(bracket));
alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd
bracket(Tpos) bracketFval(Tpos) gtdT],...
doPlot,min(bracket),max(bracket));
if alpha_c > min(bracket) && alpha_c < max(bracket)
if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))
if debug
fprintf('Bounded Cubic Extrapolation\n');
end
t = alpha_c;
else
if debug
fprintf('Bounded Secant Extrapolation\n');
end
t = alpha_s;
end
else
if debug
fprintf('Bounded Secant Extrapolation\n');
end
t = alpha_s;
end
if bracket(Tpos) > oldLOval
t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);
else
t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);
end
else
t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT
bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);
end
end
|
github
|
yqueau/shape_from_shading-master
|
minFunc_processInputOptions.m
|
.m
|
shape_from_shading-master/Toolbox/minFunc/minFunc/minFunc_processInputOptions.m
| 4,103 |
utf_8
|
8822581c3541eabe5ce7c7927a57c9ab
|
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,optTol,progTol,method,...
corrections,c1,c2,LS_init,cgSolve,qnUpdate,cgUpdate,initialHessType,...
HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...
Damped,HvFunc,bbType,cycle,...
HessianIter,outputFcn,useMex,useNegCurv,precFunc,...
LS_type,LS_interp,LS_multi,DerivativeCheck] = ...
minFunc_processInputOptions(o)
% Constants
SD = 0;
CSD = 1;
BB = 2;
CG = 3;
PCG = 4;
LBFGS = 5;
QNEWTON = 6;
NEWTON0 = 7;
NEWTON = 8;
TENSOR = 9;
verbose = 1;
verboseI= 1;
debug = 0;
doPlot = 0;
method = LBFGS;
cgSolve = 0;
o = toUpper(o);
if isfield(o,'DISPLAY')
switch(upper(o.DISPLAY))
case 0
verbose = 0;
verboseI = 0;
case 'FINAL'
verboseI = 0;
case 'OFF'
verbose = 0;
verboseI = 0;
case 'NONE'
verbose = 0;
verboseI = 0;
case 'FULL'
debug = 1;
case 'EXCESSIVE'
debug = 1;
doPlot = 1;
end
end
DerivativeCheck = 0;
if isfield(o,'DERIVATIVECHECK')
switch(upper(o.DERIVATIVECHECK))
case 1
DerivativeCheck = 1;
case 'ON'
DerivativeCheck = 1;
end
end
LS_init = 0;
LS_type = 1;
LS_interp = 2;
LS_multi = 0;
Fref = 1;
Damped = 0;
HessianIter = 1;
c2 = 0.9;
if isfield(o,'METHOD')
m = upper(o.METHOD);
switch(m)
case 'TENSOR'
method = TENSOR;
case 'NEWTON'
method = NEWTON;
case 'MNEWTON'
method = NEWTON;
HessianIter = 5;
case 'PNEWTON0'
method = NEWTON0;
cgSolve = 1;
case 'NEWTON0'
method = NEWTON0;
case 'QNEWTON'
method = QNEWTON;
Damped = 1;
case 'LBFGS'
method = LBFGS;
case 'BB'
method = BB;
LS_type = 0;
Fref = 20;
case 'PCG'
method = PCG;
c2 = 0.2;
LS_init = 2;
case 'SCG'
method = CG;
c2 = 0.2;
LS_init = 4;
case 'CG'
method = CG;
c2 = 0.2;
LS_init = 2;
case 'CSD'
method = CSD;
c2 = 0.2;
Fref = 10;
LS_init = 2;
case 'SD'
method = SD;
LS_init = 2;
end
end
maxFunEvals = getOpt(o,'MAXFUNEVALS',1000);
maxIter = getOpt(o,'MAXITER',500);
optTol = getOpt(o,'OPTTOL',1e-5);
progTol = getOpt(o,'PROGTOL',1e-9);
corrections = getOpt(o,'CORRECTIONS',100);
corrections = getOpt(o,'CORR',corrections);
c1 = getOpt(o,'C1',1e-4);
c2 = getOpt(o,'C2',c2);
LS_init = getOpt(o,'LS_INIT',LS_init);
cgSolve = getOpt(o,'CGSOLVE',cgSolve);
qnUpdate = getOpt(o,'QNUPDATE',3);
cgUpdate = getOpt(o,'CGUPDATE',2);
initialHessType = getOpt(o,'INITIALHESSTYPE',1);
HessianModify = getOpt(o,'HESSIANMODIFY',0);
Fref = getOpt(o,'FREF',Fref);
useComplex = getOpt(o,'USECOMPLEX',0);
numDiff = getOpt(o,'NUMDIFF',0);
LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);
Damped = getOpt(o,'DAMPED',Damped);
HvFunc = getOpt(o,'HVFUNC',[]);
bbType = getOpt(o,'BBTYPE',0);
cycle = getOpt(o,'CYCLE',3);
HessianIter = getOpt(o,'HESSIANITER',HessianIter);
outputFcn = getOpt(o,'OUTPUTFCN',[]);
useMex = getOpt(o,'USEMEX',1);
useNegCurv = getOpt(o,'USENEGCURV',1);
precFunc = getOpt(o,'PRECFUNC',[]);
LS_type = getOpt(o,'LS_type',LS_type);
LS_interp = getOpt(o,'LS_interp',LS_interp);
LS_multi = getOpt(o,'LS_multi',LS_multi);
end
function [v] = getOpt(options,opt,default)
if isfield(options,opt)
if ~isempty(getfield(options,opt))
v = getfield(options,opt);
else
v = default;
end
else
v = default;
end
end
function [o] = toUpper(o)
if ~isempty(o)
fn = fieldnames(o);
for i = 1:length(fn)
o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
end
end
end
|
github
|
beckja/sgp4-matlab-master
|
dspace.m
|
.m
|
sgp4-matlab-master/dspace.m
| 7,880 |
utf_8
|
347493d5de5dfaf0d63365d060fe842f
|
% -----------------------------------------------------------------------------
%
% procedure dspace
%
% this procedure provides deep space contributions to mean elements for
% perturbing third body. these effects have been averaged over one
% revolution of the sun and moon. for earth resonance effects, the
% effects have been averaged over no revolutions of the satellite.
% (mean motion)
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 6, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 -
% dedt -
% del1, del2, del3 -
% didt -
% dmdt -
% dnodt -
% domdt -
% irez - flag for resonance 0-none, 1-one day, 2-half day
% argpo - argument of perigee
% argpdot - argument of perigee dot (rate)
% t - time
% tc -
% gsto - gst
% xfact -
% xlamo -
% no - mean motion
% atime -
% em - eccentricity
% ft -
% argpm - argument of perigee
% inclm - inclination
% xli -
% mm - mean anomaly
% xni - mean motion
% nodem - right ascension of ascending node
%
% outputs :
% atime -
% em - eccentricity
% argpm - argument of perigee
% inclm - inclination
% xli -
% mm - mean anomaly
% xni -
% nodem - right ascension of ascending node
% dndt -
% nm - mean motion
%
% locals :
% delt -
% ft -
% theta -
% x2li -
% x2omi -
% xl -
% xldot -
% xnddt -
% xndt -
% xomi -
%
% coupling :
% none -
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [ atime, em, argpm, inclm, xli, mm, xni,...
nodem, dndt, nm]...
= dspace(...
d2201, d2211, d3210, d3222, d4410, d4422, d5220,...
d5232, d5421, d5433, dedt, del1, del2, del3,...
didt, dmdt, dnodt, domdt, irez, argpo, argpdot,...
t, tc, gsto, xfact, xlamo, no, atime,...
em, argpm, inclm, xli, mm, xni, nodem,...
nm)
twopi = 2.0 * pi;
ft = 0.0;
fasx2 = 0.13130908;
fasx4 = 2.8843198;
fasx6 = 0.37448087;
g22 = 5.7686396;
g32 = 0.95240898;
g44 = 1.8014998;
g52 = 1.0508330;
g54 = 4.4108898;
rptim = 4.37526908801129966e-3;
stepp = 720.0;
stepn = -720.0;
step2 = 259200.0;
% /* ----------- calculate deep space resonance effects ----------- */
dndt = 0.0;
theta = rem(gsto + tc * rptim, twopi);
em = em + dedt * t;
inclm = inclm + didt * t;
argpm = argpm + domdt * t;
nodem = nodem + dnodt * t;
mm = mm + dmdt * t;
% // sgp4fix for negative inclinations
% // the following if statement should be commented out
% // if (inclm < 0.0)
% // {
% // inclm = -inclm;
% // argpm = argpm - pi;
% // nodem = nodem + pi;
% // }
% /* - update resonances : numerical (euler-maclaurin) integration - */
% /* ------------------------- epoch restart ---------------------- */
% // sgp4fix for propagator problems
% // the following integration works for negative time steps and periods
% // the specific changes are unknown because the original code was so convoluted
ft = 0.0;
atime = 0.0;
if (irez ~= 0)
if ((atime == 0.0) || ((t >= 0.0) && (atime < 0.0)) || ...
((t < 0.0) && (atime >= 0.0)))
if (t >= 0.0)
delt = stepp;
else
delt = stepn;
end
atime = 0.0;
xni = no;
xli = xlamo;
end
iretn = 381; %// added for do loop
iret = 0; %// added for loop
while (iretn == 381)
if ((abs(t) < abs(atime)) || (iret == 351))
if (t >= 0.0)
delt = stepn;
else
delt = stepp;
end
iret = 351;
iretn = 381;
else
if (t > 0.0) %// error if prev if has atime:=0.0 and t:=0.0 (ge)
delt = stepp;
else
delt = stepn;
end
if (abs(t - atime) >= stepp)
iret = 0;
iretn = 381;
else
ft = t - atime;
iretn = 0;
end
end
% /* ------------------- dot terms calculated ------------- */
% /* ----------- near - synchronous resonance terms ------- */
if (irez ~= 2)
xndt = del1 * sin(xli - fasx2) + del2 * sin(2.0 * (xli - fasx4)) +...
del3 * sin(3.0 * (xli - fasx6));
xldot = xni + xfact;
xnddt = del1 * cos(xli - fasx2) +...
2.0 * del2 * cos(2.0 * (xli - fasx4)) +...
3.0 * del3 * cos(3.0 * (xli - fasx6));
xnddt = xnddt * xldot;
else
% /* --------- near - half-day resonance terms -------- */
xomi = argpo + argpdot * atime;
x2omi = xomi + xomi;
x2li = xli + xli;
xndt = d2201 * sin(x2omi + xli - g22) + d2211 * sin(xli - g22) +...
d3210 * sin(xomi + xli - g32) + d3222 * sin(-xomi + xli - g32)+...
d4410 * sin(x2omi + x2li - g44)+ d4422 * sin(x2li - g44) +...
d5220 * sin(xomi + xli - g52) + d5232 * sin(-xomi + xli - g52)+...
d5421 * sin(xomi + x2li - g54) + d5433 * sin(-xomi + x2li - g54);
xldot = xni + xfact;
xnddt = d2201 * cos(x2omi + xli - g22) + d2211 * cos(xli - g22) +...
d3210 * cos(xomi + xli - g32) + d3222 * cos(-xomi + xli - g32) +...
d5220 * cos(xomi + xli - g52) + d5232 * cos(-xomi + xli - g52) +...
2.0 * (d4410 * cos(x2omi + x2li - g44) +...
d4422 * cos(x2li - g44) + d5421 * cos(xomi + x2li - g54) +...
d5433 * cos(-xomi + x2li - g54));
xnddt = xnddt * xldot;
end
% /* ----------------------- integrator ------------------- */
if (iretn == 381)
xli = xli + xldot * delt + xndt * step2;
xni = xni + xndt * delt + xnddt * step2;
atime = atime + delt;
end
end % // while iretn = 381
nm = xni + xndt * ft + xnddt * ft * ft * 0.5;
xl = xli + xldot * ft + xndt * ft * ft * 0.5;
if (irez ~= 1)
mm = xl - 2.0 * nodem + 2.0 * theta;
dndt = nm - no;
else
mm = xl - nodem - argpm+ theta;
dndt = nm - no;
end
nm = no + dndt;
end
global idebug dbgfile
if idebug
debug4;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
twoline2rv.m
|
.m
|
sgp4-matlab-master/twoline2rv.m
| 7,690 |
utf_8
|
847f10aaec770fb70b0cf6860cad87c7
|
% -----------------------------------------------------------------------------
%
% procedure twoline2rv
%
% this procedure converts the two line element set character string data to
% variables and initializes the sgp4 variables. several intermediate varaibles
% and quantities are determined. note that the result is a structure so multiple
% satellites can be worked simaltaneously without having to reinitialize. the
% verfiication mode is an important option that permits quick checks of any
% changes to the underlying technical theory. this option works using a
% modified tle file in which the start, stop, and delta time values are
% included at the end of the second line of data.
%
% Author:
% Jeff Beck
% [email protected]
% 1.1 (dec 5, 2006) - Corrected line 1, char 45 adjust. jab
% 1.0 (aug 6, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 1 mar 2001
%
% inputs :
% longstr1 - TLE character string (min 69 char)
% longstr2 - TLE character string (min 69 char)
% typerun - character for mode of SGP4 execution
% 'c' = catalog mode (propagates at 20 min timesteps from
% one day before epoch to one day after)
% 'v' = verification mode (propagates according to start,
% stop, and timestep specified in longstr2)
% 'n' = normal mode (prompts user for start, stop, and
% timestep for propagation)
%
% outputs :
% satrec - structure containing all the sgp4 satellite information
%
% coupling :
% getgravconst
% days2mdhms - conversion of days to month, day, hour, minute, second
% jday - convert day month year hour minute second into julian date
% sgp4init - initialize the sgp4 variables
%
% references :
% norad spacetrack report #3
% vallado et al. 2005
% ----------------------------------------------------------------------------*/
function [satrec, startmfe, stopmfe, deltamin] = twoline2rv(whichconst, longstr1, longstr2, typerun)
global tumin radiusearthkm xke j2 j3 j4 j3oj2
rad = 57.29577951308230; % [deg/rad]
xpdotp = 229.1831180523293; % = 1440/(2*pi) [rev/day]/[rad/min]
revnum = 0;
elnum = 0;
year = 0;
satrec.error = 0;
% // set the implied decimal points since doing a formated read
% // fixes for bad input data values (missing, ...)
for (j = 11:16)
if (longstr1(j) == ' ')
longstr1(j) = '_';
end
end
if (longstr1(45) ~= ' ')
longstr1(44) = longstr1(45);
end
longstr1(45) = '.';
if (longstr1(8) == ' ')
longstr1(8) = 'U';
end
if (longstr1(10) == ' ')
longstr1(10) = '.';
end
for (j = 46:50)
if (longstr1(j) == ' ')
longstr1(j) = '0';
end
end
if (longstr1(52) == ' ')
longstr1(52) = '0';
end
if (longstr1(54) ~= ' ')
longstr1(53) = longstr1(54);
end
longstr1(54) = '.';
longstr2(26) = '.';
for (j = 27:33)
if (longstr2(j) == ' ')
longstr2(j) = '0';
end
end
if (longstr1(63) == ' ')
longstr1(63) = '0';
end
if ((length(longstr1) < 68) || (longstr1(68) == ' '))
longstr1(68) = '0';
end
% parse first line
carnumb = str2num(longstr1(1));
satrec.satnum = str2num(longstr1(3:7));
classification = longstr1(8);
intldesg = longstr1(10:17);
satrec.epochyr = str2num(longstr1(19:20));
satrec.epochdays = str2num(longstr1(21:32));
satrec.ndot = str2num(longstr1(34:43));
satrec.nddot = str2num(longstr1(44:50));
nexp = str2num(longstr1(51:52));
satrec.bstar = str2num(longstr1(53:59));
ibexp = str2num(longstr1(60:61));
numb = str2num(longstr1(63));
elnum = str2num(longstr1(65:68));
% parse second line
if (typerun == 'v')
cardnumb = str2num(longstr2(1));
satrec.satnum = str2num(longstr2(3:7));
satrec.inclo = str2num(longstr2(8:16));
satrec.nodeo = str2num(longstr2(17:25));
satrec.ecco = str2num(longstr2(26:33));
satrec.argpo = str2num(longstr2(34:42));
satrec.mo = str2num(longstr2(43:51));
satrec.no = str2num(longstr2(52:63));
revnum = str2num(longstr2(64:68));
startmfe = str2num(longstr2(70:81));
stopmfe = str2num(longstr2(83:96));
deltamin = str2num(longstr2(97:105));
else
cardnumb = str2num(longstr2(1));
satrec.satnum = str2num(longstr2(3:7));
satrec.inclo = str2num(longstr2(8:16));
satrec.nodeo = str2num(longstr2(17:25));
satrec.ecco = str2num(longstr2(26:33));
satrec.argpo = str2num(longstr2(34:42));
satrec.mo = str2num(longstr2(43:51));
satrec.no = str2num(longstr2(52:63));
revnum = str2num(longstr2(64:68));
end
% // ---- find no, ndot, nddot ----
satrec.no = satrec.no / xpdotp; %//* rad/min
satrec.nddot= satrec.nddot * 10.0^nexp;
satrec.bstar= satrec.bstar * 10.0^ibexp;
% // ---- convert to sgp4 units ----
satrec.a = (satrec.no*tumin)^(-2/3); % [er]
satrec.ndot = satrec.ndot / (xpdotp*1440.0); % [rad/min^2]
satrec.nddot= satrec.nddot / (xpdotp*1440.0*1440); % [rad/min^3]
% // ---- find standard orbital elements ----
satrec.inclo = satrec.inclo / rad;
satrec.nodeo = satrec.nodeo / rad;
satrec.argpo = satrec.argpo / rad;
satrec.mo = satrec.mo / rad;
satrec.alta = satrec.a*(1.0 + satrec.ecco*satrec.ecco) - 1.0;
satrec.altp = satrec.a*(1.0 - satrec.ecco*satrec.ecco) - 1.0;
% // ----------------------------------------------------------------
% // find sgp4epoch time of element set
% // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch)
% // and minutes from the epoch (time)
% // --------------------------------------------------------------
% // input start stop times manually
if ((typerun ~= 'v') && (typerun ~= 'c'))
startmfe = input('input start mfe: ');
stopmfe = input('input stop mfe: ');
deltamin = input('input time step in minutes: ');
end
% // perform complete catalog evaluation
if (typerun == 'c')
startmfe = -1440.0;
stopmfe = 1440.0;
deltamin = 20.0;
end
% // ------------- temp fix for years from 1950-2049 ----------------
% // ------ correct fix will occur when year is 4-digit in 2le ------
if (satrec.epochyr < 50)
year= satrec.epochyr + 2000;
else
year= satrec.epochyr + 1900;
end
[mon,day,hr,minute,sec] = days2mdh ( year,satrec.epochdays );
satrec.jdsatepoch = jday( year,mon,day,hr,minute,sec );
% // ------------- initialize the orbit at sgp4epoch --------------
sgp4epoch = satrec.jdsatepoch - 2433281.5; % days since 0 Jan 1950
% JAB (060816): Changed back to using satrec to pass arguments.
% [satrec] = sgp4init(whichconst, satrec, satrec.bstar, satrec.ecco, sgp4epoch, ...
% satrec.argpo, satrec.inclo, satrec.mo, satrec.no, satrec.nodeo);
[satrec] = sgp4init(whichconst, satrec, sgp4epoch);
|
github
|
beckja/sgp4-matlab-master
|
dscom.m
|
.m
|
sgp4-matlab-master/dscom.m
| 8,536 |
utf_8
|
9d59d451aa72b865cf7d6f6f4d1a3901
|
% -----------------------------------------------------------------------------
%
% procedure dscom
%
% this procedure provides deep space common items used by both the secular
% and periodics subroutines. input is provided as shown. this routine
% used to be called dpper, but the functions inside weren't well organized.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% epoch -
% ep - eccentricity
% argpp - argument of perigee
% tc -
% inclp - inclination
% nodep - right ascension of ascending node
% np - mean motion
%
% outputs :
% sinim , cosim , sinomm , cosomm , snodm , cnodm
% day -
% e3 -
% ee2 -
% em - eccentricity
% emsq - eccentricity squared
% gam -
% peo -
% pgho -
% pho -
% pinco -
% plo -
% rtemsq -
% se2, se3 -
% sgh2, sgh3, sgh4 -
% sh2, sh3, si2, si3, sl2, sl3, sl4 -
% s1, s2, s3, s4, s5, s6, s7 -
% ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 -
% sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 -
% xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 -
% nm - mean motion
% z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 -
% zmol -
% zmos -
%
% locals :
% a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 -
% betasq -
% cc -
% ctem, stem -
% x1, x2, x3, x4, x5, x6, x7, x8 -
% xnodce -
% xnoi -
% zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl ,
% zcosi , zsini , zcosil , zsinil ,
% zx -
% zy -
%
% coupling :
% none.
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [ sinim,cosim,sinomm,cosomm,snodm,cnodm,day,e3,ee2,em,emsq,gam,...
peo,pgho,pho,pinco,plo,rtemsq,se2,se3,sgh2,sgh3,sgh4,sh2,sh3,si2,...
si3,sl2,sl3,sl4,s1,s2,s3,s4,s5,s6,s7,ss1,ss2,ss3,ss4,ss5,ss6,ss7,...
sz1,sz2,sz3,sz11,sz12,sz13,sz21,sz22,sz23,sz31,sz32,sz33,xgh2,xgh3,...
xgh4,xh2,xh3,xi2,xi3,xl2,xl3,xl4,nm,z1,z2,z3,z11,z12,z13,z21,z22,...
z23,z31,z32,z33,zmol,zmos]...
= dscom (epoch, ep, argpp, tc, inclp, nodep, np)
% /* -------------------------- constants ------------------------- */
zes = 0.01675;
zel = 0.05490;
c1ss = 2.9864797e-6;
c1l = 4.7968065e-7;
zsinis = 0.39785416;
zcosis = 0.91744867;
zcosgs = 0.1945905;
zsings = -0.98088458;
twopi = 2.0 * pi;
% /* --------------------- local variables ------------------------ */
nm = np;
em = ep;
snodm = sin(nodep);
cnodm = cos(nodep);
sinomm = sin(argpp);
cosomm = cos(argpp);
sinim = sin(inclp);
cosim = cos(inclp);
emsq = em * em;
betasq = 1.0 - emsq;
rtemsq = sqrt(betasq);
% /* ----------------- initialize lunar solar terms --------------- */
peo = 0.0;
pinco = 0.0;
plo = 0.0;
pgho = 0.0;
pho = 0.0;
day = epoch + 18261.5 + tc / 1440.0;
xnodce = rem(4.5236020 - 9.2422029e-4 * day, twopi);
stem = sin(xnodce);
ctem = cos(xnodce);
zcosil = 0.91375164 - 0.03568096 * ctem;
zsinil = sqrt(1.0 - zcosil * zcosil);
zsinhl = 0.089683511 * stem / zsinil;
zcoshl = sqrt(1.0 - zsinhl * zsinhl);
gam = 5.8351514 + 0.0019443680 * day;
zx = 0.39785416 * stem / zsinil;
zy = zcoshl * ctem + 0.91744867 * zsinhl * stem;
zx = atan2(zx, zy);
zx = gam + zx - xnodce;
zcosgl = cos(zx);
zsingl = sin(zx);
% /* ------------------------- do solar terms --------------------- */
zcosg = zcosgs;
zsing = zsings;
zcosi = zcosis;
zsini = zsinis;
zcosh = cnodm;
zsinh = snodm;
cc = c1ss;
xnoi = 1.0 / nm;
for (lsflg = 1:2)
a1 = zcosg * zcosh + zsing * zcosi * zsinh;
a3 = -zsing * zcosh + zcosg * zcosi * zsinh;
a7 = -zcosg * zsinh + zsing * zcosi * zcosh;
a8 = zsing * zsini;
a9 = zsing * zsinh + zcosg * zcosi * zcosh;
a10 = zcosg * zsini;
a2 = cosim * a7 + sinim * a8;
a4 = cosim * a9 + sinim * a10;
a5 = -sinim * a7 + cosim * a8;
a6 = -sinim * a9 + cosim * a10;
x1 = a1 * cosomm + a2 * sinomm;
x2 = a3 * cosomm + a4 * sinomm;
x3 = -a1 * sinomm + a2 * cosomm;
x4 = -a3 * sinomm + a4 * cosomm;
x5 = a5 * sinomm;
x6 = a6 * sinomm;
x7 = a5 * cosomm;
x8 = a6 * cosomm;
z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3;
z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4;
z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4;
z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq;
z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq;
z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq;
z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7-6.0 * x3 * x5);
z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq *...
(-24.0 * (x2 * x7 + x1 * x8) - 6.0 * (x3 * x6 + x4 * x5));
z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6);
z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7);
z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq *...
(24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8));
z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8);
z1 = z1 + z1 + betasq * z31;
z2 = z2 + z2 + betasq * z32;
z3 = z3 + z3 + betasq * z33;
s3 = cc * xnoi;
s2 = -0.5 * s3 / rtemsq;
s4 = s3 * rtemsq;
s1 = -15.0 * em * s4;
s5 = x1 * x3 + x2 * x4;
s6 = x2 * x3 + x1 * x4;
s7 = x2 * x4 - x1 * x3;
% /* ----------------------- do lunar terms ------------------- */
if (lsflg == 1)
ss1 = s1;
ss2 = s2;
ss3 = s3;
ss4 = s4;
ss5 = s5;
ss6 = s6;
ss7 = s7;
sz1 = z1;
sz2 = z2;
sz3 = z3;
sz11 = z11;
sz12 = z12;
sz13 = z13;
sz21 = z21;
sz22 = z22;
sz23 = z23;
sz31 = z31;
sz32 = z32;
sz33 = z33;
zcosg = zcosgl;
zsing = zsingl;
zcosi = zcosil;
zsini = zsinil;
zcosh = zcoshl * cnodm + zsinhl * snodm;
zsinh = snodm * zcoshl - cnodm * zsinhl;
cc = c1l;
end
end
zmol = rem(4.7199672 + 0.22997150 * day - gam, twopi);
zmos = rem(6.2565837 + 0.017201977 * day, twopi);
% /* ------------------------ do solar terms ---------------------- */
se2 = 2.0 * ss1 * ss6;
se3 = 2.0 * ss1 * ss7;
si2 = 2.0 * ss2 * sz12;
si3 = 2.0 * ss2 * (sz13 - sz11);
sl2 = -2.0 * ss3 * sz2;
sl3 = -2.0 * ss3 * (sz3 - sz1);
sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes;
sgh2 = 2.0 * ss4 * sz32;
sgh3 = 2.0 * ss4 * (sz33 - sz31);
sgh4 = -18.0 * ss4 * zes;
sh2 = -2.0 * ss2 * sz22;
sh3 = -2.0 * ss2 * (sz23 - sz21);
% /* ------------------------ do lunar terms ---------------------- */
ee2 = 2.0 * s1 * s6;
e3 = 2.0 * s1 * s7;
xi2 = 2.0 * s2 * z12;
xi3 = 2.0 * s2 * (z13 - z11);
xl2 = -2.0 * s3 * z2;
xl3 = -2.0 * s3 * (z3 - z1);
xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel;
xgh2 = 2.0 * s4 * z32;
xgh3 = 2.0 * s4 * (z33 - z31);
xgh4 = -18.0 * s4 * zel;
xh2 = -2.0 * s2 * z22;
xh3 = -2.0 * s2 * (z23 - z21);
global idebug dbgfile
if idebug
debug2;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
initl.m
|
.m
|
sgp4-matlab-master/initl.m
| 3,468 |
utf_8
|
bc9bed1f2a7eec0c0bebf4d4a2ff7b5e
|
% -----------------------------------------------------------------------------
%
% procedure initl
%
% this procedure initializes the spg4 propagator. all the initialization is
% consolidated here instead of having multiple loops inside other routines.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% ecco - eccentricity 0.0 - 1.0
% epoch - epoch time in days from jan 0, 1950. 0 hr
% inclo - inclination of satellite
% no - mean motion of satellite
% satn - satellite number
%
% outputs :
% ainv - 1.0 / a
% ao - semi major axis
% con41 -
% con42 - 1.0 - 5.0 cos(i)
% cosio - cosine of inclination
% cosio2 - cosio squared
% einv - 1.0 / e
% eccsq - eccentricity squared
% method - flag for deep space 'd', 'n'
% omeosq - 1.0 - ecco * ecco
% posq - semi-parameter squared
% rp - radius of perigee
% rteosq - square root of (1.0 - ecco*ecco)
% sinio - sine of inclination
% gsto - gst at time of observation rad
% no - mean motion of satellite
%
% locals :
% ak -
% d1 -
% del -
% adel -
% po -
%
% coupling :
% gstime - find greenwich sidereal time from the julian date
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [ ainv, ao, con41, con42, cosio, cosio2, einv,...
eccsq, method, omeosq, posq, rp, rteosq, sinio,...
gsto, no]...
= initl( ecco, epoch, inclo, no, satn)
% /* -------------------- wgs-72 earth constants ----------------- */
% // sgp4fix identify constants and allow alternate values
global tumin radiusearthkm xke j2 j3 j4 j3oj2
x2o3 = 2.0 / 3.0;
% /* ------------- calculate auxillary epoch quantities ---------- */
eccsq = ecco * ecco;
omeosq = 1.0 - eccsq;
rteosq = sqrt(omeosq);
cosio = cos(inclo);
cosio2 = cosio * cosio;
% /* ------------------ un-kozai the mean motion ----------------- */
ak = (xke / no)^x2o3;
d1 = 0.75 * j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq);
del = d1 / (ak * ak);
adel = ak * (1.0 - del * del - del *...
(1.0 / 3.0 + 134.0 * del * del / 81.0));
del = d1/(adel * adel);
no = no / (1.0 + del);
ao = (xke / no)^x2o3;
sinio = sin(inclo);
po = ao * omeosq;
con42 = 1.0 - 5.0 * cosio2;
con41 = -con42-cosio2-cosio2;
ainv = 1.0 / ao;
einv = 1.0 / ecco;
posq = po * po;
rp = ao * (1.0 - ecco);
method = 'n';
gsto = gstime(epoch + 2433281.5);
global idebug dbgfile
if isempty(idebug)
idebug = 0;
elseif idebug
debug5;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
sgp4.m
|
.m
|
sgp4-matlab-master/sgp4.m
| 11,728 |
utf_8
|
4a678ba2460bab657b90e30b4475d8fa
|
% -----------------------------------------------------------------------------
%
% procedure sgp4
%
% this procedure is the sgp4 prediction model from space command. this is an
% updated and combined version of sgp4 and sdp4, which were originally
% published separately in spacetrack report #3. this version follows the nasa
% release on the internet. there are a few fixes that are added to correct
% known errors in the existing implementations.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% satrec - initialised structure from sgp4init() call.
% tsince - time eince epoch (minutes)
%
% outputs :
% r - position vector km
% v - velocity km/sec
% return code - non-zero on error.
% 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er
% 2 - mean motion less than 0.0
% 3 - pert elements, ecc < 0.0 or ecc > 1.0
% 4 - semi-latus rectum < 0.0
% 5 - epoch elements are sub-orbital
% 6 - satellite has decayed
%
% locals :
% am -
% axnl, aynl -
% betal -
% COSIM , SINIM , COSOMM , SINOMM , Cnod , Snod , Cos2u ,
% Sin2u , Coseo1 , Sineo1 , Cosi , Sini , Cosip , Sinip ,
% Cosisq , Cossu , Sinsu , Cosu , Sinu
% Delm -
% Delomg -
% Dndt -
% Eccm -
% EMSQ -
% Ecose -
% El2 -
% Eo1 -
% Eccp -
% Esine -
% Argpm -
% Argpp -
% Omgadf -
% Pl -
% R -
% RTEMSQ -
% Rdotl -
% Rl -
% Rvdot -
% Rvdotl -
% Su -
% T2 , T3 , T4 , Tc
% Tem5, Temp , Temp1 , Temp2 , Tempa , Tempe , Templ
% U , Ux , Uy , Uz , Vx , Vy , Vz
% inclm - inclination
% mm - mean anomaly
% nm - mean motion
% nodem - longi of ascending node
% xinc -
% xincp -
% xl -
% xlm -
% mp -
% xmdf -
% xmx -
% xmy -
% nodedf -
% xnode -
% nodep -
% np -
%
% coupling :
% getgravconst
% dpper
% dspace
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [satrec, r, v] = sgp4(satrec,tsince);
% /* ------------------ set mathematical constants --------------- */
twopi = 2.0 * pi;
x2o3 = 2.0 / 3.0;
temp4 = 1.0 + cos(pi-1.0e-9);
% // sgp4fix identify constants and allow alternate values
global tumin radiusearthkm xke j2 j3 j4 j3oj2
vkmpersec = radiusearthkm * xke/60.0;
% /* --------------------- clear sgp4 error flag ----------------- */
satrec.t = tsince;
satrec.error = 0;
% /* ------- update for secular gravity and atmospheric drag ----- */
xmdf = satrec.mo + satrec.mdot * satrec.t;
argpdf = satrec.argpo + satrec.argpdot * satrec.t;
nodedf = satrec.nodeo + satrec.nodedot * satrec.t;
argpm = argpdf;
mm = xmdf;
t2 = satrec.t * satrec.t;
nodem = nodedf + satrec.nodecf * t2;
tempa = 1.0 - satrec.cc1 * satrec.t;
tempe = satrec.bstar * satrec.cc4 * satrec.t;
templ = satrec.t2cof * t2;
if (satrec.isimp ~= 1)
delomg = satrec.omgcof * satrec.t;
delm = satrec.xmcof *...
((1.0 + satrec.eta * cos(xmdf))^3 -...
satrec.delmo);
temp = delomg + delm;
mm = xmdf + temp;
argpm = argpdf - temp;
t3 = t2 * satrec.t;
t4 = t3 * satrec.t;
tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 -...
satrec.d4 * t4;
tempe = tempe + satrec.bstar * satrec.cc5 * (sin(mm) -...
satrec.sinmao);
templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof +...
satrec.t * satrec.t5cof);
end
nm = satrec.no;
em = satrec.ecco;
inclm = satrec.inclo;
if (satrec.method == 'd')
tc = satrec.t;
[satrec.atime,em,argpm,inclm,satrec.xli,mm,...
satrec.xni,nodem,dndt,nm] = dspace(...
satrec.d2201,satrec.d2211,satrec.d3210,...
satrec.d3222,satrec.d4410,satrec.d4422,...
satrec.d5220,satrec.d5232,satrec.d5421,...
satrec.d5433,satrec.dedt,satrec.del1,...
satrec.del2,satrec.del3,satrec.didt,...
satrec.dmdt,satrec.dnodt,satrec.domdt,...
satrec.irez,satrec.argpo,satrec.argpdot,satrec.t,...
tc,satrec.gsto,satrec.xfact,satrec.xlamo,satrec.no,...
satrec.atime,em,argpm,inclm,satrec.xli,mm,...
satrec.xni,nodem,nm);
end % // if method = d
if (nm <= 0.0)
% fprintf(1,'# error nm %f\n', nm);
satrec.error = 2;
end
am = (xke / nm)^x2o3 * tempa * tempa;
nm = xke / am^1.5;
em = em - tempe;
% // fix tolerance for error recognition
if ((em >= 1.0) || (em < -0.001) || (am < 0.95))
% fprintf(1,'# error em %f\n', em);
satrec.error = 1;
end
if (em < 0.0)
em = 1.0e-6;
end
mm = mm + satrec.no * templ;
xlm = mm + argpm + nodem;
emsq = em * em;
temp = 1.0 - emsq;
nodem = rem(nodem, twopi);
argpm = rem(argpm, twopi);
xlm = rem(xlm, twopi);
mm = rem(xlm - argpm - nodem, twopi);
% /* ----------------- compute extra mean quantities ------------- */
sinim = sin(inclm);
cosim = cos(inclm);
% /* -------------------- add lunar-solar periodics -------------- */
ep = em;
xincp = inclm;
argpp = argpm;
nodep = nodem;
mp = mm;
sinip = sinim;
cosip = cosim;
if (satrec.method == 'd')
[ep,xincp,nodep,argpp,mp] = dpper(...
satrec.e3,satrec.ee2,satrec.peo,...
satrec.pgho,satrec.pho,satrec.pinco,...
satrec.plo,satrec.se2,satrec.se3,...
satrec.sgh2,satrec.sgh3,satrec.sgh4,...
satrec.sh2,satrec.sh3,satrec.si2,...
satrec.si3,satrec.sl2,satrec.sl3,...
satrec.sl4,satrec.t,satrec.xgh2,...
satrec.xgh3,satrec.xgh4,satrec.xh2,...
satrec.xh3,satrec.xi2,satrec.xi3,...
satrec.xl2,satrec.xl3,satrec.xl4,...
satrec.zmol,satrec.zmos,satrec.inclo,...
satrec.init,ep,xincp,nodep,argpp,mp);
if (xincp < 0.0)
xincp = -xincp;
nodep = nodep + pi;
argpp = argpp - pi;
end
if ((ep < 0.0 ) || ( ep > 1.0))
% fprintf(1,'# error ep %f\n', ep);
satrec.error = 3;
end
end % // if method = d
% /* -------------------- long period periodics ------------------ */
if (satrec.method == 'd')
sinip = sin(xincp);
cosip = cos(xincp);
satrec.aycof = -0.5*j3oj2*sinip;
% // sgp4fix for divide by zero with xinco = 180 deg
if (abs(cosip+1.0) > 1.5e-12)
satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) /...
(1.0+cosip);
else
satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) /...
temp4;
end;
end
axnl = ep * cos(argpp);
temp = 1.0 / (am * (1.0 - ep * ep));
aynl = ep* sin(argpp) + temp * satrec.aycof;
xl = mp + argpp + nodep + temp * satrec.xlcof * axnl;
% /* --------------------- solve kepler's equation --------------- */
u = rem(xl - nodep, twopi);
eo1 = u;
tem5 = 9999.9;
ktr = 1;
% // sgp4fix for kepler iteration
% // the following iteration needs better limits on corrections
while (( abs(tem5) >= 1.0e-12) && (ktr <= 10) )
sineo1 = sin(eo1);
coseo1 = cos(eo1);
tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl;
tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5;
if(abs(tem5) >= 0.95)
if tem5 > 0.0
tem5 = 0.95;
else
tem5 = -0.95;
end
end
eo1 = eo1 + tem5;
ktr = ktr + 1;
end
% /* ------------- short period preliminary quantities ----------- */
ecose = axnl*coseo1 + aynl*sineo1;
esine = axnl*sineo1 - aynl*coseo1;
el2 = axnl*axnl + aynl*aynl;
pl = am*(1.0-el2);
if (pl < 0.0)
% fprintf(1,'# error pl %f\n', pl);
satrec.error = 4;
r = [0;0;0];
v = [0;0;0];
else
rl = am * (1.0 - ecose);
rdotl = sqrt(am) * esine/rl;
rvdotl = sqrt(pl) / rl;
betal = sqrt(1.0 - el2);
temp = esine / (1.0 + betal);
sinu = am / rl * (sineo1 - aynl - axnl * temp);
cosu = am / rl * (coseo1 - axnl + aynl * temp);
su = atan2(sinu, cosu);
sin2u = (cosu + cosu) * sinu;
cos2u = 1.0 - 2.0 * sinu * sinu;
temp = 1.0 / pl;
temp1 = 0.5 * j2 * temp;
temp2 = temp1 * temp;
% /* -------------- update for short period periodics ------------ */
if (satrec.method == 'd')
cosisq = cosip * cosip;
satrec.con41 = 3.0*cosisq - 1.0;
satrec.x1mth2 = 1.0 - cosisq;
satrec.x7thm1 = 7.0*cosisq - 1.0;
end
mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) +...
0.5 * temp1 * satrec.x1mth2 * cos2u;
su = su - 0.25 * temp2 * satrec.x7thm1 * sin2u;
xnode = nodep + 1.5 * temp2 * cosip * sin2u;
xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u;
mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / xke;
rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u +...
1.5 * satrec.con41) / xke;
% /* --------------------- orientation vectors ------------------- */
sinsu = sin(su);
cossu = cos(su);
snod = sin(xnode);
cnod = cos(xnode);
sini = sin(xinc);
cosi = cos(xinc);
xmx = -snod * cosi;
xmy = cnod * cosi;
ux = xmx * sinsu + cnod * cossu;
uy = xmy * sinsu + snod * cossu;
uz = sini * sinsu;
vx = xmx * cossu - cnod * sinsu;
vy = xmy * cossu - snod * sinsu;
vz = sini * cossu;
% /* --------- position and velocity (in km and km/sec) ---------- */
r(1) = (mrt * ux)* radiusearthkm;
r(2) = (mrt * uy)* radiusearthkm;
r(3) = (mrt * uz)* radiusearthkm;
v(1) = (mvt * ux + rvdot * vx) * vkmpersec;
v(2) = (mvt * uy + rvdot * vy) * vkmpersec;
v(3) = (mvt * uz + rvdot * vz) * vkmpersec;
% // sgp4fix for decaying satellites
if (mrt < 1.0)
% printf("# decay condition %11.6f \n",mrt);
satrec.error = 6;
end
end % // if pl > 0
global idebug dbgfile
if idebug
debug7;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
sgp4init.m
|
.m
|
sgp4-matlab-master/sgp4init.m
| 14,082 |
utf_8
|
e81058548e3f659b302e532f39a9d5eb
|
% -----------------------------------------------------------------------------
%
% procedure sgp4init
%
% this procedure initializes variables for sgp4.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% satn - satellite number
% bstar - sgp4 type drag coefficient kg/m2er
% ecco - eccentricity
% epoch - epoch time in days from jan 0, 1950. 0 hr
% argpo - argument of perigee (output if ds)
% inclo - inclination
% mo - mean anomaly (output if ds)
% no - mean motion
% nodeo - right ascension of ascending node
%
% outputs :
% satrec - common values for subsequent calls
% return code - non-zero on error.
% 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er
% 2 - mean motion less than 0.0
% 3 - pert elements, ecc < 0.0 or ecc > 1.0
% 4 - semi-latus rectum < 0.0
% 5 - epoch elements are sub-orbital
% 6 - satellite has decayed
%
% locals :
% CNODM , SNODM , COSIM , SINIM , COSOMM , SINOMM
% Cc1sq , Cc2 , Cc3
% Coef , Coef1
% cosio4 -
% day -
% dndt -
% em - eccentricity
% emsq - eccentricity squared
% eeta -
% etasq -
% gam -
% argpm - argument of perigee
% ndem -
% inclm - inclination
% mm - mean anomaly
% nm - mean motion
% perige - perigee
% pinvsq -
% psisq -
% qzms24 -
% rtemsq -
% s1, s2, s3, s4, s5, s6, s7 -
% sfour -
% ss1, ss2, ss3, ss4, ss5, ss6, ss7 -
% sz1, sz2, sz3
% sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 -
% tc -
% temp -
% temp1, temp2, temp3 -
% tsi -
% xpidot -
% xhdot1 -
% z1, z2, z3 -
% z11, z12, z13, z21, z22, z23, z31, z32, z33 -
%
% coupling :
% getgravconst
% initl -
% dscom -
% dpper -
% dsinit -
% sgp4 -
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
% JAB (060816): Change back to use satrec to pass arguments.
% function [satrec] = sgp4init(whichconst, satrec, xbstar, xecco, epoch, ...
% xargpo, xinclo, xmo, xno, xnodeo);
function [satrec] = sgp4init(whichconst, satrec, epoch);
% /* ------------------------ initialization --------------------- */
% /* ----------- set all near earth variables to zero ------------ */
satrec.isimp = 0; satrec.method = 'n'; satrec.aycof = 0.0;
satrec.con41 = 0.0; satrec.cc1 = 0.0; satrec.cc4 = 0.0;
satrec.cc5 = 0.0; satrec.d2 = 0.0; satrec.d3 = 0.0;
satrec.d4 = 0.0; satrec.delmo = 0.0; satrec.eta = 0.0;
satrec.argpdot = 0.0; satrec.omgcof = 0.0; satrec.sinmao = 0.0;
satrec.t = 0.0; satrec.t2cof = 0.0; satrec.t3cof = 0.0;
satrec.t4cof = 0.0; satrec.t5cof = 0.0; satrec.x1mth2 = 0.0;
satrec.x7thm1 = 0.0; satrec.mdot = 0.0; satrec.nodedot = 0.0;
satrec.xlcof = 0.0; satrec.xmcof = 0.0; satrec.nodecf = 0.0;
% /* ----------- set all deep space variables to zero ------------ */
satrec.irez = 0; satrec.d2201 = 0.0; satrec.d2211 = 0.0;
satrec.d3210 = 0.0; satrec.d3222 = 0.0; satrec.d4410 = 0.0;
satrec.d4422 = 0.0; satrec.d5220 = 0.0; satrec.d5232 = 0.0;
satrec.d5421 = 0.0; satrec.d5433 = 0.0; satrec.dedt = 0.0;
satrec.del1 = 0.0; satrec.del2 = 0.0; satrec.del3 = 0.0;
satrec.didt = 0.0; satrec.dmdt = 0.0; satrec.dnodt = 0.0;
satrec.domdt = 0.0; satrec.e3 = 0.0; satrec.ee2 = 0.0;
satrec.peo = 0.0; satrec.pgho = 0.0; satrec.pho = 0.0;
satrec.pinco = 0.0; satrec.plo = 0.0; satrec.se2 = 0.0;
satrec.se3 = 0.0; satrec.sgh2 = 0.0; satrec.sgh3 = 0.0;
satrec.sgh4 = 0.0; satrec.sh2 = 0.0; satrec.sh3 = 0.0;
satrec.si2 = 0.0; satrec.si3 = 0.0; satrec.sl2 = 0.0;
satrec.sl3 = 0.0; satrec.sl4 = 0.0; satrec.gsto = 0.0;
satrec.xfact = 0.0; satrec.xgh2 = 0.0; satrec.xgh3 = 0.0;
satrec.xgh4 = 0.0; satrec.xh2 = 0.0; satrec.xh3 = 0.0;
satrec.xi2 = 0.0; satrec.xi3 = 0.0; satrec.xl2 = 0.0;
satrec.xl3 = 0.0; satrec.xl4 = 0.0; satrec.xlamo = 0.0;
satrec.zmol = 0.0; satrec.zmos = 0.0; satrec.atime = 0.0;
satrec.xli = 0.0; satrec.xni = 0.0;
% JAB (060816): Change back to use satrec to pass values.
% % sgp4fix - note the following variables are also passed directly via satrec.
% % it is possible to streamline the sgp4init call by deleting the "x"
% % variables, but the user would need to set the satrec.* values first. we
% % include the additional assignment in case twoline2rv is not used.
% satrec.bstar = xbstar;
% satrec.ecco = xecco;
% satrec.argpo = xargpo;
% satrec.inclo = xinclo;
% satrec.mo = xmo;
% satrec.no = xno;
% satrec.nodeo = xnodeo;
% /* -------------------- wgs-72 earth constants ----------------- */
% // sgp4fix identify constants and allow alternate values
global tumin radiusearthkm xke j2 j3 j4 j3oj2
[tumin, radiusearthkm, xke, j2, j3, j4, j3oj2] = getgravc( whichconst );
ss = 78.0 / radiusearthkm + 1.0;
qzms2t = ((120.0 - 78.0) / radiusearthkm)^4;
x2o3 = 2.0 / 3.0;
temp4 = 1.0 + cos(pi-1.0e-9);
satrec.init = 'y';
satrec.t = 0.0;
[ainv, ao, satrec.con41, con42, cosio, cosio2, einv, eccsq,...
satrec.method, omeosq, posq, rp, rteosq, sinio,...
satrec.gsto, satrec.no]...
= initl(...
satrec.ecco, epoch, satrec.inclo, satrec.no,...
satrec.satnum);
satrec.error = 0;
if (rp < 1.0)
% printf("# *** satn%d epoch elts sub-orbital ***\n", satn);
satrec.error = 5;
end
if ((omeosq >= 0.0 ) | ( satrec.no >= 0.0))
satrec.isimp = 0;
if (rp < (220.0 / radiusearthkm + 1.0))
satrec.isimp = 1;
end
sfour = ss;
qzms24 = qzms2t;
perige = (rp - 1.0) * radiusearthkm;
% /* - for perigees below 156 km, s and qoms2t are altered - */
if (perige < 156.0)
sfour = perige - 78.0;
if (perige < 98.0)
sfour = 20.0;
end
qzms24 = ((120.0 - sfour) / radiusearthkm)^4.0;
sfour = sfour / radiusearthkm + 1.0;
end
pinvsq = 1.0 / posq;
tsi = 1.0 / (ao - sfour);
satrec.eta = ao * satrec.ecco * tsi;
etasq = satrec.eta * satrec.eta;
eeta = satrec.ecco * satrec.eta;
psisq = abs(1.0 - etasq);
coef = qzms24 * tsi^4.0;
coef1 = coef / psisq^3.5;
cc2 = coef1 * satrec.no * (ao * (1.0 + 1.5 * etasq + eeta *...
(4.0 + etasq)) + 0.375 * j2 * tsi / psisq * satrec.con41 *...
(8.0 + 3.0 * etasq * (8.0 + etasq)));
satrec.cc1 = satrec.bstar * cc2;
cc3 = 0.0;
if (satrec.ecco > 1.0e-4)
cc3 = -2.0 * coef * tsi * j3oj2 * satrec.no * sinio / satrec.ecco;
end
satrec.x1mth2 = 1.0 - cosio2;
satrec.cc4 = 2.0* satrec.no * coef1 * ao * omeosq *...
(satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco *...
(0.5 + 2.0 * etasq) - j2 * tsi / (ao * psisq) *...
(-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq *...
(1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 *...
(2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * satrec.argpo)));
satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 *...
(etasq + eeta) + eeta * etasq);
cosio4 = cosio2 * cosio2;
temp1 = 1.5 * j2 * pinvsq * satrec.no;
temp2 = 0.5 * temp1 * j2 * pinvsq;
temp3 = -0.46875 * j4 * pinvsq * pinvsq * satrec.no;
satrec.mdot = satrec.no + 0.5 * temp1 * rteosq * satrec.con41 +...
0.0625 * temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4);
satrec.argpdot = -0.5 * temp1 * con42 + 0.0625 * temp2 *...
(7.0 - 114.0 * cosio2 + 395.0 * cosio4) +...
temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4);
xhdot1 = -temp1 * cosio;
satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) +...
2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio;
xpidot = satrec.argpdot+ satrec.nodedot;
satrec.omgcof = satrec.bstar * cc3 * cos(satrec.argpo);
satrec.xmcof = 0.0;
if (satrec.ecco > 1.0e-4)
satrec.xmcof = -x2o3 * coef * satrec.bstar / eeta;
end
satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1;
satrec.t2cof = 1.5 * satrec.cc1;
% // sgp4fix for divide by zero with xinco = 180 deg
if (abs(cosio+1.0) > 1.5e-12)
satrec.xlcof = -0.25 * j3oj2 * sinio *...
(3.0 + 5.0 * cosio) / (1.0 + cosio);
else
satrec.xlcof = -0.25 * j3oj2 * sinio *...
(3.0 + 5.0 * cosio) / temp4;
end
satrec.aycof = -0.5 * j3oj2 * sinio;
satrec.delmo = (1.0 + satrec.eta * cos(satrec.mo))^3;
satrec.sinmao = sin(satrec.mo);
satrec.x7thm1 = 7.0 * cosio2 - 1.0;
% /* --------------- deep space initialization ------------- */
if ((2*pi / satrec.no) >= 225.0)
satrec.method = 'd';
satrec.isimp = 1;
tc = 0.0;
inclm = satrec.inclo;
[sinim,cosim,sinomm,cosomm,snodm,cnodm,day,satrec.e3,satrec.ee2,...
em,emsq,gam,satrec.peo,satrec.pgho,satrec.pho,satrec.pinco,...
satrec.plo,rtemsq,satrec.se2,satrec.se3,satrec.sgh2,...
satrec.sgh3,satrec.sgh4,satrec.sh2,satrec.sh3,satrec.si2,...
satrec.si3,satrec.sl2,satrec.sl3,satrec.sl4,s1,s2,s3,s4,s5,...
s6,s7,ss1,ss2,ss3,ss4,ss5,ss6,ss7,sz1,sz2,sz3,sz11,sz12,...
sz13,sz21,sz22,sz23,sz31,sz32,sz33,satrec.xgh2,satrec.xgh3,...
satrec.xgh4,satrec.xh2,satrec.xh3,satrec.xi2,satrec.xi3,...
satrec.xl2,satrec.xl3,satrec.xl4,nm,z1,z2,z3,z11,z12,z13,...
z21,z22,z23,z31,z32,z33,satrec.zmol,satrec.zmos] = ...
dscom(epoch,satrec.ecco,satrec.argpo,tc,satrec.inclo,...
satrec.nodeo,satrec.no);
[satrec.ecco,satrec.inclo,satrec.nodeo,satrec.argpo,satrec.mo]...
= dpper(satrec.e3,satrec.ee2,satrec.peo,satrec.pgho,...
satrec.pho,satrec.pinco,satrec.plo,satrec.se2,satrec.se3,...
satrec.sgh2,satrec.sgh3,satrec.sgh4,satrec.sh2,satrec.sh3,...
satrec.si2,satrec.si3,satrec.sl2,satrec.sl3,satrec.sl4,...
satrec.t,satrec.xgh2,satrec.xgh3,satrec.xgh4,satrec.xh2,...
satrec.xh3,satrec.xi2,satrec.xi3,satrec.xl2,satrec.xl3,...
satrec.xl4,satrec.zmol,satrec.zmos,inclm,satrec.init,...
satrec.ecco,satrec.inclo,satrec.nodeo,satrec.argpo,satrec.mo);
argpm = 0.0;
nodem = 0.0;
mm = 0.0;
[em,argpm,inclm,mm,nm,nodem,satrec.irez,satrec.atime,...
satrec.d2201,satrec.d2211,satrec.d3210,satrec.d3222,...
satrec.d4410,satrec.d4422,satrec.d5220,satrec.d5232,...
satrec.d5421,satrec.d5433,satrec.dedt,satrec.didt,...
satrec.dmdt,dndt,satrec.dnodt,satrec.domdt,satrec.del1,...
satrec.del2,satrec.del3,...
... %ses,sghl,sghs,sgs,shl,shs,sis,sls,theta,...
satrec.xfact,satrec.xlamo,satrec.xli,satrec.xni] ...
= dsinit(...
cosim,emsq,satrec.argpo,s1,s2,s3,s4,s5,sinim,ss1,ss2,ss3,...
ss4,ss5,sz1,sz3,sz11,sz13,sz21,sz23,sz31,sz33,satrec.t,tc,...
satrec.gsto,satrec.mo,satrec.mdot,satrec.no,satrec.nodeo,...
satrec.nodedot,xpidot,z1,z3,z11,z13,z21,z23,z31,z33,em,...
argpm,inclm,mm,nm,nodem,satrec.ecco,eccsq);
end
% /* ----------- set variables if not deep space ----------- */
if (satrec.isimp ~= 1)
cc1sq = satrec.cc1 * satrec.cc1;
satrec.d2 = 4.0 * ao * tsi * cc1sq;
temp = satrec.d2 * tsi * satrec.cc1 / 3.0;
satrec.d3 = (17.0 * ao + sfour) * temp;
satrec.d4 = 0.5 * temp * ao * tsi *...
(221.0 * ao + 31.0 * sfour) * satrec.cc1;
satrec.t3cof = satrec.d2 + 2.0 * cc1sq;
satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 *...
(12.0 * satrec.d2 + 10.0 * cc1sq));
satrec.t5cof = 0.2 * (3.0 * satrec.d4 +...
12.0 * satrec.cc1 * satrec.d3 +...
6.0 * satrec.d2 * satrec.d2 +...
15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq));
end
end % // if omeosq = 0 ...
% /* finally propogate to zero epoch to initialise all others. */
if(satrec.error == 0)
[satrec, r, v] = sgp4(satrec, 0.0);
end
satrec.init = 'n';
global idebug dbgfile
if idebug
debug6;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
dsinit.m
|
.m
|
sgp4-matlab-master/dsinit.m
| 11,670 |
utf_8
|
da55f2ee28e1972f38a6439b8ffb42cb
|
% -----------------------------------------------------------------------------
%
% procedure dsinit
%
% this procedure provides deep space contributions to mean motion dot due
% to geopotential resonance with half day and one day orbits.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% Cosim, Sinim-
% Emsq - Eccentricity squared
% Argpo - Argument of Perigee
% S1, S2, S3, S4, S5 -
% Ss1, Ss2, Ss3, Ss4, Ss5 -
% Sz1, Sz3, Sz11, Sz13, Sz21, Sz23, Sz31, Sz33 -
% T - Time
% Tc -
% GSTo - Greenwich sidereal time rad
% Mo - Mean Anomaly
% MDot - Mean Anomaly dot (rate)
% No - Mean Motion
% nodeo - right ascension of ascending node
% nodeDot - right ascension of ascending node dot (rate)
% XPIDOT -
% Z1, Z3, Z11, Z13, Z21, Z23, Z31, Z33 -
% Eccm - Eccentricity
% Argpm - Argument of perigee
% Inclm - Inclination
% Mm - Mean Anomaly
% Xn - Mean Motion
% nodem - right ascension of ascending node
%
% outputs :
% em - eccentricity
% argpm - argument of perigee
% inclm - inclination
% mm - mean anomaly
% nm - mean motion
% nodem - right ascension of ascending node
% irez - flag for resonance 0-none, 1-one day, 2-half day
% atime -
% d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 -
% dedt -
% didt -
% dmdt -
% dndt -
% dnodt -
% domdt -
% del1, del2, del3 -
% Ses , Sghl , Sghs , Sgs , Shl , Shs , Sis , Sls
% theta -
% xfact -
% xlamo -
% xli -
% xni
%
% locals :
% ainv2 -
% aonv -
% cosisq -
% eoc -
% f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 -
% g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 -
% sini2 -
% temp -
% temp1 -
% theta -
% xno2 -
%
% coupling :
% getgravconst
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [ em, argpm, inclm, mm, nm, nodem, irez,...
atime, d2201, d2211, d3210, d3222, d4410, d4422,...
d5220, d5232, d5421, d5433, dedt, didt, dmdt,...
dndt, dnodt, domdt, del1, del2, del3, xfact,...
xlamo, xli, xni]...
= dsinit( ...
cosim, emsq, argpo, s1, s2, s3, s4,...
s5, sinim, ss1, ss2, ss3, ss4, ss5,...
sz1, sz3, sz11, sz13, sz21, sz23, sz31,...
sz33, t, tc, gsto, mo, mdot, no,...
nodeo, nodedot, xpidot, z1, z3, z11,...
z13, z21, z23, z31, z33, em, argpm,...
inclm, mm, nm, nodem, ecco, eccsq)
% /* --------------------- local variables ------------------------ */
twopi = 2.0 * pi;
aonv = 0.0;
q22 = 1.7891679e-6;
q31 = 2.1460748e-6;
q33 = 2.2123015e-7;
root22 = 1.7891679e-6;
root44 = 7.3636953e-9;
root54 = 2.1765803e-9;
rptim = 4.37526908801129966e-3;
root32 = 3.7393792e-7;
root52 = 1.1428639e-7;
x2o3 = 2.0 / 3.0;
znl = 1.5835218e-4;
zns = 1.19459e-5;
% // sgp4fix identify constants and allow alternate values
global tumin radiusearthkm xke j2 j3 j4 j3oj2
% /* -------------------- deep space initialization ------------ */
irez = 0;
if ((nm < 0.0052359877) && (nm > 0.0034906585))
irez = 1;
end
if ((nm >= 8.26e-3) && (nm <= 9.24e-3) && (em >= 0.5))
irez = 2;
end
d2201 = 0;
d2211 = 0;
d3210 = 0;
d3222 = 0;
d4410 = 0;
d4422 = 0;
d5220 = 0;
d5232 = 0;
d5421 = 0;
d5433 = 0;
del1 = 0;
del2 = 0;
del3 = 0;
atime = 0;
xfact = 0;
xlamo = 0;
xli = 0;
xni = 0;
% /* ------------------------ do solar terms ------------------- */
ses = ss1 * zns * ss5;
sis = ss2 * zns * (sz11 + sz13);
sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq);
sghs = ss4 * zns * (sz31 + sz33 - 6.0);
shs = -zns * ss2 * (sz21 + sz23);
% // sgp4fix for 180 deg incl
if ((inclm < 5.2359877e-2) | (inclm > pi - 5.2359877e-2))
shs = 0.0;
end
if (sinim ~= 0.0)
shs = shs / sinim;
end
sgs = sghs - cosim * shs;
% /* ------------------------- do lunar terms ------------------ */
dedt = ses + s1 * znl * s5;
didt = sis + s2 * znl * (z11 + z13);
dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq);
sghl = s4 * znl * (z31 + z33 - 6.0);
shll = -znl * s2 * (z21 + z23);
% // sgp4fix for 180 deg incl
if ((inclm < 5.2359877e-2) | (inclm > pi - 5.2359877e-2))
shll = 0.0;
end
domdt = sgs + sghl;
dnodt = shs;
if (sinim ~= 0.0)
domdt = domdt - cosim / sinim * shll;
dnodt = dnodt + shll / sinim;
end
% /* ----------- calculate deep space resonance effects -------- */
dndt = 0.0;
theta = rem(gsto + tc * rptim, twopi);
em = em + dedt * t;
inclm = inclm + didt * t;
argpm = argpm + domdt * t;
nodem = nodem + dnodt * t;
mm = mm + dmdt * t;
% // sgp4fix for negative inclinations
% // the following if statement should be commented out
% //if (inclm < 0.0)
% // {
% // inclm = -inclm;
% // argpm = argpm - pi;
% // nodem = nodem + pi;
% // }
% /* -------------- initialize the resonance terms ------------- */
if (irez ~= 0)
aonv = (nm / xke)^x2o3;
% /* ---------- geopotential resonance for 12 hour orbits ------ */
if (irez == 2)
cosisq = cosim * cosim;
emo = em;
em = ecco;
emsqo = emsq;
emsq = eccsq;
eoc = em * emsq;
g201 = -0.306 - (em - 0.64) * 0.440;
if (em <= 0.65)
g211 = 3.616 - 13.2470 * em + 16.2900 * emsq;
g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc;
g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc;
g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc;
g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc;
g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc;
else
g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc;
g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc;
g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc;
g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc;
g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc;
if (em > 0.715)
g520 =-5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc;
else
g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq;
end
end
if (em < 0.7)
g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc;
g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc;
g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc;
else
g533 =-37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc;
g521 =-51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc;
g532 =-40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc;
end
sini2= sinim * sinim;
f220 = 0.75 * (1.0 + 2.0 * cosim+cosisq);
f221 = 1.5 * sini2;
f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq);
f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq);
f441 = 35.0 * sini2 * f220;
f442 = 39.3750 * sini2 * sini2;
f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim- 5.0 * cosisq) +...
0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq) );
f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim +...
10.0 * cosisq) + 6.56250012 * (1.0+2.0 * cosim - 3.0 * cosisq));
f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim+cosisq *...
(-12.0 + 8.0 * cosim + 10.0 * cosisq));
f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim+cosisq *...
(12.0 + 8.0 * cosim - 10.0 * cosisq));
xno2 = nm * nm;
ainv2 = aonv * aonv;
temp1 = 3.0 * xno2 * ainv2;
temp = temp1 * root22;
d2201 = temp * f220 * g201;
d2211 = temp * f221 * g211;
temp1 = temp1 * aonv;
temp = temp1 * root32;
d3210 = temp * f321 * g310;
d3222 = temp * f322 * g322;
temp1 = temp1 * aonv;
temp = 2.0 * temp1 * root44;
d4410 = temp * f441 * g410;
d4422 = temp * f442 * g422;
temp1 = temp1 * aonv;
temp = temp1 * root52;
d5220 = temp * f522 * g520;
d5232 = temp * f523 * g532;
temp = 2.0 * temp1 * root54;
d5421 = temp * f542 * g521;
d5433 = temp * f543 * g533;
xlamo = rem(mo + nodeo + nodeo-theta - theta, twopi);
xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no;
em = emo;
emsq = emsqo;
end
% /* ---------------- synchronous resonance terms -------------- */
if (irez == 1)
g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq);
g310 = 1.0 + 2.0 * emsq;
g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq);
f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim);
f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim);
f330 = 1.0 + cosim;
f330 = 1.875 * f330 * f330 * f330;
del1 = 3.0 * nm * nm * aonv * aonv;
del2 = 2.0 * del1 * f220 * g200 * q22;
del3 = 3.0 * del1 * f330 * g300 * q33 * aonv;
del1 = del1 * f311 * g310 * q31 * aonv;
xlamo = rem(mo + nodeo + argpo - theta, twopi);
xfact = mdot + xpidot - rptim + dmdt + domdt + dnodt - no;
end
% /* ------------ for sgp4, initialize the integrator ---------- */
xli = xlamo;
xni = no;
atime = 0.0;
nm = no + dndt;
end
global idebug dbgfile
if idebug
debug3;
end
return;
|
github
|
beckja/sgp4-matlab-master
|
getgravc.m
|
.m
|
sgp4-matlab-master/getgravc.m
| 2,528 |
utf_8
|
ae2503a6d6bc8364024c498f6aa53c1d
|
% -----------------------------------------------------------------------------
%
% function getgravc
%
% this function gets constants for the propagator. note that mu is identified to
% facilitiate comparisons with newer models.
%
% author : david vallado 719-573-2600 21 jul 2006
%
% inputs :
% whichconst - which set of constants to use 721, 72, 84
%
% outputs :
% tumin - minutes in one time unit
% radiusearthkm - radius of the earth in km
% xke - reciprocal of tumin
% j2, j3, j4 - un-normalized zonal harmonic values
% j3oj2 - j3 divided by j2
%
% locals :
% mu - earth gravitational parameter
%
% coupling :
%
% references :
% norad spacetrack report #3
% vallado, crawford, hujsak, kelso 2006
% [tumin, radiusearthkm, xke, j2, j3, j4, j3oj2] = getgravc(whichconst);
% --------------------------------------------------------------------------- */
function [tumin, radiusearthkm, xke, j2, j3, j4, j3oj2] = getgravc(whichconst);
global tumin radiusearthkm xke j2 j3 j4 j3oj2
switch whichconst
case 721
% -- wgs-72 low precision str#3 constants --
radiusearthkm = 6378.135; %// km
xke = 0.0743669161;
tumin = 1.0 / xke;
j2 = 0.001082616;
j3 = -0.00000253881;
j4 = -0.00000165597;
j3oj2 = j3 / j2;
case 72
% ------------ wgs-72 constants ------------
mu = 398600.8; %// in km3 / s2
radiusearthkm = 6378.135; %// km
xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu);
tumin = 1.0 / xke;
j2 = 0.001082616;
j3 = -0.00000253881;
j4 = -0.00000165597;
j3oj2 = j3 / j2;
case 84
% ------------ wgs-84 constants ------------
mu = 398600.5; %// in km3 / s2
radiusearthkm = 6378.137; %// km
xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu);
tumin = 1.0 / xke;
j2 = 0.00108262998905;
j3 = -0.00000253215306;
j4 = -0.00000161098761;
j3oj2 = j3 / j2;
otherwise
printf('unknown gravity option (%d)\n',whichconst);
end; % case
|
github
|
beckja/sgp4-matlab-master
|
dpper.m
|
.m
|
sgp4-matlab-master/dpper.m
| 6,425 |
utf_8
|
68de1aa803b8f81da5d8c912ea768925
|
% -----------------------------------------------------------------------------
%
% procedure dpper
%
% this procedure provides deep space long period periodic contributions
% to the mean elements. by design, these periodics are zero at epoch.
% this used to be dscom which included initialization, but it's really a
% recurring function.
%
% Author:
% Jeff Beck
% [email protected]
% 1.0 (aug 7, 2006) - update for paper dav
% original comments from Vallado C++ version:
% author : david vallado 719-573-2600 28 jun 2005
%
% inputs :
% e3 -
% ee2 -
% peo -
% pgho -
% pho -
% pinco -
% plo -
% se2 , se3 , Sgh2, Sgh3, Sgh4, Sh2, Sh3, Si2, Si3, Sl2, Sl3, Sl4 -
% t -
% xh2, xh3, xi2, xi3, xl2, xl3, xl4 -
% zmol -
% zmos -
% ep - eccentricity 0.0 - 1.0
% inclo - inclination - needed for lyddane modification
% nodep - right ascension of ascending node
% argpp - argument of perigee
% mp - mean anomaly
%
% outputs :
% ep - eccentricity 0.0 - 1.0
% inclp - inclination
% nodep - right ascension of ascending node
% argpp - argument of perigee
% mp - mean anomaly
%
% locals :
% alfdp -
% betdp -
% cosip , sinip , cosop , sinop ,
% dalf -
% dbet -
% dls -
% f2, f3 -
% pe -
% pgh -
% ph -
% pinc -
% pl -
% sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis ,
% sll , sls
% xls -
% xnoh -
% zf -
% zm -
%
% coupling :
% none.
%
% references :
% hoots, roehrich, norad spacetrack report #3 1980
% hoots, norad spacetrack report #6 1986
% hoots, schumacher and glover 2004
% vallado, crawford, hujsak, kelso 2006
% ----------------------------------------------------------------------------*/
function [ ep, inclp, nodep, argpp, mp]...
= dpper(...
e3, ee2, peo, pgho, pho, pinco, plo, se2,...
se3, sgh2, sgh3, sgh4, sh2, sh3, si2, si3,...
sl2, sl3, sl4, t, xgh2, xgh3, xgh4, xh2,...
xh3, xi2, xi3, xl2, xl3, xl4, zmol,...
zmos, inclo, init, ep, inclp, nodep, argpp, mp)
% /* --------------------- local variables ------------------------ */
twopi = 2.0 * pi;
% /* ---------------------- constants ----------------------------- */
zns = 1.19459e-5;
zes = 0.01675;
znl = 1.5835218e-4;
zel = 0.05490;
% /* --------------- calculate time varying periodics ----------- */
zm = zmos + zns * t;
% // be sure that the initial call has time set to zero
if (init == 'y')
zm = zmos;
end
zf = zm + 2.0 * zes * sin(zm);
sinzf = sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * cos(zf);
ses = se2* f2 + se3 * f3;
sis = si2 * f2 + si3 * f3;
sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf;
sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf;
shs = sh2 * f2 + sh3 * f3;
zm = zmol + znl * t;
if (init == 'y')
zm = zmol;
end
zf = zm + 2.0 * zel * sin(zm);
sinzf = sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * cos(zf);
sel = ee2 * f2 + e3 * f3;
sil = xi2 * f2 + xi3 * f3;
sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf;
sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf;
shll = xh2 * f2 + xh3 * f3;
pe = ses + sel;
pinc = sis + sil;
pl = sls + sll;
pgh = sghs + sghl;
ph = shs + shll;
if (init == 'n')
% // 0.2 rad = 11.45916 deg
% // sgp4fix for lyddane choice
% // add next four lines to set up use of original inclination per strn3 ver
ildm = 'y';
if (inclo >= 0.2)
ildm = 'n';
end
pe = pe - peo;
pinc = pinc - pinco;
pl = pl - plo;
pgh = pgh - pgho;
ph = ph - pho;
inclp = inclp + pinc;
ep = ep + pe;
sinip = sin(inclp);
cosip = cos(inclp);
% /* ----------------- apply periodics directly ------------ */
% // sgp4fix for lyddane choice
% // strn3 used original inclination - this is technically feasible
% // gsfc used perturbed inclination - also technically feasible
% // probably best to readjust the 0.2 limit value and limit discontinuity
% // use next line for original strn3 approach and original inclination
% // if (inclo >= 0.2)
% // use next line for gsfc version and perturbed inclination
if (inclp >= 0.2)
ph = ph / sinip;
pgh = pgh - cosip * ph;
argpp = argpp + pgh;
nodep = nodep + ph;
mp = mp + pl;
else
% /* ---- apply periodics with lyddane modification ---- */
sinop = sin(nodep);
cosop = cos(nodep);
alfdp = sinip * sinop;
betdp = sinip * cosop;
dalf = ph * cosop + pinc * cosip * sinop;
dbet = -ph * sinop + pinc * cosip * cosop;
alfdp = alfdp + dalf;
betdp = betdp + dbet;
nodep = rem(nodep, twopi);
xls = mp + argpp + cosip * nodep;
dls = pl + pgh - pinc * nodep * sinip;
xls = xls + dls;
xnoh = nodep;
nodep = atan2(alfdp, betdp);
if (abs(xnoh - nodep) > pi)
if (nodep < xnoh)
nodep = nodep + twopi;
else
nodep = nodep - twopi;
end
end
mp = mp + pl;
argpp = xls - mp - cosip * nodep;
end
end % // if init == 'n'
global idebug dbgfile
if idebug
debug1;
end
return;
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
RunSegment.m
|
.m
|
Shape-Appearance-Model-master/RunSegment.m
| 1,836 |
utf_8
|
46624029608ef5ccac13d7c99650b8fc
|
function RunSegment
% Segment a bunch of images to generate "imported" versions.
% This is a very simple function for doing this.
images = spm_select(Inf,'nifti');
parfor i=1:size(images,1)
image = deblank(images(i,:));
fprintf('Segmenting %s... ', image);
tic
do_seg(image)
fprintf('...%g s\n', toc);
end
function do_seg(image)
clear obj
obj.bb = NaN(2,3);
obj.bb = [-90 -126 -72; 90 90 108];
obj.vox = 2;
obj.cleanup = 1;
obj.mrf = 2;
obj.affreg = 'mni';
obj.reg = [0 0.001 0.5 0.05 0.2]*0.1;
obj.fwhm = 1;
obj.samp = 3;
obj.biasreg = 0.001*(1/5);
obj.biasfwhm = 60;
tpmname = fullfile(spm('dir'),'tpm','TPM.nii');
obj.lkp = [1 1 2 2 3 3 4 4 5 5 5 6 6];
obj.tpm = spm_load_priors8(tpmname);
obj.image = spm_vol(char(image));
M = obj.image(1).mat;
c = (obj.image(1).dim+1)/2;
obj.image(1).mat(1:3,4) = -M(1:3,1:3)*c(:);
[Affine1,ll1] = spm_maff8(obj.image(1),8,(0+1)*16,obj.tpm,[],obj.affreg); % Closer to rigid
Affine1 = Affine1*(obj.image(1).mat/M);
obj.image(1).mat = M;
% Run using the origin from the header
[Affine2,ll2] = spm_maff8(obj.image(1),8,(0+1)*16,obj.tpm,[],obj.affreg); % Closer to rigid
% Pick the result with the best fit
if ll1>ll2
obj.Affine = Affine1;
else
obj.Affine = Affine2;
end
% Initial affine registration.
obj.Affine = spm_maff8(obj.image(1),obj.samp*2,(obj.fwhm+1)*16,obj.tpm, obj.Affine, obj.affreg); % Closer to rigid
obj.Affine = spm_maff8(obj.image(1),obj.samp*2, obj.fwhm, obj.tpm, obj.Affine, obj.affreg);
% Run the actual segmentation
res = spm_preproc8(obj);
% Final iteration, so write out the required data.
required = false(max(obj.lkp),4);
required(1:3,2) = true;
spm_preproc_write8(res,required,false(1,2),false(1,2),obj.mrf,obj.cleanup,obj.bb,obj.vox,'.');
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
PG.m
|
.m
|
Shape-Appearance-Model-master/PG.m
| 5,032 |
utf_8
|
2a7dc384d9b8af45b4366ac123830288
|
function PG(dat,s)
% Combined principal geodesic analysis and generalized(ish) PCA
% FORMAT PG(dat,s)
% dat - a data structure containing filenames etc
% s - various settings
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
spm_field('boundary',0);
spm_diffeo('boundary',0);
if nargin<2
s = dat;
end
if ~isfield(s,'continue') || s.continue==false
if ~exist('s','var'), error('No settings'); end
PGdistribute('init',s);
PGdistribute('share',dat);
% Start from scratch
[s0,s1,s2,mat] = PGdistribute('SuffStats',s);
s.vx = sqrt(sum(mat(1:3,1:3).^2));
[mu,noise] = ComputeMean(s0,s1,s2,s);
d = [size(mu) 1 1];
[mu_fa,Wa,Wv,WWa,WWv,WW] = CreateBases(s,mu,mat);
K = size(WW,1);
PGdistribute('RandomZ',K);
[ss.N,ss.Z,ss.ZZ,ss.S] = PGdistribute('GetZZ');
PGdistribute('AddToZ',-ss.Z/ss.N);
ss.ZZ = ss.ZZ - ss.Z*ss.Z'/ss.N;
ss.Z = ss.Z*0;
[U,S] = svd(ss.ZZ);
Rz = sqrt(ss.N)*U/sqrtm(S);
%Rz = U/sqrtm(S);
ss.ZZ = Rz'*ss.ZZ*Rz;
ss.S = Rz'*ss.S *Rz;
PGdistribute('TransfZ',Rz');
[ss.N,ss.Z,ss.ZZ,ss.S] = PGdistribute('GetZZ');
s.omega = 1;
else
% Continue from previous results
new_s = s;
load(fullfile(s.result_dir,['train' s.result_name '.mat']),...
'Wa','Wv','WWa','WWv','mat','dat','ss','A','B','mu','s','noise','dat');
d = [size(mu) 1 1];
if isfield(new_s,'nu_factor')
s.nu_factor = new_s.nu_factor;
noise.nu_factor = s.nu_factor;
end
if isfield(new_s,'v_settings')
s.v_settings = new_s.v_settings;
end
if isfield(new_s,'a_settings')
s.a_settings = new_s.a_settings;
end
if isfield(new_s,'mu_settings')
s.mu_settings = new_s.mu_settings;
end
% Should really include some checks here
PGdistribute('init',s);
PGdistribute('share',dat);
[ss.N,ss.Z,ss.ZZ,ss.S] = PGdistribute('GetZZ');
Cv = eye(size(ss.ZZ))*max(diag(ss.ZZ))/ss.N*0.1; % Break symmetry if necessary
PGdistribute('AddRandZ',Cv);
[ss.N,ss.Z,ss.ZZ,ss.S] = PGdistribute('GetZZ');
WWa = UpdateWWa(Wa,s);
WWv = UpdateWWv(Wv,s);
[Wa,Wv,WWa,WWv,ss,~] = OrthAll(Wa,Wv,WWa,WWv,ss,s);
end
if ~isfield(s,'lambda'), s.lambda = [1 1]; end
maxit = 15; if isfield(s,'maxit'), maxit = s.maxit; end
[A,B,lb_qA,lb_pA,ldA] = SetReg(ss.ZZ+ss.S,ss.N,s);
lb_A = lb_pA - lb_qA;
if isfield(s,'debug') && s.debug
subplot(2,2,1); image(ColourPic(mu,s.likelihood)); axis image ij off;
drawnow
end
for iter = 1:maxit
fprintf('%-3d ', iter);
[Wa,Wv,WW,s.omega] = Mstep(mu,Wa,Wv,noise,B,ss.ZZ,A,WWa,WWv,s);
lb_pW = -0.5*trace(B*WW); % + const
RegZ = double(s.lambda(1)*A + s.lambda(2)*WW);
ss = PGdistribute('UpdateLatentVariables',mu,Wa,Wv,noise,RegZ,s);
lb_L = [ss.L(1) ss.L(3)];
noise = NoiseModel(ss,s,d);
% Zero-mean Z and recompute the mean mu
% fprintf(' (%g,%g) ', norm(ss.Z/ss.N),sqrt(trace(ss.ZZ)/ss.N));
PGdistribute('AddToZ',-ss.Z/ss.N);
ss.ZZ = ss.ZZ - ss.Z*ss.Z'/ss.N;
ss.Z = ss.Z*0;
[ss.gmu,ss.Hmu,~] = PGdistribute('MeanDerivatives',mu,Wa,Wv,noise,s);
[mu,lb_pmu] = UpdateMu(mu,ss.gmu,ss.Hmu,ss.N,s);
if isfield(s,'ondisk') && s.ondisk
mu_fa(:) = mu(:);
end
if isfield(s,'debug') && s.debug
subplot(2,2,1); image(ColourPic(mu,s.likelihood)); axis image ij off;
subplot(2,2,2); imagesc(abs(ss.ZZ)/ss.N); colorbar; axis image; title ZZ
subplot(2,2,3); imagesc(abs(WW)); colorbar; axis image; title WW
subplot(2,2,4); imagesc(abs(WWv)); colorbar; axis image; title WWv
drawnow
end
lb = lb_L(1) + s.lambda(1)*(lb_A + 0.5*ss.N*ldA) + s.lambda(1)*lb_pW + lb_pmu + noise.lb_lam;
fprintf('%9.6g %7.4g %9.6g %9.6g %9.6g %9.6g\n',...
(ss.L(1)+s.lambda(1)*lb_pW), s.omega, s.lambda(1)*(lb_A + 0.5*ss.N*ldA), s.lambda(1)*lb_pW + lb_pmu + noise.lb_lam, lb, lb+lb_L(2));
WWa = UpdateWWa(Wa,s);
WWv = UpdateWWv(Wv,s);
[Wa,Wv,WWa,WWv,ss,WW] = OrthAll(Wa,Wv,WWa,WWv,ss,s);
[A,B,lb_qA,lb_pA,ldA] = SetReg(ss.ZZ-ss.Z'*ss.Z/ss.N+ss.S,ss.N,s);
lb_A = lb_pA - lb_qA;
RegZ = double(s.lambda(1)*A + s.lambda(2)*WW);
dat = PGdistribute('Collect');
save(fullfile(s.result_dir,['train' s.result_name '.mat']),...
'Wa','Wv','WWa','WWv','mat','dat','ss','A','B','RegZ','mu','s','noise','dat','-v7.3');
if isfield(s,'debug') && s.debug
subplot(2,2,1); image(ColourPic(mu,s.likelihood)); axis image ij off;
subplot(2,2,2); imagesc(abs(ss.ZZ)/ss.N); colorbar; axis image; title ZZ
subplot(2,2,3); imagesc(abs(WW)); colorbar; axis image; title WW
subplot(2,2,4); imagesc(abs(WWv)); colorbar; axis image; title WWv
drawnow
end
end
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
UpdateZpar.m
|
.m
|
Shape-Appearance-Model-master/UpdateZpar.m
| 10,887 |
utf_8
|
9aa54220e670de9748ac5e9db0e85705
|
function [z,S,L,omisc] = UpdateZpar(z,f,mu,Wa,Wv,A,s,noise)
% Update latent variables for all images
% FORMAT [z,S,L,omisc] = UpdateZpar(z,f,mu,Wa,Wv,A,s,noise)
%
% z - Cell array of latent variables
% f - Cell array of observations
% mu - Mean
% Wa - Appearance basis functions
% Wv - Shape basis functions
% A - Precision matrix of z (assumed zero mean)
% s - Settings. Uses s.v_settings, s.nit, s.vx & s.int_args
% noise - Noise precision (Gaussian model only)
%
% S - Covariance of uncertainty of z (Laplace approximation)
% L - Log-likelihood
% omisc - An assortment of statistics
%
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
%CompSmo = false;
%CompMu = false;
a0 = GetA0(z,Wa,mu); % Compute linear combination of appearance modes
v0 = GetV0(z,Wv); % Linear combination of shape components
psi = GetPsi(v0,s);
subj = struct('f',f,'z',z,'a0',a0,'v0',v0,'psi',psi,'a',[],'Ha',[],'g',[],'H1',[],'nll',[],'S',[],'dz',[],'da',[],'dv',[],'stop',false);
A = double(A); % Use double
K = size(A,1);
for subit=1:s.nit
parfor n=1:numel(subj)
if ~subj(n).stop
subj(n).g = 0; % Gradients
subj(n).H1 = 0; % Hessian
[ll,subj(n).a,subj(n).Ha] = LikelihoodDerivatives(subj(n).f,subj(n).a0,subj(n).psi,noise,s);
subj(n).nll = -ll + 0.5*subj(n).z'*A*subj(n).z;
end
end
for x3=1:size(Wv,3)
% Work slice by slice to save memory
wa = Wa(:,:,x3,:,:);
wv = Wv(:,:,x3,:,:);
% Passing lots of data (broadcast variables) within the parfor may be slowing things down
parfor n=1:numel(subj)
if ~subj(n).stop
[dg,dh] = SliceComp(subj(n).z,subj(n).a(:,:,x3,:),subj(n).Ha(:,:,x3,:),subj(n).a0,x3,wa,wv,s);
subj(n).g = subj(n).g + double(dg);
subj(n).H1 = subj(n).H1 + double(dh);
end
end
end
parfor n=1:numel(subj)
if ~subj(n).stop
subj(n).H1 = (subj(n).H1+subj(n).H1')/2; % Ensure totally symmetric (rounding errors)
% This should not be needed, but can be an extra layer of protection if the shooting explodes
if any(~isfinite(subj(n).g(:))) || any(~isfinite(subj(n).H1(:)))
subj(n).g(~isfinite(subj(n).g)) = 0;
subj(n).H1(~isfinite(subj(n).H1)) = 0;
end
g = subj(n).g + double(A*subj(n).z); % Add prior term of gradient
H = subj(n).H1 + double(A); % Add prior term of hessian
R = (max(diag(H))*1e-9)*eye(K); % Regularisation done in case H is singular
H = H+R;
subj(n).S = inv(H); % S encodes the uncertainty of the z estimates (Laplace approximation)
subj(n).dz = H\g; % Search direction for updating z
end
end
da0 = GetA0({subj(:).dz},Wa);
dv0 = GetV0({subj(:).dz},Wv);
parfor n=1:numel(subj)
if ~subj(n).stop
% A Gauss-Newton update can sometimes overshoot, so a backtracking (Armijo) linesearch
% is used to ensure the objective function improves.
[subj(n).z,nll,misc] = LineSearch(subj(n).z,subj(n).nll,subj(n).dz,subj(n).a0,da0{n},subj(n).v0,dv0{n},subj(n).f,noise,A,s);
% If there's an a0 field, then the linesearch has found a better solution, so save some of
% the stuff that has been computed, ready for the next iteration.
if isfield(misc,'a0')
subj(n).a0 = misc.a0;
subj(n).v0 = misc.v0;
subj(n).psi = misc.psi;
if abs(nll-subj(n).nll)<1e-3
subj(n).stop = true;
end
subj(n).nll = nll;
else
subj(n).stop = true;
end
end
end
if all(cat(1,subj.stop)), break; end
end
z = {subj.z};
S = {subj.S};
% Update the log-likelihood to include the 1/sqrt((2*pi)^d det|Sigma|) part of the Gaussian
% distribution of the prior, as well as a Laplace approximation for p(f|M) = \int_z p(f,z|M) dz
% See Section 4.4 of Bishop's book, where the Laplace approximation is described for
% use in model comparison.
L = [0 0 0];
for n=1:numel(subj)
L = L + [-subj(n).nll, (0.5*LogDet(A)-0.5*K*log(2*pi)), (0.5*LogDet(subj(n).S) + 0.5*K*log(2*pi))];
end
if nargout>=4
% If necessary, compute some extra stuff that is used for the learning part of the model
omisc = struct('s0',0,'s1',0);
%if CompSmo
% omisc.SmoSuf = 0;
%end
%if CompMu
% omisc.gmu = single(0);
% omisc.Hmu = single(0);
%end
for n=1:numel(subj)
%if CompSmo
% % Compute sufficient statistics used for estimating the smoothness of the residuals.
% % These are used for adjusting the number of observations via a bit of random field theory.
% [s0,s1,SmoSuf] = ComputeSmoSuf(subj(n).f,subj(n).a0,subj(n).psi,s);
% omisc.SmoSuf = omisc.SmoSuf + SmoSuf;
%else
[s0,s1] = ComputeSmoSuf(subj(n).f,subj(n).a0,subj(n).psi,s);
%end
% This was originally an adjustment to the sufficient statistics for computing the noise (Gaussian npoise model).
% The idea was to make a Bayesian estimate that accounts for the uncertainty with which
% z is estimated. In practice though, the effect is tiny compared to the lack of independence
% of the neighbouring voxels.
% if false % Fix later
% switch lower(s.likelihood)
% case {'normal','gaussian'}
% % Adjustment for uncertainty in z
% s1 = s1 + trace(H\H1)/noise.lam;
% end
% end
omisc.s1 = omisc.s1 + s1;
omisc.s0 = omisc.s0 + s0;
%if CompMu
% % Sufficient statistics that are used for recomouting the mean
% [gmu,Hmu] = LikelihoodDerivatives(subj(n).f,subj(n).a0,subj(n).psi,noise,s);
% omisc.gmu = omisc.gmu + gmu;
% omisc.Hmu = omisc.Hmu + Hmu;
%end
end
end
%==========================================================================
%
%==========================================================================
function [g,H1] = SliceComp(z,a,Ha,a0,x3,wa,wv,s)
g = 0;
H1 = 0;
d = [size(a0) 1 1]; % Ensure dimensions are a 1x4 vector
d = d(1:4);
Ka = size(wa,5); % Number of appearance modes
Kv = size(wv,5); % Number of shape modes
if numel(z)==Ka+Kv
% Shape and appearance are combined and controlled together
K = Ka+Kv;
Koff = Ka;
else
% Shape and appearance controlled by separate z elements
K = Ka;
Koff = 0;
end
% Basis functions encoding appearance modes, or derivatives w.r.t. warps
% This encodes derivatives of f1 w.r.t z (ignoring scaling by Jacobians) - df1/dz
B = zeros(prod([d(1:2) d(4:end)]),K);
% Fill in appearance modes
B(:,1:size(wa,5)) = reshape(wa,[prod(d([1,2,4])) size(wa,5)]);
% Fill in derivatives w.r.t. warps
tmp = zeros([d(1:2) 1 d(4:end) Kv],'single');
for l=1:d(4)
g1 = (a0([2:end, 1],:,x3,l) - a0([end, 1:(end-1)],:,x3,l))/2;
g2 = (a0(:,[2:end, 1],x3,l) - a0(:,[end, 1:(end-1)],x3,l))/2;
g3 = (a0(:,:,rem(x3+1+d(3)-1,d(3))+1,l) - a0(:,:,rem(x3-1+d(3)-1,d(3))+1,l))/2;
tmp(:,:,1,l,:) = bsxfun(@times,wv(:,:,1,1,:),-g1)...
+ bsxfun(@times,wv(:,:,1,2,:),-g2)...
+ bsxfun(@times,wv(:,:,1,3,:),-g3);
end
B(:,(1:Kv)+Koff) = B(:,(1:Kv)+Koff) + reshape(tmp,[prod(d([1 2 4])) Kv]);
B = reshape(B,[prod(d([1,2,4])),K]); % Reshape for easier matrix-vector multiplication
g = g + double(B'*a(:)); % dE/dz = dE/df1 * df1/dz
% Compute Hessian
switch lower(s.likelihood)
case {'multinomial','categorical'}
% Computations are slightly different for the multinomial (categorical) noise model
ind = Horder(d(4)); % Not all fields of Ha are saved, as it is a field of symmetric matrices (c.f. standard interview question about 1+2+3+4+...)
B = reshape(B,[d(1)*d(2),d(4),K]);
for l1=1:d(4)
B2l = reshape(B(:,l1,:),[d(1)*d(2),K]);
B1lt = B2l';
hal = Ha(:,:,1,ind(l1,l1));
H1 = H1 + double(B1lt*bsxfun(@times,hal(:),B2l));
for l2=(l1+1):d(4)
B2l = reshape(B(:,l2,:),[d(1)*d(2),K]);
hal = Ha(:,:,1,ind(l1,l2));
H1 = H1 + 2*double(B1lt*bsxfun(@times,hal(:),B2l));
end
end
otherwise
% Simpler computations as each component can be treated separately (ie a field of diagonal matrices)
B = reshape(B,[d(1)*d(2),d(4),K]);
for l=1:d(4)
Bl = reshape(B(:,l,:),[d(1)*d(2),K]);
hal = Ha(:,:,1,l);
H1 = H1 + double(Bl'*bsxfun(@times,hal(:),Bl));
end
end
%==========================================================================
%
%==========================================================================
function [z,nll,misc] = LineSearch(oz,onll,dz,a0o,da0,v0o,dv0,f,noise,A,s)
verb = isfield(s,'verbose') && s.verbose;
if verb, fprintf(' %g ', onll); end
misc = struct; % Some intermediate computations may be returned (if a better solution is found)
armijo = 1; % Line-search parameter is decreased until objective function improves
nsubit = 6; % Maximum number of halvings
for subit = 1:nsubit
z = oz - armijo*dz;
if numel(da0)>0
a0 = a0o - armijo*da0;
else
a0 = a0o;
end
if numel(dv0)>0
v0 = v0o - armijo*dv0;
psi = GetPsi(v0,s); % Could achieve slight speedup by precomputing the kernel
else
v0 = v0o;
psi = [];
end
nll = -LikelihoodDerivatives(f,a0,psi,noise,s) + 0.5*z'*A*z;
if verb, fprintf(' %g', nll); end %ShowPic(f,a0,psi,mu,s); end
if nll>onll && abs(nll-onll)/abs(nll) > 1e-6
armijo = armijo*0.5;
else
misc.a0 = a0;
misc.v0 = v0;
misc.psi = psi;
if verb, fprintf('\n'); end
return;
end
end
z = oz;
nll = onll;
if verb, fprintf('\n'); end
%==========================================================================
%
%==========================================================================
%function ShowPic(f,a0,psi,mu,s)
%%return; % This function is disabled
%
%a1 = Pull(a0,psi);
%mu1 = Pull(mu,psi);
%
%msk = ~isfinite(f);
%ff = f;
%switch lower(s.likelihood)
%case {'multinomial','categorical'}
% sig = SoftMax(a1);
%case {'binomial','binary'}
% sig = 1./(1+exp(-a1));
%otherwise % case {'normal','gaussian'}
% sig = a1;
%end
%ff(msk) = sig(msk);
%
%imagesc([ColourPic(ff) ColourPic(a1,s.likelihood) ColourPic(mu1,s.likelihood)]);
%axis image ij off; drawnow; %set(gca,'CLim',[0 1]); drawnow
%
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
ShapeDerivatives.m
|
.m
|
Shape-Appearance-Model-master/ShapeDerivatives.m
| 5,129 |
utf_8
|
59874b2be246eebdea37d2415bbbeba4
|
function [gv,Hv,nll] = ShapeDerivatives(dat,mu,Wa,Wv,noise,s)
% Return derivatives w.r.t. shape basis functions
% FORMAT [gv,Hv,nll] = ShapeDerivatives(dat,mu,Wa,Wv,noise,s)
%
% dat - Structure containing various information about each image.
% Fields for each image n are:
% dat(n).f - Image data.
% dat(n).z - Expectations of latent variables.
% dat(n).S - Covariances of latent variables.
% mu - Mean.
% Wa - Appearance basis functions.
% Wv - Shape basis functions.
% noise - Noise information.
% s - Settings. Uses s.likelihood, s.ondisk, s.result_dir and
% s.result_name.
%
% gv - Gradients for updating Wv.
% Hv - Hessians for updating Wv.
% nll - Negative log-likelihood.
%
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
if isempty(dat), gv = []; Hv = []; nll = 0; return; end
Kv = size(Wv,5);
Ka = size(Wa,5);
K = size(dat(1).z,1);
if (Ka == Kv) && (Ka == K)
Koff = 0;
else
Koff = Ka;
end
if Kv==0, gv = zeros([Kv 0],'single'); Hv = []; nll = []; return; end
d = [size(mu) 1 1];
d = d(1:4);
batchsize = 1;
if isfield(s,'batchsize'), batchsize = s.batchsize; end
if isfield(s,'ondisk') && s.ondisk
gv = file_array(fullfile(s.result_dir,[s.result_name '_gv.dat']), [d(1:3) 3 Kv],'float32',352);
Hv = file_array(fullfile(s.result_dir,[s.result_name '_Hv.dat']), [d(1:3) 6 Kv],'float32',352);
else
gv = zeros([d(1:3) 3 Kv],'single');
Hv = zeros([d(1:3) 6 Kv],'single');
end
nll = 0;
% Compute 1st and 2nd derivatives w.r.t. velocities
for k=1:Kv
gv(:,:,:,:,k) = 0;
Hv(:,:,:,:,k) = 0;
end
if Ka==0
% The same gradients can be used throughout
a0 = mu;
Gmu = CompGrads(a0);
else
Gmu = {};
end
for n1=1:batchsize:numel(dat)
nn = n1:min(n1+(batchsize-1),numel(dat));
z = {dat(nn).z};
%S = {dat(nn).S};
cell1 = GetV0(z,Wv); % Replaced by gradients
cell2 = GetA0(z,Wa,mu); % Replaced by Hessians
dat1 = dat(nn);
parfor n=1:numel(nn)
psi = GetPsi(cell1{n},s);
a0 = cell2{n};
f = GetDat(dat1(n),s);
[ll,a,Ha] = LikelihoodDerivatives(f,a0,psi,noise,s);
nll = nll - ll;
if Ka>0
G = CompGrads(a0);
else
G = Gmu;
end
[cell1{n},cell2{n}] = ShapeDerivs(a,Ha,G,s.likelihood);
end
% Add appropriate amount of gradient and Hessian
for k=1:Kv
g1 = single(0);
H1 = single(0);
for n=1:numel(cell1)
g1 = g1 + cell1{n}*z{n}(k+Koff);
ezz = z{n}(k+Koff)^2;% + S{n}(k+Koff,k+Koff);
H1 = H1 + cell2{n}*ezz;
end
gv(:,:,:,:,k) = gv(:,:,:,:,k) + g1;
Hv(:,:,:,:,k) = Hv(:,:,:,:,k) + H1;
end
end
%==========================================================================
%
%==========================================================================
function [g,H] = ShapeDerivs(a,Ha,G,likelihood)
d = [size(a) 1 1];
d = d(1:4);
g = zeros([d(1:3),3],'single'); % First derivatives
H = zeros([d(1:3),6],'single'); % Second derivatives
switch lower(likelihood)
case {'normal','gaussian'}
for l=1:d(4)
al =-a(:,:,:,l);
g(:,:,:,1) = g(:,:,:,1) + al.*G{l,1};
g(:,:,:,2) = g(:,:,:,2) + al.*G{l,2};
g(:,:,:,3) = g(:,:,:,3) + al.*G{l,3};
wl = Ha(:,:,:,l);
H(:,:,:,1) = H(:,:,:,1) + wl.*G{l,1}.*G{l,1};
H(:,:,:,2) = H(:,:,:,2) + wl.*G{l,2}.*G{l,2};
H(:,:,:,3) = H(:,:,:,3) + wl.*G{l,3}.*G{l,3};
H(:,:,:,4) = H(:,:,:,4) + wl.*G{l,1}.*G{l,2};
H(:,:,:,5) = H(:,:,:,5) + wl.*G{l,1}.*G{l,3};
H(:,:,:,6) = H(:,:,:,6) + wl.*G{l,2}.*G{l,3};
end
case {'binomial','binary'}
g(:,:,:,1) =-a.*G{1,1};
g(:,:,:,2) =-a.*G{1,2};
g(:,:,:,3) =-a.*G{1,3};
wt = Ha+1e-4;
H(:,:,:,1) = wt.*G{1,1}.*G{1,1};
H(:,:,:,2) = wt.*G{1,2}.*G{1,2};
H(:,:,:,3) = wt.*G{1,3}.*G{1,3};
H(:,:,:,4) = wt.*G{1,1}.*G{1,2};
H(:,:,:,5) = wt.*G{1,1}.*G{1,3};
H(:,:,:,6) = wt.*G{1,2}.*G{1,3};
case {'multinomial','categorical'}
g = zeros([d(1:3) 3],'single');
for l=1:d(4)
al =-a(:,:,:,l);
g(:,:,:,1) = g(:,:,:,1) + al.*G{l,1};
g(:,:,:,2) = g(:,:,:,2) + al.*G{l,2};
g(:,:,:,3) = g(:,:,:,3) + al.*G{l,3};
end
H = zeros([d(1:3) 6],'single');
ind = Horder(d(4));
for l1 = 1:d(4)
for l2 = l1:d(4)
wt = Ha(:,:,:,ind(l1,l2));
if l1~=l2, wt = wt*2; end
H(:,:,:,1) = H(:,:,:,1) + wt.*G{l1,1}.*G{l2,1};
H(:,:,:,2) = H(:,:,:,2) + wt.*G{l1,2}.*G{l2,2};
H(:,:,:,3) = H(:,:,:,3) + wt.*G{l1,3}.*G{l2,3};
H(:,:,:,4) = H(:,:,:,4) + wt.*G{l1,1}.*G{l2,2};
H(:,:,:,5) = H(:,:,:,5) + wt.*G{l1,1}.*G{l2,3};
H(:,:,:,6) = H(:,:,:,6) + wt.*G{l1,2}.*G{l2,3};
end
end
otherwise
error('Unknown likelihood function.');
end
g(~isfinite(g)) = 0;
H(~isfinite(H)) = 0;
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
runPGfit.m
|
.m
|
Shape-Appearance-Model-master/runPGfit.m
| 2,121 |
utf_8
|
9a1ff3483c2c998e3811edd46c72e5e9
|
function runPGfit(jsn_settings)
% Run The shape-appearance model on "imported" scans
% For help, type:
% runPG --help
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
if nargin<1 || (ischar(jsn_settings) && (strcmp(jsn_settings,'--help') || strcmp(jsn_settings,'--h')))
show_instructions
return
end
settings = spm_jsonread(jsn_settings);
train_file = settings.train;
filenames = settings.input;
latent_file = settings.output;
res = load(train_file);
[pth,~,~] = fileparts(train_file);
if isa(res.Wv,'file_array')
[~,nam,ext] = fileparts(res.Wv.fname);
res.Wv.fname = fullfile(pth,[nam ext]);
end
if isa(res.Wa,'file_array')
[~,nam,ext] = fileparts(res.Wa.fname);
res.Wa.fname = fullfile(pth,[nam ext]);
end
t_settings = res.s;
t_settings.nit = t_settings.maxit*t_settings.nit;
% Get data
dat = struct('f',filenames,'z',zeros(res.s.Kv,1));
for n=1:numel(dat)
dat(n).f = char(dat(n).f{:});
end
%t_settings.verbose = true;
% Run the fitting
[dat,~] = UpdateLatentVariables(dat,res.mu,res.Wa,res.Wv,res.noise,res.RegZ,t_settings);
% Save the latent variable expectations
Z = cat(2,dat.z);
N = size(Z,2);
Zc = cell(N,1);
for n=1:N
Zc{n} = Z(:,n);
end
spm_jsonwrite(latent_file,Zc);
function show_instructions
disp('Usage: runPGfit settings.jsn');
disp(' ');
disp('Input images must first be imported using SPM12''s Segment tool, giving a series of rc1*.nii and rc2*.nii files.');
disp('The settings.jsn is a JSON file with the following general structure:');
disp('{"train":"trainXXX.mat", % Name of mat file generated by training.');
disp(' "output":"output.jsn", % Name of output file containing estimated latent variables.');
disp(' "input":[["rc1SCAN01.nii","rc2SCAN01.nii"],');
disp(' ["rc1SCAN02.nii","rc2SCAN02.nii"],');
disp(' ["rc1SCAN03.nii","rc2SCAN03.nii"],');
disp(' : : ');
disp(' ["rc1SCANXX.nii","rc2SCANXX.nii"]]');
disp(' ');
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
OrthogonalisationMat.m
|
.m
|
Shape-Appearance-Model-master/OrthogonalisationMat.m
| 4,481 |
utf_8
|
804e54eaf9b5550ccec1cc2ea8ec6236
|
function [T,iT,A] = OrthogonalisationMat(ZZ,S,WW,N,s)
% Orthogonalisation matrix
% FORMAT [T,iT,A] = OrthogonalisationMat(ZZ,S,WW,N,s)
%
% ZZ - Z*Z', where Z are the latent variables
% S - E[Z*Z'] = Z*Z' + S
% WW - Wa'*La*Wa + Wv'*Lv*Wv
% N - size(Z,2)
% s - Settings.
%
% T - Transform.
% iT - Inverse transform.
% A - Precision matrix for distribution of latent variables.
%
% Compute a suitable orthogonalisation matrix (T) and its inverse (iT).
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
Ka = s.Ka;
Kv = s.Kv;
K = size(ZZ,1);
T = zeros(K,K);
iT = zeros(K,K);
% Figure out which blocks of ZZ should be orthogonalised.
if Ka==K && Kv==K
ind = {1:K};
else
ind = {1:Ka,(1:Kv)+Ka};
end
% Find matrix T (and iT - its inverse) that orthogonalises the blocks
for i=1:numel(ind)
[T(ind{i},ind{i}),iT(ind{i},ind{i})] = OrthogonalisationMatrix(ZZ(ind{i},ind{i}),WW(ind{i},ind{i}));
end
% The remainder of the code figures out how to rescale the transform T, such that
% the ``energy'' is minimised.
ZZ1 = T*ZZ*T'; % Transformed Z*Z'
EZZ1 = T*(ZZ+S)*T'; % Transformed E[Z*Z']
WW1 = N*iT'*WW*iT; % Transformed W'*L*W
% Model parameters (q) are logs of the rescaling factors, which ensures
% they remain positive.
q = zeros(K,1); % It would be -0.5*log(N) if B = eye(K);
Q = diag(exp(q)); % Diagonal rescaling matrix
A = SetReg(Q*EZZ1*Q,N,s); % E-step
E = 0.5*(trace(Q*ZZ1*Q*A) + trace(WW1/(Q*Q))); % Initial objective function
for iter=1:100
% E-step: Compute precision matrix (A) of latent variables
% using current estimate of the transform (T).
A = SetReg(Q*EZZ1*Q,N,s);
% Current objective function for outer loop
oE0 = E;
% Find the rescaling of T that minimises the "energy" using
% the current estimate of the A matrix.
for subit=1:10
R = A.*ZZ1'+A'.*ZZ1;
% Gradient
g1 = Q*R*diag(Q);
g2 =-2*(Q^2\diag(WW1));
g = g1+g2;
% Hessian
H1 = Q*R*Q + diag(g1);
H2 = 4*(Q^2\WW1);
H = H1+H2;
% Gauss-Newton update (with regularisation)
H = H + max(diag(H))*1e-6*eye(size(H));
q = q - H\g;
q = min(max(q,-10),10);
Q = diag(exp(q));
% Check objective function for convergence
oE = E;
E = 0.5*(trace(Q*ZZ1*Q*A) + trace(WW1/(Q*Q)));
if (oE-E)/E < 1e-8, break; end
end
% If outer-loop objective function is unchannged, then done.
if abs(oE0-E)/E < 1e-7, break; end
end
T = Q*T;
iT = iT/Q;
%==========================================================================
%
%==========================================================================
function [T,iT] = OrthogonalisationMatrix(ZZ,WW)
% Use SVD to orthognalise
% FORMAT [T,iT] = OrthogonalisationMatrix(ZZ,WW)
%
% ZZ - Z*Z' + S
% WW - W'*L*W
%
% T - Orthogonalisation matrix
% iT - Inverse of T - roughly
%
% Finds a transform that make ZZ and WW orthogonal, but the resulting
% transform needs to be rescaled such that an "energy" term is minimised.
%__________________________________________________________________________
if isempty(ZZ) && isempty(WW)
T = [];
iT = [];
return;
end
[Vz,Dz2] = svd(double(ZZ));
[Vw,Dw2] = svd(double(WW));
Dz = diag(sqrt(diag(Dz2)+eps));
Dw = diag(sqrt(diag(Dw2)+eps));
[U,D,V] = svd(Dw*Vw'*Vz*Dz');
Dz = Dz+max(abs(Dz(:)))*1e-8*eye(size(Dz));
Dw = Dw+max(abs(Dw(:)))*1e-8*eye(size(Dw));
T = D*V'*(Dz\Vz');
iT = Vw*(Dw\U);
% % Code for working out the gradients and Hessians of the
% % for the energy minimisation
% q = sym('q',[3,1],'real');
% Q = diag(exp(q));
% A = sym('a',[3,3],'real');
% ZZ1 = sym('x',[3,3],'real');
% y = sym('y',[3,1],'real');
% WW1 = diag(y);
% E = trace(Q*ZZ1*Q*A) + trace(WW1*inv(Q*Q));
%
% pretty(simplify(diff(E,sym('q1')),1000))
% pretty(simplify(diff(diff(E,sym('q1')),sym('q2')),1000))
% pretty(simplify(diff(diff(E,sym('q1')),sym('q1')),1000))
%
% g1 = Q*(A.*ZZ1'+A'.*ZZ1)*diag(Q);
% g2 = -Q^2\diag(WW1)*2;
% g = g1+g2;
% H1 = Q*(A'.*ZZ1 + A.*ZZ1')*Q +diag(g1);
% H2 = 4*WW1*Q^(-2);
% H = H1+H2;
%
% d1 = simplify(g(1) -diff(E,sym('q1')),1000)
% d11 = simplify(H(1,1)-diff(diff(E,sym('q1')),sym('q1')),1000)
% d12 = simplify(H(1,2)-diff(diff(E,sym('q1')),sym('q2')),1000)
|
github
|
WTCN-computational-anatomy-group/Shape-Appearance-Model-master
|
runPG.m
|
.m
|
Shape-Appearance-Model-master/runPG.m
| 4,027 |
utf_8
|
2655cc1399f4ae964792a6e35f3394ec
|
function runPG(jsn_filenames, jsn_settings)
% Run The shape-appearance model on "imported" scans
% For help, type:
% runPG --help
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
if nargin>=2
settings = spm_jsonread(jsn_settings);
s = struct('Ka', 0,...
'Kv', 0,...
'linked', false,...
'vx', [1 1 1],...
'v_settings', [1e-4 1e-1 2 0.25 0.5]*0.1,...
'a_settings', [1e-3 1e-1 0]*10,...
'mu_settings', [1e-3 1e-1 0],...
'mg_its', [3 3],...
'int_args', 8,...
'nit', 1,...
'maxit', 8,...
'omega', 1.0,...
'lambda', [0.9 0.1],...
'nu0', 0,...
'nu_factor', 1,...
'likelihood', 'multinomial',...
'slices', [],...
'result_name', 'test',...
'result_dir', tempdir,...
'ondisk', true,...
'batchsize', 4,...
'debug', false,...
'verbose', false);
fldnames = fieldnames(settings);
for i=1:numel(fldnames)
if isfield(s,fldnames{i})
s.(fldnames{i}) = settings.(fldnames{i});
s.(fldnames{i}) = s.(fldnames{i})(:)';
end
end
if isfield(settings,'K')
s.Ka = settings.K;
s.Kv = settings.K;
s.linked = true;
end
end
if nargin<1 || (ischar(jsn_filenames) && (strcmp(jsn_filenames,'--help') || strcmp(jsn_filenames,'--h')))
show_instructions
else
files = spm_jsonread(jsn_filenames);
dat = struct('f',files);
for n=1:numel(files)
dat(n).f = char(dat(n).f{:});
end
%disp('Running PG with the following settings...');
%disp(s)
PG(dat,s)
end
function show_instructions
disp('Usage: runPG filenames.jsn settings.jsn');
disp(' ');
disp('Images must first be imported using SPM12''s Segment tool, giving a series of rc1*.nii and rc2*.nii files.');
disp('The filenames.jsn is a JSON file with the following general structure, where SCANXX is some filename:');
disp('[["rc1SCAN01.nii","rc2SCAN01.nii"],');
disp(' ["rc1SCAN02.nii","rc2SCAN02.nii"],');
disp(' ["rc1SCAN03.nii","rc2SCAN03.nii"],');
disp(' : : ');
disp(' ["rc1SCANXX.nii","rc2SCANXX.nii"]]');
disp(' ');
disp('The settings.jsn file contains various settings, which are of the following form:');
disp('{"K":64, % Number of shape and appearance components');
disp(' "vx":[1.5 1.5 1.5], % Voxel sizes (mm - matches those of "imported" images)');
disp(' "v_settings":[1e-05,0.01,0.2,0.025,0.05], % Registration regularisation settings.');
disp(' "a_settings":[0.01,1,0], % Appearance regularisation settings.');
disp(' "mu_settings":[0.001,0.1,0], % Mean image regularisation settings.');
disp(' "maxit":8, % Number of iterations.');
disp(' "result_name":"test", % Name of results files.');
disp([' "result_dir":"' tempdir '", % Name of result directory.']);
disp(' "batchsize":4} % Batch-size (for local parallelisation).');
disp(' ');
disp('If no settings.jsn file is provided, or if some settings are not specified,');
disp('then default values (shown in the example above) are assumed.');
disp(' ');
disp('Depending on the amount of data, execution can take a very long time.');
disp('Outputs are saved at each iteration in the specified result_dir.');
disp(' ');
disp('The latent variables of interest may be obtained via MATLAB:');
disp(' load(fullfile(settings.result_dir,[''train'' settings.result_name ''.mat'']))');
disp(' Z = cat(2,dat.z);');
disp(' ');
|
github
|
oshaban/MusicRecognition-master
|
orionGUI.m
|
.m
|
MusicRecognition-master/orionGUI.m
| 5,156 |
utf_8
|
f8e18abecc150c003678e78f42b0b9f9
|
function varargout = orionGUI(varargin)
% ORIONGUI MATLAB code for orionGUI.fig
% ORIONGUI, by itself, creates a new ORIONGUI or raises the existing
% singleton*.
%
% H = ORIONGUI returns the handle to a new ORIONGUI or the handle to
% the existing singleton*.
%
% ORIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ORIONGUI.M with the given input arguments.
%
% ORIONGUI('Property','Value',...) creates a new ORIONGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before orionGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to orionGUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help orionGUI
% Last Modified by GUIDE v2.5 24-Apr-2017 12:41:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @orionGUI_OpeningFcn, ...
'gui_OutputFcn', @orionGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before orionGUI is made visible.
function orionGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to orionGUI (see VARARGIN)
% Choose default command line output for orionGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes orionGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = orionGUI_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;
% --- Executes on button press in createDatabaseButton.
function createDatabaseButton_Callback(hObject, eventdata, handles)
% hObject handle to createDatabaseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
notify = msgbox('Creating database');
%PUT CREATEDATABASE FUNCTION
delete(notify);
% --- Executes on button press in recordButton.
function recordButton_Callback(hObject, eventdata, handles)
% hObject handle to recordButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Record Song
fs = 44100;
recordingTime = 10;
A = audiorecorder(fs,16,1); %Record in audio
notify = msgbox('RECORDING');
recordblocking(A,recordingTime); %Records from microphone
delete(notify);
micRecording = getaudiodata(A);
audiowrite('mic.wav',micRecording,fs)
%Create constellation for the recording
hashRecording = create_constellation_adaptive_threshold('mic.wav')';
%Must declare global variables being used
global database
global songNames
matches = zeros(1,length(database)); %Stores number of matches for each database song
%Search for the matching song
for(j=1:length(database))
hashList = cell2mat(database(j))'; %Constellation for a corresponding database song
%Searches a nx3 hash matrix, where the columns correspond to
%f1,f2,deltaT
for( i=1:size(hashRecording,1) )
f = ismembertol(hashRecording(i,:),hashList,1,'ByRows',true,'DataScale',[1 1 0.05]);
%Checks to see if f1 is within 2, f2 is within 2, and deltaT is
%within 0.1 of the hashes in hashRecording
if(f==1)
matches(j) = matches(j)+1;
end
end
end
%Find location of song with most matches
[maxMatches,maxIndex] = max(matches);
%Print song with most matches
set(handles.resultBox ,'string',char( songNames(maxIndex)) )
%Plots graph with number of matches
axes(handles.bargraph)
bar(1:length(matches),matches)
title('Number of Hits per Song')
xlabel('Song Numbers')
ylabel('Number of Hits')
|
github
|
emilymacq/Project-Clear-Lungs-master
|
mfcc.m
|
.m
|
Project-Clear-Lungs-master/ARCHIVE/Matlab Files/mfcc.m
| 4,866 |
utf_8
|
953a29880fb3e712bee932d0f8ca9e4a
|
[x Fs] = audioread('Crackles - Early Inspiratory (Rales).mp3');
left_channel = x(:,1);
coefficients = melcepst(left_channel, Fs)
function [c,tc]=melcepst(s,fs,w,nc,p,n,inc,fl,fh)
%MELCEPST Calculate the mel cepstrum of a signal C=(S,FS,W,NC,P,N,INC,FL,FH)
%
%
% Simple use: (1) c=melcepst(s,fs) % calculate mel cepstrum with 12 coefs, 256 sample frames
% (2) c=melcepst(s,fs,'E0dD') % include log energy, 0th cepstral coef, delta and delta-delta coefs
%
% Inputs:
% s speech signal
% fs sample rate in Hz (default 11025)
% w mode string (see below)
% nc number of cepstral coefficients excluding 0'th coefficient [default 12]
% p number of filters in filterbank [default: floor(3*log(fs)) = approx 2.1 per ocatave]
% n length of frame in samples [default power of 2 < (0.03*fs)]
% inc frame increment [default n/2]
% fl low end of the lowest filter as a fraction of fs [default = 0]
% fh high end of highest filter as a fraction of fs [default = 0.5]
%
% w any sensible combination of the following:
%
% 'R' rectangular window in time domain
% 'N' Hanning window in time domain
% 'M' Hamming window in time domain (default)
%
% 't' triangular shaped filters in mel domain (default)
% 'n' hanning shaped filters in mel domain
% 'm' hamming shaped filters in mel domain
%
% 'p' filters act in the power domain
% 'a' filters act in the absolute magnitude domain (default)
%
% '0' include 0'th order cepstral coefficient
% 'E' include log energy
% 'd' include delta coefficients (dc/dt)
% 'D' include delta-delta coefficients (d^2c/dt^2)
%
% 'z' highest and lowest filters taper down to zero (default)
% 'y' lowest filter remains at 1 down to 0 frequency and
% highest filter remains at 1 up to nyquist freqency
%
% If 'ty' or 'ny' is specified, the total power in the fft is preserved.
%
% Outputs: c mel cepstrum output: one frame per row. Log energy, if requested, is the
% first element of each row followed by the delta and then the delta-delta
% coefficients.
% tc fractional time in samples at the centre of each frame
% with the first sample being 1.
%
% BUGS: (1) should have power limit as 1e-16 rather than 1e-6 (or possibly a better way of choosing this)
% and put into VOICEBOX
% (2) get rdct to change the data length (properly) instead of doing it explicitly (wrongly)
% Copyright (C) Mike Brookes 1997
% Version: $Id: melcepst.m 4914 2014-07-24 08:44:26Z dmb $
%
% VOICEBOX is a MATLAB toolbox for speech processing.
% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
if nargin<2 fs=11025; end
if nargin<3 w='M'; end
if nargin<4 nc=12; end
if nargin<5 p=floor(3*log(fs)); end
if nargin<6 n=pow2(floor(log2(0.03*fs))); end
if nargin<9
fh=0.5;
if nargin<8
fl=0;
if nargin<7
inc=floor(n/2);
end
end
end
if isempty(w)
w='M';
end
if any(w=='R')
[z,tc]=enframe(s,n,inc);
elseif any (w=='N')
[z,tc]=enframe(s,hanning(n),inc);
else
[z,tc]=enframe(s,hamming(n),inc);
end
f=rfft(z.');
[m,a,b]=melbankm(p,n,fs,fl,fh,w);
pw=f(a:b,:).*conj(f(a:b,:));
pth=max(pw(:))*1E-20;
if any(w=='p')
y=log(max(m*pw,pth));
else
ath=sqrt(pth);
y=log(max(m*abs(f(a:b,:)),ath));
end
c=rdct(y).';
nf=size(c,1);
nc=nc+1;
if p>nc
c(:,nc+1:end)=[];
elseif p<nc
c=[c zeros(nf,nc-p)];
end
if ~any(w=='0')
c(:,1)=[];
nc=nc-1;
end
if any(w=='E')
c=[log(max(sum(pw),pth)).' c];
nc=nc+1;
end
% calculate derivative
if any(w=='D')
vf=(4:-1:-4)/60;
af=(1:-1:-1)/2;
ww=ones(5,1);
cx=[c(ww,:); c; c(nf*ww,:)];
vx=reshape(filter(vf,1,cx(:)),nf+10,nc);
vx(1:8,:)=[];
ax=reshape(filter(af,1,vx(:)),nf+2,nc);
ax(1:2,:)=[];
vx([1 nf+2],:)=[];
if any(w=='d')
c=[c vx ax];
else
c=[c ax];
end
elseif any(w=='d')
vf=(4:-1:-4)/60;
ww=ones(4,1);
cx=[c(ww,:); c; c(nf*ww,:)];
vx=reshape(filter(vf,1,cx(:)),nf+8,nc);
vx(1:8,:)=[];
c=[c vx];
end
if nargout<1
[nf,nc]=size(c);
% t=((0:nf-1)*inc+(n-1)/2)/fs;
ci=(1:nc)-any(w=='0')-any(w=='E');
imh = imagesc(tc/fs,ci,c.');
axis('xy');
xlabel('Time (s)');
ylabel('Mel-cepstrum coefficient');
map = (0:63)'/63;
colormap([map map map]);
colorbar;
end
end
|
github
|
zelanolab/breathmetrics-master
|
getSecondaryRespiratoryFeatures.m
|
.m
|
breathmetrics-master/breathmetrics_functions/getSecondaryRespiratoryFeatures.m
| 8,041 |
utf_8
|
8977404fbda7d4cd229c1b0202d4d726
|
function respirationStatistics = getSecondaryRespiratoryFeatures( Bm, verbose )
%calculates features of respiratory data. Running this method assumes that
% you have already derived all possible features
if nargin < 2
verbose = 0;
end
if verbose == 1
disp('Calculating secondary respiratory features')
end
% first find valid breaths
% edited 4/11/20
% split nBreaths into inhales and exhales to fix indexing error from
% myPeak error in findRespiratoryExtrema
nInhales=length(Bm.inhaleOnsets);
nExhales=length(Bm.exhaleOnsets);
if isempty(Bm.statuses)
validInhaleInds=1:nInhales;
validExhaleInds=1:nExhales;
else
IndexInvalid = strfind(Bm.statuses,'rejected');
invalidBreathInds = find(not(cellfun('isempty',IndexInvalid)));
validInhaleInds=setdiff(1:nInhales,invalidBreathInds);
validExhaleInds=setdiff(1:nExhales,invalidBreathInds);
if isempty(validInhaleInds)
warndlg('No valid breaths found. If the status of a breath is set to ''rejected'', it will not be used to compute secondary features');
end
end
nValidInhales=length(validInhaleInds);
nValidExhales=length(validExhaleInds);
%%% Breathing Rate %%%
% breathing rate is the sampling rate over the average number of samples
% in between breaths.
% this is tricky when certain breaths have been rejected
breathDiffs=nan(1,1);
vbIter=1;
for i = 1:nValidInhales-1
thisBreath=validInhaleInds(i);
nextBreath=validInhaleInds(i+1);
% if there is no rejected breath between these breaths, they can be
% used to compute breathing rate.
if nextBreath == thisBreath+1
breathDiffs(1,vbIter)=Bm.inhaleOnsets(nextBreath)-Bm.inhaleOnsets(thisBreath);
vbIter=vbIter+1;
end
end
breathingRate = Bm.srate/mean(breathDiffs);
%%% Inter-Breath Interval %%%
% inter-breath interval is the inverse of breathing rate
interBreathInterval = 1/breathingRate;
%%% Coefficient of Variation of Breathing Rate %%%
% this describes variability in time between breaths
cvBreathingRate = std(breathDiffs)/mean(breathDiffs);
if strcmp(Bm.dataType,'humanAirflow') || strcmp(Bm.dataType,'rodentAirflow')
% the following features can only be computed for airflow data
%%% Peak Flow Rates %%%
% the maximum rate of airflow at each inhale and exhale
% inhales
validInhaleFlows=excludeOutliers(Bm.peakInspiratoryFlows, validInhaleInds);
avgMaxInhaleFlow = mean(validInhaleFlows);
% exhales
validExhaleFlows=excludeOutliers(Bm.troughExpiratoryFlows, validExhaleInds);
avgMaxExhaleFlow = mean(validExhaleFlows);
%%% Breath Volumes %%%
% the volume of each breath is the integral of the airflow
% inhales
validInhaleVolumes=excludeOutliers(Bm.inhaleVolumes, validInhaleInds);
avgInhaleVolume = mean(validInhaleVolumes);
% exhales
validExhaleVolumes=excludeOutliers(Bm.exhaleVolumes, validExhaleInds);
avgExhaleVolume = mean(validExhaleVolumes);
%%% Tidal volume %%%
% tidal volume is the total air displaced by inhale and exhale
avgTidalVolume = avgInhaleVolume + avgExhaleVolume;
%%% Minute Ventilation %%%
% minute ventilation is the product of respiration rate and tidal volume
minuteVentilation = breathingRate * avgTidalVolume;
%%% Duty Cycle %%%
% duty cycle is the percent of each breathing cycle that was spent in
% a phase
% get avg duration of each phase
avgInhaleDuration = nanmean(Bm.inhaleDurations);
avgExhaleDuration = nanmean(Bm.exhaleDurations);
% because pauses don't necessarily occur on every breath, multiply this
% value by total number that occured.
pctInhalePause=sum(~isnan(Bm.inhalePauseDurations))/nValidInhales;
avgInhalePauseDuration = nanmean(Bm.inhalePauseDurations(validInhaleInds)) * pctInhalePause;
pctExhalePause=sum(~isnan(Bm.exhalePauseDurations))/nValidExhales;
avgExhalePauseDuration = nanmean(Bm.exhalePauseDurations(validExhaleInds)) * pctExhalePause;
inhaleDutyCycle = avgInhaleDuration / interBreathInterval;
inhalePauseDutyCycle = avgInhalePauseDuration / interBreathInterval;
exhaleDutyCycle = avgExhaleDuration / interBreathInterval;
exhalePauseDutyCycle = avgExhalePauseDuration / interBreathInterval;
CVInhaleDuration = nanstd(Bm.inhaleDurations)/avgInhaleDuration;
CVInhalePauseDuration = nanstd(Bm.inhalePauseDurations)/avgInhalePauseDuration;
CVExhaleDuration = nanstd(Bm.exhaleDurations)/avgExhaleDuration;
CVExhalePauseDuration = nanstd(Bm.exhalePauseDurations)/avgExhalePauseDuration;
% if there were no pauses, the average pause duration is 0, not nan
if isempty(avgInhalePauseDuration) || isnan(avgInhalePauseDuration)
avgInhalePauseDuration=0;
end
if isempty(avgExhalePauseDuration) || isnan(avgExhalePauseDuration)
avgExhalePauseDuration=0;
end
% coefficient of variation in breath size describes variability of breath
% sizes
CVTidalVolume = std(validInhaleVolumes)/mean(validInhaleVolumes);
end
% assigning values for output
if strcmp(Bm.dataType,'humanAirflow') || strcmp(Bm.dataType,'rodentAirflow')
keySet= {
'Breathing Rate';
'Average Inter-Breath Interval';
'Average Peak Inspiratory Flow';
'Average Peak Expiratory Flow';
'Average Inhale Volume';
'Average Exhale Volume';
'Average Tidal Volume';
'Minute Ventilation';
'Duty Cycle of Inhale';
'Duty Cycle of Inhale Pause';
'Duty Cycle of Exhale';
'Duty Cycle of Exhale Pause';
'Coefficient of Variation of Inhale Duty Cycle';
'Coefficient of Variation of Inhale Pause Duty Cycle';
'Coefficient of Variation of Exhale Duty Cycle';
'Coefficient of Variation of Exhale Pause Duty Cycle';
'Average Inhale Duration';
'Average Inhale Pause Duration';
'Average Exhale Duration';
'Average Exhale Pause Duration';
'Percent of Breaths With Inhale Pause';
'Percent of Breaths With Exhale Pause';
'Coefficient of Variation of Breathing Rate';
'Coefficient of Variation of Breath Volumes';
};
valueSet={
breathingRate;
interBreathInterval;
avgMaxInhaleFlow;
avgMaxExhaleFlow;
avgInhaleVolume;
avgExhaleVolume;
avgTidalVolume;
minuteVentilation;
inhaleDutyCycle;
inhalePauseDutyCycle;
exhaleDutyCycle;
exhalePauseDutyCycle;
CVInhaleDuration;
CVInhalePauseDuration;
CVExhaleDuration;
CVExhalePauseDuration;
avgInhaleDuration;
avgInhalePauseDuration;
avgExhaleDuration;
avgExhalePauseDuration;
pctInhalePause
pctExhalePause;
cvBreathingRate;
CVTidalVolume;
};
elseif strcmp(Bm.dataType,'humanBB') || strcmp(Bm.dataType,'rodentThermocouple')
keySet= {
'Breathing Rate';
'Average Inter-Breath Interval';
'Coefficient of Variation of Breathing Rate';
};
valueSet={
breathingRate;
interBreathInterval;
cvBreathingRate;
};
end
respirationStatistics = containers.Map(keySet,valueSet);
if verbose == 1
disp('Secondary Respiratory Features')
for this_key = 1:length(keySet)
fprintf('%s : %0.5g', keySet{this_key},valueSet{this_key});
fprintf('\n')
end
end
end
function validVals=excludeOutliers(origVals,validBreathInds)
% rejects values exceeding 2 stds from the mean
upperBound=nanmean(origVals) + 2 * nanstd(origVals);
lowerBound=nanmean(origVals) - 2 * nanstd(origVals);
validValInds = find(origVals(origVals > lowerBound & origVals < upperBound));
validVals = origVals(intersect(validValInds, validBreathInds));
end
|
github
|
zelanolab/breathmetrics-master
|
bmGui.m
|
.m
|
breathmetrics-master/breathmetrics_functions/bmGui.m
| 31,014 |
utf_8
|
4e14dbe96f2d5f05f74db27414b25bb4
|
function newBM = bmGui(bmObj)
% This is the GUI for breathmetrics that allows users to edit respiratory
% features, annotate breaths, and reject breaths from analysis.
%
% input: bmObj is a breathmetrics class object that has feature
% estimations complete
%
% output: newBM is the modified breathmetrics object. If the figure window
% is closed without saving, the original breathmetrics object will be
% returned.
%%% initialize static parameters %%%
S.myColors=parula(5);
if strcmp(bmObj.dataType,'humanBB')
breathSelectMenuColNames={'Breath No.';'Inhale';'Exhale';'Status';'Note'};
else
breathSelectMenuColNames={'Breath No.';'Onset';'Offset';'Status';'Note'};
end
S.breathSelectMenuColNames=breathSelectMenuColNames;
S.breathEditMenuColNames={'Inhale';'Inhale Pause';'Exhale';'Exhale Pause'};
S.bmInit=copy(bmObj);
% figure parameters
myPadding=10;
figureWindowWidth=1250;
figureWindowHeight=560;
figureXInit=0;
figureYInit=figureWindowHeight;
figureWindowInds=[figureXInit,figureYInit,figureWindowWidth,figureWindowHeight];
buttonSize=[125,25];
biggerButtonSize=[180,40];
smallerButtonSize=[100,50];
%%% INITIALIZE LOCATIONS OF FIGURE ELEMENTS %%%
%%% LEFT SIDE %%%
% text above table to select breath
breathSelectMenuTitleTextBottom=figureWindowHeight-biggerButtonSize(2)-myPadding;
breathSelectMenuTitleTextWidth=350;
breathSelectMenuX=myPadding*2;
breathSelectTitleTextInds = [...
breathSelectMenuX,...
breathSelectMenuTitleTextBottom,...
breathSelectMenuTitleTextWidth,...
biggerButtonSize(2)];
% table to select breath
breathSelectMenuWidth=breathSelectMenuTitleTextWidth;
breathSelectMenuRight=breathSelectMenuX+breathSelectMenuWidth;
breathSelectMenuHeight=breathSelectMenuTitleTextBottom-myPadding*4;
breathSelectMenuBottom=breathSelectMenuTitleTextBottom-breathSelectMenuHeight-myPadding;
breathSelectMenuInds = [...
breathSelectMenuX,...
breathSelectMenuBottom,...
breathSelectMenuWidth,...
breathSelectMenuHeight];
%%% buttons on left side %%%
% previous breath and next breath buttons
prevBreathButtonX=breathSelectMenuRight+myPadding;
nextBreathButtonX=prevBreathButtonX+smallerButtonSize(1);
breathNavButtonBottom=breathSelectMenuTitleTextBottom-smallerButtonSize(2)-myPadding;
prevBreathButtonInds=[...
prevBreathButtonX,...
breathNavButtonBottom,...
smallerButtonSize(1),...
smallerButtonSize(2)];
nextBreathButtonInds=[...
nextBreathButtonX,...
breathNavButtonBottom,...
smallerButtonSize(1),...
smallerButtonSize(2)];
leftSideButtonSpacing=-myPadding-biggerButtonSize(2);
leftSideButtonPadding=myPadding*4;
% button to add note to selected breath
noteButtonX=breathSelectMenuRight+myPadding;
noteButtonBottom=breathNavButtonBottom+leftSideButtonSpacing-leftSideButtonPadding;
noteButtonInds=[...
noteButtonX,...
noteButtonBottom,...
biggerButtonSize(1),...
biggerButtonSize(2)];
% button to reject breath
rejectButtonBottom=noteButtonBottom+leftSideButtonSpacing;
rejectButtonInds=[...
noteButtonX,...
rejectButtonBottom,...
biggerButtonSize(1),...
biggerButtonSize(2)];
% button to undo changes to this breath
undoBreathButtonY=rejectButtonBottom+leftSideButtonSpacing-leftSideButtonPadding;
undoBreathButtonInds=[...
noteButtonX,...
undoBreathButtonY,...
biggerButtonSize(1),...
biggerButtonSize(2)];
% button to save all changes
saveAllChangesButtonBottom=myPadding*3;
saveAllChangesButtonInds=[...
noteButtonX,...
saveAllChangesButtonBottom,...
biggerButtonSize(1),...
biggerButtonSize(2)];
%%% RIGHT SIDE %%%
% plotting axis
plottingAxisWidth=600;
plottingAxisHeight=300;
% text above axis
axisTextBottom=breathSelectMenuTitleTextBottom;
plottingAxisNudge=50;
plottingAxisX=noteButtonX+biggerButtonSize(1)+myPadding+plottingAxisNudge;
plottingAxisBottom=axisTextBottom-myPadding*2 - plottingAxisHeight;
axisTextInds = [...
plottingAxisX,...
axisTextBottom,...
plottingAxisWidth,...
biggerButtonSize(2)];
axisWindowInds=[...
plottingAxisX,...
plottingAxisBottom,...
plottingAxisWidth,...
plottingAxisHeight
];
% editable text boxes that show params of breaths and buttons to
% initialize new instances of pauses
breathEditTextBoxHeight=50;
breathEditTextBoxTitleHeight=25;
breathEditTextBoxWidth=100;
onsetEditTextBoxTitleBottom=plottingAxisBottom-breathEditTextBoxHeight-myPadding-10;
onsetEditTextBoxBottom=onsetEditTextBoxTitleBottom-breathEditTextBoxHeight;
pauseInitButtonBottom=onsetEditTextBoxBottom-buttonSize(2)-myPadding;
pauseRemoveButtonBottom=pauseInitButtonBottom-buttonSize(2);
% looping to define locations for buttons
xIter=plottingAxisX+myPadding;
onsetEditTextBoxTitleInds=zeros(4,4);
onsetEditTextBoxInds=zeros(4,4);
pauseInitButtonInds=zeros(4,4);
pauseRemoveButtonInds=zeros(4,4);
% make special padding so they look nice
phasePadding=(plottingAxisWidth-4*breathEditTextBoxWidth)/3 - myPadding*2;
for i=1:4
thisEditBoxInds=[xIter,...
onsetEditTextBoxBottom,...
breathEditTextBoxWidth,...
breathEditTextBoxHeight];
onsetEditTextBoxInds(i,:)=thisEditBoxInds;
thisEditBoxTitleInds=[xIter,...
onsetEditTextBoxTitleBottom,...
breathEditTextBoxWidth,...
breathEditTextBoxTitleHeight];
onsetEditTextBoxTitleInds(i,:)=thisEditBoxTitleInds;
thisPauseInitButtonInds=[xIter,...
pauseInitButtonBottom,...
breathEditTextBoxWidth,...
buttonSize(2)];
pauseInitButtonInds(i,:)=thisPauseInitButtonInds;
thisPauseRemoveButtonInds=[xIter,...
pauseRemoveButtonBottom,...
breathEditTextBoxWidth,...
buttonSize(2)];
pauseRemoveButtonInds(i,:)=thisPauseRemoveButtonInds;
xIter=xIter+phasePadding+breathEditTextBoxWidth;
end
S.xLims=[-3,3];
S.yLims=[-1,1];
%%% initialize figure %%%
S.fh = figure(...
'position',figureWindowInds,...
'menubar','none',...
'name','BreathMetrics GUI',...
'numbertitle','off',...
'resize','off', ...
'KeyPressFcn', @keyPress);
movegui(S.fh,'center')
% most data is stored in S.fh.UserData
% initialize this variable here
% breath edit menu
% if data type is breathing belt there are no pauses
% check for this here and insert nans as placeholders
if strcmp(bmObj.dataType,'humanBB')
inhalePauseOnsets = NaN(size(bmObj.inhaleOnsets));
exhalePauseOnsets = NaN(size(bmObj.exhaleOnsets));
else
inhalePauseOnsets = bmObj.inhalePauseOnsets;
exhalePauseOnsets = bmObj.exhalePauseOnsets;
end
UserData.breathEditMat=[bmObj.inhaleOnsets;inhalePauseOnsets;bmObj.exhaleOnsets;exhalePauseOnsets]'/bmObj.srate;
% breath number and n breaths
UserData.thisBreath=1;
nBreaths=length(bmObj.inhaleOnsets);
UserData.nBreaths=nBreaths;
% organize bm params
% Make copy of initial breathmetrics class
UserData.bmObj=copy(S.bmInit);
% params for breath select menu
breathInds=(1:nBreaths)';
% breathing belts don't have offsets
if strcmp(bmObj.dataType,'humanBB')
% not true offsets, use exhale offset as placeholder
BMinhaleOnsets=(bmObj.inhaleOnsets/bmObj.srate)';
BMexhaleOffsets=(bmObj.exhaleOnsets/bmObj.srate)';
else
BMinhaleOnsets=(bmObj.inhaleOnsets/bmObj.srate)';
BMexhaleOffsets=(bmObj.exhaleOffsets/bmObj.srate)';
end
breathSelectMat=num2cell([breathInds,BMinhaleOnsets,BMexhaleOffsets]);
% statuses ('valid','edited','rejected')
if isempty(bmObj.statuses)
breathStatuses=cell(nBreaths,1);
breathStatuses(:)={'valid'};
breathSelectMat(:,4)=breathStatuses;
else
breathSelectMat(:,4)=bmObj.statuses;
end
if isempty(bmObj.notes)
% make empty array for notes
breathNotes=cell(nBreaths,1);
breathSelectMat(:,5)=breathNotes;
else
breathSelectMat(:,5)=bmObj.notes;
end
UserData.breathSelectMat=breathSelectMat;
% storage for temporary changes to breaths
UserData.tempPhaseOnsetChanges=UserData.breathEditMat(1,:);
% save original data in case user want to revert back
UserData.initialBreathEditMat=UserData.breathEditMat;
% changes when user wants to save
UserData.Tag=[];
% output variable
UserData.newBM=[];
% save bm params into fh.UserData
set(S.fh, 'UserData', UserData);
%%% LISTEN FOR KEYPRESSES %%%
function keyPress(src, e)
switch e.Key
case 'leftarrow'
prevBreathCallback(src, e, S);
case 'rightarrow'
nextBreathCallback(src, e, S);
case 'u'
undoChangesCallback(src, e, S);
case 'r'
rejectBreathCallback(src, e, S);
case 'n'
noteCallback(src, e, S);
end
end
%%% POPULATE FIGURE WITH ELEMENTS %%%
%%% left side %%%
% title above breath select menu
S.breathSelectTitleText = uicontrol(...
'style','text',...
'unit','pix',...
'position',breathSelectTitleTextInds,...
'string','Select A Breath',...
'fontsize',16);
% breath selection table
S.uit = uitable(...
'Position',breathSelectMenuInds,...
'ColumnName',S.breathSelectMenuColNames,...
'Data',S.fh.UserData.breathSelectMat);
S.prevBreathButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',prevBreathButtonInds,...
'fontsize',12,...
'string','Previous Breath');
S.nextBreathButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',nextBreathButtonInds,...
'fontsize',12,...
'string','Next Breath');
S.noteButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',noteButtonInds,...
'fontsize',14,...
'string','Add Note To This Breath');
% button to reject selected breath from analysis
S.rejectButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',rejectButtonInds,...
'fontsize',14,...
'string','Reject This Breath');
% button to reject selected breath from analysis
S.undoChangesButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',undoBreathButtonInds,...
'fontsize',12,...
'string','Undo Changes To This Breath');
% button to reject selected breath from analysis
S.saveChangesButton = uicontrol(...
'style','push',...
'units','pixels',...
'position',saveAllChangesButtonInds,...
'fontsize',14,...
'string','SAVE ALL CHANGES');
%%% right side %%%
% title above breath select menu
S.axisText = uicontrol(...
'style','text',...
'unit','pix',...
'position',axisTextInds,...
'string','Plot and Edit This Breath',...
'fontsize',16);
% plotting window
S.ax = axes(...
'units','pixels',...
'position',axisWindowInds,...
'Xlim',S.yLims,...
'YLim',S.xLims,...
'XGrid','on',...
'YGrid','on');
grid(S.ax,'on')
% for zooming
set(S.ax.Toolbar,'Visible','on');
% text boxes to display and edit phase onsets
for i=1:4
% title field
S.phaseEditTexts(i) = uicontrol(...
'style','text',...
'unit','pix',...
'position',onsetEditTextBoxTitleInds(i,:),...
'string',S.breathEditMenuColNames{i},...
'backgroundcolor',S.myColors(i+1,:),...
'fontsize',12);
% editable box field
S.phaseEditors(i) = uicontrol(...
'style','edit',...
'units','pix',...
'min',0,'max',1,... % for editing (?)
'position',onsetEditTextBoxInds(i,:),...
'backgroundcolor','w',...
'HorizontalAlign','center',...
'fontsize',16);
end
for i=1:4
if ismember(i,[2,4])
% buttons to create new pauses
S.pauseInits(i) = uicontrol(...
'style','push',...
'units','pixels',...
'position',pauseInitButtonInds(i,:),...
'fontsize',14,...
'string','Create');
% buttons to remove pauses
S.pauseRemoves(i) = uicontrol(...
'style','push',...
'units','pixels',...
'position',pauseRemoveButtonInds(i,:),...
'fontsize',14,...
'string','Remove');
end
end
% set call functions here to include all elements of figure
%%% left side %%%
set(S.uit,'CellSelectionCallback',{@uitable_CellSelectionCallback,S})
% breath navigation buttons
set(S.prevBreathButton,'call',{@prevBreathCallback,S});
set(S.nextBreathButton,'call',{@nextBreathCallback,S});
% left side buttons
set(S.noteButton,'call',{@noteCallback,S});
set(S.rejectButton,'call',{@rejectBreathCallback,S});
set(S.undoChangesButton,'call',{@undoChangesCallback,S});
set(S.saveChangesButton,'call',{@saveAllChangesCallback,S});
%%% right side %%%
% change plot when phase text is edited
set(S.phaseEditors(:),'call',{...
@editPlotFromTextCallback,...
S});
% pause buttons
for i=1:4
% create and remove pauses
if ismember(i,[2,4])
set(S.pauseInits(i),'call',{...
@createNewPauseFromButtonCallback,...
S,...
S.breathEditMenuColNames{i}});
set(S.pauseRemoves(i),'call',{...
@removePauseFromButtonCallback,...
S,...
S.breathEditMenuColNames{i}});
end
end
% plot first breath when this initializes
plotMeCallback({},{},S,0);
%%% Run until user clicks save all changes %%%
% save function changes tag of button to 'done'
waitfor(S.saveChangesButton,'Tag');
try
% get new bmObj from userdata
newBM=S.fh.UserData.newBM;
% recompute breath durations, volumes, etc.
newBM.manualAdjustPostProcess();
close(S.fh);
% prompt user to save output variable
answer = questdlg('Do you want to write a copy of the output to a file?', ...
'Yes', ...
'No');
if strcmp(answer,'Yes')
[file,path]=uiputfile('*.mat');
save(fullfile(path,file),'newBM');
end
catch
newBM=S.bmInit;
% if figure is closed without saving.
disp('No changes have been saved.');
end
end % main function
%%
%%% CALLBACK FUNCTIONS %%%
%%
%%% left side %%%
% select cell on table and remember breath number
function uitable_CellSelectionCallback(varargin)
% save the selected breath in UserData when you click a row in the table
eventdata=varargin{2};
S=varargin{3};
% sometimes this is called when eventdata is empty
if size(eventdata.Indices,1)>0
selectedRow = eventdata.Indices(1);
UserData=S.fh.UserData;
UserData.thisBreath=selectedRow;
% overwrite changes to last breath with this breath's params
UserData.tempPhaseOnsetChanges=UserData.breathEditMat(UserData.thisBreath,:);
set( S.fh, 'UserData', UserData);
% plot this breath when you click on it
plotMeCallback({},{},S,0);
end
end
% go to breath before this one
function [] = prevBreathCallback(varargin)
S = varargin{3}; % Get the structure.
UserData=S.fh.UserData;
thisBreath=UserData.thisBreath;
if thisBreath == 1
goToBreath=1;
else
goToBreath=thisBreath-1;
end
UserData.thisBreath=goToBreath;
% overwrite changes to last breath with this breath's params
UserData.tempPhaseOnsetChanges=UserData.breathEditMat(UserData.thisBreath,:);
set( S.fh, 'UserData', UserData);
plotMeCallback({},{},S,0);
end
% go to next breath
function [] = nextBreathCallback(varargin)
S = varargin{3}; % Get the structure.
UserData=S.fh.UserData;
thisBreath=UserData.thisBreath;
if thisBreath == UserData.nBreaths
goToBreath=UserData.nBreaths;
else
goToBreath=thisBreath+1;
end
UserData.thisBreath=goToBreath;
% overwrite changes to last breath with this breath's params
UserData.tempPhaseOnsetChanges=UserData.breathEditMat(UserData.thisBreath,:);
set( S.fh, 'UserData', UserData);
plotMeCallback({},{},S,0);
end
% add note to selected breath
function [] = noteCallback(varargin)
% Callback for pushbutton
S = varargin{3}; % Get the structure.
UserData=S.fh.UserData;
% prompt user for note
noteToAdd = inputdlg('Add a Note');
if ~isempty(noteToAdd)
% add note
UserData.breathSelectMat{UserData.thisBreath,5}=noteToAdd{1};
set( S.fh, 'UserData', UserData);
set( S.uit,'Data',S.fh.UserData.breathSelectMat);
end
end
% revert all changes made to this breath back to original
function undoChangesCallback(varargin)
S=varargin{3};
UserData=S.fh.UserData;
originalVals=UserData.initialBreathEditMat(UserData.thisBreath,:);
UserData.tempPhaseOnsetChanges=originalVals;
UserData.breathSelectMat{UserData.thisBreath,4}='valid';
set( S.fh, 'UserData', UserData);
set( S.uit,'Data',S.fh.UserData.breathSelectMat);
% plot it with black line
plotMeCallback({},{},S,1);
end
% reject selected breath
function [] = rejectBreathCallback(varargin)
% Callback for pushbutton
S = varargin{3}; % Get the structure.
UserData=S.fh.UserData;
% set status of this breath to rejected
UserData.breathSelectMat{UserData.thisBreath,4}='rejected';
set( S.fh, 'UserData', UserData);
set( S.uit,'Data',S.fh.UserData.breathSelectMat);
% plot it with red line
plotMeCallback({},{},S,1);
end
% function to plot current breath
function [] = plotMeCallback(varargin)
% Callback function that plots data for this breath, which is saved in
% temporary storage
S = varargin{3}; % Get the structure.
bmObj = S.fh.UserData.bmObj; % get bm
UserData=S.fh.UserData;
if nargin<4
isUpdatePlot=0;
else
isUpdatePlot=1;
end
if nargin>3
if iscell(varargin(4))
if varargin{4}==0
isUpdatePlot=0;
end
end
end
% get range of onset and offset of this breath
io=UserData.breathSelectMat{UserData.thisBreath,2};
eo=UserData.breathSelectMat{UserData.thisBreath,3};
breathStatus=UserData.breathSelectMat{UserData.thisBreath,4};
lineType='k-';
breathInfo='';
switch breathStatus
case 'valid'
lineType='k-';
breathInfo=breathStatus;
case 'edited'
lineType='b-';
breathInfo=breathStatus;
case 'rejected'
lineType='r-';
breathInfo=breathStatus;
end
if isnan(eo)
ibi=bmObj.secondaryFeatures('Average Inter-Breath Interval');
eo=io+ibi;
end
% plot breathing centered on selected breath
thisMidpoint=mean([io,eo]);
if ~isnan(thisMidpoint)
nSamplesInRecording=length(bmObj.baselineCorrectedRespiration);
plottingWindowLims=[...
round(S.xLims(1)*bmObj.srate+(io*bmObj.srate)),...
round(S.xLims(2)*bmObj.srate+(eo*bmObj.srate))];
% make sure plotting window doesn't extend beyond boundaries of
% data
if plottingWindowLims(1)<1
plottingWindowLims(1)=1;
end
if plottingWindowLims(2)>nSamplesInRecording-1
plottingWindowLims(2)=nSamplesInRecording;
end
plottingWindowInds=plottingWindowLims(1):plottingWindowLims(2);
try
timeThisWindow=bmObj.time(plottingWindowInds);
catch
keyboard
end
respThisWindow=bmObj.baselineCorrectedRespiration(plottingWindowInds);
newXLims=[min(timeThisWindow),max(timeThisWindow)];
hold(S.ax,'off');
plot(S.ax,...
timeThisWindow,...
respThisWindow,...
lineType,...
'LineWidth',2);
hold(S.ax,'on');
% update labels and title
titleText=sprintf('Breath %i/%i (%s)', ...
UserData.thisBreath,...
UserData.nBreaths,...
breathInfo);
set(get(S.ax,'XLabel'),'String','Time (S)');
set(get(S.ax,'YLabel'),'String','Amplitude');
set(get(S.ax,'title'),'String',titleText);
% update xlims
set(S.ax,'XLim',newXLims);
% draw helpful grid
grid(S.ax,'on');
% plot last exhale
if UserData.thisBreath>1
lastBreath=UserData.thisBreath-1;
% if exhale pause, plot exhale pause, if not just plot last exhale
lastExhalePause=S.fh.UserData.breathEditMat(lastBreath,4);
if ~isnan(lastExhalePause)
thisXInd=lastExhalePause;
thisYInd=bmObj.baselineCorrectedRespiration(1,round(lastExhalePause*bmObj.srate));
thisLabel='Last Exhale Pause';
else
lastExhale=UserData.breathEditMat(lastBreath,3);
thisXInd=lastExhale;
thisYInd=bmObj.baselineCorrectedRespiration(1,round(lastExhale*bmObj.srate));
thisLabel='Last Exhale';
end
scatter(thisXInd,thisYInd,'ko','filled','SizeData',80);
text(thisXInd,thisYInd,thisLabel,...
'VerticalAlignment','top',...
'HorizontalAlignment','left');
end
% plot next inhale
if UserData.thisBreath<UserData.nBreaths
nextBreath=UserData.thisBreath+1;
nextInhale=UserData.breathEditMat(nextBreath,1);
thisYInd=bmObj.baselineCorrectedRespiration(1,round(nextInhale*bmObj.srate));
scatter(nextInhale,thisYInd,'ko','filled','SizeData',80);
text(nextInhale,thisYInd,'Next Inhale',...
'VerticalAlignment','top',...
'HorizontalAlignment','left');
end
% create phase points for this breath
for ph=1:4
if ~isUpdatePlot
thisPhaseOnset=S.fh.UserData.breathEditMat(S.fh.UserData.thisBreath,ph);
else
thisPhaseOnset=S.fh.UserData.tempPhaseOnsetChanges(ph);
end
% put it in the edit box
set(S.phaseEditors(ph),'String',num2str(thisPhaseOnset));
if ~isnan(thisPhaseOnset)
thisPhaseInd=round(thisPhaseOnset*bmObj.srate);
if thisPhaseInd==0
thisPhaseInd=1;
end
if thisPhaseInd>length(bmObj.baselineCorrectedRespiration)
thisPhaseInd=length(bmObj.baselineCorrectedRespiration);
end
thisPhaseYInd=bmObj.baselineCorrectedRespiration(1,thisPhaseInd);
% make draggable points for this breath
dp=drawpoint(S.ax,...
'Position',[thisPhaseOnset,thisPhaseYInd],...
'Tag',S.breathEditMenuColNames{ph},...
'Color',S.myColors(ph+1,:));
addlistener(dp,'ROIMoved',@(src,evnt)pointMoveCallback(src,evnt,S));
end
end
end
end
%%% right side %%%
% create new pause onset
function createNewPauseFromButtonCallback(varargin)
S=varargin{3};
pauseType=varargin{4};
% get numbers in each phase edit field
UserData=S.fh.UserData;
if strcmp(pauseType,'Inhale Pause')
pauseInd=2;
thisMidpoint=mean(UserData.breathEditMat(UserData.thisBreath,[1,3]));
else
pauseInd=4;
thisExhale=UserData.breathEditMat(UserData.thisBreath,3);
if UserData.thisBreath<UserData.nBreaths
nextInhale=UserData.breathEditMat(UserData.thisBreath+1,1);
thisMidpoint=mean([thisExhale,nextInhale]);
else
theseLims=get(S.ax,'XLim');
thisMidpoint=mean([thisExhale,theseLims(2)]);
end
end
tempPhaseOnsetChanges=nan(1,4);
for ph=1:4
if ph==pauseInd
set(S.phaseEditors(ph),'String',num2str(thisMidpoint));
end
newInd=get(S.phaseEditors(ph),'String');
if isnumeric(str2double(newInd))
tempPhaseOnsetChanges(1,ph)=str2double(newInd);
else
disp('This must be a number');
end
end
tempPhaseOnsetChanges(1,pauseInd)=thisMidpoint;
% save it
UserData.tempPhaseOnsetChanges=tempPhaseOnsetChanges;
set( S.fh, 'UserData', UserData);
saveTempChangesCallback({},{},S);
plotMeCallback({},{},S,1);
end
% remove pause from figure
function removePauseFromButtonCallback(varargin)
S=varargin{3};
pauseType=varargin{4};
% get numbers in each phase edit field
UserData=S.fh.UserData;
if strcmp(pauseType,'Inhale Pause')
pauseInd=2;
else
pauseInd=4;
end
tempPhaseOnsetChanges=nan(1,4);
for ph=1:4
if ph==pauseInd
set(S.phaseEditors(ph),'String','NaN');
end
newInd=get(S.phaseEditors(ph),'String');
if isnumeric(str2double(newInd))
tempPhaseOnsetChanges(1,ph)=str2double(newInd);
else
disp('This must be a number');
end
end
% save changes
UserData.tempPhaseOnsetChanges=tempPhaseOnsetChanges;
set( S.fh, 'UserData', UserData);
saveTempChangesCallback({},{},S);
plotMeCallback({},{},S,1);
end
% when you edit the text in the phase textbox it automatically moves the
% point
function editPlotFromTextCallback(varargin)
S=varargin{3};
% get numbers in each phase edit field
UserData=S.fh.UserData;
tempPhaseOnsetChanges=nan(1,4);
for ph=1:4
newInd=get(S.phaseEditors(ph),'String');
if isnumeric(str2double(newInd))
tempPhaseOnsetChanges(1,ph)=str2double(newInd);
else
disp('This must be a number');
end
end
% save changes
UserData.tempPhaseOnsetChanges=tempPhaseOnsetChanges;
set( S.fh, 'UserData', UserData);
saveTempChangesCallback({},{},S);
plotMeCallback({},{},S,1);
end
% This is called when you move a point
function pointMoveCallback(varargin)
% which point was moved
src=varargin{1};
thisTag=src.Tag;
thisXPos=src.Position(1);
S=varargin{3};
UserData=S.fh.UserData;
if ~isempty(thisTag)
switch thisTag
case 'Inhale'
tagInd=1;
case 'Inhale Pause'
tagInd=2;
case 'Exhale'
tagInd=3;
case 'Exhale Pause'
tagInd=4;
end
% set temporary data at phase corresponding to the point to new x
% location
UserData.tempPhaseOnsetChanges(1,tagInd)=thisXPos;
set( S.fh, 'UserData', UserData);
saveTempChangesCallback({},{},S);
plotMeCallback({},{},S,1);
end
end
% saves temporary changes into storage
% calls validityDecision to check that points make sense
function saveTempChangesCallback(varargin)
S=varargin{3};
UserData=S.fh.UserData;
newVals=UserData.tempPhaseOnsetChanges;
UserData=S.fh.UserData;
newValsInSamples=round(newVals*UserData.bmObj.srate);
% check that new vals are valid
[changesAreValid,errorText]=checkNewVals(S,newValsInSamples);
% raise error if there is one
if ~isempty(errorText)
% f = uifigure;
% uialert(f,errorText,'BM GUI Error');
warndlg(errorText);
end
if changesAreValid
% check if values are new
oldValsInSamples=UserData.breathEditMat(UserData.thisBreath,:)*UserData.bmObj.srate;
% doing this way to handle nans
valueDiffs=nansum([newValsInSamples;-oldValsInSamples],1);
if sum(valueDiffs)~=0
% save these values
UserData.breathEditMat(UserData.thisBreath,:)=UserData.tempPhaseOnsetChanges;
% set status of this breath to edited
UserData.breathSelectMat{UserData.thisBreath,4}='edited';
set( S.fh, 'UserData', UserData);
set( S.uit,'Data',S.fh.UserData.breathSelectMat);
else
% warndlg('No changes have been made. Update the plot after you move a point before attempting to save.');
end
end
end
% checks that selected phases for this breath are valid before saving
function [validityDecision,errorText]=checkNewVals(S,newVals)
validityDecision=1;
errorText=[];
UserData=S.fh.UserData;
inhaleOnset=newVals(1);
inhalePauseOnset=newVals(2);
exhaleOnset=newVals(3);
exhalePauseOnset=newVals(4);
% check that changes are valid
% rules:
% points must be within bounds of recording
% phases must proceed in correct order (i,ip,e,ep)
% check for pauses because nans break things
isInhalePause=~isnan(inhalePauseOnset);
isExhalePause=~isnan(exhalePauseOnset);
recordingLen=length(UserData.bmObj.rawRespiration);
% are inhales and exhales within bounds of recording?
if any(newVals<1)
validityDecision=0;
errorText='Selected points are not within the timecourse of the recording.';
end
if any(newVals>recordingLen)
validityDecision=0;
errorText='Selected points are not within the timecourse of the recording.';
end
% check that phases proceed in order
% check inhale
% inhale lims
if UserData.thisBreath==1
inhaleMinBoundary=1;
else
% last exhale
inhaleMinBoundary=UserData.breathEditMat(UserData.thisBreath-1,3)*UserData.bmObj.srate;
end
if isInhalePause
inhaleMaxBoundary=inhalePauseOnset;
else
inhaleMaxBoundary=exhaleOnset;
end
% compare value to lims
if inhaleOnset<inhaleMinBoundary || inhaleOnset>inhaleMaxBoundary
validityDecision=0;
errorText='Invalid Inhale Value. It must take place after the preceeding exhale and before the next exhale.';
end
% check inhale pause
if isInhalePause
% lims
ipMinBoundary=inhaleOnset;
ipMaxBoundary=exhaleOnset;
% compare to lims
if inhalePauseOnset<ipMinBoundary || inhalePauseOnset>ipMaxBoundary
validityDecision=0;
errorText='Invalid Inhale Pause Value. It must take place after the preceeding inhale and before the next exhale.';
end
end
% check exhale
% lims
if isInhalePause
exhaleMinBoundary=inhalePauseOnset;
else
exhaleMinBoundary=inhaleOnset;
end
if UserData.thisBreath==UserData.nBreaths
exhaleMaxBoundary=recordingLen;
else
% next inhale
exhaleMaxBoundary=UserData.breathEditMat(UserData.thisBreath+1,1)*UserData.bmObj.srate;
end
% compare value to lims
if exhaleOnset<exhaleMinBoundary || exhaleOnset>exhaleMaxBoundary
validityDecision=0;
errorText='Invalid Exhale Value. It must take place after the preceeding inhale or inhale pause and before the next exhale pause or inhale.';
end
% check exhale pause
if isExhalePause
% lims
epMinBoundary=exhaleOnset;
if UserData.thisBreath==UserData.nBreaths
epMaxBoundary=recordingLen;
else
% next inhale
epMaxBoundary=UserData.breathEditMat(UserData.thisBreath+1,1)*UserData.bmObj.srate;
end
% compare to lims
if exhalePauseOnset<epMinBoundary || exhalePauseOnset>epMaxBoundary
validityDecision=0;
errorText='Invalid Exhale Pause Value. It must take place after the preceeding exhale and before the next inhale.';
end
end
end
% save all changes that have been made
function saveAllChangesCallback(varargin)
src=varargin{1};
S=varargin{3};
UserData=S.fh.UserData;
% convert from time back to samples
inhaleOnsets=round(UserData.breathEditMat(:,1)' * UserData.bmObj.srate);
inhalePauseOnsets=round(UserData.breathEditMat(:,2)' * UserData.bmObj.srate);
exhaleOnsets=round(UserData.breathEditMat(:,3)' * UserData.bmObj.srate);
exhalePauseOnsets=round(UserData.breathEditMat(:,4)' * UserData.bmObj.srate);
statuses=UserData.breathSelectMat(:,4)';
notes=UserData.breathSelectMat(:,5)';
answer = questdlg('Are you sure that you want to save all changes? This window will be closed and your edits will be saved into the output variable.', ...
'Yes', ...
'No');
if strcmp(answer,'Yes')
newBM=UserData.bmObj;
newBM.inhaleOnsets=inhaleOnsets;
newBM.inhalePauseOnsets=inhalePauseOnsets;
newBM.exhaleOnsets=exhaleOnsets;
newBM.exhalePauseOnsets=exhalePauseOnsets;
newBM.notes=notes;
newBM.statuses=statuses;
newBM.featuresManuallyEdited=1;
UserData.newBM=newBM;
set( S.fh, 'UserData', UserData);
% setting tag to done triggers figure to save in main function.
set( src, 'Tag', 'done');
end
end
|
github
|
lbrandt/ez-shocks-master
|
jln_compute_uy.m
|
.m
|
ez-shocks-master/JLN2015/jln_compute_uy.m
| 1,919 |
utf_8
|
b8836eddf77388356060468d2369e765
|
function [U, evy, phi, lambda, phiy] = jln_compute_uy(xy,thy,yb,py,evf,phif)
% -------------------------------------------------------------------------
% Compute expected volatility of predictors up to horizon h
% -------------------------------------------------------------------------
% Initialize parameters
h = length(evf);
r = size(evf{1},2);
pf = size(phif,1)/r;
pz = (length(yb)-1-py)/r;
T = length(xy);
% Preallocate variables
U = zeros(T,h);
if pf >1; evf0 = sparse(1,r*(pf-1),0); end;
if pf==1; evf0 = []; end;
if py >1; evy0 = sparse(1,py-1,0); end;
if py==1; evy0 = []; end;
% Construct the main phi matrix
if pf >pz; lambda_topright = sparse(1,(pf-pz)*r,0); end;
if pf==pz; lambda_topright = []; end;
if py >1; lambda_bottom = sparse(py-1,r*pf,0); end;
if py==1; lambda_bottom = []; end;
lambda = [yb(py+2:end),lambda_topright;lambda_bottom];
phiy_top = yb(2:py+1);
if py >1; phiy_bottom = [sparse(1:py-1,1:py-1,1),sparse(py-1,1,0)]; end;
if py==1; phiy_bottom = []; end;
phiy = [phiy_top;phiy_bottom];
phi_topright = sparse(r*pf,py,0);
phi = [phif,phi_topright;lambda,phiy];
% Compute uncertainty using the recursion
alpha = thy(1);
beta = thy(2);
tau2 = thy(3);
x = xy;
for j = 1:h
evy{j} = expectedvar(alpha,beta,tau2,x,j); %Et[(v^y_t)^2]
end;
for t = 1:T
for j = 1:h
ev = sparse(1:r*pf+py,1:r*pf+py,[evf{j}(t,:),evf0,evy{j}(t),evy0]);
if j == 1; u = ev; end;
if j > 1; u = phi*u*phi' + ev; end;
U(t,j) = u(r*pf+1,r*pf+1); % select relevant entry
end
end
end
% Auxiliary function
function [out] = expectedvar(a,b,t2,x,h)
% -------------------------------------------------------------------------
% Compute Et[exp{x(t+h)}] using the AR(1) law of motion for x(t)
% -------------------------------------------------------------------------
out = exp(a*(1-b^h)/(1-b)+t2/2*(1-b^(2*h))/(1-b^2)+ b^h*x);
end
|
github
|
lbrandt/ez-shocks-master
|
jln_compute_uf.m
|
.m
|
ez-shocks-master/JLN2015/jln_compute_uf.m
| 1,211 |
utf_8
|
1a05c90e2da7e0b8622fbdf4cd008662
|
function [evf,phif] = jln_compute_uf(xf,thf,fb,h)
% -------------------------------------------------------------------------
% Compute expected volatility of predictors up to horizon h,and construct
% coefficient matrix phiF
% -------------------------------------------------------------------------
% Initialize parameters
r = size(xf,2);
pf = size(fb,2)-1;
% Create phif matrix
phif_top = [];
for j = 2:pf+1
phif_top = [phif_top,sparse(1:r,1:r,fb(:,j))];
end
if pf > 1
phif_bot = [sparse(1:r*(pf-1),1:r*(pf-1),1),sparse(r*(pf-1),r,0)];
phif = [phif_top;phif_bot];
else
phif = phif_top;
end
% Compute evf
evf = cell(h,1);
for j = 1:h;
for i = 1:r
alpha = thf(1,i);
beta = thf(2,i);
tau2 = thf(3,i);
x = xf(:,i);
evf{j}(:,i) = expectedvar(alpha,beta,tau2,x,j); %Et[(v^f_t)^2]
end;
end;
end
% Auxiliary function
function [out] = expectedvar(a,b,t2,x,h)
% -------------------------------------------------------------------------
% Compute Et[exp{x(t+h)}] using the AR(1) law of motion for x(t)
% -------------------------------------------------------------------------
out = exp(a*(1-b^h)/(1-b)+t2/2*(1-b^(2*h))/(1-b^2)+ b^h*x);
end
|
github
|
lbrandt/ez-shocks-master
|
compute_uy.m
|
.m
|
ez-shocks-master/MATLAB/compute_uy.m
| 2,279 |
utf_8
|
fb890a41e1a15dc300343172f9686568
|
function [U, evy] = compute_uy(xy,thy,yb,py,evf,phif)
% -------------------------------------------------------------------------
% Compute expected volatility of predictors up to horizon h
%
%
% Input
% xy Latent?
% thy Parameter vector of logVar process [3 x 1]
% yb ybetas
% py ylags
% evf expected variance in factors
% phif factors companion matrix
%
% Output
% U uncertainty
% evy expected variance in y
%
% Dependencies {source}
%
% -------------------------------------------------------------------------
% Initialize parameters
h = length(evf);
r = size(evf{1},2);
pf = size(phif,1)/r;
pz = (length(yb)-1-py)/r;
T = length(xy);
% Preallocate variables
U = zeros(T,h);
if pf >1; evf0 = sparse(1,r*(pf-1),0); end;
if pf==1; evf0 = []; end;
if py >1; evy0 = sparse(1,py-1,0); end;
if py==1; evy0 = []; end;
% Construct the main phi matrix
if pf >pz; lambda_topright = sparse(1,(pf-pz)*r,0); end;
if pf==pz; lambda_topright = []; end;
if py >1; lambda_bottom = sparse(py-1,r*pf,0); end;
if py==1; lambda_bottom = []; end;
lambda = [yb(py+2:end),lambda_topright;lambda_bottom];
phiy_top = yb(2:py+1);
if py >1; phiy_bottom = [sparse(1:py-1,1:py-1,1),sparse(py-1,1,0)]; end; % Why not use speye?
if py==1; phiy_bottom = []; end;
phiy = [phiy_top;phiy_bottom];
phi_topright = sparse(r*pf,py,0);
phi = [phif,phi_topright;lambda,phiy];
% Compute uncertainty using the recursion
alpha = thy(1);
beta = thy(2);
tau2 = thy(3);
x = xy;
for j = 1:h
evy{j} = expectedvar(alpha,beta,tau2,x,j); % Et[(v^y_t)^2]
end;
for t = 1:T
for j = 1:h
ev = sparse(1:r*pf+py,1:r*pf+py,[evf{j}(t,:),evf0,evy{j}(t),evy0]);
if j == 1; u = ev; end;
if j > 1; u = phi*u*phi' + ev; end;
U(t,j) = u(r*pf+1,r*pf+1); % select relevant entry
end
end
end
% Auxiliary function
function [out] = expectedvar(a,b,t2,x,h)
% -------------------------------------------------------------------------
% Compute Et[exp{x(t+h)}] using the AR(1) law of motion for x(t)
% -------------------------------------------------------------------------
out = exp(a*(1-b^h)/(1-b)+t2/2*(1-b^(2*h))/(1-b^2)+ b^h*x);
end
|
github
|
lbrandt/ez-shocks-master
|
kde.m
|
.m
|
ez-shocks-master/MATLAB/kde.m
| 5,478 |
utf_8
|
83553f2f78c03c6231ba48e24eb20343
|
function [bandwidth,density,xmesh,cdf]=kde(data,n,MIN,MAX)
% Reliable and extremely fast kernel density estimator for one-dimensional data;
% Gaussian kernel is assumed and the bandwidth is chosen automatically;
% Unlike many other implementations, this one is immune to problems
% caused by multimodal densities with widely separated modes (see example). The
% estimation does not deteriorate for multimodal densities, because we never assume
% a parametric model for the data.
% INPUTS:
% data - a vector of data from which the density estimate is constructed;
% n - the number of mesh points used in the uniform discretization of the
% interval [MIN, MAX]; n has to be a power of two; if n is not a power of two, then
% n is rounded up to the next power of two, i.e., n is set to n=2^ceil(log2(n));
% the default value of n is n=2^12;
% MIN, MAX - defines the interval [MIN,MAX] on which the density estimate is constructed;
% the default values of MIN and MAX are:
% MIN=min(data)-Range/10 and MAX=max(data)+Range/10, where Range=max(data)-min(data);
% OUTPUTS:
% bandwidth - the optimal bandwidth (Gaussian kernel assumed);
% density - column vector of length 'n' with the values of the density
% estimate at the grid points;
% xmesh - the grid over which the density estimate is computed;
% - If no output is requested, then the code automatically plots a graph of
% the density estimate.
% cdf - column vector of length 'n' with the values of the cdf
% Reference:
% Kernel density estimation via diffusion
% Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010)
% Annals of Statistics, Volume 38, Number 5, pages 2916-2957.
%
% Example:
% data=[randn(100,1);randn(100,1)*2+35 ;randn(100,1)+55];
% kde(data,2^14,min(data)-5,max(data)+5);
data=data(:); %make data a column vector
if nargin<2 % if n is not supplied switch to the default
n=2^14;
end
n=2^ceil(log2(n)); % round up n to the next power of 2;
if nargin<4 %define the default interval [MIN,MAX]
minimum=min(data); maximum=max(data);
Range=maximum-minimum;
MIN=minimum-Range/2; MAX=maximum+Range/2;
end
% set up the grid over which the density estimate is computed;
R=MAX-MIN; dx=R/(n-1); xmesh=MIN+[0:dx:R]; N=length(unique(data));
%bin the data uniformly using the grid defined above;
initial_data=histc(data,xmesh)/N; initial_data=initial_data/sum(initial_data);
a=dct1d(initial_data); % discrete cosine transform of initial data
% now compute the optimal bandwidth^2 using the referenced method
I=[1:n-1]'.^2; a2=(a(2:end)/2).^2;
% use fzero to solve the equation t=zeta*gamma^[5](t)
t_star=root(@(t)fixed_point(t,N,I,a2),N);
% smooth the discrete cosine transform of initial data using t_star
a_t=a.*exp(-[0:n-1]'.^2*pi^2*t_star/2);
% now apply the inverse discrete cosine transform
if (nargout>1)|(nargout==0)
density=idct1d(a_t)/R;
end
% take the rescaling of the data into account
bandwidth=sqrt(t_star)*R;
density(density<0)=eps; % remove negatives due to round-off error
if nargout==0
figure(1), plot(xmesh,density)
end
% for cdf estimation
if nargout>3
f=2*pi^2*sum(I.*a2.*exp(-I*pi^2*t_star));
t_cdf=(sqrt(pi)*f*N)^(-2/3);
% now get values of cdf on grid points using IDCT and cumsum function
a_cdf=a.*exp(-[0:n-1]'.^2*pi^2*t_cdf/2);
cdf=cumsum(idct1d(a_cdf))*(dx/R);
% take the rescaling into account if the bandwidth value is required
bandwidth_cdf=sqrt(t_cdf)*R;
end
end
%################################################################
function out=fixed_point(t,N,I,a2)
% this implements the function t-zeta*gamma^[l](t)
l=7;
f=2*pi^(2*l)*sum(I.^l.*a2.*exp(-I*pi^2*t));
for s=l-1:-1:2
K0=prod([1:2:2*s-1])/sqrt(2*pi); const=(1+(1/2)^(s+1/2))/3;
time=(2*const*K0/N/f)^(2/(3+2*s));
f=2*pi^(2*s)*sum(I.^s.*a2.*exp(-I*pi^2*time));
end
out=t-(2*N*sqrt(pi)*f)^(-2/5);
end
%##############################################################
function out = idct1d(data)
% computes the inverse discrete cosine transform
[nrows,ncols]=size(data);
% Compute weights
weights = nrows*exp(i*(0:nrows-1)*pi/(2*nrows)).';
% Compute x tilde using equation (5.93) in Jain
data = real(ifft(weights.*data));
% Re-order elements of each column according to equations (5.93) and
% (5.94) in Jain
out = zeros(nrows,1);
out(1:2:nrows) = data(1:nrows/2);
out(2:2:nrows) = data(nrows:-1:nrows/2+1);
% Reference:
% A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
end
%##############################################################
function data=dct1d(data)
% computes the discrete cosine transform of the column vector data
[nrows,ncols]= size(data);
% Compute weights to multiply DFT coefficients
weight = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).'];
% Re-order the elements of the columns of x
data = [ data(1:2:end,:); data(end:-2:2,:) ];
% Multiply FFT by weights:
data= real(weight.* fft(data));
end
function t=root(f,N)
% try to find smallest root whenever there is more than one
N=50*(N<=50)+1050*(N>=1050)+N*((N<1050)&(N>50));
tol=10^-12+0.01*(N-50)/1000;
flag=0;
while flag==0
try
t=fzero(f,[0,tol]);
flag=1;
catch
tol=min(tol*2,.1); % double search interval
end
if tol==.1 % if all else fails
t=fminbnd(@(x)abs(f(x)),0,.1); flag=1;
end
end
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
getPpState.m
|
.m
|
DirCol5i-master/DirCol5i/getPpState.m
| 2,418 |
utf_8
|
7e0733032826758d23a4c10b4ecdebde
|
function [PPx, PPdx, PPddx, PPdddx, PPddddx] = getPpState(t,x,dx,ddx)
% [PPx, PPdx, PPddx, PPdddx, PPddddx] = getPpState(t,x,dx,ddx)
%
% This function computes pp-form splines for the state and derivatives, to
% be evalauted by Matlab's ppval() command.
%
% INPUTS:
% t = [1,nt] = time at the knot points
% x = [nx,nt] = position at the knot points
% dx = [nx,nt] = velocity at the knot points
% ddx = [nx,nt] = acceleration at the knot points
%
% OUTPUTS: nc = 3*(nt-1)
% PPx = pp-form struct with x trajectory
% PPdx = pp-form struct with dx trajectory
% PPddx = pp-form struct with ddx trajectory
% PPdddx = pp-form struct with dddx trajectory
% PPddddx = pp-form struct with ddddx trajectory
%
%%%% Dimension stuff:
nt = length(t);
nx = size(x,1);
ns = nt - 1;
%%%% Break apart by segment:
iA = 1:(nt-1);
iB = 2:nt;
tA = t(iA);
tB = t(iB);
%%%% Construct the state splines
tLow = ones(nx,1)*tA;
tUpp = ones(nx,1)*tB;
xLow = x(:,iA);
xUpp = x(:,iB);
dxLow = dx(:,iA);
dxUpp = dx(:,iB);
ddxLow = ddx(:,iA);
ddxUpp = ddx(:,iB);
[C1,C2,C3,C4,C5,C6] = autoGen_stateSplineCoeffs(...
0*tLow,tUpp-tLow,...
xLow,xUpp,...
dxLow,dxUpp,...
ddxLow,ddxUpp);
% State:
orderQuintic = 6;
C = zeros(nx*ns,orderQuintic);
for i=1:ns
idx = nx*(i-1)+(1:nx);
C(idx,:) = [C6(:,i),C5(:,i),C4(:,i),C3(:,i),C2(:,i),C1(:,i)];
end
PPx = getPp(t,C,orderQuintic,nx);
% Derivative:
C = zeros(nx*ns,orderQuintic-1);
for i=1:ns
idx = nx*(i-1)+(1:nx);
C(idx,:) = [5*C6(:,i),4*C5(:,i),3*C4(:,i),2*C3(:,i),1*C2(:,i)];
end
PPdx = getPp(t,C,orderQuintic-1,nx);
% Second Derivative:
C = zeros(nx*ns,orderQuintic-2);
for i=1:ns
idx = nx*(i-1)+(1:nx);
C(idx,:) = [5*4*C6(:,i),4*3*C5(:,i),3*2*C4(:,i),2*1*C3(:,i)];
end
PPddx = getPp(t,C,orderQuintic-2,nx);
% Third Derivative:
C = zeros(nx*ns,orderQuintic-3);
for i=1:ns
idx = nx*(i-1)+(1:nx);
C(idx,:) = [5*4*3*C6(:,i),4*3*2*C5(:,i),3*2*1*C4(:,i)];
end
PPdddx = getPp(t,C,orderQuintic-3,nx);
% Fourth Derivative:
C = zeros(nx*ns,orderQuintic-4);
for i=1:ns
idx = nx*(i-1)+(1:nx);
C(idx,:) = [5*4*3*2*C6(:,i),4*3*2*1*C5(:,i)];
end
PPddddx = getPp(t,C,orderQuintic-4,nx);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pp = getPp(tKnot,coeff,order,nDim)
pp.form = 'pp';
pp.breaks = tKnot;
pp.coefs = coeff;
pp.pieces = length(tKnot)-1;
pp.order = order;
pp.dim = nDim;
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
Derive_Splines.m
|
.m
|
DirCol5i-master/DirCol5i/Derive_Splines.m
| 2,334 |
utf_8
|
daf7621dfaf229534a357716fc7cbb59
|
function Derive_Splines()
%
% Derive the equations that are usedto construct the splines to interpolate
% the solution.
%
% Here we assume that the function is defined over the domain [tA, tB]
%
% The state and control at the upper boundary is given by xB and uB, while
% the state and control ad the lower boundary is given by xA and uA;
%
deriveStateSpline();
deriveControlSpline();
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [C,t,x,dx,ddx] = getPolynomial(n)
%
% y(t) = C1 + C2*t + C3*t^2 + ...
%
% INPUTS:
% n = Order of the polynomial
%
% OUTPUTS: (all symbolic)
% C = [n+1, 1] = vector of coefficients
C = sym('C',[n+1,1],'real'); %Coefficients of polynomial
t = sym('t', 'real'); %continuous time t0 <= t < t1
x = sym(0);
for i = 1:(n+1)
x = x + C(i)*t^(i-1);
end
dx = diff(x,t);
ddx = diff(dx,t);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function deriveStateSpline()
order = 5;
[C,t,x,dx,ddx] = getPolynomial(order);
syms tA tB xA dxA ddxA xB dxB ddxB 'real'
eqn1 = subs(x,t,tA) - xA;
eqn2 = subs(dx,t,tA) - dxA;
eqn3 = subs(ddx,t,tA) - ddxA;
eqn4 = subs(x,t,tB) - xB;
eqn5 = subs(dx,t,tB) - dxB;
eqn6 = subs(ddx,t,tB) - ddxB;
eqns = [eqn1;eqn2;eqn3;eqn4;eqn5;eqn6];
[A,b] = equationsToMatrix(eqns,C);
soln = A\b;
matlabFunction(soln(1),soln(2),soln(3),soln(4),soln(5),soln(6),...
'file','autoGen_stateSplineCoeffs.m',...
'vars',{tA,tB,xA,xB,dxA,dxB,ddxA,ddxB},...
'outputs',{'C1','C2','C3','C4','C5','C6'});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function deriveControlSpline()
order = 3;
[C,t,u,du] = getPolynomial(order);
syms tA tB uA duA uB duB 'real'
eqn1 = subs(u,t,tA) - uA;
eqn2 = subs(du,t,tA) - duA;
eqn3 = subs(u,t,tB) - uB;
eqn4 = subs(du,t,tB) - duB;
eqns = [eqn1;eqn2;eqn3;eqn4];
[A,b] = equationsToMatrix(eqns,C);
soln = A\b;
matlabFunction(soln(1),soln(2),soln(3),soln(4),...
'file','autoGen_controlSplineCoeffs.m',...
'vars',{tA,tB,uA,uB,duA,duB},...
'outputs',{'C1','C2','C3','C4'});
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
meshAnalysis.m
|
.m
|
DirCol5i-master/DirCol5i/meshAnalysis.m
| 2,386 |
utf_8
|
380d2c8d28aadcda6056613a31f81ccc
|
function mesh = meshAnalysis(soln,F,Opt)
%
% This function computes the error estimates for a given solution to the
% trajectory optimization problem.
%
t = soln.knotPts.t;
ns = length(t)-1;
nx = size(soln.knotPts.x,1);
Eta = zeros(nx,ns); % Integral of absolute error in each segment
dynErr = @(time)( abs(getDynErr(time,soln,F)) ); % Error at time t in the dynamics
tol = Opt.mesh.tol/10; %Error estimate tolerance (slightly overestimate)
for k=1:ns % Loop through each segment
Eta(:,k) = rombergQuadrature(dynErr, t([k,k+1]), tol);
end
mesh = meshAnalysisCore(Eta,Opt,soln);
mesh.dynErrFun = dynErr; % pp struct to interpolate error in each segment
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dynErr = getDynErr(t,soln,F)
%
% Compute the local defect in the dynamics equations
%
x = ppval(soln.pp.x,t);
dx = ppval(soln.pp.dx,t);
ddx = ppval(soln.pp.ddx,t);
u = ppval(soln.pp.u,t);
dynErr = F.dynamics(t,x,dx,ddx,u);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mesh = meshAnalysisCore(Eta,Opt,soln)
tol = Opt.mesh.tol;
nMax = Opt.mesh.maxSubDivide;
err = max(Eta,[],1); %Choose dimension with maximum error in each segment
methodOrder = 6; % Collocation method order
tolTarget = 0.1*tol; % From Betts - try to do about 10 times better than required
n = (tolTarget./err).^(-1/methodOrder); % Estimate how many sub-divisions are required
n = ceil(n);
n(n<1) = 1;
n(n>nMax) = nMax;
mesh.tol = tol;
mesh.maxErr = max(max(Eta));
mesh.converged = mesh.maxErr < mesh.tol;
mesh.segErr = Eta; %Integral of absolute error in each segment
mesh.subdivide = n;
mesh.previous = soln.guess.frac;
mesh.proposed = getNewMesh(mesh.previous, n);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newMesh = getNewMesh(oldMesh, nSubDivide)
%
% Sub-divides the old mesh to get the new mesh.
%
newMesh = zeros(1,sum(nSubDivide));
idx = 0;
for k = 1:length(nSubDivide)
index = idx + (1:nSubDivide(k));
newMesh(index) = ones(1,nSubDivide(k))*oldMesh(k)/nSubDivide(k);
idx = index(end);
end
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
dirCol5i.m
|
.m
|
DirCol5i-master/DirCol5i/dirCol5i.m
| 20,012 |
utf_8
|
eb1247a06c75c294e407759448a9dfe9
|
function output = dirCol5i(problem)
% output = dirCol5i(problem)
%
% Solves a continuous-time, single-phase trajectory optimization problem,
% with implicit second order dynamics.
%
% NOTATION:
%
% continuous (path) input, listed in order:
% t = [1, nTime] = time vector (col points)
% x = [nx, nTime] = position at each col point
% dx = [nx, nTime] = velocity at each col point
% ddx = [nx, nTime] = acceleration at each col point
% dddx = [nx, nTime] = jerk at each col point
% ddddx = [nx, nTime] = snap at each col point
% u = [nu, nTime] = control vector at each col point
% du = [nu, nTime] = control rate vector at each col point
%
% boundary (end-point) input, listed in order:
% t0 = initial time
% t1 = final time
% x0 = x(t0) = initial position
% x1 = x(t1) = final position
% dx0 = dx(t0) = initial velocity
% dx1 = dx(t1) = final velocity
%
% INPUT: "problem" -- struct with fields:
%
% func -- struct for user-defined functions, passed as function handles
%
% zero = dynamics(t,x,dx,ddx,u)
% zero = [nx,nTime] = equality constraint, drive to zero
%
% dObj = pathObj(t,x,dx,ddx,u, dddx, ddddx, du)
% dObj = [1, nTime] = integrand from the cost function
%
% obj = bndObj(boundary)
% obj = scalar = objective function for boundry points
%
% [c, ceq] = pathCst(t,x,dx,ddx,u)
% c = column vector of inequality constraints ( c <= 0 )
% ceq = column vector of equality constraints ( c == 0 )
%
% [c, ceq] = bndCst(boundary)
% c = column vector of inequality constraints ( c <= 0 )
% ceq = column vector of equality constraints ( c == 0 )
%
% How to pass parameters to your functions:
% - suppose that your dynamics function is pendulum.m and it
% accepts a struct of parameters p. When you are setting up the
% problem, define the struc p in your workspace and then use the
% following command to pass the function:
% problem.func.dynamics = @(t,x,u)( pendulum(t,x,u,p) );
%
%
% bounds - struct with bounds for the problem:
%
% .t0.low = [scalar]
% .t0.upp = [scalar]
%
% .t1.low = [scalar]
% .t1.upp = [scalar]
%
% .x0.low = [nx,1] = bounds on initial position
% .x0.upp = [nx,1]
%
% .x.low = [nx,1] = bound on position along the trajectory
% .x.upp = [nx,1]
%
% .x1.low = [nx,1] = bounds on final position
% .x1.upp = [nx,1]
%
% .dx0.low = [nx,1] = bounds on initial velocity
% .dx0.upp = [nx,1]
%
% .dx.low = [nx,1] = bound on velocity along the trajectory
% .dx.upp = [nx,1]
%
% .dx1.low = [nx,1] = bounds on final velocity
% .dx1.upp = [nx,1]
%
% .u.low = [nu, 1] = bounds on control along the trajectory
% .u.upp = [nu, 1]
%
%
%
% guess - struct with an initial guess at the trajectory
%
% .t = [1, nt]
% .x = [nx, nt]
% .dx = [nx, nt]
% .ddx = [nx, nt] (optional)
% .u = [nu, nt]
% .du = [nu, nt] (optional)
%
% options = options for the transcription algorithm (this function)
%
% .nlpOpt = options to pass through to fmincon
%
% .mesh = struct of options for constructing and refining the mesh
% .nSegmentInit = scalar int = number of segment for first mesh
% .tol = scalar = tolerance for mesh refinement in an interval
% .maxIter = scalar int = limit on mesh refinement (1 = no refinement)
% .maxSubDivide = scalar int = limit on how segment sub-division
%
%
% OUTPUT: "ouput" -- struct with fields:
%
% .options = copy of problem.options, includeding default values
%
% .bounds = copy of problem.bounds;
%
% .func = copy of problem.func
%
% .soln(nIter) = struct array with information about each mesh iteration
%
%
% .grid = trajectory at the collocation points
% .t = [1, nCol] = time
% .w = [1, nCol] = quadrature weights
% .x = [nx, nCol] = position
% .dx = [nx, nCol] = velocity
% .ddx = [nx, nCol] = acceleration
% .dddx = [nx, nCol] = jerk
% .ddddx = [nx, nCol] = snap
% .u = [nu, nCol] = control
% .du = [nu, nCol] = control rate
%
% .pp = A collection of "pp" structs that define piecewise-polynomial
% splines in matlab. Evaluate the splines using ppval. The field names
% are identical to those in col. For interpolating the solution. Splines
% are method-consistent. Also, derivative relationships are obtained by
% direct differentiation of the splines (in both the interpolation and
% the collocation method).
%
% .info = information about the optimization run
% .nlpTime = time (seconds) spent in fmincon
% .exitFlag = fmincon exit flag
% .objVal = value of the objective function
% .[all fields in the fmincon "output" struct]
%
% .guess = initialization for each mesh iteration
%
% .mesh = details about the mesh for this iteration
%
%
global DIM USE_LOBOTTO_POINTS
USE_LOBOTTO_POINTS = true; % True == algorithm in paper
% Check the inputs, populate with defaults
problem = inputValidation(problem);
% To make code more readable
B = problem.bounds;
F = problem.func;
Opt = problem.options;
% Basic problem dimension stuff:
DIM = [];
DIM.nx = size(problem.guess.x,1);
DIM.nu = size(problem.guess.u,1);
% Convert the user's guess into a spline for interpolation:
G.x = spline(problem.guess.t, problem.guess.x);
G.dx = spline(problem.guess.t, problem.guess.dx);
G.ddx = spline(problem.guess.t, problem.guess.ddx);
G.u = spline(problem.guess.t, problem.guess.u);
G.du = spline(problem.guess.t, problem.guess.du);
% Compute an initial mesh to solve on:
nSegment = Opt.mesh.nSegmentInit;
G.frac = ones(1,nSegment)/nSegment;
G.tSpan = problem.guess.t([1,end]);
for iMesh = 1:Opt.mesh.maxIter
if iMesh == 1
soln(iMesh) = dirColGaussCore(G,B,F,Opt); %#ok<AGROW>
else
G = soln(iMesh-1).pp;
G.frac = soln(iMesh-1).mesh.proposed;
G.tSpan = soln(iMesh-1).knotPts.t([1,end]);
soln(iMesh) = dirColGaussCore(G,B,F,Opt); %#ok<AGROW>
end
if soln(iMesh).mesh.converged
break;
end
end
output.soln = soln;
output.bounds = B;
output.func = F;
output.options = Opt;
output.problem = problem;
% General stats about the problem:
nMesh = length(soln);
output.summary.nlp.objVal = zeros(1,nMesh);
output.summary.nlp.time = zeros(1,nMesh);
output.summary.nlp.exit = zeros(1,nMesh);
output.summary.nlp.nIter = zeros(1,nMesh);
output.summary.nlp.nEval = zeros(1,nMesh);
output.summary.mesh.nSegment = zeros(1,nMesh);
output.summary.mesh.maxError = zeros(1,nMesh);
for i=1:nMesh
output.summary.nlp.objVal(i) = output.soln(i).info.objVal;
output.summary.nlp.time(i) = output.soln(i).info.nlpTime;
output.summary.nlp.exit(i) = output.soln(i).info.exitFlag;
output.summary.nlp.nIter(i) = output.soln(i).info.iterations;
output.summary.nlp.nEval(i) = output.soln(i).info.funcCount;
output.summary.mesh.nSegment(i) = length(output.soln(i).mesh.previous);
output.summary.mesh.maxError(i) = output.soln(i).mesh.maxErr;
end
end
function soln = dirColGaussCore(G,B,F,Opt)
%
% This is where the actual work of the algorithm comes in
%
global DIM %Store the problem dimensions
% Compute dimensions for the problem
unpackDecVars([]); %Force a reset of the persistent variables.
computeDimensions(G.frac); % sets DIM (global variable)
%%%% Unpack problem bounds:
tLow = [B.t0.low, B.t1.low];
tUpp = [B.t0.upp, B.t1.upp];
xLow = [B.x0.low, B.x.low*ones(1,DIM.nKnot-2), B.x1.low];
xUpp = [B.x0.upp, B.x.upp*ones(1,DIM.nKnot-2), B.x1.upp];
dxLow = [B.dx0.low, B.dx.low*ones(1,DIM.nKnot-2), B.dx1.low];
dxUpp = [B.dx0.upp, B.dx.upp*ones(1,DIM.nKnot-2), B.dx1.upp];
ddxLow = -inf(size(dxLow));
ddxUpp = inf(size(dxUpp));
uLow = B.u.low*ones(1,DIM.nKnot);
uUpp = B.u.upp*ones(1,DIM.nKnot);
duLow = -inf(size(uLow));
duUpp = inf(size(uUpp));
zLow = packDecVars(tLow, xLow, dxLow, ddxLow, uLow, duLow);
zUpp = packDecVars(tUpp, xUpp, dxUpp, ddxUpp, uUpp, duUpp);
%%%% Unpack the problem guess
tKnotGuess = G.tSpan(1) + (G.tSpan(2)-G.tSpan(1))*DIM.tKnot;
tBndGuess = G.tSpan;
xGuess = ppval(G.x,tKnotGuess);
dxGuess = ppval(G.dx,tKnotGuess);
ddxGuess = ppval(G.ddx,tKnotGuess);
uGuess = ppval(G.u,tKnotGuess);
duGuess = ppval(G.du,tKnotGuess);
zGuess = packDecVars(tBndGuess,xGuess,dxGuess,ddxGuess,uGuess,duGuess);
%%%% Set-Up for fmincon
P.objective = @(z)( myObjective(z,F) );
P.nonlcon = @(z)( myConstraint(z,F,B) );
P.x0 = zGuess;
P.lb = zLow;
P.ub = zUpp;
P.Aineq = []; P.bineq = [];
P.Aeq = []; P.beq = [];
P.options = Opt.nlpOpt;
P.solver = 'fmincon';
%%%% Call fmincon to solve the non-linear program (NLP)
tic;
[zSoln, objVal,exitFlag,output] = fmincon(P);
nlpTime = toc;
% Unpack the solution:
[t, w, x, dx, ddx, dddx, ddddx, u, du,...
soln.pp, soln.knotPts] = unpackDecVars(zSoln);
% Store the solution col:
soln.colPts = makeStruct(t, w, x, dx, ddx, dddx, ddddx, u, du);
% Initial guess:
soln.guess = G;
% Store the solver info
soln.info = output;
soln.info.nlpTime = nlpTime;
soln.info.exitFlag = exitFlag;
soln.info.objVal = objVal;
% Compute the error estimates:
soln.mesh = meshAnalysis(soln,F,Opt);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function computeDimensions(frac)
%
% Extract relevant dimensions and other constants from the problem struct
%
global DIM
% Col Fraction = fraction of trajectory for each segment
DIM.meshFraction = frac;
DIM.meshFraction = DIM.meshFraction/sum(DIM.meshFraction); %Normalize
DIM.nSegment = length(DIM.meshFraction);
%Time at knot points, with trajectory mapped to [0,1]
DIM.tKnot = cumsum([0,DIM.meshFraction]);
DIM.nKnot = length(DIM.tKnot); %Number of knot points
% Time at the boundaries of each segment:
DIM.tLow = DIM.tKnot(1:(end-1));
DIM.tUpp = DIM.tKnot(2:end);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function z = packDecVars(t,x,dx,ddx,u,du)
%
% Packs all decision variables into a single column vector
%
% INPUTS:
% tBnd = [t0, t1] = [initialTime, finalTime]
% xKnot = [nx, nt] = position at each knot point
% dxKnot = [nx, nt] = velocity at each knot point
% ddxKnot = [nx, nt] = acceleration at each knot point
% uCol = [nu, nt] = control at lower and upper edge of each segment
%
% OUTPUTS:
% z = decision variables = [tBnd;xKnot;vKnot;uCol], where each component
% is a column vector, created using the reshape command.
%
global DIM % Holds problem dimensions
t = t([1,end]); %Allow passing entire time vector or just boundary
z = [...
reshape(t,2,1);
reshape(x,DIM.nx*DIM.nKnot,1);
reshape(dx,DIM.nx*DIM.nKnot,1);
reshape(ddx,DIM.nx*DIM.nKnot,1);
reshape(u,DIM.nu*DIM.nKnot,1);
reshape(du,DIM.nu*DIM.nKnot,1)];
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function [...
tCol, wCol, ...
xCol, dxCol, ddxCol, dddxCol, ddddxCol,...
uCol, duCol,...
pp, knotPts] = unpackDecVars(z)
%
% Unpacks the decision variables into useful matricies
%
% INPUTS:
% z = decision variables = [tBnd;xKnot;vKnot;uKnot;duKnot], where each
% component is a column vector, created using the reshape command.
%
% OUTPUTS
% tCol = [1, nc] = time at each col points
% wCol = [1, nc] = quadrature weights
% xCol = [nx, nc] = position at col points
% dxCol = [nx, nc] = velocity at col points
% ddxCol = [nx, nc] = accel at col points
% dddxCol = [nx, nc] = jerk at col points
% ddddxCol = [nx, nc] = snap at col points
% uCol = [nu, nc] = control at col points
% duCol = [nu, nc] = derivative of control at col points
% pp = pp-splines for state, control, and derivatives
%
global DIM % Holds problem dimensions
persistent zLast tLast wLast xLast dxLast ddxLast dddxLast ddddxLast uLast duLast
%%%% Figure out if we need to recompute the spline interpolants
if isempty(z) %Used to force a reset of the persistent variables.
zLast = [];
return;
elseif isempty(zLast)
zLast = zeros(size(z));
end
recompute = nargout > 9 || any(zLast~=z);
if recompute % Then we will need to compute the spline interpolation
zLast = z;
% Compute indicies for extraction
tIdx = 1:2;
xIdx = tIdx(end) + (1:(DIM.nx*DIM.nKnot));
dxIdx = xIdx(end) + (1:(DIM.nx*DIM.nKnot));
ddxIdx = dxIdx(end) + (1:(DIM.nx*DIM.nKnot));
uIdx = ddxIdx(end) + (1:(DIM.nu*DIM.nKnot));
duIdx = uIdx(end) + (1:(DIM.nu*DIM.nKnot));
% Extract and reshape to vectors
tBnd = z(tIdx);
t = tBnd(1) + (tBnd(2)-tBnd(1))*DIM.tKnot;
x = reshape(z(xIdx), DIM.nx, DIM.nKnot);
dx = reshape(z(dxIdx), DIM.nx, DIM.nKnot);
ddx = reshape(z(ddxIdx), DIM.nx, DIM.nKnot);
u = reshape(z(uIdx), DIM.nu, DIM.nKnot);
du = reshape(z(duIdx), DIM.nu, DIM.nKnot);
% Interpolate the values at the collocation points:
[tLast, wLast, xLast, dxLast, ddxLast, dddxLast, ddddxLast] = getColPtState(t,x,dx,ddx);
[~, uLast, duLast] = getColPtControl(t,u,du);
end
tCol = tLast;
wCol = wLast;
xCol = xLast;
dxCol = dxLast;
ddxCol = ddxLast;
dddxCol = dddxLast;
ddddxCol = ddddxLast;
uCol = uLast;
duCol = duLast;
if nargout > 9
% This is only called on the very last iteration, to compute the
% pp-splines for interpolating the final solution.
[pp.x, pp.dx, pp.ddx, pp.dddx, pp.ddddx] = getPpState(t,x,dx,ddx);
[pp.u, pp.du] = getPpControl(t,u,du);
knotPts = makeStruct(t,x,dx,ddx, u, du);
end
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function cost = myObjective(z,F)
%
% This function unpacks the decision variables, sends them to the
% user-defined objective functions, and then returns the final cost
%
% INPUTS:
% z = column vector of decision variables
% pack = details about how to convert decision variables into t,x, and u
% pathObj = user-defined integral objective function
% endObj = user-defined end-point objective function
%
% OUTPUTS:
% cost = scale cost for this set of decision variables
%
% Compute state and controls at collocation points
[t, w,x, dx, ddx, dddx, ddddx,u, du] = unpackDecVars(z);
% Compute the cost integral along trajectory
if isempty(F.pathObj)
integralCost = 0;
else
integrand = F.pathObj(t,x,dx,ddx,u, dddx, ddddx, du); %Calculate the integrand of the cost function
integralCost = sum(integrand*w');
end
% Compute the cost at the boundaries of the trajectory
if isempty(F.bndObj)
bndCost = 0;
else
t0 = t(1);
t1 = t(end);
x0 = x(:,1);
x1 = x(:,end);
dx0 = dx(:,1);
dx1 = dx(:,end);
bndCost = F.bndObj(t0,t1,x0,x1,dx0,dx1);
end
cost = bndCost + integralCost;
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function [c, ceq] = myConstraint(z, F, B)
%
% This function unpacks the decision variables, computes the defects along
% the trajectory, and then evaluates the user-defined constraint functions.
%
% INPUTS:
% z = column vector of decision variables
% F = struct with user-defined functions
% B = struct with bounds
%
% OUTPUTS:
% c = inequality constraints to be passed to fmincon
% ceq = equality constraints to be passed to fmincon
%
global USE_LOBOTTO_POINTS
%%%% Extract trajectory from decision variables
[t, ~,x, dx, ddx, ~, ~,u, ~] = unpackDecVars(z);
if USE_LOBOTTO_POINTS
%%%% Remove redundant points:
% The lobotto points are doubled on the intermediate segment endpoints
idxRm = 4:4:(length(t)-1);
t(idxRm) = [];
x(:,idxRm) = [];
dx(:,idxRm) = [];
ddx(:,idxRm) = [];
u(:,idxRm) = [];
end
%%%% Solve dynamics along the trajectory:
dynDefect = F.dynamics(t,x,dx,ddx,u); %Implicit dynamics
nt = length(t);
nx = size(x,1);
ceq_dyn = reshape(dynDefect,nt*nx,1);
%%%% Compute the user-defined constraints:
if isempty(F.pathCst)
c_path = [];
ceq_path = [];
else
[c_pathRaw, ceq_pathRaw] = F.pathCst(t,x,dx,ddx,u);
c_path = reshape(c_pathRaw,numel(c_pathRaw),1);
ceq_path = reshape(ceq_pathRaw,numel(ceq_pathRaw),1);
end
if isempty(F.bndCst)
c_bnd = [];
ceq_bnd = [];
else
boundary.t0 = t(1);
boundary.t1 = t(end);
boundary.x0 = x(:,1);
boundary.x1 = x(:,end);
boundary.dx0 = dx(:,1);
boundary.dx1 = dx(:,end);
[c_bnd, ceq_bnd] = F.bndCst(boundary);
end
%%%% Enforce constraints on collocation points:
% TODO: This code could be optimized much better
nc = length(t); %Number of collocation points
One = ones(1,nc); % used for vectorization (below)
c_collPtCst = [...
B.x.low*One - x;
x - B.x.upp*One;
B.dx.low*One - dx;
dx - B.dx.upp*One;
B.u.low*One - u;
u - B.u.upp*One];
c_collPtCst = c_collPtCst(~isinf(c_collPtCst));
c_collPtCst = reshape(c_collPtCst,numel(c_collPtCst),1);
%%%% Pack everything up:
c = [c_path; c_bnd; c_collPtCst];
ceq = [ceq_dyn; ceq_path; ceq_bnd];
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function problem = inputValidation(user)
% problem = inputValidation(problem)
%
% Does input validation on the problem struct, as well as filling in
% default values for all fields.
%
% This is a utility function, and should not be called by the user.
%
% For now, this just fills in defaults, and does not do a careful check on
% the inputs.
%
%%%% Set up the default values:
[nx,nt] = size(user.guess.x);
nu = size(user.guess.u, 1);
default.func.dynamics = [];
default.func.pathObj = [];
default.func.bndObj = [];
default.func.pathCst = [];
default.func.bndCst = [];
default.bounds.t0.low = 0;
default.bounds.t0.upp = 0;
default.bounds.t1.low = 0;
default.bounds.t1.upp = inf;
default.bounds.x.low = -inf(nx,1);
default.bounds.x.upp = inf(nx,1);
default.bounds.dx.low = -inf(nx,1);
default.bounds.dx.upp = inf(nx,1);
default.bounds.u.low = -inf(nu,1);
default.bounds.u.upp = inf(nu,1);
default.bounds.du.low = -inf(nu,1);
default.bounds.du.upp = inf(nu,1);
default.bounds.x0.low = -inf(nx,1);
default.bounds.x0.upp = inf(nx,1);
default.bounds.dx0.low = -inf(nx,1);
default.bounds.dx0.upp = inf(nx,1);
default.bounds.x1.low = -inf(nx,1);
default.bounds.x1.upp = inf(nx,1);
default.bounds.dx1.low = -inf(nx,1);
default.bounds.dx1.upp = inf(nx,1);
default.guess.t = linspace(0,1,nt);
default.guess.x = zeros(nx,nt);
default.guess.dx = zeros(nx,nt);
default.guess.ddx = zeros(nx,nt);
default.guess.u = zeros(nu,nt);
default.guess.du = zeros(nu,nt);
default.options.nlpOpt = optimset('fmincon');
default.options.nlpOpt.Display = 'iter';
default.options.nlpOpt.MaxFunEvals = 5e4;
default.options.mesh.nSegmentInit = 5;
default.options.mesh.tol = 1e-3;
default.options.mesh.maxIter = 5;
default.options.mesh.maxSubDivide = 4;
default.auxdata = [];
%%%% Merge with the user-defined options:
problem = mergeOptions(default, user, 'problem');
%%%% Input Validation:
if isempty(problem.func.dynamics)
error('User must specify: problem.func.dynamics');
end
if problem.options.mesh.maxIter < 1
warning('problem.options.mesh.maxIter = %d must be positive!',problem.options.mesh.maxIter);
disp(' --> setting: problem.options.mesh.maxIter = 1;');
problem.options.mesh.maxIter = 1;
end
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
Derive_Coeffs.m
|
.m
|
DirCol5i-master/DirCol5i/Derive_Coeffs.m
| 3,023 |
utf_8
|
a117095c256a3938299f213fff8977c9
|
function Derive_Coeffs()
%
% Derive the equations that are used to compute the collocation points
%
% The state and control at the upper boundary is given by xB and uB, while
% the state and control ad the lower boundary is given by xA and uA;
%
deriveCollocationState();
deriveCollocationControl();
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [C,t,x,dx,ddx,dddx,ddddx] = getPolynomial(n)
%
% y(t) = C1 + C2*t + C3*t^2 + ...
%
% INPUTS:
% n = Order of the polynomial
%
% OUTPUTS: (all symbolic)
% C = [n+1, 1] = vector of coefficients
C = sym('C',[n+1,1],'real'); %Coefficients of polynomial
t = sym('t', 'real'); %continuous time t0 <= t < t1
x = sym(0);
for i = 1:(n+1)
x = x + C(i)*t^(i-1);
end
dx = diff(x,t);
ddx = diff(dx,t);
dddx = diff(ddx,t);
ddddx = diff(dddx,t);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function deriveCollocationState()
order = 5;
[C,t,x,dx,ddx,dddx,ddddx] = getPolynomial(order);
syms xA dxA ddxA xB dxB ddxB 'real'
tA = sym(-1);
tB = sym(1);
eqn1 = subs(x,t,tA) - xA;
eqn2 = subs(dx,t,tA) - dxA;
eqn3 = subs(ddx,t,tA) - ddxA;
eqn4 = subs(x,t,tB) - xB;
eqn5 = subs(dx,t,tB) - dxB;
eqn6 = subs(ddx,t,tB) - ddxB;
eqns = [eqn1;eqn2;eqn3;eqn4;eqn5;eqn6];
[A,b] = equationsToMatrix(eqns,C);
soln = A\b;
X = subs(x,{'C1','C2','C3','C4','C5','C6'},{soln(1),soln(2),soln(3),soln(4),soln(5),soln(6)});
dX = subs(dx,{'C1','C2','C3','C4','C5','C6'},{soln(1),soln(2),soln(3),soln(4),soln(5),soln(6)});
ddX = subs(ddx,{'C1','C2','C3','C4','C5','C6'},{soln(1),soln(2),soln(3),soln(4),soln(5),soln(6)});
dddX = subs(dddx,{'C1','C2','C3','C4','C5','C6'},{soln(1),soln(2),soln(3),soln(4),soln(5),soln(6)});
ddddX = subs(ddddx,{'C1','C2','C3','C4','C5','C6'},{soln(1),soln(2),soln(3),soln(4),soln(5),soln(6)});
%% %% Write out functions
matlabFunction(...
X,dX,ddX,dddX,ddddX,...
'file','autoGen_getColPtState.m',...
'vars',{t,xA,xB,dxA,dxB,ddxA,ddxB},...
'outputs',{...
'X','dX','ddX','dddX','ddddX'});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function deriveCollocationControl()
order = 3;
[C,t,u,du] = getPolynomial(order);
syms uA duA dduA uB duB dduB 'real'
tA = sym(-1);
tB = sym(1);
eqn1 = subs(u,t,tA) - uA;
eqn2 = subs(du,t,tA) - duA;
eqn3 = subs(u,t,tB) - uB;
eqn4 = subs(du,t,tB) - duB;
eqns = [eqn1;eqn2;eqn3;eqn4];
[A,b] = equationsToMatrix(eqns,C);
soln = A\b;
U = subs(u,{'C1','C2','C3','C4'},{soln(1),soln(2),soln(3),soln(4)});
dU = subs(du,{'C1','C2','C3','C4'},{soln(1),soln(2),soln(3),soln(4)});
%% %% Write out functions
matlabFunction(...
U, dU,...
'file','autoGen_getColPtControl.m',...
'vars',{t,uA,uB,duA,duB},...
'outputs',{...
'U', 'dU'});
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
getPpControl.m
|
.m
|
DirCol5i-master/DirCol5i/getPpControl.m
| 1,475 |
utf_8
|
1a1cecad8544790a88c775fe0200eb24
|
function [PPu, PPdu] = getPpControl(t,u,du)
% [PPu, PPdu] = getPpControl(t,u,du)
%
% This function computes pp-form splines for the control and control rate,
% to be evalauted by Matlab's ppval() command.
%
% INPUTS:
% t = [1,nt] = time at the knot points
% u = [nu,nt] = position at the knot points
% du = [nu,nt] = velocity at the knot points
%
% OUTPUTS: nc = 3*(nt-1)
% PPu = pp-form struct with u trajectory
% PPdu = pp-form struct with du trajectory
%
%%%% Dimension stuff:
nt = length(t);
nu = size(u,1);
ns = nt - 1;
%%%% Break apart by segment:
iA = 1:(nt-1);
iB = 2:nt;
tA = t(iA);
tB = t(iB);
%%%% Construct the state splines
tLow = ones(nu,1)*tA;
tUpp = ones(nu,1)*tB;
uLow = u(:,iA);
uUpp = u(:,iB);
duLow = du(:,iA);
duUpp = du(:,iB);
[C1,C2,C3,C4] = autoGen_controlSplineCoeffs(...
0*tLow,tUpp-tLow,...
uLow,uUpp,...
duLow,duUpp);
% State:
orderCubic = 4;
C = zeros(nu*ns,orderCubic);
for i=1:ns
idu = nu*(i-1)+(1:nu);
C(idu,:) = [C4(:,i),C3(:,i),C2(:,i),C1(:,i)];
end
PPu = getPp(t,C,orderCubic,nu);
% Derivative:
C = zeros(nu*ns,orderCubic-1);
for i=1:ns
idu = nu*(i-1)+(1:nu);
C(idu,:) = [3*C4(:,i),2*C3(:,i),1*C2(:,i)];
end
PPdu = getPp(t,C,orderCubic-1,nu);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pp = getPp(tKnot,coeff,order,nDim)
pp.form = 'pp';
pp.breaks = tKnot;
pp.coefs = coeff;
pp.pieces = length(tKnot)-1;
pp.order = order;
pp.dim = nDim;
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
drawCartPoleAnim.m
|
.m
|
DirCol5i-master/DirCol5i/demo/cartPole/drawCartPoleAnim.m
| 2,133 |
utf_8
|
2334402558a3114d7f969148319c70cd
|
function drawCartPoleAnim(~,p,xLow, xUpp, yLow, yUpp)
% drawCartPoleTraj(t,p,xLow, xUpp, yLow, yUpp)
%
% INPUTS:
% t = [1,n] = time stamp for the data in p1 and p2
% p = [4,n] = [p1;p2];
%
clf; hold on;
Cart_Width = 0.15;
Cart_Height = 0.05;
p1 = p(1:2,:);
p2 = p(3:4,:);
Pole_Width = 4; %pixels
%%%% Figure out the window size:
xLow = xLow - 0.7*Cart_Width;
xUpp = xUpp + 0.7*Cart_Width;
yLow = yLow - 0.7*Cart_Height;
yUpp = yUpp + 0.7*Cart_Height;
Limits = [xLow,xUpp,yLow,yUpp];
%%%% Get color map for the figure
% map = colormap;
% tMap = linspace(t(1),t(end),size(map,1))';
%%%% Plot Rails
plot([Limits(1) Limits(2)],-0.5*Cart_Height*[1,1],'k-','LineWidth',2)
%%%% Draw the trace of the pendulum tip (continuously vary color)
% nTime = length(t);
% for i=1:(nTime-1)
% idx = i:(i+1);
% x = p2(1,idx);
% y = p2(2,idx);
% c = interp1(tMap,map,mean(t(idx)));
% plot(x,y,'Color',c);
% end
%%%% Compute the frames for plotting:
% tFrame = linspace(t(1), t(end), nFrame);
% cart = interp1(t',p1',tFrame')';
% pole = interp1(t',p2',tFrame')';
cart = p1;
pole = p2;
% for i = 1:nFrame
% Compute color:
color = [0.2,0.7,0.1]; %interp1(tMap,map,tFrame(i));
%Plot Cart
x = cart(1) - 0.5*Cart_Width;
y = -0.5*Cart_Height;
w = Cart_Width;
h = Cart_Height;
hCart = rectangle('Position',[x,y,w,h],'LineWidth',2);
set(hCart,'FaceColor',color);
set(hCart,'EdgeColor',0.8*color);
%Plot Pendulum
Rod_X = [cart(1), pole(1)];
Rod_Y = [cart(2), pole(2)];
plot(Rod_X,Rod_Y,'k-','LineWidth',Pole_Width,'Color',color)
%Plot Bob and hinge
plot(pole(1),pole(2),'k.','MarkerSize',40,'Color',color)
plot(cart(1),cart(2),'k.','MarkerSize',60,'Color',color)
% end
%These commands keep the window from automatically rescaling in funny ways.
axis(Limits);
axis('equal');
axis manual;
axis off;
end
function [xLow, xUpp, yLow, yUpp] = getBounds(p1,p2)
%
% Returns the upper and lower bound on the data in val
%
val = [p1,p2];
xLow = min(val(1,:));
xUpp = max(val(1,:));
yLow = min(val(2,:));
yUpp = max(val(2,:));
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
drawCartPoleTraj.m
|
.m
|
DirCol5i-master/DirCol5i/demo/cartPole/drawCartPoleTraj.m
| 2,398 |
utf_8
|
20f52ba1988786981dace289cd54ae77
|
function drawCartPoleTraj(t,p1,p2,nFrame,scale)
% drawCartPoleTraj(t,p1,p2,nFrame,scale)
%
% INPUTS:
% t = [1,n] = time stamp for the data in p1 and p2
% p1 = [2,n] = [x;y] = position of center of the cart
% p2 = [2,n] = [x;y] = position of tip of the pendulum
% nFrame = scalar integer = number of "freeze" frames to display
%
hold on;
if nargin == 4
scale = 'big';
end
if strcmp(scale,'big')
Cart_Width = 0.15;
Cart_Height = 0.05;
Pole_Width = 4;
Bob_Size = 50;
else
Cart_Width = 0.1;
Cart_Height = 0.03;
Pole_Width = 2;
Bob_Size = 20;
end
%%%% Figure out the window size:
[xLow, xUpp, yLow, yUpp] = getBounds(p1,p2);
xLow = xLow - 0.7*Cart_Width;
xUpp = xUpp + 0.7*Cart_Width;
yLow = yLow - 0.7*Cart_Height;
yUpp = yUpp + 0.7*Cart_Height;
Limits = [xLow,xUpp,yLow,yUpp];
%%%% Get color map for the figure
map = colormap;
tMap = linspace(t(1),t(end),size(map,1))';
%%%% Plot Rails
plot([Limits(1) Limits(2)],-0.5*Cart_Height*[1,1],'k-','LineWidth',2)
%%%% Draw the trace of the pendulum tip (continuously vary color)
nTime = length(t);
for i=1:(nTime-1)
idx = i:(i+1);
x = p2(1,idx);
y = p2(2,idx);
c = interp1(tMap,map,mean(t(idx)));
plot(x,y,'Color',c);
end
%%%% Compute the frames for plotting:
tFrame = linspace(t(1), t(end), nFrame);
cart = interp1(t',p1',tFrame')';
pole = interp1(t',p2',tFrame')';
for i = 1:nFrame
% Compute color:
color = interp1(tMap,map,tFrame(i));
%Plot Cart
x = cart(1,i) - 0.5*Cart_Width;
y = -0.5*Cart_Height;
w = Cart_Width;
h = Cart_Height;
hCart = rectangle('Position',[x,y,w,h],'LineWidth',2);
set(hCart,'FaceColor',color);
set(hCart,'EdgeColor',0.8*color);
%Plot Pendulum
Rod_X = [cart(1,i), pole(1,i)];
Rod_Y = [cart(2,i), pole(2,i)];
plot(Rod_X,Rod_Y,'k-','LineWidth',Pole_Width,'Color',color)
%Plot Bob and hinge
plot(pole(1,i),pole(2,i),'k.','MarkerSize',Bob_Size,'Color',color)
plot(cart(1,i),cart(2,i),'k.','MarkerSize',Bob_Size,'Color',color)
end
%These commands keep the window from automatically rescaling in funny ways.
axis(Limits);
axis('equal');
axis manual;
axis off;
end
function [xLow, xUpp, yLow, yUpp] = getBounds(p1,p2)
%
% Returns the upper and lower bound on the data in val
%
val = [p1,p2];
xLow = min(val(1,:));
xUpp = max(val(1,:));
yLow = min(val(2,:));
yUpp = max(val(2,:));
end
|
github
|
MatthewPeterKelly/DirCol5i-master
|
Derive_Equations.m
|
.m
|
DirCol5i-master/DirCol5i/demo/fiveLinkBiped/Derive_Equations.m
| 22,988 |
utf_8
|
5a6b34d66510b3b791e404e07d4dc5ec
|
function Derive_Equations()
%%%% Derive Equations - Five Link Biped Model %%%%
%
% This function derives the equations of motion, as well as some other useful
% equations (kinematics, contact forces, ...) for the five-link biped
% model.
%
%
% Nomenclature:
%
% - There are five links, which will be numbered starting with "1" for the
% stance leg tibia, increasing as the links are father from the base joint,
% and ending with "5" for the swing leg tibia.
% 1 - stance leg tibia (lower leg)
% 2 - stance leg femur (upper leg)
% 3 - torso
% 4 - swing leg femur
% 5 - swing leg tibia
%
% - This script uses absolute angles, which are represented with "q". All
% angles use positive convention, with the zero angle corresponding to a
% vertically aligned link configuration. [q] = [0] has the torso balanced
% upright, with both legs fully extended straight below it.
%
% - Derivatives with respect to time are notated by prepending a "d". For
% example the rate of change in an absolute angle is "dq" and angular
% acceleration would be "ddq"
%
% - Joint positions are given with "P", center of mass positions are "G"
%
% For full derivation, see the appendix of my tutorial paper:
% "An Introduction to Trajectory Optimization..."
% https://epubs.siam.org/doi/abs/10.1137/16M1062569
%
clc; clear;
disp('Creating variables and derivatives...')
%%%% Absolute orientation (angle) of each link
q1 = sym('q1', 'real');
q2 = sym('q2','real');
q3 = sym('q3','real');
q4 = sym('q4','real');
q5 = sym('q5','real');
%%%% Absolute angular rate of each link
dq1 = sym('dq1','real');
dq2 = sym('dq2','real');
dq3 = sym('dq3','real');
dq4 = sym('dq4','real');
dq5 = sym('dq5','real');
%%%% Absolute angular acceleration of each linke
ddq1 = sym('ddq1','real');
ddq2 = sym('ddq2','real');
ddq3 = sym('ddq3','real');
ddq4 = sym('ddq4','real');
ddq5 = sym('ddq5','real');
%%%% Torques at each joint
u1 = sym('u1','real'); %Stance foot
u2 = sym('u2','real'); %Stance knee
u3 = sym('u3','real'); %Stance hip
u4 = sym('u4','real'); %Swing hip
u5 = sym('u5','real'); %Swing knee
%%%% Mass of each link
m1 = sym('m1','real');
m2 = sym('m2','real');
m3 = sym('m3','real');
m4 = sym('m4','real');
m5 = sym('m5','real');
%%%% Distance between parent joint and link center of mass
c1 = sym('c1','real');
c2 = sym('c2','real');
c3 = sym('c3','real');
c4 = sym('c4','real');
c5 = sym('c5','real');
%%%% Length of each link
l1 = sym('l1','real');
l2 = sym('l2','real');
l3 = sym('l3','real');
l4 = sym('l4','real');
l5 = sym('l5','real');
%%%% Moment of inertia of each link about its own center of mass
I1 = sym('I1','real');
I2 = sym('I2','real');
I3 = sym('I3','real');
I4 = sym('I4','real');
I5 = sym('I5','real');
g = sym('g','real'); % Gravity
Fx = sym('Fx','real'); %Horizontal contact force at stance foot
Fy = sym('Fy','real'); %Vertical contact force at stance foot
empty = sym('empty','real'); %Used for vectorization, user should pass a vector of zeros
t = sym('t','real'); %dummy continuous time
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Set up coordinate system and unit vectors %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
i = sym([1;0]); %Horizontal axis
j = sym([0;1]); %Vertical axis
e1 = cos(q1)*(j) + sin(q1)*(-i); %unit vector from P0 -> P1, (contact point to stance knee)
e2 = cos(q2)*(j) + sin(q2)*(-i); %unit vector from P1 -> P2, (stance knee to hip)
e3 = cos(q3)*(j) + sin(q3)*(-i); %unit vector from P2 -> P3, (hip to shoulders);
e4 = -cos(q4)*(j) - sin(q4)*(-i); %unit vector from P2 -> P4, (hip to swing knee);
e5 = -cos(q5)*(j) - sin(q5)*(-i); %unit vector from P4 -> P5, (swing knee to swing foot);
P0 = 0*i + 0*j; %stance foot = Contact point = origin
P1 = P0 + l1*e1; %stance knee
P2 = P1 + l2*e2; %hip
P3 = P2 + l3*e3; %shoulders
P4 = P2 + l4*e4; %swing knee
P5 = P4 + l5*e5; %swing foot
G1 = P1 - c1*e1; % CoM stance leg tibia
G2 = P2 - c2*e2; % CoM stance leg febur
G3 = P3 - c3*e3; % CoM torso
G4 = P2 + c4*e4; % CoM swing leg femur
G5 = P4 + c5*e5; % CoM swing leg tibia
G = (m1*G1 + m2*G2 + m3*G3 + m4*G4 + m5*G5)/(m1+m2+m3+m4+m5); %Center of mass for entire robot
%%%% Define a function for doing '2d' cross product: dot(a x b, k)
cross2d = @(a,b)(a(1)*b(2) - a(2)*b(1));
%%%% Weight of each link:
w1 = -m1*g*j;
w2 = -m2*g*j;
w3 = -m3*g*j;
w4 = -m4*g*j;
w5 = -m5*g*j;
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Derivatives %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
q = [q1;q2;q3;q4;q5];
dq = [dq1;dq2;dq3;dq4;dq5];
ddq = [ddq1;ddq2;ddq3;ddq4;ddq5];
u = [u1;u2;u3;u4;u5];
z = [t;q;dq;u]; % time-varying vector of inputs
% Neat trick to compute derivatives using the chain rule
derivative = @(in)( jacobian(in,[q;dq])*[dq;ddq] );
% Velocity of the swing foot (used for step constraints)
dP5 = derivative(P5);
% Compute derivatives for the CoM of each link:
dG1 = derivative(G1); ddG1 = derivative(dG1);
dG2 = derivative(G2); ddG2 = derivative(dG2);
dG3 = derivative(G3); ddG3 = derivative(dG3);
dG4 = derivative(G4); ddG4 = derivative(dG4);
dG5 = derivative(G5); ddG5 = derivative(dG5);
dG = derivative(G); ddG = derivative(dG);
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Calculations: %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
singleStanceDynamics();
objectiveFunctions();
heelStrikeDynamics();
mechanicalEnergy();
contactForces();
kinematics();
disp('Done!');
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Single-Stance Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% I solve the dynamics here by carefully selecting angular momentum balance
% equations about each joint, working my way out the kinematic tree from
% the root.
function singleStanceDynamics()
disp('Deriving single stance dynamics...')
%%%% AMB - entire system @ P0
eqnTorque0 = ...
cross2d(G1-P0,w1) + ...
cross2d(G2-P0,w2) + ...
cross2d(G3-P0,w3) + ...
cross2d(G4-P0,w4) + ...
cross2d(G5-P0,w5) + ...
u1;
eqnInertia0 = ...
cross2d(G1-P0,m1*ddG1) + ddq1*I1 + ...
cross2d(G2-P0,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P0,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P0,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P0,m5*ddG5) + ddq5*I5;
%%%% AMB - swing leg, torso, stance femer @ stance knee
eqnTorque1 = ...
cross2d(G2-P1,w2) + ...
cross2d(G3-P1,w3) + ...
cross2d(G4-P1,w4) + ...
cross2d(G5-P1,w5) + ...
u2;
eqnInertia1 = ...
cross2d(G2-P1,m2*ddG2) + ddq2*I2 + ...
cross2d(G3-P1,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P1,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P1,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg, torso @ hip
eqnTorque2 = ...
cross2d(G3-P2,w3) + ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u3;
eqnInertia2 = ...
cross2d(G3-P2,m3*ddG3) + ddq3*I3 + ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing leg @ hip
eqnTorque3 = ...
cross2d(G4-P2,w4) + ...
cross2d(G5-P2,w5) + ...
u4;
eqnInertia3 = ...
cross2d(G4-P2,m4*ddG4) + ddq4*I4 + ...
cross2d(G5-P2,m5*ddG5) + ddq5*I5 ;
%%%% AMB - swing tibia % swing knee
eqnTorque4 = ...
cross2d(G5-P4,w5) + ...
u5;
eqnInertia4 = ...
cross2d(G5-P4,m5*ddG5) + ddq5*I5 ;
%%%% Collect and solve equations:
eqns = [...
eqnTorque0 - eqnInertia0;
eqnTorque1 - eqnInertia1;
eqnTorque2 - eqnInertia2;
eqnTorque3 - eqnInertia3;
eqnTorque4 - eqnInertia4];
[MM, FF] = equationsToMatrix(eqns,ddq); % ddq = MM\ff;
%%%% Compute gradients:
[m, mi, mz, mzi, mzd] = computeGradients(MM,z,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,z,empty);
% Write function file:
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_dynSs.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'u1','u2','u3','u4','u5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g','empty'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Objective Functions %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function objectiveFunctions()
%%%% Torque-squared objective function
F = u1*u1 + u2*u2 + u3*u3 + u4*u4 + u5*u5;
[f, ~, fz, fzi, ~] = computeGradients(F,z,empty);
matlabFunction(f,fz,fzi,...
'file','autoGen_obj_torqueSquared.m',...
'vars',{'u1','u2','u3','u4','u5'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Heel-Strike Dynamics %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function heelStrikeDynamics()
disp('Deriving heel-strike dynamics...')
%%%% Notes:
% xF - heelStrike(xI) --> constraint --> 0
% xF - collision(footSwap(xI));
%
% Angles before heel-strike:
q1m = sym('q1m','real');
q2m = sym('q2m','real');
q3m = sym('q3m','real');
q4m = sym('q4m','real');
q5m = sym('q5m','real');
qm = [q1m;q2m;q3m;q4m;q5m];
% Angles after heel-strike
q1p = sym('q1p','real');
q2p = sym('q2p','real');
q3p = sym('q3p','real');
q4p = sym('q4p','real');
q5p = sym('q5p','real');
qp = [q1p;q2p;q3p;q4p;q5p];
% Angular rates before heel-strike:
dq1m = sym('dq1m','real');
dq2m = sym('dq2m','real');
dq3m = sym('dq3m','real');
dq4m = sym('dq4m','real');
dq5m = sym('dq5m','real');
dqm = [dq1m;dq2m;dq3m;dq4m;dq5m];
% Angular rates after heel-strike
dq1p = sym('dq1p','real');
dq2p = sym('dq2p','real');
dq3p = sym('dq3p','real');
dq4p = sym('dq4p','real');
dq5p = sym('dq5p','real');
dqp = [dq1p;dq2p;dq3p;dq4p;dq5p];
% Compute kinematics before heel-strike:
inVars = {'q1','q2','q3','q4','q5','dq1','dq2','dq3','dq4','dq5'};
outVarsM = {'q1m','q2m','q3m','q4m','q5m','dq1m','dq2m','dq3m','dq4m','dq5m'};
% P0m = subs(P0,inVars,outVarsM);
P1m = subs(P1,inVars,outVarsM);
P2m = subs(P2,inVars,outVarsM);
% P3m = subs(P3,inVars,outVarsM);
P4m = subs(P4,inVars,outVarsM);
P5m = subs(P5,inVars,outVarsM);
dP5m = subs(dP5,inVars,outVarsM);
G1m = subs(G1,inVars,outVarsM);
G2m = subs(G2,inVars,outVarsM);
G3m = subs(G3,inVars,outVarsM);
G4m = subs(G4,inVars,outVarsM);
G5m = subs(G5,inVars,outVarsM);
dG1m = subs(dG1,inVars,outVarsM);
dG2m = subs(dG2,inVars,outVarsM);
dG3m = subs(dG3,inVars,outVarsM);
dG4m = subs(dG4,inVars,outVarsM);
dG5m = subs(dG5,inVars,outVarsM);
% Compute kinematics after heel-strike:
outVarsP = {'q1p','q2p','q3p','q4p','q5p','dq1p','dq2p','dq3p','dq4p','dq5p'};
P0p = subs(P0,inVars,outVarsP);
P1p = subs(P1,inVars,outVarsP);
P2p = subs(P2,inVars,outVarsP);
% P3p = subs(P3,inVars,outVarsP);
P4p = subs(P4,inVars,outVarsP);
% P5p = subs(P5,inVars,outVarsP);
dP5p = subs(dP5,inVars,outVarsP);
G1p = subs(G1,inVars,outVarsP);
G2p = subs(G2,inVars,outVarsP);
G3p = subs(G3,inVars,outVarsP);
G4p = subs(G4,inVars,outVarsP);
G5p = subs(G5,inVars,outVarsP);
dG1p = subs(dG1,inVars,outVarsP);
dG2p = subs(dG2,inVars,outVarsP);
dG3p = subs(dG3,inVars,outVarsP);
dG4p = subs(dG4,inVars,outVarsP);
dG5p = subs(dG5,inVars,outVarsP);
%%%% AMB - entire system @ New stance foot
eqnHs0m = ... %Before collision
cross2d(G1m-P5m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P5m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P5m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P5m,m4*dG4m) + dq4m*I4 + ...
cross2d(G5m-P5m,m5*dG5m) + dq5m*I5;
eqnHs0 = ... %After collision
cross2d(G1p-P0p,m1*dG1p) + dq1p*I1 + ...
cross2d(G2p-P0p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P0p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P0p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P0p,m5*dG5p) + dq5p*I5;
%%%% AMB - new swing leg, torso, stance femer @ stance knee
eqnHs1m = ... %Before collision
cross2d(G1m-P4m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P4m,m2*dG2m) + dq2m*I2 + ...
cross2d(G3m-P4m,m3*dG3m) + dq3m*I3 + ...
cross2d(G4m-P4m,m4*dG4m) + dq4m*I4;
eqnHs1 = ... %After collision
cross2d(G2p-P1p,m2*dG2p) + dq2p*I2 + ...
cross2d(G3p-P1p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P1p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P1p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg, torso @ new hip
eqnHs2m = ... %Before collision
cross2d(G3m-P2m,m3*dG3m) + dq3m*I3 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2 + ...
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1;
eqnHs2 = ... %After collision
cross2d(G3p-P2p,m3*dG3p) + dq3p*I3 + ...
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing leg @ new hip
eqnHs3m = ... %Before collision
cross2d(G1m-P2m,m1*dG1m) + dq1m*I1 + ...
cross2d(G2m-P2m,m2*dG2m) + dq2m*I2;
eqnHs3 = ... %After collision
cross2d(G4p-P2p,m4*dG4p) + dq4p*I4 + ...
cross2d(G5p-P2p,m5*dG5p) + dq5p*I5;
%%%% AMB - swing tibia @ new swing knee
eqnHs4m = ... %Before collision
cross2d(G1m-P1m,m1*dG1m) + dq1m*I1;
eqnHs4 = ... %After collision
cross2d(G5p-P4p,m5*dG5p) + dq5p*I5;
%%%% Collect and solve equations:
eqnHs = [...
eqnHs0m - eqnHs0;
eqnHs1m - eqnHs1;
eqnHs2m - eqnHs2;
eqnHs3m - eqnHs3;
eqnHs4m - eqnHs4];
[MM, FF] = equationsToMatrix(eqnHs,dqp);
%%%% Compute gradients:
tp = sym('tp','real'); %Initial trajectory time
tm = sym('tm','real'); %Final trajectory time
zBnd = [tp;qp;dqp;tm;qm;dqm];
[m, mi, mz, mzi, mzd] = computeGradients(MM,zBnd,empty);
[f, fi, fz, fzi, fzd] = computeGradients(FF,zBnd,empty);
% Heel-strike
matlabFunction(m, mi, f, fi,... %dynamics
mz, mzi, mzd, fz, fzi, fzd,... %gradients
'file','autoGen_cst_heelStrike.m',...
'vars',{...
'q1p','q2p','q3p','q4p','q5p',...
'q1m','q2m','q3m','q4m','q5m',...
'dq1m','dq2m','dq3m','dq4m','dq5m',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5','empty'});
% Collision velocity of the swing foot:
cst = [-dP5p(2); dP5m(2)]; %Swing foot velocity before and after collision (negative sign is intentional, since output is constrained to be negative);
cstJac = jacobian(cst,zBnd); %Gradient
matlabFunction(cst, cstJac,...
'file','autoGen_cst_footVel.m',...
'vars',{...
'q1p','q2p','q4p','q5p',...
'q1m','q2m','q4m','q5m',...
'dq1p','dq2p','dq4p','dq5p',...
'dq1m','dq2m','dq4m','dq5m',...
'l1','l2','l4','l5'});
% Step length and height constraint:
stepLength = sym('stepLength','real');
ceq = [P5m(1)-stepLength; P5m(2)];
ceqJac = jacobian(ceq,zBnd); %Gradient
matlabFunction(ceq, ceqJac,...
'file','autoGen_cst_steplength.m',...
'vars',{...
'q1m','q2m','q4m','q5m',...
'l1','l2','l4','l5','stepLength'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Mechanical Energy %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function mechanicalEnergy()
disp('Deriving mechanical energy...')
%%%% Energy:
KineticEnergy = ...
0.5*m1*dot(dG1,dG1) + 0.5*I1*dq1^2 + ...
0.5*m2*dot(dG2,dG2) + 0.5*I2*dq2^2 + ...
0.5*m3*dot(dG3,dG3) + 0.5*I3*dq3^2 + ...
0.5*m4*dot(dG4,dG4) + 0.5*I4*dq4^2 + ...
0.5*m5*dot(dG5,dG5) + 0.5*I5*dq5^2;
PotentialEnergy = ...
m1*g*G1(2) + ...
m2*g*G2(2) + ...
m3*g*G3(2) + ...
m4*g*G4(2) + ...
m5*g*G5(2);
matlabFunction(KineticEnergy, PotentialEnergy,...
'file','autoGen_energy.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'm1','m2','m3','m4','m5',...
'I1','I2','I3','I4','I5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'KE','PE'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Contact Forces %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function contactForces()
%%%% Contact Forces:
eqnForce5 = w1 + w2 + w3 + w4 + w5 + Fx*i + Fy*j;
eqnInertia5 = (m1+m2+m3+m4+m5)*ddG;
[AA,bb] = equationsToMatrix(eqnForce5-eqnInertia5,[Fx;Fy]);
ContactForces = AA\bb;
matlabFunction(ContactForces(1),ContactForces(2),...
'file','autoGen_contactForce.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'dq1','dq2','dq3','dq4','dq5',...
'ddq1','ddq2','ddq3','ddq4','ddq5',...
'm1','m2','m3','m4','m5',...
'l1','l2','l3','l4',...
'c1','c2','c3','c4','c5',...
'g'},...
'outputs',{'Fx','Fy'});
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
% Write Kinematics Files %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
function kinematics()
disp('Writing kinematics files...')
P = [P1; P2; P3; P4; P5];
Gvec = [G1; G2; G3; G4; G5];
% Used for plotting and animation
matlabFunction(P,Gvec,'file','autoGen_getPoints.m',...
'vars',{...
'q1','q2','q3','q4','q5',...
'l1','l2','l3','l4','l5',...
'c1','c2','c3','c4','c5'},...
'outputs',{'P','Gvec'});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Helper Functions %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [m, mi, mz, mzi, dim] = computeGradients(M,z,empty)
%
% This function computes the gradients of a matrix M with respect the the
% variables in z, and then returns both the matrix and its gradient as
% column vectors of their non-zero elements, along with the linear indicies
% to unpack them. It also simplifies m and mz.
%
% INPUTS:
% M = [na, nb] = symbolic matrix
% z = [nc, 1] = symbolic vector
%
% OUTPUTS:
% m = [nd, 1] = symbolic vector of non-zero elements in M
% i = [nd, 1] = linear indicies to map m --> [na,nb] matrix
% mz = [ne, 1] = symbolic vector of non-zero elements in Mz
% iz = [ne, 1] = linear indicies to map mz --> [na,nb,nc] array
% dim = [3,1] = [na,nb,nc] = dimensions of 3d version of mz
%
[na, nb] = size(M);
nc = size(z,1);
M = simplify(M);
mz2 = jacobian(M(:),z); %Compute jacobian of M, by first reshaping M to be a column vector
mz3 = reshape(mz2,na,nb,nc); %Expand back out to a three-dimensional array
mz3 = simplify(mz3);
% Extract non-zero elements to a column vector:
mi = find(M);
m = M(mi);
mzi = find(mz3);
mz = mz3(mzi); mz = mz(:); %Collapse to a column vector
dim = [na,nb,nc];
% Pad any constant terms with "empty" to permit vectorization:
m = vectorizeHack(m, z, empty);
mz = vectorizeHack(mz, z, empty);
end
function x = vectorizeHack(x, z, empty)
%
% This function searches for any elements of x that are not dependent on
% any element of z. In this case, the automatically generated code will
% fail to vectorize properly. One solution is to add an array of zeros
% (empty) to the element.
%
% x = column vector of symbolic expressions
% z = column vector of symbolic variables
% z = symbolic variable, which the user will set equal to zero.
%
% Compute dependencies
g = jacobian(x,z);
% Check for rows of x with no dependence on z
[n,m] = size(g);
idxConst = true(n,1);
for i=1:n
for j=1:m
if ~isequal(sym(0),g(i,j))
idxConst(i) = false;
break;
end
end
end
% Add empty to those enteries
x(idxConst) = x(idxConst) + empty;
end
|
github
|
MaralKay/Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master
|
hks.m
|
.m
|
Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master/hks.m
| 774 |
utf_8
|
04ef538fa99a2f2ff4c904bd1f45fbd3
|
% Computes heat kernel signature H_t(x,x), where H_t(x,y) is the heat kernel
%
% Usage: desc = hks(evecs,evals,T)
%
% Input: evecs - (n x k) Laplace-Beltrami eigenvectors arranged as columns
% evals - (k x 1) corresponding Laplace-Beltrami eigenvalues
% T - (1 x t) time values
%
% Output: desc - (n x t) matrix with the values of HKS for different t as columns
%
% (c) Michael Bronstein 2012 http://www.inf.usi.ch/bronstein
%
% M. M. Bronstein, I. Kokkinos, "Scale-invariant heat kernel signatures for non-rigid
% shape recognition", CVPR 2010.
function desc = hks(evecs,evals,T)
desc = zeros(size(evecs,1),length(T));
for k = 1:length(T)
desc(:,k) = sum(evecs.^2 .* repmat(exp(-T(k)*evals(:))',[size(evecs,1) 1]),2);
end
end
|
github
|
MaralKay/Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master
|
sihks.m
|
.m
|
Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master/sihks.m
| 1,242 |
utf_8
|
4965726d4d73b1af91710031977ab428
|
% Computes scale-covariant and scale-invariant heat kernel signature (SI-HKS)
%
% Usage: [sc,si] = sihks(evecs,evals,T,Omega)
%
% Input: evecs - (n x k) Laplace-Beltrami eigenvectors arranged as columns
% evals - (k x 1) corresponding Laplace-Beltrami eigenvalues
% alpha - log scalespace basis
% T - (1 x t) time values (used as alpha.^T)
% Omega - (1 x w) frequency samples
%
% Output: sc - (n x t) matrix with the values of the scale-covariant HKS
% for different t as columns
% si - (n x w) matrix with the values of the scale-invariant HKS
% for different omega as columns
%
% (c) Michael Bronstein 2012 http://www.inf.usi.ch/bronstein
%
% M. M. Bronstein, I. Kokkinos, "Scale-invariant heat kernel signatures for non-rigid
% shape recognition", CVPR 2010.
function [si sc] = sihks(evecs,evals,alpha,T,Omega)
sc = zeros(size(evecs,1),length(T));
for k = 1:length(T)
sc(:,k) = - log(alpha)*sum(evecs.^2 .* repmat(alpha^T(k)*evals(:)'.*exp(-alpha^T(k)*evals(:))',[size(evecs,1) 1]),2) ./ ...
sum(evecs.^2 .* repmat(exp(-alpha^T(k)*evals(:))',[size(evecs,1) 1]),2);
end
si = abs(fft(sc,[],2));
si = si(:,Omega);
|
github
|
MaralKay/Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master
|
mshlp_matrix.m
|
.m
|
Scale-invariant-Heat-Kernel-Signature-Descriptor-Evaluation-master/mshlp_matrix.m
| 1,679 |
utf_8
|
769d89f1fad49c165703383fd490805c
|
function [W A] = mshlp_matrix(shape, opt)
%
% Compute the Laplace-Beltrami matrix from mesh
%
% INPUTS
% filename: off file of triangle mesh.
% opt.htype: the way to compute the parameter h. h = hs * neighborhoodsize
% if htype = 'ddr' (data driven); h = hs if hytpe = 'psp' (pre-specify)
% Default : 'ddr'
% opt.hs: the scaling factor that scales the neighborhood size to the
% parameter h where h^2 = 4t.
% Default: 2, must > 0
% opt.rho: The cut-off for Gaussion function evaluation.
% Default: 3, must > 0
% opt.dtype: the way to compute the distance
% dtype = 'euclidean' or 'geodesic';
% Default : 'euclidean'
%
% OUTPUTS
% W: symmetric weight matrix
% A: area weight per vertex, the Laplace matrix = diag(1./ A) * W
if nargin < 1
error('Too few input arguments');
elseif nargin < 2
opt.hs = 2;
opt.rho = 3;
opt.htype = 'ddr';
%opt.dtype = 'euclidean';
opt.dtype = 'cotangent';
end
opt=parse_opt(opt);
if opt.hs <= 0 | opt.rho <= 0
error('Invalid values in opt');
end
%[II JJ SS, AA] = mshlpmatrix(shape.TRIV, shape.X, shape.Y, shape.Z, opt);
[II JJ SS, AA] = meshlp(shape.TRIV, shape.X, shape.Y, shape.Z, opt);
W = sparse(II, JJ, SS);
A = AA;
% Parsing Option.
function option = parse_opt(opt)
option = opt;
option_names = {'hs', 'rho', 'htype', 'dtype'};
if ~isfield(option,'hs'),
option = setfield(option,'hs',2);
end
if ~isfield(option,'rho'),
option = setfield(option,'rho', 3);
end
if ~isfield(option,'htype'),
option = setfield(option,'htype', 'ddr');
end
if ~isfield(option,'dtype'),
option = setfield(option,'dtype', 'euclidean');
end
|
github
|
albanie/mcnDeepLab-master
|
setup_mcnDeepLab.m
|
.m
|
mcnDeepLab-master/setup_mcnDeepLab.m
| 1,531 |
utf_8
|
5dc2dfa0f371dc30c1138a3a658907f2
|
function setup_mcnDeepLab()
%SETUP_MCNDEEPLAB Sets up mcnDeepLab, by adding its folders
% to the Matlab path
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
% add dependencies
check_dependency('autonn') ;
check_dependency('mcnExtraLayers') ;
check_dependency('mcnDatasets') ;
root = fileparts(mfilename('fullpath')) ;
addpath(root, [root '/pascal'], [root '/core']) ;
% -----------------------------------
function check_dependency(moduleName)
% -----------------------------------
name2path = @(name) strrep(name, '-', '_') ;
setupFunc = ['setup_', name2path(moduleName)] ;
if exist(setupFunc, 'file')
vl_contrib('setup', moduleName) ;
else
% try adding the module to the path
addpath(fullfile(vl_rootnn, 'contrib', moduleName)) ;
if exist(setupFunc, 'file')
vl_contrib('setup', moduleName) ;
else
waiting = true ;
msg = ['module %s was not found on the MATLAB path. Would you like ' ...
'to install it now? (y/n)\n'] ;
prompt = sprintf(msg, moduleName) ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
vl_contrib('install', moduleName) ;
vl_contrib('compile', moduleName) ;
vl_contrib('setup', moduleName) ;
return ;
case 'n'
throw(exception) ;
otherwise
fprintf('input %s not recognised, please use `y` or `n`\n', str) ;
end
end
end
end
|
github
|
albanie/mcnDeepLab-master
|
deeplab_demo.m
|
.m
|
mcnDeepLab-master/deeplab_demo.m
| 3,026 |
utf_8
|
9e0427727fae3e9a179bbd095c3ae49d
|
function deeplab_demo(varargin)
%DEEPLAB_DEMO Minimalistic demonstration of a pretrained deeplab model
% DEEPLAB_DEMO a semantic segmentation demo with a deeplab model
%
% DEEPLAB_DEMO(..., 'option', value, ...) accepts the following
% options:
%
% `modelPath`:: ''
% Path to a valid deeplab matconvnet model. If none is provided, a model
% will be downloaded.
%
% `gpus`:: []
% Device on which to run network
%
% `wrapper` :: dagnn
% The matconvnet wrapper to be used (both dagnn and autonn are supported)
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.modelPath = '' ;
opts.wrapper = 'dagnn' ;
opts = vl_argparse(opts, varargin) ;
% Load or download an example faster-rcnn model:
modelName = 'deeplab-res101-v2.mat' ; % slower, mutliscale model
paths = {opts.modelPath, ...
modelName, ...
fullfile(vl_rootnn, 'data', 'models-import', modelName)} ;
ok = find(cellfun(@(x) exist(x, 'file'), paths), 1) ;
if isempty(ok)
fprintf('Downloading the DeepLab model ... this may take a while\n') ;
opts.modelPath = fullfile(vl_rootnn, 'data/models-import', modelName) ;
mkdir(fileparts(opts.modelPath)) ; base = 'http://www.robots.ox.ac.uk' ;
url = sprintf('%s/~albanie/models/deeplab/%s', base, modelName) ;
urlwrite(url, opts.modelPath) ;
else
opts.modelPath = paths{ok} ;
end
% Load the network with the chosen wrapper
net = loadModel(opts) ;
% Load test image
imPath = fullfile(vl_rootnn, 'contrib/mcnDeepLab/misc/000022.jpg') ;
origIm = single(imread(imPath)) ;
% choose variables to track
predIdx = net.getVarIndex(net.meta.predVar) ;
% resize to ensure multilpe of 32 and subtract mean
meanIm = reshape(net.meta.normalization.averageImage, [1 1 3]) ;
im = bsxfun(@minus, origIm, meanIm) ;
sz = [size(im,1), size(im,2)] ;
sz_ = round(sz / 32)*32 ;
im = imresize(im, sz_) ;
% set inputs
sample = {'data', im} ;
switch opts.wrapper
case 'dagnn', inputs = {sample} ; net.mode = 'test' ;
case 'autonn', inputs = {sample, 'test'} ;
end
% run network and retrieve results
net.eval(inputs{:}) ;
switch opts.wrapper
case 'dagnn', preds = squeeze(net.vars(predIdx).value) ;
case 'autonn', preds = squeeze(net.vars{predIdx}) ;
end
% visualise predictions
[~,labels] = max(preds, [], 3) ;
figure('pos',[0 0 900 500])
subplot(1,2,1) ; imagesc(origIm/ 255) ;
title('original image') ;
axis off ;
subplot(1,2,2) ; cmap = VOClabelcolormap ; colormap(cmap) ;
imagesc(labels) ;
axis off ;
title('predicted segmentation') ;
if exist('zs_dispFig', 'file'), zs_dispFig ; end
% ----------------------------
function net = loadModel(opts)
% ----------------------------
net = load(opts.modelPath) ; net = dagnn.DagNN.loadobj(net) ;
switch opts.wrapper
case 'dagnn'
net.mode = 'test' ;
case 'autonn'
out = Layer.fromDagNN(net, @extras_autonn_custom_fn) ; net = Net(out{:}) ;
end
|
github
|
albanie/mcnDeepLab-master
|
deeplab_evaluation.m
|
.m
|
mcnDeepLab-master/core/deeplab_evaluation.m
| 6,225 |
utf_8
|
fc1dc52c89ad6ed118bf665a3e5e6e74
|
function info = deeplab_evaluation(expDir, net, opts)
% Setup data
if exist(opts.dataOpts.imdbPath, 'file')
imdb = load(opts.dataOpts.imdbPath) ;
else
imdb = opts.dataOpts.getImdb(opts) ;
imdbDir = fileparts(opts.dataOpts.imdbPath) ;
if ~exist(imdbDir, 'dir'), mkdir(imdbDir) ; end
save(opts.dataOpts.imdbPath, '-struct', 'imdb') ;
end
switch opts.testset
case 'val', setLabel = 2 ;
case 'test', setLabel = 3 ;
end
testIdx = find(imdb.images.set == setLabel & imdb.images.segmentation) ;
% Compare the validation set to the one used in the FCN paper
% valNames = sort(imdb.images.name(val)') ;
% valNames = textread('data/seg11valid.txt', '%s') ;
% valNames_ = textread('data/seg12valid-tvg.txt', '%s') ;
% assert(isequal(valNames, valNames_)) ;
% -------------------------------------------------------------------------
% Run evaluation
% -------------------------------------------------------------------------
mkdirRecursive(expDir) ;
prepareGPUs(opts, true) ;
if ~isempty(opts.gpus) && strcmp(net.device, 'cpu'), net.move('gpu') ; end
net.mode = 'test' ;
confusion = zeros(21) ;
predIdx = net.getVarIndex(net.meta.predVar) ;
for ii = 1:numel(testIdx)
imId = testIdx(ii) ;
name = imdb.images.name{imId} ;
rgbPath = sprintf(imdb.paths.image, name) ;
labelsPath = sprintf(imdb.paths.classSegmentation, name) ;
% Load an image and gt segmentation
rgb = vl_imreadjpeg({rgbPath}) ;
rgb = rgb{1} ;
anno = imread(labelsPath) ;
lb = single(anno) ;
lb = mod(lb + 1, 256) ; % 0 = ignore, 1 = bkg
% Subtract the mean (color)
meanIm = net.meta.normalization.averageImage ;
if numel(meanIm) == 3
meanIm = reshape(meanIm, [1 1 3]) ;
end
im = bsxfun(@minus, single(rgb), meanIm) ;
% Some networks requires the image to be a multiple of 32 pixels
if opts.batchOpts.imageNeedsToBeMultiple
sz = [size(im,1), size(im,2)] ;
sz_ = round(sz / 32)*32 ;
im_ = imresize(im, sz_) ;
else
im_ = im ;
end
if ~isempty(opts.gpus), im_ = gpuArray(im_) ; end
net.eval({'data', im_}) ;
scores_ = gather(net.vars(predIdx).value) ;
[~,pred_] = max(scores_,[],3) ;
if opts.batchOpts.imageNeedsToBeMultiple
pred = imresize(pred_, sz, 'method', 'nearest') ;
else
pred = pred_ ;
end
% Accumulate errors
ok = lb > 0 ;
confusion = confusion + accumarray([lb(ok),pred(ok)],1,[21 21]) ;
% Plots
if mod(ii - 1,100) == 0 || ii == numel(testIdx)
clear info ;
[info.iu, info.miu, info.pacc, info.macc] = getAccuracies(confusion) ;
fprintf('IU ') ;
fprintf('%4.1f ', 100 * info.iu) ;
fprintf('\n(%d/%d) meanIU: %5.2f pixelAcc: %5.2f, meanAcc: %5.2f\n', ...
ii, numel(testIdx), 100*info.miu, 100*info.pacc, 100*info.macc) ;
figure(1) ; clf;
imagesc(normalizeConfusion(confusion)) ;
axis image ; set(gca,'ydir','normal') ;
colormap(jet) ;
drawnow ;
% Print segmentation
figure(100) ;clf ;
displayImage(rgb/255, lb, pred) ;
drawnow ;
% Save segmentation
imPath = fullfile(expDir, [name '.png']) ;
imwrite(pred,labelColors(),imPath,'png');
end
end
% Save results
resPath = opts.cacheOpts.resultsCache ;
mkdirRecursive(fileparts(resPath)) ;
save(resPath, '-struct', 'info') ;
% ------------------------------
function mkdirRecursive(dirname)
% ------------------------------
fprintf('at %s\n', dirname) ;
while ~exist(fileparts(dirname), 'dir')
fprintf('at %s\n', dirname) ;
mkdirRecursive(fileparts(dirname)) ;
end
if ~exist(dirname, 'dir'), mkdir(dirname) ; end
% -------------------------------------------------------------------------
function nconfusion = normalizeConfusion(confusion)
% -------------------------------------------------------------------------
% normalize confusion by row (each row contains a gt label)
nconfusion = bsxfun(@rdivide, double(confusion), double(sum(confusion,2))) ;
% -------------------------------------------------------------------------
function [IU, meanIU, pixelAccuracy, meanAccuracy] = getAccuracies(confusion)
% -------------------------------------------------------------------------
pos = sum(confusion,2) ;
res = sum(confusion,1)' ;
tp = diag(confusion) ;
IU = tp ./ max(1, pos + res - tp) ;
meanIU = mean(IU) ;
pixelAccuracy = sum(tp) / max(1,sum(confusion(:))) ;
meanAccuracy = mean(tp ./ max(1, pos)) ;
% -------------------------------------------------------------------------
function displayImage(im, lb, pred)
% -------------------------------------------------------------------------
subplot(2,2,1) ;
image(im) ;
axis image ;
title('source image') ;
subplot(2,2,2) ;
image(uint8(lb-1)) ;
axis image ;
title('ground truth')
cmap = labelColors() ;
subplot(2,2,3) ;
image(uint8(pred-1)) ;
axis image ;
title('predicted') ;
colormap(cmap) ;
% -------------------------------------------------------------------------
function cmap = labelColors()
% -------------------------------------------------------------------------
N=21;
cmap = zeros(N,3);
for i=1:N
id = i-1; r=0;g=0;b=0;
for j=0:7
r = bitor(r, bitshift(bitget(id,1),7 - j));
g = bitor(g, bitshift(bitget(id,2),7 - j));
b = bitor(b, bitshift(bitget(id,3),7 - j));
id = bitshift(id,-3);
end
cmap(i,1)=r; cmap(i,2)=g; cmap(i,3)=b;
end
cmap = cmap / 255;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
|
github
|
albanie/mcnDeepLab-master
|
deeplab_zoo.m
|
.m
|
mcnDeepLab-master/core/deeplab_zoo.m
| 1,653 |
utf_8
|
310b5820ee1d14f7689d844df7c474d4
|
function net = deeplab_zoo(modelName)
%DEEPLAB_ZOO - load segmentation network by name
% DEEPLAB_ZOO(MODELNAME) - loads a segmenter by its given name.
% If it cannot be found on disk, it will be downloaded via the world
% wide web.
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
modelNames = {
'deeplab-vggvd-t-v2' ...
'deeplab-vggvd-v2' ...
'deeplab-res101-t-v2' ...
'deeplab-res101-v2' ...
} ;
msg = sprintf('%s: unrecognised model', modelName) ;
assert(ismember(modelName, modelNames), msg) ;
modelDir = fullfile(vl_rootnn, 'data/models-import') ;
modelPath = fullfile(modelDir, sprintf('%s.mat', modelName)) ;
if ~exist(modelPath, 'file'), fetchModel(modelName, modelPath) ; end
net = dagnn.DagNN.loadobj(load(modelPath)) ;
% ---------------------------------------
function fetchModel(modelName, modelPath)
% ---------------------------------------
waiting = true ;
prompt = sprintf(strcat('%s was not found at %s\nWould you like to ', ...
' download it from THE INTERNET (y/n)?\n'), modelName, modelPath) ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
if ~exist(fileparts(modelPath), 'dir'), mkdir(fileparts(modelPath)) ; end
fprintf(sprintf('Downloading %s ... \n', modelName)) ;
baseUrl = 'http://www.robots.ox.ac.uk/~albanie/models/deeplab' ;
url = sprintf('%s/%s.mat', baseUrl, modelName) ;
urlwrite(url, modelPath) ;
return ;
case 'n', throw(exception) ;
otherwise, fprintf('input %s not recognised, please use `y/n`\n', str) ;
end
end
|
github
|
albanie/mcnDeepLab-master
|
deeplab_pascal_evaluation.m
|
.m
|
mcnDeepLab-master/pascal/deeplab_pascal_evaluation.m
| 5,141 |
utf_8
|
c0b0c72bdc03a36ad8dc210abfa818fc
|
function deeplab_pascal_evaluation(varargin)
%DEEPLAB_PASCAL_EVALUATION evaluate FCN on pascal VOC 2012
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.net = [] ;
opts.gpus = 1 ;
opts.modelName = 'deeplab-vggvd-v2' ;
opts.dataDir = fullfile(vl_rootnn, 'data') ;
% configure model options
opts.modelOpts.get_eval_batch = @fcn_eval_get_batch ;
opts = vl_argparse(opts, varargin) ;
% load network
if isempty(opts.net)
net = deeplab_zoo(opts.modelName) ;
else
net = opts.net ;
end
% evaluation options
opts.testset = 'val' ;
opts.prefetch = true ;
% configure batch opts
batchOpts.batchSize = 1 ;
batchOpts.numThreads = 1 ;
batchOpts.use_vl_imreadjpeg = true ;
batchOpts.imageNeedsToBeMultiple = true ;
% cache configuration
cacheOpts.refreshPredictionCache = false ;
cacheOpts.refreshDecodedPredCache = false ;
cacheOpts.refreshEvaluationCache = false ;
cacheOpts.refreshFigures = false ;
% configure dataset options
dataOpts.name = 'pascal' ;
dataOpts.decoder = 'serial' ;
dataOpts.getImdb = @(x) getPascalYearImdb(12, x) ; % 2012 data
dataOpts.displayResults = @displayPascalResults ;
dataOpts.root = fullfile(vl_rootnn, 'data', 'datasets') ;
dataOpts.imdbPath = fullfile(opts.dataDir, 'pascal12/standard_imdb/imdb.mat') ;
dataOpts.configureImdbOpts = @configureImdbOpts ;
dataOpts.vocEdition = '12' ;
dataOpts.includeTest = false ;
dataOpts.includeSegmentation = true ;
dataOpts.includeDetection = true ;
dataOpts.vocAdditionalSegmentations = false ;
dataOpts.dataRoot = dataOpts.root ;
% configure paths
tail = fullfile('evaluations', dataOpts.name, opts.modelName) ;
expDir = fullfile(vl_rootnn, 'data', tail) ;
resultsFile = sprintf('%s-%s-results.mat', opts.modelName, opts.testset) ;
rawPredsFile = sprintf('%s-%s-raw-preds.mat', opts.modelName, opts.testset) ;
decodedPredsFile = sprintf('%s-%s-decoded.mat', opts.modelName, opts.testset) ;
evalCacheDir = fullfile(expDir, 'eval_cache') ;
cacheOpts.rawPredsCache = fullfile(evalCacheDir, rawPredsFile) ;
cacheOpts.decodedPredsCache = fullfile(evalCacheDir, decodedPredsFile) ;
cacheOpts.resultsCache = fullfile(evalCacheDir, resultsFile) ;
cacheOpts.evalCacheDir = evalCacheDir ;
% configure meta options
opts.dataOpts = dataOpts ;
opts.batchOpts = batchOpts ;
opts.cacheOpts = cacheOpts ;
deeplab_evaluation(expDir, net, opts) ;
% -----------------------------------------------------------
function opts = configureImdbOpts(expDir, opts)
% -----------------------------------------------------------
% configure VOC options
% (must be done after the imdb is in place since evaluation
% paths are set relative to data locations)
opts.dataOpts = configureVOC(expDir, opts.dataOpts, 'test') ;
%-----------------------------------------------------------
function dataOpts = configureVOC(expDir, dataOpts, testset)
%-----------------------------------------------------------
% LOADPASCALOPTS Load the pascal VOC database options
%
% NOTE: The Pascal VOC dataset has a number of directories
% and attributes. The paths to these directories are
% set using the VOCdevkit code. The VOCdevkit initialization
% code assumes it is being run from the devkit root folder,
% so we make a note of our current directory, change to the
% devkit root, initialize the pascal options and then change
% back into our original directory
VOCRoot = fullfile(dataOpts.dataRoot, 'VOCdevkit2007') ;
VOCopts.devkitCode = fullfile(VOCRoot, 'VOCcode') ;
% check the existence of the required folders
assert(logical(exist(VOCRoot, 'dir')), 'VOC root directory not found') ;
assert(logical(exist(VOCopts.devkitCode, 'dir')), 'devkit code not found') ;
currentDir = pwd ; cd(VOCRoot) ; addpath(VOCopts.devkitCode) ;
VOCinit ; % VOCinit loads database options into a variable called VOCopts
dataDir = fullfile(VOCRoot, '2007') ;
VOCopts.localdir = fullfile(dataDir, 'local') ;
VOCopts.imgsetpath = fullfile(dataDir, 'ImageSets/Main/%s.txt') ;
VOCopts.imgpath = fullfile(dataDir, 'ImageSets/Main/%s.txt') ;
VOCopts.annopath = fullfile(dataDir, 'Annotations/%s.xml') ;
VOCopts.cacheDir = fullfile(expDir, '2007/Results/Cache') ;
VOCopts.drawAPCurve = false ;
VOCopts.testset = testset ;
detDir = fullfile(expDir, 'VOCdetections') ;
% create detection and cache directories if required
requiredDirs = {VOCopts.localdir, VOCopts.cacheDir, detDir} ;
for i = 1:numel(requiredDirs)
reqDir = requiredDirs{i} ;
if ~exist(reqDir, 'dir') , mkdir(reqDir) ; end
end
VOCopts.detrespath = fullfile(detDir, sprintf('%%s_det_%s_%%s.txt', 'test')) ;
dataOpts.VOCopts = VOCopts ;
cd(currentDir) ; % return to original directory
% ---------------------------------------------------------------------------
function displayPascalResults(modelName, aps, opts)
% ---------------------------------------------------------------------------
fprintf('\n============\n') ;
fprintf(sprintf('%s set performance of %s:', opts.testset, modelName)) ;
fprintf('%.1f (mean ap) \n', 100 * mean(aps)) ;
fprintf('\n============\n') ;
|
github
|
gregjeffrey/Power-System-Fault-Analysis-master
|
get_Ybus.m
|
.m
|
Power-System-Fault-Analysis-master/get_Ybus.m
| 1,087 |
utf_8
|
9dfa600ce65ddbdda2e4bb5615c7144a
|
%%
%Function get_Ybus
%Creates admittance matrix given dataset of resistances, reactances, and
%susceptances.
%Inputs:
%data: matrix containing the given data
%R: Number of the column in 'data' containing Resistance
%X: Number of the column in 'data' containing Reactance
%B: Number of the column in 'data' containing Susceptance
%system_size: Number of buses in the system
function Ybus = get_Ybus(data, R, X, B, system_size)
Ybus = zeros(system_size, system_size);
i=1;
while(data(i, 1) ~= 0)
to = data(i, 1);
from = data(i, 2);
%Adds series + shunt admittances to diagonal component for TO bus
Ybus(to, to) = Ybus(to, to) + 1/(data(i, R) + 1i*data(i, X)) + 1i*0.5*data(i, B);
%Adds series + shunt admittances to diagonal component for FROM bus
Ybus(from, from) = Ybus(from, from) + 1/(data(i, R) + 1i*data(i, X)) + 1i*0.5*data(i, B);
%Creates mutual admittance entries
Ybus(to, from) = -1/(data(i, R) + 1i*data(i, X));
Ybus(from, to) = Ybus(to, from);
i=i+1;
end
end
|
github
|
dbyun425/micscanning-master
|
load_mic.m
|
.m
|
micscanning-master/load_mic.m
| 898 |
utf_8
|
b664719a4bce1a20a54bcafed037c6b7
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% load mic file - just like XDM Toolkit
%
%
% sidewidth is the width of one side of the triangle
%
%
% File Format:
% Col 1-3 x, y, z
% Col 4 1 = triangle pointing up, 2 = triangle pointing down
% Col 5 - Generation number
% Col 7-9 orientation
% Col 10 Confidence
%
%
function [output, sidewidth]= load_mic(filename, numCols)
snp = textread( filename );
sidewidth = snp(1, 1);
output = snp(2:end, :);
% fd = fopen(filename);
% remove first line
% sidewidth = fgetl(fd);
% sidewidth = str2double(sidewidth);
% if(numCols == 9)
% output = fscanf(fd, '%g %g %g %d %d %d %g %g %g', [numCols, inf]);
% elseif(numCols == 10)
% output = fscanf(fd, '%g %g %g %d %d %d %g %g %g %g', [numCols, inf]);
% elseif(numCols == 10)
% output = fscanf(fd, '%g %g %g %d %d %d %g %g %g %g', [numCols, inf]);
% end
% output = output';
% fclose(fd);
end
|
github
|
dbyun425/micscanning-master
|
plot_mic_V2017.m
|
.m
|
micscanning-master/plot_mic_V2017.m
| 24,584 |
utf_8
|
91e26a25a250747f9a587a1c4e5bf52f
|
% The code contained in this file originated in the CMU Suter Research
% Group with contributions from Frankie Li, Jonathan Lind, David Menasche,
% Rulin Chen, RM Suter, and others.
% A set of utility functions (rotation representation conversions) from the
% Cornell University group of Paul Dawson et al is used and appears at the
% end of the file.
% This is a stand-alone set of functions that plot information in
% .mic files
% Usage information can be seen by typing 'plot_mic([0])'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% plot_mic.m
%%
%% Usage:
%% plot_mic( snp, sidewidth, plotType, ConfidenceRange, Symmetry, NewFigure, bCenter, bTightFit, ConfColorScaleRange, ConfColorScaleType )
%%
%%
%% snp - a snapshot read from a .mic file using load_mic
%% sidewidth - the width of one side of a hexagon returned by load_mic
%% plotType - 1 => plots of orientations, 2 => plots of confidence level
%%
%% Note that there is limitations on the colormap resolution.
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% .mic File Format:
%% Col 1-3 x, y, z
%% Col 4 1 = triangle pointing up, 2 = triangle pointing down
%% Col 5 generation number; triangle size = sidewidth /(2^generation number )
%% Col 6 Phase - 1 = exist, 0 = not fitted
%% Col 7-9 orientation
%% Col 10 Confidence
%%
%% There may be other information in additions columns
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot_mic( varargin )
% Suter group
% figure(3);
% Symmetry = 'NON'
% Symmetry = 'CUB'
% Symmetry = 'HEX';
degrad = 180./pi;
%%%%% Interpret input variables
if ( nargin < 5 )
DisplayUsage();
error('ERROR: Not enough arguments: first five are required.');
end
ValidPlotType = [1, 2, 3, 4, 5, 6 ,9];
snp = varargin{1};
sidewidth = varargin{2};
plotType = varargin{3};
ConfidenceRange = varargin{4};
%if(varargin{5} == 1)
% Symmetry = 'CUB'
%elseif(varargin{5} == 2)
% Symmetry = 'HEX'
%else
% Symmetry = 'NON'
%end
Symmetry = varargin{5};
%% default parameters
NewFigure = false;
bCenter = false;
bTightFit = true;
if( nargin >= 6 )
NewFigure = varargin{6};
if(NewFigure)
figure();
end
% dz = varargin{5};
end
if( nargin >= 7 )
bCenter = varargin{7};
end
if( nargin >= 8 )
bTightFit = varargin{8};
end
if( nargin >= 9 )
ConfColorScale = varargin{9};
end
if( nargin >= 10 )
ColorType = varargin{10};
else
ColorType = 'Red';
end
%if( plotType < 1 & plotType > 9 )
% DisplayUsage();
% error('Plot Type not defined! See USAGE for detail');
%end
%%%%% Select entries with confidence in range
ConfSize = size( ConfidenceRange );
if( ConfSize(1) > 1 || ConfSize(2) > 1 )
findvec = snp(:, 10) >= ConfidenceRange(1) & snp(:, 10) <= ConfidenceRange(2);
else
findvec = snp(:, 10) >= ConfidenceRange ;
end
snp = snp(findvec, :);
%%%%% Extract vectors
if(plotType~=9)
% GetTriangleVertices is below in this file
[tri_x, tri_y, snp_Euler, snp_Conf ] = GetTriangleVertices( snp, sidewidth );
else
% Requires external GetTriangleVerticesGrainID (Lind??)
[tri_x, tri_y, snp_Euler, snp_Conf ] = GetTriangleVerticesGrainID( snp, sidewidth );
end
%%%%%%%%%% The next section selects plot types and puts plot quantities in 'tmp'
%%%%% Plot grain map (scaled Eulers?)
if(plotType == 1)
tmp = [ snp_Euler ]/480;
tmp = [1-tmp(:, 1), tmp(:, 2), 1-tmp(:, 3)];
%%%%% Plot Confidence map; options for range and color scale type
elseif(plotType == 2)
if( nargin < 8 )
tmp = (snp_Conf - min(snp_Conf));
tmp = tmp/max(tmp);
tmp = [tmp, zeros(length(tmp), 1), 1-tmp];
xConf = [0:0.01:1]';
colormap( [ xConf, xConf * 0, 1- xConf] );
caxis( [min(snp_Conf), max(snp_Conf) ] );
%caxis( [min(snp_Conf), max(snp_Conf) ] );
else % clipping
tmp = [ snp_Conf ];
tmp = max(tmp, ConfColorScale(1));
tmp = min(tmp, ConfColorScale(2) );
% tmp = [ snp_Conf ] - ConfColorScale(1); % original auto rescale
% original auto rescale
disp('rescale');
tmp = tmp - min(tmp);
tmp = tmp /( max(tmp) - min(tmp) );
if( strcmp( ColorType, 'Red') )
tmp = [tmp, zeros(length(tmp), 1), 1-tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
colormap( [ xConf, xConf * 0, 1- xConf] );
elseif( strcmp(ColorType, 'Gray') )
tmp = [tmp , tmp, tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
colormap( [ xConf, xConf , xConf] );
elseif( strcmp(ColorType, 'iGray') )
tmp = [max(tmp) - tmp , max(tmp) - tmp, max(tmp) - tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
cmap = [ xConf, xConf , xConf];
colormap( flipud(cmap) );
else
error('Unknown colorscale type');
end
caxis( [ConfColorScale(1),ConfColorScale(2)] );
end
% colorbar( 'location', 'eastoutside');
%%%%% plot Rodrigues vector orientation map (with scaling options)
elseif(plotType==3)
tmp = RodOfQuat( QuatOfRMat( RMatOfBunge(snp_Euler', 'degrees') ) )';
InRange = tmp(:, 1) > -10e5 & tmp(:, 1) < 10e5 ...
& tmp(:, 2) > -10e5 & tmp(:, 2) < 10e5 ...
& tmp(:, 3) > -10e5 & tmp(:, 3) < 10e5;
tmp2 = tmp( InRange, :);
%%% Set R-vector limits by symmetry about x,y,z axes
if(Symmetry == 'CUB')
%Scale by size of CUBIC FZ (fixes color scale for whole range)
disp('Color scaling to Cubic symmetry FZ')
sym = 90.
f = tan(sym/degrad/4);
disp(['R_1, R_2, R_3: Sym angle = ', num2str(sym),', Rvec range = +/-', num2str(f)])
tmp2(:, 1) = (tmp2(:, 1) + f)/(2*f);
big = max(tmp2(:,1));
small = min(tmp2(:,1));
disp(['Color range in data: Max = ', num2str(big),', Min = ',num2str(small)])
tmp2(:, 2) = (tmp2(:, 2) + f)/(2*f);
big = max(tmp2(:,1));
small = min(tmp2(:,1));
disp(['Color range in data: Max = ', num2str(big),', Min = ',num2str(small)])
tmp2(:, 3) = (tmp2(:, 3) + f)/(2*f);
big = max(tmp2(:,1));
small = min(tmp2(:,1));
disp(['Color range in data: Max = ', num2str(big),', Min = ',num2str(small)])
% Scale by size of HEXAGONAL FZ (fixes color scale for whole range)
elseif(Symmetry == 'HEX')
disp('Color scaling to Hexagonal symmetry FZ')
sym = 180.; % Two fold
f = tan(sym/degrad/4);
disp(['R_1, R_2: Sym angle = ', num2str(sym),', Rvec range = +/-', num2str(f)])
tmp2(:,1) = (tmp2(:,1) + f)/(2*f);
big = max(tmp2(:,1));
small = min(tmp2(:,1));
disp(['Color range in data: Max = ', num2str(big),', Min = ',num2str(small)])
tmp2(:,2) = (tmp2(:,2) + f)/(2*f);
big = max(tmp2(:,2));
small = min(tmp2(:,2));
disp(['Color range in data: Max = ', num2str(big),', Min = ',num2str(small)])
disp(' ')
sym = 60.; % Six fold about c-axis
f = tan(sym/degrad/4);
disp(['R_3: Sym angle = ',num2str(sym),', Rvec range = +/-',num2str(f)])
tmp2(:,3) = (tmp2(:,3) + f)/(2*f);
big = max(tmp2(:,3));
small = min(tmp2(:,3));
disp(['Color range in data: Max = ', num2str(big), ', Min = ', num2str(small)])
tmp( InRange, :) = tmp2;
else
disp('Color scaling to input range (no symmetry consideration)')
%Scale by INPUT RANGE used (expand scale for seeing subtle stuff)
tmp2(:, 1) = tmp2(:, 1) - min(tmp2(:, 1));
tmp2(:, 2) = tmp2(:, 2) - min(tmp2(:, 2));
tmp2(:, 3) = tmp2(:, 3) - min(tmp2(:, 3));
tmp2(:,1) = tmp2(:,1)/max(tmp2(:,1));
tmp2(:,2) = tmp2(:,2)/max(tmp2(:,2));
tmp2(:,3) = tmp2(:,3)/max(tmp2(:,3));
tmp( InRange, :) = tmp2;
end
%%%%%
elseif(plotType == 4) % plot pole figure
tmp = fixedEulerColor( snp_Euler );
%%%%%
elseif(plotType == 5)
disp('IPF');
tmp = inversePoleFigureColor([ snp_Euler ] * pi/180);
%%%%% Plot the mesh
elseif(plotType == 6)
tmp = [snp_Euler]/480;
tmp = [1-tmp(:, 1), tmp(:, 2), 1-tmp(:, 3)];
size_vec = size(tmp);
tri_color = ones(1, size_vec(1), size_vec(2));
% figure;
axis equal;
% do this plot here:
h = patch(tri_x, tri_y, tri_color);
%%%%% Misorientation map
elseif(plotType == 7)
tmp = [ snp_Conf ];
tmp = tmp/max(tmp);
tmp = [tmp, zeros(length(tmp), 1), 1-tmp];
step = ( max(snp_Conf) - min(snp_Conf) ) /10;
xConf = [min(snp_Conf):step:max(snp_Conf)]';
xConf = xConf / max(xConf);
colormap( [ xConf, xConf * 0, 1- xConf] );
caxis( [min(snp_Conf), max(snp_Conf) ] );
colorbar( 'location', 'eastoutside');
%%%%%
elseif(plotType == 8) % plot Euler angle color map (grain map)
% set color scale in [0:1]
tmp = snp_Euler ;
tmp(:, 1) = tmp(:, 1) - min(tmp(:, 1)) ;
tmp(:, 2) = tmp(:, 2) - min(tmp(:, 2)) ;
tmp(:, 3) = tmp(:, 3) - min(tmp(:, 3)) ;
tmp(:, 3) = tmp(:, 3) / max(tmp(:, 3));
tmp(:, 2) = tmp(:, 2) / max(tmp(:, 2));
tmp(:, 1) = tmp(:, 1) / max(tmp(:, 1));
%%%%%
elseif(plotType == 9) % plot GrainIDs
if( nargin < 8 )
tmp = [ snp_Conf ];
tmp = [ snp_Conf ] - min( snp_Conf ); % original auto rescale
tmp = tmp /( max(snp_Conf) - min(snp_Conf) ); % original auto rescale
tmp = [tmp, zeros(length(tmp), 1), 1-tmp];
xConf = [0:0.01:1]';
colormap( [ xConf, xConf * 0, 1- xConf] );
caxis( [min(snp_Conf), max(snp_Conf) ] ); % original, auto rescale
caxis( [min(snp_Conf), max(snp_Conf) ] );
else % clipping
tmp = [ snp_Conf ];
tmp = max(tmp, ConfColorScale(1));
tmp = min(tmp, ConfColorScale(2) );
% tmp = [ snp_Conf ] - ConfColorScale(1); % original auto rescale
% original auto rescale
disp('rescale');
tmp = tmp - min(tmp);
tmp = tmp /( max(tmp) - min(tmp) );
if( strcmp( ColorType, 'Red') )
tmp = [tmp, zeros(length(tmp), 1), 1-tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
colormap( [ xConf, xConf * 0, 1- xConf] );
elseif( strcmp(ColorType, 'Gray') )
tmp = [tmp , tmp, tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
colormap( [ xConf, xConf , xConf] );
elseif( strcmp(ColorType, 'iGray') )
tmp = [max(tmp) - tmp , max(tmp) - tmp, max(tmp) - tmp];
xConf = [ min(tmp):0.01:max(tmp)]';
cmap = [ xConf, xConf , xConf];
colormap( flipud(cmap) );
else
error('Unknown type');
end
caxis( [ConfColorScale(1),ConfColorScale(2)] ); % original, auto rescal
end
nMinSize = 100;
gids = unique(snp(:,11));
for i=1:length(gids)
ind = find( snp(:,11) == gids(i) );
if size(ind,1) > nMinSize
x_avg = mean( snp(ind,1) );
y_avg = mean( snp(ind,2) );
text(x_avg,y_avg, num2str(gids(i)), 'Color', 'w','FontSize',10);
end
end
colorbar( 'location', 'eastoutside');
end
%%%%% Fill color arrays from tmp and shift origin and axes if requested (except for mesh plotting)
if( plotType ~= 6 )
size_vec = size(tmp);
tri_color = zeros(1, size_vec(1), size_vec(2));
tri_color(1, :, :) = tmp;
%figure;
if ~bCenter
if ( ~bTightFit )
%axis([ -sidewidth, sidewidth, -sidewidth, sidewidth]);
axis([ -sidewidth, sidewidth, -sidewidth, sidewidth]);
else
%micCenter = [mean(snp(:, 1)), mean( snp(:, 2) )];
micCenter = [mean(tri_x(:)), mean( tri_y(:))];
dx = max( tri_x(:) ) - min( tri_x(:) );
dy = max( tri_y(:) ) - min( tri_y(:) );
newSw = 1.1*max( [dx, dy] ) / 2; % adjust 1.1 fudge factor for more asymmetric cases than Zr
%axis([ micCenter(1) - newSw, micCenter(1) + newSw, micCenter(2) - newSw, micCenter(2) + newSw ] );
axis([ micCenter(1) - newSw, micCenter(1) + newSw, micCenter(2) - newSw, micCenter(2) + newSw ] );
end
else
findvec = find( snp(:, 6) > 0 );
xCenter = mean( snp(findvec, 1) );
yCenter = mean( snp(findvec, 2) );
%axis([ -sidewidth + xCenter, sidewidth + xCenter, -sidewidth + yCenter, sidewidth + yCenter]);
axis([ -sidewidth + xCenter, sidewidth + xCenter, -sidewidth + yCenter, sidewidth + yCenter]);
end
end
%%%%% Make the plot!
%if( nargin >= 5 )
% zs = zeros(3,length(tri_x))+dz;
% %size(tri_x)
% %size(zs)
% %size(tri_color)
% h = patch(tri_x, tri_y, zs, tri_color, 'EdgeColor', 'none');
% %alpha(h,1);
% else
h = patch(tri_x, tri_y, tri_color, 'EdgeColor', 'none');
%end
if(plotType==2)
colorbar( 'location', 'eastoutside');
end
xlabel('X (mm)', 'FontSize', 20);
ylabel('Y (mm)', 'FontSize', 20);
set(gca , 'FontSize', 16);
box on;
%axis square;
axis equal;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% GetTriangleVertices
%%
%% Compute all vertices given a legacy snapshot format
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [tri_x, tri_y, snp_Euler, snp_Conf ] = GetTriangleVertices( snp, sidewidth )
% Suter group
snp(:,5) = 2.^ snp(:, 5);
% find range
max_x = 1*sidewidth;
max_y = 1*sidewidth;
min_x = -1*sidewidth;
min_y = -1*sidewidth;
% find all fitted triangles
snp = sortrows(snp, 6);
findvec = find(snp(:, 6) > 0);
snp = snp(findvec, :);
% sort by triangle
snp = sortrows(snp, 4);
% find triangles pointing up
downsIndex = find(snp(:, 4) > 1);
upsIndex = find(snp(:, 4) <= 1);
ups = snp(upsIndex, :);
downs = snp(downsIndex, :);
ups_sides = sidewidth ./ ups(:, 5);
downs_sides = sidewidth ./ downs(:, 5);
% calculate ups v1, ups v2, and ups v3
ups_v1 = ups(:, 1:2); % (x, y)
ups_v2 = ups(:, 1:2);
ups_v2(:, 1) = ups_v2(:, 1) + ups_sides; % (x+s, y) direction
ups_v3 = ups(:, 1:2);
ups_v3(:, 1) = ups_v3(:, 1) + ups_sides/2; % (x+s/2, y)
ups_v3(:, 2) = ups_v3(:, 2) + ups_sides/2 * sqrt(3); % (x+s/2, y+s/2 *sqrt(3));
% calculate downs v1, downs v2, and downs v3
downs_v1 = downs(:, 1:2); % (x, y)
downs_v2 = downs(:, 1:2);
downs_v2(:, 1) = downs_v2(:, 1) + downs_sides; % (x+s, y) direction
downs_v3 = downs(:, 1:2);
downs_v3(:, 1) = downs_v3(:, 1) + downs_sides/2; % (x+s/2, y)
downs_v3(:, 2) = downs_v3(:, 2) - downs_sides/2 * sqrt(3); % (x+s/2, y - s/2 *sqrt(3));
% format is in [v1; v2; v3], where v1, v2, and v3 are rol vectors
tri_x = [ [ups_v1(:, 1); downs_v1(:, 1)]'; [ups_v2(:, 1); downs_v2(:, 1)]'; [ups_v3(:, 1); downs_v3(:, 1)]'];
tri_y = [ [ups_v1(:, 2); downs_v1(:, 2)]'; [ups_v2(:, 2); downs_v2(:, 2)]'; [ups_v3(:, 2); downs_v3(:, 2)]'];
snp_Reordered = [ ups; downs];
snp_Euler = snp_Reordered( :, 7:9 );
% snp_Conf = snp_Reordered( :, 10 );
snp_Conf = snp_Reordered( :, 10 );
% snp_Conf = snp_Reordered( :, 13 ) ./snp_Reordered( :, 14 );
end
function [tri_x, tri_y, snp_Euler, snp_GID ] = GetTriangleVerticesGrainID( snp, sidewidth )
% Suter group
snp(:,5) = 2.^ snp(:, 5);
% find range
max_x = 1*sidewidth;
max_y = 1*sidewidth;
min_x = -1*sidewidth;
min_y = -1*sidewidth;
% find all fitted triangles
snp = sortrows(snp, 6);
findvec = find(snp(:, 6) > 0);
snp = snp(findvec, :);
% sort by triangle
snp = sortrows(snp, 4);
% find triangles pointing up
downsIndex = find(snp(:, 4) > 1);
upsIndex = find(snp(:, 4) <= 1);
ups = snp(upsIndex, :);
downs = snp(downsIndex, :);
ups_sides = sidewidth ./ ups(:, 5);
downs_sides = sidewidth ./ downs(:, 5);
% calculate ups v1, ups v2, and ups v3
ups_v1 = ups(:, 1:2); % (x, y)
ups_v2 = ups(:, 1:2);
ups_v2(:, 1) = ups_v2(:, 1) + ups_sides; % (x+s, y) direction
ups_v3 = ups(:, 1:2);
ups_v3(:, 1) = ups_v3(:, 1) + ups_sides/2; % (x+s/2, y)
ups_v3(:, 2) = ups_v3(:, 2) + ups_sides/2 * sqrt(3); % (x+s/2, y+s/2 *sqrt(3));
% calculate downs v1, downs v2, and downs v3
downs_v1 = downs(:, 1:2); % (x, y)
downs_v2 = downs(:, 1:2);
downs_v2(:, 1) = downs_v2(:, 1) + downs_sides; % (x+s, y) direction
downs_v3 = downs(:, 1:2);
downs_v3(:, 1) = downs_v3(:, 1) + downs_sides/2; % (x+s/2, y)
downs_v3(:, 2) = downs_v3(:, 2) - downs_sides/2 * sqrt(3); % (x+s/2, y - s/2 *sqrt(3));
% format is in [v1; v2; v3], where v1, v2, and v3 are rol vectors
tri_x = [ [ups_v1(:, 1); downs_v1(:, 1)]'; [ups_v2(:, 1); downs_v2(:, 1)]'; [ups_v3(:, 1); downs_v3(:, 1)]'];
tri_y = [ [ups_v1(:, 2); downs_v1(:, 2)]'; [ups_v2(:, 2); downs_v2(:, 2)]'; [ups_v3(:, 2); downs_v3(:, 2)]'];
snp_Reordered = [ ups; downs];
snp_Euler = snp_Reordered( :, 7:9 );
% snp_Conf = snp_Reordered( :, 10 );
snp_GID = snp_Reordered( :, 11 );
% snp_Conf = snp_Reordered( :, 13 ) ./snp_Reordered( :, 14 );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% DisplayUsage
%%
%%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DisplayUsage()
% Suter group
disp(' ')
disp('Use [SnapShotName, SideWidth] = LOAD_MIC(mic_filename, #columns) to load data')
disp(' ')
disp('USAGE: plot_mic( SnapShotName, SideWidth, PlotType, Confidence{min or [min max]}, Symmetry{"CUB", "HEX","NON"},'),
disp(' NewFigure{default=false}, bCenter{default=false}, bTightFit{default=true}, ConfColorScaleRange, ConfColorScaleType )')
disp(' (first five arguments are required)')
disp(' ')
disp(' PlotType = 1 -- Direct mapping of Euler angles to RGB color (not recommended)')
disp(' PlotType = 2 -- Confidence map')
disp(' PlotType = 3 -- Map of RF-vectors represented by RGB colors')
disp(' PlotType = 5 -- Inverse Pole Figure (implementation not verified)')
disp(' PlotType = 6 -- Mesh Structure')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% fixedEulerColor
%%
%%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Suter group
function colorOut = fixedEulerColor(Eu)
colorOut = Eu;
EuSize = size(Eu);
EuLength = EuSize(1);
% calculate misorientation from fixed color and vectors (cubic symmetry)
%
% (35, 45, 0)
% (90, 35, 45)
% (42, 37, 9)
% (59, 37, 63)
% (0, 45, 0)
% (0, 0, 0)
% (90, 25, 65)
colorList = cell(7, 2);
colorList{1, 1} = [35, 45, 0];
colorList{2, 1} = [90, 35, 45];
colorList{3, 1} = [42, 37, 9];
colorList{4, 1} = [59, 37, 63];
colorList{5, 1} = [0, 45, 0];
colorList{6, 1} = [0, 0, 0];
colorList{7, 1} = [90, 25, 65];
colorList{1, 2} = [.5, 0, 0];
colorList{2, 2} = [0, .5, 0];
colorList{3, 2} = [0, 0, .5];
colorList{4, 2} = [.5, .5, 0];
colorList{5, 2} = [0, .5, 1];
colorList{6, 2} = [.5, 0, .5];
colorList{7, 2} = [.5, .5, .5];
allowedMisorient = 15;
cubicSymOps = GetCubicSymOps();
test = zeros(EuLength, 2);
for i = 1:EuLength
minMisorient = 360;
minJ = -1;
for j = 1:7
currentMisorient = misorient_sym_deg(Eu(i, :), colorList{j, 1}, cubicSymOps, 24);
if(currentMisorient < minMisorient)
minMisorient = currentMisorient;
minJ = j;
end
end
test(i, 1) = minJ;
test(i, 2) = minMisorient;
if(minJ > -1 & minMisorient < allowedMisorient)
colorOut(i, :) = colorList{minJ, 2};
else
colorOut(i, :) = [0, 0, 0];
end
end
disp('end');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rmat = RMatOfBunge(bunge, units)
% From Cornell OdfPf package
% RMatOfBunge - Rotation matrix from Bunge angles.
%
% USAGE:
%
% rmat = RMatOfBunge(bunge, units)
%
% INPUT:
%
% bunge is 3 x n,
% the array of Bunge parameters
% units is a string,
% either 'degrees' or 'radians'
%
% OUTPUT:
%
% rmat is 3 x 3 x n,
% the corresponding rotation matrices
%
if (nargin < 2)
error('need second argument, units: ''degrees'' or ''radians''')
end
%
if (strcmp(units, 'degrees'))
%
indeg = 1;
bunge = bunge*(pi/180);
%
elseif (strcmp(units, 'radians'))
indeg = 0;
else
error('angle units need to be specified: ''degrees'' or ''radians''')
end
%
n = size(bunge, 2);
cbun = cos(bunge);
sbun = sin(bunge);
%
rmat = [
cbun(1, :).*cbun(3, :) - sbun(1, :).*cbun(2, :).*sbun(3, :);
sbun(1, :).*cbun(3, :) + cbun(1, :).*cbun(2, :).*sbun(3, :);
sbun(2, :).*sbun(3, :);
-cbun(1, :).*sbun(3, :) - sbun(1, :).*cbun(2, :).*cbun(3, :);
-sbun(1, :).*sbun(3, :) + cbun(1, :).*cbun(2, :).*cbun(3, :);
sbun(2, :).*cbun(3, :);
sbun(1, :).*sbun(2, :);
-cbun(1, :).*sbun(2, :);
cbun(2, :)
];
rmat = reshape(rmat, [3 3 n]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function quat = QuatOfRMat(rmat)
% From Cornell OdfPf package
% QuatOfRMat - Quaternion from rotation matrix
%
% USAGE:
%
% quat = QuatOfRMat(rmat)
%
% INPUT:
%
% rmat is 3 x 3 x n,
% an array of rotation matrices
%
% OUTPUT:
%
% quat is 4 x n,
% the quaternion representation of `rmat'
%
% Find angle of rotation.
%
ca = 0.5*(rmat(1, 1, :) + rmat(2, 2, :) + rmat(3, 3, :) - 1);
ca = min(ca, +1);
ca = max(ca, -1);
angle = squeeze(acos(ca))';
%
% Three cases for the angle:
%
% * near zero -- matrix is effectively the identity
% * near pi -- binary rotation; need to find axis
% * neither -- general case; can use skew part
%
tol = 1.0e-4;
anear0 = (angle < tol);
nnear0 = length(anear0);
angle(anear0) = 0;
raxis = [rmat(3, 2, :) - rmat(2, 3, :);
rmat(1, 3, :) - rmat(3, 1, :);
rmat(2, 1, :) - rmat(1, 2, :)];
raxis = squeeze(raxis);
raxis(:, anear0) = 1;
%
special = angle > pi - tol;
nspec = sum(special);
if (nspec > 0)
%disp(['special: ', num2str(nspec)]);
sangle = repmat(pi, [1, nspec]);
tmp = rmat(:, :, special) + repmat(eye(3), [1, 1, nspec]);
tmpr = reshape(tmp, [3, 3*nspec]);
tmpnrm = reshape(dot(tmpr, tmpr), [3, nspec]);
[junk, ind] = max(tmpnrm);
ind = ind + (0:3:(3*nspec-1));
saxis = squeeze(tmpr(:, ind));
raxis(:, special) = saxis;
end
%debug.angle = angle;
%debug.raxis = raxis;
quat = QuatOfAngleAxis(angle, raxis);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rod = RodOfQuat(quat)
% From Cornell OdfPf package
% RodOfQuat - Rodrigues parameterization from quaternion.
%
% USAGE:
%
% rod = RodOfQuat(quat)
%
% INPUT:
%
% quat is 4 x n,
% an array whose columns are quaternion paramters;
% it is assumed that there are no binary rotations
% (through 180 degrees) represented in the input list
%
% OUTPUT:
%
% rod is 3 x n,
% an array whose columns form the Rodrigues parameterization
% of the same rotations as quat
%
rod = quat(2:4, :)./repmat(quat(1,:), [3 1]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function quat = QuatOfAngleAxis(angle, raxis)
% QuatOfAngleAxis - Quaternion of angle/axis pair.
% From Cornell OdfPf package
%
% USAGE:
%
% quat = QuatOfAngleAxis(angle, rotaxis)
%
% INPUT:
%
% angle is an n-vector,
% the list of rotation angles
% raxis is 3 x n,
% the list of rotation axes, which need not
% be normalized (e.g. [1 1 1]'), but must be nonzero
%
% OUTPUT:
%
% quat is 4 x n,
% the quaternion representations of the given
% rotations. The first component of quat is nonnegative.
%
halfangle = 0.5*angle(:)';
cphiby2 = cos(halfangle);
sphiby2 = sin(halfangle);
%
rescale = sphiby2 ./sqrt(dot(raxis, raxis, 1));
%
quat = [cphiby2; repmat(rescale, [3 1]) .* raxis ] ;
%
q1negative = (quat(1,:) < 0);
quat(:, q1negative) = -1*quat(:, q1negative);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
EvanZhuang/MRI-Reconstruction-with-Sparse-Optimization-master
|
project.m
|
.m
|
MRI-Reconstruction-with-Sparse-Optimization-master/project.m
| 1,132 |
utf_8
|
c5d93efc36b5bf7d07eb13d0de914d34
|
% Take an image and project in into a matrix
% suitable for backprojection
%
% Calling: ct_data = project (image_data, K)
%
% Input: image_data - The gray scale image
% K - Number of projections
%
% Output: ct_data - The projected data
%
% version 1.2, 6/11-97 Joergen Arendt Jensen
function ct_data = project (image_data,K)
% Pre-allocate storage for the projection
% and ensure that the image is retangular
[N,M]=size(image_data);
N=max(N,M);
image_data(N,N)=0;
ct_data=zeros(N,K);
% Make the index matrix
xm = ((1:N)'-N/2) * ones(1,M);
ym = ones(N,1) * ((1:M)-M/2);
% Do the different summations
dtheta=pi/K;
for i=1:K
disp([num2str(i/K*100),'% done'])
% Rotate the array
theta = (i-1)*dtheta;
x = floor( xm*cos(theta) - ym*sin(theta) + N/2 + 0.5);
y = floor( xm*sin(theta) + ym*cos(theta) + M/2 + 0.5);
inside = (x>=1) & (x<=N) & (y>=1) & (y<=M);
x = x.*inside + 1*(1-inside);
y = y.*inside + 1*(1-inside);
% Find the projection
pro = sum (image_data(x + (y-1)*N) .* inside)';
ct_data(:,i) = pro(N:-1:1);
end
|
github
|
wenchaodudu/SNLDA-master
|
LapPLSI.m
|
.m
|
SNLDA-master/LapPLSI/LapPLSI.m
| 8,559 |
utf_8
|
6da6b433a5a9f0bc241b5c792b1c5d4b
|
function [Pz_d_final, Pw_z_final, Obj_final, nIter_final,Pz_d_init,Pw_z_init] = LapPLSI(X, K, W, options, Pz_d, Pw_z)
% Laplacian Probabilistic Latent Semantic Indexing/Alnalysis (LapPLSI) using generalized EM
%
% where
% X
% Notation:
% X ... (mFea x nSmp) term-document matrix (observed data)
% X(i,j) stores number of occurrences of word i in document j
%
% mFea ... number of words (vocabulary size)
% nSmp ... number of documents
% K ... number of topics
% W ... weight matrix of the affinity graph
%
% options ... Structure holding all settings
% options.lambda: manifold regularization prameter (default 1000)
%
% You only need to provide the above four inputs.
%
% Pz_d ... P(z|d)
% Pw_z ... P(w|z) corresponds to beta parameter in LDA
%
%
% References:
% [1] Deng Cai, Qiaozhu Mei, Jiawei Han, ChengXiang Zhai, "Modeling Hidden
% Topics on Document Manifold", Proc. 2008 ACM Conf. on Information and
% Knowledge Management (CIKM'08), Napa Valley, CA, Oct. 2008.
% [2] Qiaozhu Mei, Deng Cai, Duo Zhang, ChengXiang Zhai, "Topic Modeling
% with Network Regularization", Proceedings of the World Wide Web
% Conference ( WWW'08), 2008
%
%
% This software is based on the implementation of pLSA from
%
% Peter Gehler
% Max Planck Institute for biological Cybernetics
% [email protected]
% Feb 2006
% http://www.kyb.mpg.de/bs/people/pgehler/code/index.html
%
% version 2.0 --June/2009
% version 1.1 --June/2008
% version 1.0 --Nov/2007
%
% Written by Deng Cai (dengcai AT gmail.com)
%
maxLoop = 100;
if min(min(X)) < 0
error('Input should be nonnegative!');
end
differror = 1e-7;
if isfield(options,'error')
differror = options.error;
end
maxIter = [];
if isfield(options, 'maxIter')
maxIter = options.maxIter;
end
nRepeat = 10;
if isfield(options,'nRepeat')
nRepeat = options.nRepeat;
end
minIter = 30;
if isfield(options,'minIter')
minIter = options.minIter;
end
meanFitRatio = 0.1;
if isfield(options,'meanFitRatio')
meanFitRatio = options.meanFitRatio;
end
lambda = 1000;
if isfield(options,'lambda')
lambda = options.lambda;
end
gamma = 0.1;
if isfield(options,'gamma')
gamma = options.gamma;
end
nStep = 200;
if isfield(options,'nStep')
nStep = options.nStep;
end
Verbosity = 0;
if isfield(options,'Verbosity')
Verbosity = options.Verbosity;
end
DCol = full(sum(W,2));
D = spdiags(DCol,0,speye(size(W,1)));
L = D - W;
if isfield(options,'NormW') && options.NormW
D_mhalf = DCol.^-.5;
tmpD_mhalf = repmat(D_mhalf,1,nSmp);
L = (tmpD_mhalf.*L).*tmpD_mhalf';
clear D_mhalf tmpD_mhalf;
L = max(L, L');
end
if ~exist('Pz_d','var')
[Pz_d,Pw_z] = pLSA_init(X,K);
Pz_d_init = Pz_d;`
Pw_z_init = Pw_z;
else
nRepeat = 1;
end
Pd = sum(X)./sum(X(:));
Pd = full(Pd);
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
selectInit = 1;
if nRepeat == 1
selectInit = 0;
minIter = 0;
end
tryNo = 0;
[Pw_z,Pz_d] = mex_EMstep(X,Pw_d,Pw_z,Pz_d);
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
LogL = mex_logL(X,Pw_d,Pd);
ObjLap = sum(sum(Pz_d*L.*Pz_d))*2;
Obj = LogL-ObjLap*lambda;
nIter = 1;
meanFit = Obj*10;
for i=1:nStep
Pz_d = (1-gamma)*Pz_d + gamma*Pz_d*W./repmat(DCol',K,1);
end
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
LogLNew = mex_logL(X,Pw_d,Pd);
ObjLapNew = sum(sum(Pz_d*L.*Pz_d))*2;
ObjNew = LogLNew-ObjLapNew*lambda;
if ObjNew > Obj
nIter = nIter + 1;
LogL(end+1) = LogLNew;
ObjLap(end+1) = ObjLapNew;
Obj(end+1) = ObjNew;
end
disp('Beginning loop.')
while tryNo < nRepeat
disp(['Iteration number ', num2str(tryNo)])
tryNo = tryNo+1;
maxErr = 1;
while(maxErr > differror)
Pw_z_old = Pw_z;
Pz_d_old = Pz_d;
[Pw_z,Pz_d] = mex_EMstep(X,Pw_d,Pw_z,Pz_d);
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
LogLNew = mex_logL(X,Pw_d,Pd);
deltaLogL = LogLNew-LogL(end);
ObjLapNew = sum(sum(Pz_d*L.*Pz_d))*2;
deltaObjLap = ObjLapNew - ObjLap(end);
deltaObj = deltaLogL-deltaObjLap*lambda;
loopNo = 0;
loopNo2 = 0;
while deltaObj < 0
loopNo = 0;
while deltaObj < 0
for i=1:nStep
Pz_d = (1-gamma)*Pz_d + gamma*Pz_d*W./repmat(DCol',K,1);
end
ObjLapNew = sum(sum(Pz_d*L.*Pz_d))*2;
deltaObjLap = ObjLapNew - ObjLap(end);
deltaObj = deltaLogL-deltaObjLap*lambda;
loopNo = loopNo + 1;
if loopNo > maxLoop
break;
end
end
if loopNo > maxLoop
break;
end
loopNo2 = loopNo2 + 1;
if loopNo2 > maxLoop
break;
end
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
LogLNew = mex_logL(X,Pw_d,Pd);
deltaLogL = LogLNew-LogL(end);
deltaObj = deltaLogL-deltaObjLap*lambda;
end
IterValid = 1;
StopIter = 0;
if loopNo > maxLoop || loopNo2 > maxLoop
Pw_z = Pw_z_old;
Pz_d = Pz_d_old;
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
if nStep > 1
nStep = ceil(nStep/2);
IterValid = 0;
elseif gamma > 0.01
gamma = gamma/2;
IterValid = 0;
else
StopIter = 1;
end
else
LogL(end+1) = LogLNew;
ObjLap(end+1) = ObjLapNew;
Obj(end+1) = LogL(end)-ObjLap(end)*lambda;
end
if StopIter
maxErr = 0;
elseif IterValid
nIter = nIter + 1;
if nIter > minIter
if selectInit
maxErr = 0;
else
meanFit = meanFitRatio*meanFit + (1-meanFitRatio)*Obj(end);
maxErr = (meanFit-Obj(end))/meanFit;
if ~isempty(maxIter)
if nIter >= maxIter
maxErr = 0;
end
end
end
end
if Verbosity
if length(LogL) > 1
disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(Obj(end)),' deltaLogL: ',num2str(Obj(end)-Obj(end-1)),' maxErr:',num2str(maxErr)]);
else
disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(Obj(end)),' maxErr:',num2str(maxErr)]);
end
end
end
end
if tryNo == 1
Pz_d_final = Pz_d;
Pw_z_final = Pw_z;
nIter_final = nIter;
LogL_final = LogL;
ObjLap_final = ObjLap;
Obj_final = Obj;
Pw_d_final = Pw_d;
else
if Obj(end) > Obj_final(end)
Pz_d_final = Pz_d;
Pw_z_final = Pw_z;
nIter_final = nIter;
LogL_final = LogL;
ObjLap_final = ObjLap;
Obj_final = Obj;
Pw_d_final = Pw_d;
end
end
if selectInit
if tryNo < nRepeat
%re-start
[Pz_d,Pw_z] = pLSA_init(X,K);
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
[Pw_z,Pz_d] = mex_EMstep(X,Pw_d,Pw_z,Pz_d);
Pw_d = mex_Pw_d(X,Pw_z,Pz_d);
LogL = mex_logL(X,Pw_d,Pd);
ObjLap = sum(sum(Pz_d*L.*Pz_d))*2;
Obj = LogL-ObjLap*lambda;
nIter = 1;
else
tryNo = tryNo - 1;
minIter = 0;
selectInit = 0;
Pz_d = Pz_d_final;
Pw_z= Pw_z_final;
LogL = LogL_final;
ObjLap = ObjLap_final;
Obj = Obj_final;
nIter = nIter_final;
meanFit = Obj(end)*10;
Pw_d = Pw_d_final;
end
end
end
function [Pz_d,Pw_z,Pz_q] = pLSA_init(X,K,Xtest)
[mFea,nSmp] = size(X);
Pz_d = rand(K,nSmp);
Pz_d = Pz_d ./ repmat(sum(Pz_d,1),K,1);
% random assignment
Pw_z = rand(mFea,K);
Pw_z = Pw_z./repmat(sum(Pw_z,1),mFea,1);
if nargin > 2
nTest = size(Xtest,2);
Pz_q = rand(K,nTest);
Pz_q = Pz_q ./ repmat(sum(Pz_q),K,1);
end
|
github
|
fennialesmana/sleep-stage-identification-master
|
PSOforSVM.m
|
.m
|
sleep-stage-identification-master/PSOforSVM.m
| 8,792 |
utf_8
|
49a47260c88138452e9cff72a3245d90
|
function [result, startTime, endTime] = PSOforSVM(nFeatures, trainingData, ...
testingData, PSOSettings)
%Running PSO with SVM for feature selection
% Syntax:
% [result, startTime, endTime] = PSOforSVM(nFeatures, trainingData, ...
% testingData, PSOSettings)
%
% Input:
% *) nFeatures - total number of features to be selected
% *) trainingData - training data (Matrix size: total samples X nFeatures)
% *) testingData - testing data (Matrix size: total samples X nFeatures)
% *) PSOSettings - struct contains PSO parameters, examples:
% PSOSettings.MAX_ITERATION = MAX_ITERATION;
% PSOSettings.nParticles = 20;
% PSOSettings.W = 0.6;
% PSOSettings.c1 = 1.2;
% PSOSettings.c2 = 1.2;
% PSOSettings.Wa = 0.95;
% PSOSettings.Wf = 0.05;
%
% Output:
% *) result - struct contains records of PSO SVM result
% *) startTime - time when the experiment starts
% *) endTime - time when the experiment ends
startTime = clock;
%% PSO PARAMETER PREPARATION
populationPosition = rand(PSOSettings.nParticles, nFeatures) > 0.5;
for i=1:PSOSettings.nParticles
while sum(populationPosition(i, 1:nFeatures)) == 0
populationPosition(i, :) = rand(1, nFeatures) > 0.5;
end
end
populationVelocity = int64(zeros(PSOSettings.nParticles, 1)); % in decimal value
% pBest
pBest(PSOSettings.nParticles).position = [];
pBest(PSOSettings.nParticles).fitness = [];
pBest(PSOSettings.nParticles).trainingAccuracy = [];
pBest(PSOSettings.nParticles).testingAccuracy = [];
for i=1:PSOSettings.nParticles
pBest(i).position = false(1, nFeatures);
% max fitness value
pBest(i).fitness = repmat(-1000000, PSOSettings.nParticles, 1);
pBest(i).trainingAccuracy = 0;
pBest(i).testingAccuracy = 0;
end
% gBest
gBest.position = false(1, nFeatures);
gBest.fitness = -1000000; % max fitness value all particle all iteration
gBest.trainingAccuracy = [];
gBest.testingAccuracy = [];
gBest.fromIteration = [];
gBest.fromParticle = [];
% initialize struct data
result(PSOSettings.MAX_ITERATION+1).iteration = [];
result(PSOSettings.MAX_ITERATION+1).populationPosition = [];
result(PSOSettings.MAX_ITERATION+1).pBest = [];
result(PSOSettings.MAX_ITERATION+1).time = [];
result(PSOSettings.MAX_ITERATION+1).trainingAccuracy = [];
result(PSOSettings.MAX_ITERATION+1).testingAccuracy = [];
result(PSOSettings.MAX_ITERATION+1).gBest = [];
% END OF PSO PARAMETER PREPARATION
%% INITIALIZATION STEP
%fitness function evaluation
[trainAccArr, testAccArr, timeArr, populationFitness, pBest] = ...
evaluatefitness(PSOSettings, nFeatures, trainingData, testingData, ...
populationPosition, pBest);
gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, populationFitness, ...
populationPosition, gBest, 0);
% save initial data
result(1).iteration = 0;
result(1).populationPosition = populationPosition;
result(1).pBest = pBest;
result(1).time = timeArr;
result(1).trainingAccuracy = trainAccArr;
result(1).testingAccuracy = testAccArr;
result(1).gBest = gBest;
% END OF INITIALIZATION STEP
%% PSO ITERATION
for iteration=1:PSOSettings.MAX_ITERATION
% Update Velocity
r1 = rand();
r2 = rand();
for i=1:PSOSettings.nParticles
% calculate velocity value
positionDec = int64(bintodec(populationPosition(i, :)));
populationVelocity(i, 1) = PSOSettings.W * populationVelocity(i, 1) + ...
PSOSettings.c1 * r1 * (bintodec(pBest(i).position) - positionDec) ...
+ PSOSettings.c2 * r2 * (bintodec(gBest.position) - positionDec);
% update particle position
newPosDec = abs(int64(positionDec + populationVelocity(i, 1)));
newPosBin = dectobin(newPosDec);
% if the total bits is lower than nFeatures, add zeros in front
if size(newPosBin, 2) < nFeatures
newPosBin = [zeros(1, (nFeatures)-size(newPosBin, 2)) newPosBin];
end
% if the total bits is higher than nFeatures, get first nFeatures
if size(newPosBin, 2) > nFeatures
newPosBin = newPosBin(1, 1:nFeatures);
end
% if the number of selected features is 0
while sum(newPosBin(1, 1:nFeatures)) == 0
newPosBin(1, 1:nFeatures) = rand(1, nFeatures) > 0.5;
end
% set the new value of position
populationPosition(i, :) = newPosBin;
end
% fitness function evaluation
[trainAccArr, testAccArr, timeArr, populationFitness, pBest] = ...
evaluatefitness(PSOSettings, nFeatures, trainingData, testingData, ...
populationPosition, pBest);
gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, ...
populationFitness, populationPosition, gBest, iteration+1);
% save data
result(iteration+1).iteration = iteration;
result(iteration+1).populationPosition = populationPosition;
result(iteration+1).pBest = pBest;
result(iteration+1).time = timeArr;
result(iteration+1).trainingAccuracy = trainAccArr;
result(iteration+1).testingAccuracy = testAccArr;
result(iteration+1).gBest = gBest;
end
% END OF PSO ITERATION
endTime = clock;
end
function [trainAccArr, testAccArr, timeArr, populationFitness, pBest] = ...
evaluatefitness(PSOSettings, nFeatures, trainingData, testingData, ...
populationPosition, pBest)
trainAccArr = zeros(PSOSettings.nParticles, 1);
testAccArr = zeros(PSOSettings.nParticles, 1);
timeArr = zeros(PSOSettings.nParticles, 1);
populationFitness = zeros(PSOSettings.nParticles, 1);
for i=1:PSOSettings.nParticles
tic;
% TRAINING
maskedTrainingFeature = featuremasking(trainingData, ...
populationPosition(i, 1:nFeatures)); % remove unselected features
Model = trainSVM(maskedTrainingFeature, trainingData(:,end), 'RBF');
trainAcc = testSVM(maskedTrainingFeature, trainingData(:,end), Model);
% TESTING
maskedTestingFeature = featuremasking(testingData, ...
populationPosition(i, 1:nFeatures)); % remove unselected features
testAcc = testSVM(maskedTestingFeature, testingData(:,end), Model);
populationFitness(i, 1) = fitness(PSOSettings.Wa, PSOSettings.Wf, ...
testAcc, populationPosition(i, 1:nFeatures));
% pBest update
ischanged = 0;
if populationFitness(i, 1) > pBest(i).fitness
ischanged = 1;
elseif populationFitness(i, 1) == pBest(i).fitness
if pBest(i).testingAccuracy < testAcc
ischanged = 1;
elseif pBest(i).trainingAccuracy < trainAcc
ischanged = 1;
elseif sum(pBest(i).position(1, 1:nFeatures)) > ...
sum(populationPosition(i, 1:nFeatures))
ischanged = 1;
end
end
if ischanged
pBest(i).fitness = populationFitness(i, 1);
pBest(i).position = populationPosition(i, :);
pBest(i).trainingAccuracy = trainAcc;
pBest(i).testingAccuracy = testAcc;
end
% end of pBest update
timeArr(i) = toc;
trainAccArr(i) = trainAcc;
testAccArr(i) = testAcc;
end
end
function gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, ...
populationFitness, populationPosition, gBest, iteration)
if max(populationFitness) >= gBest.fitness
found = find(populationFitness == max(populationFitness));
if length(found) > 1
% if have the same gBest fitness value, get the max of testAcc
found = found(testAccArr(found) == max(testAccArr(found)));
if length(found) > 1
% if have the same testAcc, get the max of trainAcc
found = found(trainAccArr(found) == max(trainAccArr(found)));
if length(found) > 1
% if have the same trainAcc, get the min of selected features
found = ...
found(sum(populationPosition(found, 1:nFeatures), 2) ...
== min(sum(populationPosition(found, 1:nFeatures), 2)));
if length(found) > 1
% if have the same selected feature, get the first
found = found(1);
end
end
end
end
gBest.fitness = populationFitness(found);
gBest.position = populationPosition(found, :);
gBest.trainingAccuracy = trainAccArr(found);
gBest.testingAccuracy = testAccArr(found);
gBest.fromIteration = iteration;
gBest.fromParticle = found;
end
end
|
github
|
fennialesmana/sleep-stage-identification-master
|
PSOforELM.m
|
.m
|
sleep-stage-identification-master/PSOforELM.m
| 10,611 |
utf_8
|
204d568999568aafa1e6b26495535184
|
function [result, startTime, endTime] = PSOforELM(nFeatures, trainingData, ...
testingData, PSOSettings)
%Running PSO with ELM for feature selection and number of hidden nodes
%optimization
% Syntax:
% [result, startTime, endTime] = PSOforELM(nFeatures, trainingData, ...
% testingData, PSOSettings)
%
% Input:
% *) nFeatures - total number of features to be selected
% *) trainingData - training data (Matrix size: total samples X nFeatures)
% *) testingData - testing data (Matrix size: total samples X nFeatures)
% *) PSOSettings - struct contains PSO parameters, examples:
% PSOSettings.MAX_ITERATION = MAX_ITERATION;
% PSOSettings.nParticles = 20;
% PSOSettings.W = 0.6;
% PSOSettings.c1 = 1.2;
% PSOSettings.c2 = 1.2;
% PSOSettings.Wa = 0.95;
% PSOSettings.Wf = 0.05;
%
% Output:
% *) result - struct contains records of PSO ELM result
% *) startTime - time when the experiment starts
% *) endTime - time when the experiment ends
startTime = clock;
%% PSO PARAMETER PREPARATION
% max total bits for hidden nodes
nHiddenBits = length(dectobin(size(trainingData, 1)));
populationPosition = rand(PSOSettings.nParticles, nFeatures+nHiddenBits) > 0.5;
for i=1:PSOSettings.nParticles
while bintodec(populationPosition(i, nFeatures+1:end)) < nFeatures || ...
bintodec(populationPosition(i, nFeatures+1:end)) > ...
size(trainingData, 1) || sum(populationPosition(i, 1:nFeatures)) == 0
populationPosition(i, :) = rand(1, nFeatures+nHiddenBits) > 0.5;
end
end
populationVelocity = int64(zeros(PSOSettings.nParticles, 1)); % in decimal value
% pBest
pBest(PSOSettings.nParticles).position = [];
pBest(PSOSettings.nParticles).fitness = [];
pBest(PSOSettings.nParticles).trainingAccuracy = [];
pBest(PSOSettings.nParticles).testingAccuracy = [];
for i=1:PSOSettings.nParticles
pBest(i).position = false(1, nFeatures+nHiddenBits);
% max fitness value
pBest(i).fitness = repmat(-1000000, PSOSettings.nParticles, 1);
pBest(i).trainingAccuracy = 0;
pBest(i).testingAccuracy = 0;
end
% gBest
gBest.position = false(1, nFeatures+nHiddenBits);
gBest.fitness = -1000000; % max fitness value all particle all iteration
gBest.trainingAccuracy = [];
gBest.testingAccuracy = [];
gBest.fromIteration = [];
gBest.fromParticle = [];
% initialize struct data
result(PSOSettings.MAX_ITERATION+1).iteration = [];
result(PSOSettings.MAX_ITERATION+1).populationPosition = [];
result(PSOSettings.MAX_ITERATION+1).pBest = [];
result(PSOSettings.MAX_ITERATION+1).time = [];
result(PSOSettings.MAX_ITERATION+1).trainingAccuracy = [];
result(PSOSettings.MAX_ITERATION+1).testingAccuracy = [];
result(PSOSettings.MAX_ITERATION+1).model = [];
result(PSOSettings.MAX_ITERATION+1).gBest = [];
% END OF PSO PARAMETER PREPARATION
%% INITIALIZATION STEP
%fitness function evaluation
[modelArr, trainAccArr, testAccArr, timeArr, populationFitness, pBest] = ...
evaluatefitness(PSOSettings, nFeatures, trainingData, testingData, ...
populationPosition, pBest);
gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, populationFitness, ...
populationPosition, gBest, 0);
% save initial data
result(1).iteration = 0;
result(1).populationPosition = populationPosition;
result(1).pBest = pBest;
result(1).time = timeArr;
result(1).trainingAccuracy = trainAccArr;
result(1).testingAccuracy = testAccArr;
%result(1).model = modelArr;
result(1).gBest = gBest;
% END OF INITIALIZATION STEP
%% PSO ITERATION
for iteration=1:PSOSettings.MAX_ITERATION
% Update Velocity
r1 = rand();
r2 = rand();
for i=1:PSOSettings.nParticles
% calculate velocity value
positionDec = int64(bintodec(populationPosition(i, :)));
populationVelocity(i, 1) = PSOSettings.W * populationVelocity(i, 1) + ...
PSOSettings.c1 * r1 * (bintodec(pBest(i).position) - positionDec) ...
+ PSOSettings.c2 * r2 * (bintodec(gBest.position) - positionDec);
% update particle position
newPosDec = abs(int64(positionDec + populationVelocity(i, 1)));
newPosBin = dectobin(newPosDec);
% if the total bits is lower than nFeatures + nHiddenBits,
% add zeros in front
if size(newPosBin, 2) < (nFeatures + nHiddenBits)
newPosBin = ...
[zeros(1, (nFeatures + nHiddenBits) - size(newPosBin, 2)) ...
newPosBin];
end
% if the number of hidden node is more than the number of samples
if bintodec(newPosBin(1, nFeatures+1:end)) > size(trainingData, 1) ...
|| size(newPosBin(1, nFeatures+1:end), 2) > nHiddenBits
newPosBin = ...
[newPosBin(1, 1:nFeatures) dectobin(size(trainingData, 1))];
end
% if the number of selected features is 0
while sum(newPosBin(1, 1:nFeatures)) == 0
newPosBin(1, 1:nFeatures) = rand(1, nFeatures) > 0.5;
end
% set the new value of position
populationPosition(i, :) = newPosBin;
end
% fitness function evaluation
[modelArr, trainAccArr, testAccArr, timeArr, populationFitness, pBest] = ...
evaluatefitness(PSOSettings, nFeatures, trainingData, testingData, ...
populationPosition, pBest);
gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, ...
populationFitness, populationPosition, gBest, iteration+1);
% save data
result(iteration+1).iteration = iteration;
result(iteration+1).populationPosition = populationPosition;
result(iteration+1).pBest = pBest;
result(iteration+1).time = timeArr;
result(iteration+1).trainingAccuracy = trainAccArr;
result(iteration+1).testingAccuracy = testAccArr;
%result(iteration+1).model = modelArr;
result(iteration+1).gBest = gBest;
end
% END OF PSO ITERATION
endTime = clock;
end
function [modelArr, trainAccArr, testAccArr, timeArr, populationFitness, ...
pBest] = evaluatefitness(PSOSettings, nFeatures, trainingData, ...
testingData, populationPosition, pBest)
modelArr(PSOSettings.nParticles).inputWeight = []; % ELM Specific
modelArr(PSOSettings.nParticles).outputWeight = []; % ELM Specific
trainAccArr = zeros(PSOSettings.nParticles, 1);
testAccArr = zeros(PSOSettings.nParticles, 1);
timeArr = zeros(PSOSettings.nParticles, 1);
populationFitness = zeros(PSOSettings.nParticles, 1);
for i=1:PSOSettings.nParticles
tic;
% TRAINING
maskedTrainingFeature = featuremasking(trainingData, ...
populationPosition(i, 1:nFeatures)); % remove unselected features
% prepare the target data
% (example: transformation from 4 into [0 0 0 1 0 0])
trainingTarget = full(ind2vec(trainingData(:,end)'))';
[Model, trainAcc] = trainELM(maskedTrainingFeature, trainingTarget, ...
bintodec(populationPosition(i, nFeatures+1:end)));
% TESTING
maskedTestingFeature = featuremasking(testingData, ...
populationPosition(i, 1:nFeatures)); % remove unselected features
% prepare the target data
% (example: transformation from 4 into [0 0 0 1 0 0])
testingTarget = full(ind2vec(testingData(:,end)'))';
testAcc = testELM(maskedTestingFeature, testingTarget, Model);
populationFitness(i, 1) = fitness(PSOSettings.Wa, PSOSettings.Wf, ...
testAcc, populationPosition(i, 1:nFeatures));
% pBest update
ischanged = 0;
if populationFitness(i, 1) > pBest(i).fitness
ischanged = 1;
elseif populationFitness(i, 1) == pBest(i).fitness
if pBest(i).testingAccuracy < testAcc
ischanged = 1;
elseif pBest(i).trainingAccuracy < trainAcc
ischanged = 1;
elseif sum(pBest(i).position(1, 1:nFeatures)) > ...
sum(populationPosition(i, 1:nFeatures))
ischanged = 1;
elseif bintodec(pBest(i).position(1, nFeatures+1:end)) > ...
bintodec(populationPosition(i, nFeatures+1:end))
ischanged = 1;
end
end
if ischanged
pBest(i).fitness = populationFitness(i, 1);
pBest(i).position = populationPosition(i, :);
pBest(i).trainingAccuracy = trainAcc;
pBest(i).testingAccuracy = testAcc;
end
% end of pBest update
modelArr(i) = Model;
timeArr(i) = toc;
trainAccArr(i) = trainAcc;
testAccArr(i) = testAcc;
end
end
function gBest = gbestupdate(nFeatures, trainAccArr, testAccArr, ...
populationFitness, populationPosition, gBest, iteration)
if max(populationFitness) >= gBest.fitness
found = find(populationFitness == max(populationFitness));
if length(found) > 1
% if have the same gBest fitness value, get the max of testAcc
found = found(testAccArr(found) == max(testAccArr(found)));
if length(found) > 1
% if have the same testAcc, get the max of trainAcc
found = found(trainAccArr(found) == max(trainAccArr(found)));
if length(found) > 1
% if have the same trainAcc, get the min of selected features
found = ...
found(sum(populationPosition(found, 1:nFeatures), 2) ...
== min(sum(populationPosition(found, 1:nFeatures), 2)));
if length(found) > 1
% if have the same selected feature,
% get the min of hidden node
hn = zeros(length(found), 1);
for i=1:length(found)
hn(i, 1) = bintodec(populationPosition(found(i), ...
nFeatures+1:end));
end
found = found(hn == min(hn));
if length(found) > 1
found = found(1);
end
end
end
end
end
gBest.fitness = populationFitness(found);
gBest.position = populationPosition(found, :);
gBest.trainingAccuracy = trainAccArr(found);
gBest.testingAccuracy = testAccArr(found);
gBest.fromIteration = iteration;
gBest.fromParticle = found;
end
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/TWSVM/kfold_eval.m
| 4,734 |
utf_8
|
c1ec58774ff997676fa8879f8fcaf986
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\twsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =TWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =TWSVM(test,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/TWSVM/seperate_eval.m
| 4,663 |
utf_8
|
e28eab0313e4b288c9b4fdafd338b3e9
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\twsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =TWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =TWSVM(test,DataTrain,OptPara);
test_acc = length(find(Predict_Y==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/TBSVM/kfold_eval.m
| 5,080 |
utf_8
|
aa320b87a76fbacccd0746456baeb945
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\TWSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =TWSVM(testX,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
Predict_Y =TWSVM(testX,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/TBSVM/seperate_eval.m
| 5,095 |
utf_8
|
f619d250ebb42830f697d2dcfa3a232e
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\TWSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =TWSVM(testX,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and valuation with optimal parameter value
clear DataTrain;
DataTrain.A = dataX(dataY==1,:);
DataTrain.B = dataX(dataY==-1,:);
% DataTrain.A = [trainX(trainY==1,:);testX(testY==1,:)];
% DataTrain.B = [trainX(trainY==-1,:);testX(testY==-1,:)];
Predict_Y =TWSVM(test_data,DataTrain,OptPara);
test_acc = length(find(Predict_Y==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/WLTSVM/kfold_eval.m
| 4,880 |
utf_8
|
c32281432da1d1f5d5e5753ed9ce2b78
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\wltsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =WLTSVM(testX,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
Predict_Y =WLTSVM(testX,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/WLTSVM/seperate_eval.m
| 4,895 |
utf_8
|
9ef1248fb63e1bc397f500ec87441620
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\wltsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
DataTrain.A = trainX(trainY==1,:);
DataTrain.B = trainX(trainY==-1,:);
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =WLTSVM(testX,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and valuation with optimal parameter value
clear DataTrain;
DataTrain.A = dataX(dataY==1,:);
DataTrain.B = dataX(dataY==-1,:);
% DataTrain.A = [trainX(trainY==1,:);testX(testY==1,:)];
% DataTrain.B = [trainX(trainY==-1,:);testX(testY==-1,:)];
Predict_Y =WLTSVM(test_data,DataTrain,OptPara);
test_acc = length(find(Predict_Y==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/PinTSVM/kfold_eval.m
| 5,592 |
utf_8
|
9b8af63cdf93adf1d233c2530c9b31f5
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\pintsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
disp('Data belongs to multi-class, please provide binary class data');
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
% c1 = [10^-5,10^-4,10^-3,10^-2,10^-1,10^0,10^1,10^2,10^3,10^4,10^5];
% c2 = [10^-5,10^-4,10^-3,10^-2,10^-1,10^0,10^1,10^2,10^3,10^4,10^5];
c1 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
c2 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
v1 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
v2 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
t1 = [0.05,0.1,0.2,0.5,1];
t2 = [0.05,0.1,0.2,0.5,1];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for v=1:length(v1)
for t=1:length(t1)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.v1=v1(v);
FunPara.v2=v1(v);
FunPara.t1=t1(t);
FunPara.t2=t1(t);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =pinTSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.v1=FunPara.v1; OptPara.v2=FunPara.v2;
OptPara.t1=FunPara.t1; OptPara.t2=FunPara.t2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =pinTSVM(test,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y'==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
rmpath('F:\Chandan\Tanveer_Sir\Suganthan\JMLR_2014\PinTSVM\pintsvm');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/PinTSVM/seperate_eval.m
| 5,545 |
utf_8
|
85a4067f1bff841c4aa5569a64d701cb
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\pintsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
% c1 = [10^-5,10^-4,10^-3,10^-2,10^-1,10^0,10^1,10^2,10^3,10^4,10^5];
% c2 = [10^-5,10^-4,10^-3,10^-2,10^-1,10^0,10^1,10^2,10^3,10^4,10^5];
c1 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
c2 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
v1 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
v2 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7];
t1 = [0.05,0.1,0.2,0.5,1];
t2 = [0.05,0.1,0.2,0.5,1];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
% c5 = [2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for v=1:length(v1)
for t=1:length(t1)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.v1=v1(v);
FunPara.v2=v1(v);
FunPara.t1=t1(t);
FunPara.t2=t1(t);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =pinTSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.v1=FunPara.v1; OptPara.v2=FunPara.v2;
OptPara.t1=FunPara.t1; OptPara.t2=FunPara.t2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =pinTSVM(test,DataTrain,OptPara);
test_acc = length(find(Predict_Y'==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
rmpath('F:\Chandan\Tanveer_Sir\Suganthan\JMLR_2014\PinTSVM\pintsvm');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
scale_range_rbf.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/PinTSVM/scale_range_rbf.m
| 1,009 |
utf_8
|
80c8fa1d98467244e1fe73d77c0bcf00
|
%SCALE_RANGE Give a vector of scales
%
% SIG = SCALE_RANGE(X,NR,NMAX)
%
% INPUT
% X Data matrix or dataset
% NR Number of scales (default = 20)
% NMAX Number of (random) points to consider (default = 500)
%
% OUTPUT
% SIG Vector of scale values
%
% DESCRIPTION
% Give a reasonable range of scales SIG for the dataset X. The largest
% scale is given first. If NR is given, the number of scales is NR.
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function sig = scale_range_rbf(x,nr,Nmax)
if nargin<3
Nmax = 500;
end
if nargin<2
nr = 20;
end
% Compute the distances
d = sqrt(sqeucldistm(x,x));
% Find the largest and the smallest distance:
dmax = max(d(:));
d(d<=1e-12) = dmax;
dmin = min(d(:));
% ... and compute the range:
%log10 = log(10);
%sig = logspace(log(dmax)/log10,log(dmin)/log10,nr);
sig = linspace(dmax,dmin,nr);
return
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LSTWSVM/kfold_eval.m
| 4,742 |
utf_8
|
24f7c3407eb23e045e11c43c07bd31ee
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\lstwsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =LSTWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =LSTWSVM(test,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y'==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LSTWSVM/seperate_eval.m
| 4,671 |
utf_8
|
7ee0c2b90c2bb1083404d2a41a220ac1
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\lstwsvm']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =LSTWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =LSTWSVM(test,DataTrain,OptPara);
test_acc = length(find(Predict_Y'==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/RELS_TWSVM/kfold_eval.m
| 5,896 |
utf_8
|
b0c426cfc81535deb2d09cacc1343c1c
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\rels_TWSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
c6 = [0.5,0.6,0.7,0.8,0.9,1.0]; %%% Energy1
c7 = [0.5,0.6,0.7,0.8,0.9,1.0]; %%% Energy2
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
for n=1:length(c6)
% for o=1:length(c7)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Energy.E1=c6(n);
% Energy.E2=c7(o);
Energy.E2=c6(n);
Predict_Y =PROP_ELS_TWSVM(test,DataTrain,FunPara,Energy);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
OptEPara.E1=Energy.E1;OptEPara.E2=Energy.E2;
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
% end
end
% end
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =PROP_ELS_TWSVM(test,DataTrain,OptPara,OptEPara);
test_acc(f)=length(find(Predict_Y'==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara','OptEPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/RELS_TWSVM/seperate_eval.m
| 5,818 |
utf_8
|
087b68883003601402d424fc77ed16f9
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\rels_TWSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
%c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
%c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
c6 = [0.5,0.6,0.7,0.8,0.9,1.0]; %%% Energy1
c7 = [0.5,0.6,0.7,0.8,0.9,1.0]; %%% Energy2
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
for n=1:length(c6)
% for o=1:length(c7)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Energy.E1=c6(n);
% Energy.E2=c7(o);
Energy.E2=c6(n);
Predict_Y =PROP_ELS_TWSVM(test,DataTrain,FunPara,Energy);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
OptEPara.E1=Energy.E1;OptEPara.E2=Energy.E2;
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
% end
end
% end
end
% end
end
%%%% Training and valuation with optimal parameter value
clear DataTrain test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =PROP_ELS_TWSVM(test,DataTrain,OptPara,OptEPara);
test_acc = length(find(Predict_Y'==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara','OptEPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LPP_TSVM/kfold_eval.m
| 4,767 |
utf_8
|
8516e828d53b5cf7372b23a490c1c0e5
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\lppTSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
disp('Data belongs to multi-class, please provide binary class data');
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
try
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10]; %%% mu or sigma of RBF
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
c=c1(i);
kern_para = c5(m);
Predict_Y =lpp_TSVM(DataTrain,test,kern_para,c);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c=c;
OptPara.kernPara = kern_para;
OptPara.kerntype = 'rbf';
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =lpp_TSVM(DataTrain,test,OptPara.kernPara,OptPara.c);
test_acc(f)=length(find(Predict_Y==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
catch
disp('error in the code');
keyboard
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.