text:
clear; close all;

d = 100;
beta = 1e-1;
X = rand(1,d);
w = randn;
b = randn;
t = w'*X+b+beta*randn(1,d);
x = linspace(min(X),max(X),d);   % test data

[model,llh] = linRegVb(X,t);
% [model,llh] = rvmRegVb(X,t);
plot(llh);
[y, sigma] = linRegPred(model,x,t);
figure
plotCurveBar(x,y,sigma);
hold on;
plot(X,t,'o');
hold off

author: PRML

repo: PRMLT

save_path: github-repos/MATLAB/PRML-PRMLT


text:
function SeamVector=removalMap(X,lines);
% REMOVALMAP takes a given image and finds the ordered set of (vertical)
% seams that are removed from an image and returns them in an array, where
% the Nth column in the array corresponds to the Nth seam to be removed.
%
% Author: Danny Luong
%         http://danluong.com
%
% Last updated: 12/20/07

[rows cols dim]=size(X);

E=findEnergy(X);    %Finds the gradient image

for i=1:min(lines,cols-1)

    %find "energy map" image used for seam calculation given the gradient image
    S=findSeamImg(E);

    %find seam vector given input "energy map" seam calculation image
    SeamVector(:,i)=findSeam(S);

    %remove seam from image
    X=SeamCut(X,SeamVector(:,i));
    E=SeamCut(E,SeamVector(:,i));

    %updates size of image
    [rows cols dim]=size(X);
end

author: Sable

repo: mcbench-benchmarks


text:
function [parameters,ll,Ht,VCV,scores] = gogarch(data,p,q,gjrType,type,startingVals,options)
% OGARCH(p,q) and GOGARCH(p,q) multivarate volatility model estimation
%
% USAGE:
%  [PARAMETERS] = rarch(DATA,P,Q)
%  [PARAMETERS,LL,HT,VCV,SCORES] = gogarch(DATA,P,Q,GJRTYPE,TYPE,STARTINGVALS,OPTIONS)
%
% INPUTS:
%   DATA         - A T by K matrix of zero mean residuals -OR-
%                    K by K by T array of covariance estimators (e.g. realized covariance)
%   P            - Positive, scalar integer representing the number of symmetric innovations. Can
%                    also be a K by 1 vector with lag lengths for each series.
%   Q            - Non-negative, scalar integer representing the number of conditional covariance
%                    lags Can also be a K by 1 vector with lag lengths for each series.
 %  GJRTYPE      - [OPTIONAL] Either 1 (TARCH/AVGARCH) or 2 (GJR-GARCH/GARCH/ARCH).  Can also be a K
%                    by 1 vector containing the model type for each for each series. Default is 2.
%   TYPE         - [OPTIONAL] String, one of 'GOGARCH' (Default) or 'OGARCH'
%   STARTINGVALS - [OPTIONAL] Vector of starting values to use.  See parameters and COMMENTS.
%   OPTIONS      - [OPTIONAL] Options to use in the model optimization (fmincon)
%
% OUTPUTS:
%   PARAMETERS   - Estimated parameters in the order:
%                    OGARCH:
%                    [vol(1) ... vol(K)]
%                    GOGARCH:
%                    [phi(1) ... phi(K(K-1)/2) vol(1) ... vol(K)]
%                    where vol(i) = [alpha(i,1) ... alpha(i,P(i)) beta(i,1) ... beta(i,Q(i))]
%   LL           - The log likelihood at the optimum
%   HT           - A [K K T] dimension matrix of conditional covariances
%   VCV          - A numParams^2 square matrix of robust parameter covariances (A^(-1)*B*A^(-1)/T)
%   SCORES       - A T by numParams matrix of individual scores
%
% COMMENTS:
%   The orthonormal matrix is constructed from K(K-1)/2 angles using PHI2U
%
%
% EXAMPLES:
%   % OGARCH(1,1)
%   parameters = gogarch(data,1,1,[],'OGARCH')
%   % GOGARCH(1,1)
%   parameters = gogarch(data,1,1)
%
% See also BEKK, RARCH, DCC, TARCH, PHI2U

% Copyright: Kevin Sheppard
% kevin.sheppard@economics.ox.ac.uk
% Revision: 1    Date: 4/15/2012

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input Argument Checking
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch nargin
    case 3
        gjrType = [];
        type = [];
        startingVals = [];
        options = [];
    case 4
        type = [];
        startingVals = [];
        options = [];
    case 5
        startingVals = [];
        options = [];
    case 6
        options = [];
    case 7
        % Nothing
    otherwise
        error('3 to 7 inputs required.')
end

if ndims(data)==3
    [k,~,T] = size(data);
else
    [T,k] = size(data);
    temp = zeros(k,k,T);
    for t=1:T
        temp(:,:,t) = data(t,:)'*data(t,:);
    end
    data = temp;
end

if isscalar(p)
    p = ones(k,1)*p;
end
if isscalar(q)
    q = ones(k,1)*q;
end

if isempty(gjrType)
    gjrType = 2;
end
if isscalar(gjrType)
    gjrType = ones(k,1)*gjrType;
end

if isempty(type)
    type = 'gogarch';
end
type = lower(type);
if ~ismember(type,{'gogarch','ogarch'})
    error('TYPE must be either ''GoGARCH'' or ''OGARCH''');
end
if strcmpi(type,'gogarch')
    isGogarch = true;
else
    isGogarch = false;
end

if ~isempty(startingVals)
    count = sum(p) + sum(q);
    if isGogarch
        count = count + k*(k-1)/2;
    end
    if length(startingVals)~=count
        error('STARTINGVALS does not have the correct number of parameters.')
    end
    if isGogarch
        if any(startingVals(1:k*(k-1)/2))>pi || any(startingVals(1:k*(k-1)/2))<0
            error('STARTGINVALS 1 to K*(K-1)/2 must be between 0 and 3.141592')
        end
    end
end

if isempty(options)
    options = optimset('fmincon');
    options.Display = 'iter';
    options.Diagnostics = 'on';
    options.Algorithm = 'sqp';
else
    try
        optimset(options);
    catch ME
        error('OPTIONS does not appear to be a valid options structure.')
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Preliminary Estimation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
S = mean(data,3);
[P,L] = eig(S);
P = P';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Starting Values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isempty(startingVals)
    startingOptions  =  optimset('fminunc');
    startingOptions.TolFun = 1e-005;
    startingOptions.TolX = 1e-005;
    startingOptions.Display = 'none';
    startingOptions.LargeScale ='off';
    startingOptions.MaxFunEvals = 400*(max(p)+max(q));

    Zinv = L^(-0.5)*P';
    stdData = zeros(k,k,T);
    for t=1:T
        stdData(:,:,t) = Zinv*data(:,:,t)*Zinv';
    end
    volParams = cell(k,1);
    V = zeros(T,k);
    for i=1:k
        volData = sqrt(squeeze(stdData(i,i,:)));
        [temp,~,V(:,i)] = tarch(volData,p(i),0,q(i),[],gjrType(i),[],startingOptions);
        volParams{i} = temp(2:(1+p(i)+q(i)));
    end
    if isGogarch
        startingVals = zeros(1,k*(k-1)/2)+.0001;
    end
    for i=1:k
        startingVals = [startingVals volParams{i}']; %#ok<AGROW>
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OGARCH
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
w = .06*.94.^(0:sqrt(T));
w = w/sum(w);
if isGogarch
    offset = k*(k-1)/2;
else
    offset = 0;
end
parameters = startingVals;
ogarchOptions = optimset('fmincon');
if isGogarch
    ogarchOptions.Display = 'off';
else
    ogarchOptions.Display = 'iter';
end
ogarchOptions.Algorithm = 'sqp';
for i=1:k
    if gjrType==1
        backCast = w*abs(volData(1:length(w)));
    else
        backCast = w*(volData(1:length(w))).^2;
    end
    count = p(i) + q(i);
    LB = zeros(count,1);
    UB = LB + 1;
    A = ones(1,count);
    b = 1;
    volStart = parameters(offset + (1:count));
    volData = sqrt(squeeze(stdData(i,i,:)));
    parameters(offset + (1:count)) = fmincon(@ogarch_likelihood,volStart,A,b,[],[],LB,UB,[],ogarchOptions,volData,p(i),q(i),gjrType(i),backCast);
    offset = offset + count;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GOGARCH
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isGogarch
    v = length(startingVals);
    LB = zeros(1,v);
    UB = LB + 1;
    LB(1:(k*(k-1)/2)) = 1e-6;
    UB(1:(k*(k-1)/2)) = .99998*pi;
    A = zeros(k,v);
    b = .99998*ones(1,k);
    offset = k*(k-1)/2;
    for i=1:k
        count = p(i)+q(i);
        Ai = ones(1,count);
        A(i,offset + (1:count)) = Ai;
        offset = offset + count;
    end
    parameters = fmincon(@gogarch_likelihood,startingVals,A,b,[],[],LB,UB,[],options,data,p,q,gjrType,P,L,false,false);
    [ll,~,Ht] = gogarch_likelihood(parameters,data,p,q,gjrType,P,L,false,false);
else
    [ll,~,Ht] = gogarch_likelihood(parameters,data,p,q,gjrType,P,L,true,false);
end
ll = -ll;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Inference
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
k2 = k*(k+1)/2;
v = k2+length(parameters);
scores = zeros(T,v);
count = 1;
for j=1:k
    for i=j:k
        scores(:,count) = squeeze(data(i,j,:) - S(i,j));
        count = count + 1;
    end
end
[~,s] = gradient_2sided(@gogarch_likelihood,parameters',data,p,q,gjrType,P,L,~isGogarch,false);
scores(:,k2+1:v) = s;
B = covnw(scores,ceil(1.2*T^(1/3)));
A = zeros(v);
A(1:k2,1:k2) = -eye(k2);
m = length(parameters);
parameters = [vech(S)' parameters]';
temp = hessian_2sided_nrows(@gogarch_likelihood,parameters,m,data,p,q,gjrType,P,L,~isGogarch,true);
A((k2+1):v,:) = temp/T;
Ainv = A\eye(v);
VCV = Ainv*B*Ainv'/T;

author: bashtage

repo: mfe-toolbox


text:
function varargout = xexpintinv(varargin)
%XEXPINTINV EXPINT(1/Z)/Z

switch class(varargin{1})

    case 'double'
        z = varargin{1};
        varargout{1} = (1./z).*expint(1./z);

    case 'sdpvar'
        varargout{1} = InstantiateElementWise(mfilename,varargin{:});

    case 'char'

        operator = CreateBasicOperator('positive','callback');
        operator.derivative = @derivative;
        operator.range = [0 1];
        operator.domain = [0 inf];

        varargout{1} = [];
        varargout{2} = operator;
        varargout{3} = varargin{3};

    otherwise
        error([upper(mfilename) ' called with weird argument']);
end

function d = derivative(z);
d = (-1./z.^2).*expint(1./z)+(1./z).*(-z.*exp(-1./z)).*(-1./z.^2);

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
 function out = equivs(var1, var2, varargin)
%function out = equivs(var1, var2, command)
%|
%| verify that var1 and var2 are equivalent to within single precision accuracy
%| if not, print error message.  an alternative to isequal().
%| See also: jf_equal
%|
%| option
%|	'thresh'	threshold (default: 1e-6)
%|	'format'	format for displaying the two variables (default: '')
%|	'fail'	0|1	if 1 (default) then fail if not equivalent, else warn
%|
%| out
%|	out		0|1
%|
%| Copyright 2007, Jeff Fessler, University of Michigan

if nargin == 1 && streq(var1, 'test'), equivs_test, return, end
if nargin < 2, ir_usage, end

arg.thresh = 1e-6;
arg.format = '';
arg.fail = true;
arg = vararg_pair(arg, varargin);

if isempty(var1) && isempty(var2)
	ok = true;

elseif ~isequal(size(var1), size(var2))
	printm([': size(%s) = %s'], inputname(1), mat2str(size(var1)))
        printm([': size(%s) = %s'], inputname(2), mat2str(size(var2)))
	equivs_show(var1, var2, inputname(1), inputname(2), arg.format)
	if arg.fail
		fail('incompatible dimensions')
	else
		warn('incompatible dimensions')
		return
	end

else
	var1 = var1(:);
	var2 = var2(:);
	if any(isnan(var1)) || any(isnan(var2))
		if arg.fail
			fail('nan')
		else
			warn('nan')
			ok = false;
			return
		end
	end

	norm = (max(abs(var1)) + max(abs(var2))) / 2;
	if ~norm
		ok = true; % both zero!
	else
		err = max(abs(var1-var2)) / norm;
		ok = err < arg.thresh;
	end
end

if nargout
	out = ok;
end

if ok
	return
end

[name line] = caller_name;
if isempty(name)
	str = '';
else
	str = sprintf('%s %d:', name, line);
end

name1 = inputname(1);
name2 = inputname(2);
minmax(var1, ['equivs ' name1 ':'])
minmax(var2, ['equivs ' name2 ':'])
diff = var1 - var2;
if ~isreal(diff)
	diff = abs(diff);
end
minmax(diff)
printm([str ' normalized difference of %g between "%s" "%s"'], ...
	err, name1, name2);
if arg.fail
	fail('not equal to within single precision, thresh=%g', arg.thresh)
else
	warn('not equal to within single precision, thresh=%g', arg.thresh)
end

function equivs_show(var1, var2, name1, name2, format)
if isempty(format), return, end
disp(name1)
disp(num2str(var1, format))
disp(name2)
disp(num2str(var2, format))

function equivs_test
rng(0)
x = randn(1000,200);
y = dsingle(x);
equivs(x,y)

passed = 0;
try
	y = x + 2e-6 * max(x(:));
	equivs(x,y)
	passed = 1;
catch
end
if passed, error 'this should have failed!', end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function varargout = analyze_hsi(varargin)
% ANALYZE_HSI MATLAB code for analyze_hsi.fig
%      ANALYZE_HSI, by itself, creates a new ANALYZE_HSI or raises the existing
%      singleton*.
%
%      H = ANALYZE_HSI returns the handle to a new ANALYZE_HSI or the handle to
%      the existing singleton*.
%
%      ANALYZE_HSI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ANALYZE_HSI.M with the given input arguments.
%
%      ANALYZE_HSI('Property','Value',...) creates a new ANALYZE_HSI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before analyze_hsi_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to analyze_hsi_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 analyze_hsi

% Last Modified by GUIDE v2.5 24-Jan-2016 15:26:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @analyze_hsi_OpeningFcn, ...
                   'gui_OutputFcn',  @analyze_hsi_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 analyze_hsi is made visible.
function analyze_hsi_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 analyze_hsi (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes analyze_hsi wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% Doesn't help
% set(handles.uitoggletool_probe,'state','off');

dcm_obj = datacursormode;
set(dcm_obj,'UpdateFcn',{@my_data_cursor_updatefcn,hObject})

user_data = get(hObject,'UserData');
if ~isempty(user_data)
    load(user_data);
    set(hObject,'UserData',[]);
    handles = load_image(rgb,I,R_gt,A_gt,names,wl,I_gt,gt_colors,tick_labels,handles);
    guidata(hObject,handles);
end

function txt = my_data_cursor_updatefcn(~,event_obj,hObject)
% Customizes text of data tips
handles = guidata(hObject);
pos = get(event_obj,'Position');
ind = get(event_obj, 'DataIndex');
txt = num2str(pos);

% show spectra
spectra = squeeze(handles.I(pos(2),pos(1),:));
wl = handles.wl';
plot(handles.axes_spectra,wl,spectra);
ylim(handles.axes_spectra,[0 1]);

% show the other cursor
handles = delete_ui_handles(handles,'other_cursor');
hold(handles.axes_gt,'on');
other_cursor = plot(handles.axes_gt,pos(1),pos(2),'s','MarkerSize',5,...
    'MarkerFaceColor','w','MarkerEdgeColor','k','LineWidth',2);
hold(handles.axes_gt,'off');
handles.other_cursor = other_cursor;

% update status
set(handles.text_status, 'string', get_gt_name_by_position(handles,pos));

guidata(hObject, handles);

function gt_name = get_gt_name_by_position(handles, pos)
gt_vec = squeeze(handles.A_gt(pos(2),pos(1),:));
gt_name = strjoin(handles.gt_names(gt_vec==1),', ');

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

% --------------------------------------------------------------------
function pavia_Callback(hObject, eventdata, handles)
% hObject    handle to pavia (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[I,R_gt,A_gt,names,wl,rgb] = load_pavia_university([],0);
tick_labels = {'Asphalt','Meadows','Gravel','Trees','Metal',...
    'Soil','Bitumen','Bricks','Shadows'};
M = size(A_gt,3);
colors = distinguishable_colors(M);
I_gt = A_gt2I_gt(A_gt);

handles = load_image(rgb,I,R_gt,A_gt,names,wl,I_gt,colors,tick_labels,handles);
guidata(hObject,handles);

function handles = load_image(rgb,I,R_gt,A_gt,names,wl,I_gt,colors,tick_labels,handles)
% show rgb image and the ground truth
imshow(rgb,'parent',handles.axes_image);
show_gt_image(I_gt,colors,handles.axes_gt,tick_labels);
show_gt_spectra(R_gt,wl,colors,handles.axes_gt_spectra,tick_labels)

% load gt names into the listbox
display_names = [{'All'}, names];
set(handles.listbox_gt_names,'String',display_names,...
	'Value',1);
set(handles.popupmenu_change_gt,'String',names,'Value',1);

% save handles
handles.rgb = rgb;
handles.I = I;
handles.R_gt = R_gt;
handles.A_gt = A_gt;
handles.I_gt = I_gt;
handles.tick_labels = tick_labels;
handles.gt_colors = colors;
handles.gt_names = names;
handles.wl = wl;

function show_gt_image(I_gt,colors,axes_gt,tick_labels)
I_gt = uint8(I_gt);
colors = [1 1 1;colors];
M = length(tick_labels);
im = findobj(axes_gt,'type','image');
if isempty(im) || ~isequal(size(get(im,'CData')), size(I_gt))
    imshow(I_gt,colors,'parent',axes_gt);
else
    set(im,'CData',I_gt);
    colormap(colors);
end

function show_gt_spectra(R_gt,wl,colors,axes_gt_spectra,tick_labels)
M = length(tick_labels);
cla(axes_gt_spectra);
hold(axes_gt_spectra,'on');
for i = 1:M
    plot(axes_gt_spectra,wl,R_gt(i,:),'LineWidth',0.5,'Color',colors(i,:));
end
hold(axes_gt_spectra,'off');
ylim(axes_gt_spectra,[0 1]);

% xlabel('Wavelength (micrometer)','fontsize',5);
% ylabel('Reflectance','fontsize',5);
lgh = legend(axes_gt_spectra, tick_labels);
set(lgh,'fontsize',5);

function edit_crop_pos_Callback(hObject, eventdata, handles)
% hObject    handle to edit_crop_pos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_crop_pos as text
%        str2double(get(hObject,'String')) returns contents of edit_crop_pos as a double

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

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton_crop.
function pushbutton_crop_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_crop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
crop_pos = handles.crop_pos;
set(handles.edit_crop_pos,'string','x1 y1 x2 y2');
handles = delete_ui_handles(handles,'roi_rectangle');
handles.crop_pos = [];

x1 = crop_pos(1);
y1 = crop_pos(2);
x2 = crop_pos(3);
y2 = crop_pos(4);

I = handles.I;
A_gt = handles.A_gt;
rgb = handles.rgb;
gt_names1 = handles.gt_names;
I_gt = handles.I_gt;
gt_colors1 = handles.gt_colors;
tick_labels1 = handles.tick_labels;

I1 = I(y1:y2,x1:x2,:);
A_gt1 = A_gt(y1:y2,x1:x2,:);
rgb1 = rgb(y1:y2,x1:x2,:);
M = size(A_gt,3);

[R_gt1,index_to_be_removed] = get_gt_mean_spectra(I1,A_gt1,1:M);

A_gt1(:,:,index_to_be_removed) = [];
R_gt1(index_to_be_removed,:) = [];
gt_names1(index_to_be_removed) = [];
tick_labels1(index_to_be_removed) = [];
gt_colors1(index_to_be_removed,:) = [];

% Reset the I_gt values to range from 1 to M
I_gt1 = A_gt2I_gt(A_gt1);

handles = load_image(rgb1,I1,R_gt1,A_gt1,gt_names1,handles.wl,I_gt1, ...
    gt_colors1,tick_labels1,handles);
guidata(hObject,handles);

% --------------------------------------------------------------------
function Edit_Callback(hObject, eventdata, handles)
% hObject    handle to Edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function select_roi_Callback(hObject, eventdata, handles)
% hObject    handle to select_roi (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
fh = figure;imshow(handles.rgb);
[roi,x1,y1,x2,y2] = selectroi(getimage);
close(fh);
handles.crop_pos = [x1,y1,x2,y2];
handles = update_crop_display(handles);
guidata(hObject,handles);

% --- Executes on key press with focus on edit_crop_pos and none of its controls.
function edit_crop_pos_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to edit_crop_pos (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
if strcmp(eventdata.Key, 'return')
    handles.crop_pos = str2num(get(hObject,'string'));
    handles = update_crop_display(handles);
    guidata(hObject,handles);
end

function handles = update_crop_display(handles)
roi = handles.crop_pos;
set(handles.edit_crop_pos,'string',num2str(handles.crop_pos));

handles = delete_ui_handles(handles,'roi_rectangle');
handles.roi_rectangle = draw_roi_rectangle(handles.axes_image, roi);

function rect_h = draw_roi_rectangle(axes_h, roi)
x = [roi(1),roi(3),roi(3),roi(1)];
y = [roi(2),roi(2),roi(4),roi(4)];
x = [x,x(1)];
y = [y,y(1)];

hold(axes_h,'on');
rect_h = plot(axes_h,x,y,'r-','Linewidth',2);
hold(axes_h,'off');

function handles = delete_ui_handles(handles, ui_str)
if isfield(handles,ui_str)
    try
        delete(handles.(ui_str));
    catch me
        disp(['Error to delete ui handles ',num2str(handles.(ui_str))]);
    end
    handles.(ui_str) = [];
end

% --- Executes on selection change in listbox_gt_names.
function listbox_gt_names_Callback(hObject, eventdata, handles)
% hObject    handle to listbox_gt_names (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox_gt_names contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox_gt_names

if strcmp(get(handles.figure1,'SelectionType'),'normal') % If single left click
    index_selected = get(handles.listbox_gt_names,'Value');
    I_gt = handles.I_gt;
    colors = handles.gt_colors;
    M = size(colors,1);
    tick_labels = handles.tick_labels;
    axes_gt = handles.axes_gt;
    if index_selected == 1
        show_gt_image(I_gt,colors,axes_gt,tick_labels);
    else
        ind = index_selected - 1;
        for j = 1:M
            if j ~= ind
                I_gt(I_gt==j) = 0;
            end
        end
        show_gt_image(I_gt,colors,axes_gt,tick_labels);
    end
    handles.I_gt_current = I_gt;
elseif strcmp(get(hObject,'SelectionType'),'open') % If double click
end

guidata(hObject,handles);

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

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton_clear.
function pushbutton_clear_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_clear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.edit_crop_pos,'string','x1 y1 x2 y2');
handles = delete_ui_handles(handles,'roi_rectangle');

guidata(hObject,handles);

% --- Executes on selection change in popupmenu_modify_size.
function popupmenu_modify_size_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_modify_size (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_modify_size contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_modify_size

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

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

% Hint: get(hObject,'Value') returns toggle state of radiobutton_add_gt

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

% Hint: get(hObject,'Value') returns toggle state of radiobutton_remove_gt

% --------------------------------------------------------------------
function Save_Callback(hObject, eventdata, handles)
% hObject    handle to Save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
rgb = handles.rgb;
I = handles.I;
R_gt = handles.R_gt;
A_gt = handles.A_gt;
names = handles.gt_names;
wl = handles.wl;
I_gt = handles.I_gt;
gt_colors = handles.gt_colors;
tick_labels = handles.tick_labels;

[savefile, pathname] = uiputfile('*.mat','Save Dataset As');

set(gcf,'Pointer','watch');
drawnow;
save(fullfile(pathname, savefile),'rgb','I','R_gt','A_gt','names', ...
    'wl','I_gt','gt_colors','tick_labels');
set(gcf,'Pointer','arrow');

% --------------------------------------------------------------------
function menu_dataset_Callback(hObject, eventdata, handles)
% hObject    handle to menu_dataset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename,pathname] = uigetfile('*.mat','Select the dataset file');
if isequal(filename,0)
    return;
end

R_gt = [];
A_gt = [];
rgb = [];
load(fullfile(pathname,filename));

[rgb, R_gt, A_gt, names, I_gt, gt_colors, tick_labels] = ...
    add_missing_info_for_loading_image(I, wl, R_gt, A_gt, rgb);

handles = load_image(rgb,I,R_gt,A_gt,names,wl,I_gt,gt_colors,tick_labels,handles);
guidata(hObject,handles);

% --------------------------------------------------------------------
function uitoggletool_probe_OnCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_probe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

disable_other_togglebuttons_in_toolbar(handles,hObject);

function disable_other_togglebuttons_in_toolbar(handles,current)
all_togglebuttons = [handles.uitoggletool_probe, ...
    handles.uitoggletool_zoom_in, handles.uitoggletool_zoom_out, ...
    handles.uitoggletool_pan, handles.uitoggletool_modify_gt];
% This does not actually disables the actions
for togglebutton = all_togglebuttons
    if togglebutton ~= current
%         set(togglebutton,'state','off');
    end
end

% --------------------------------------------------------------------
function uitoggletool_zoom_in_OnCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_zoom_in (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
disable_other_togglebuttons_in_toolbar(handles,hObject);

% --------------------------------------------------------------------
function uitoggletool_zoom_out_OnCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_zoom_out (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
disable_other_togglebuttons_in_toolbar(handles,hObject);

% --------------------------------------------------------------------
function uitoggletool_pan_OnCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_pan (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
disable_other_togglebuttons_in_toolbar(handles,hObject);

% --------------------------------------------------------------------
function uitoggletool_modify_gt_OnCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_modify_gt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
disable_other_togglebuttons_in_toolbar(handles,hObject);

% handles.old_button_down_fcn = get(gcf,'WindowButtonDownFcn');
% handles.old_button_motion_fcn = get(gcf,'WindowButtonMotionFcn');
% handles.old_button_up_fcn = get(gcf,'WindowButtonUpFcn');

set(gcf,'WindowButtonDownFcn',@my_button_down_fcn);
set(gcf,'WindowButtonMotionFcn',@my_button_motion_fcn);
set(gcf,'WindowButtonUpFcn',@my_button_up_fcn);

% set(gcf,'Pointer','crosshair');

% --------------------------------------------------------------------
function uitoggletool_modify_gt_OffCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_modify_gt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% if isfield(handles,'old_button_down_fcn') && ...
%         isfield(handles,'old_button_motion_fcn')
set(handles.figure1,'WindowButtonDownFcn',[]);
set(handles.figure1,'WindowButtonMotionFcn',[]);
set(handles.figure1,'WindowButtonUpFcn',[]);
% end
% set(gcf,'Pointer','arrow');
handles = delete_ui_handles(handles, 'modify_circle');
handles = delete_ui_handles(handles, 'reference_circle');
handles = delete_ui_handles(handles, 'prepare_circle');

axes_hs = [handles.axes_image, handles.axes_gt];
for axes_h = axes_hs
    circles = findobj(axes_h,'type','rectangle');
    delete(circles);
end

guidata(hObject,handles);

function my_button_down_fcn(src,eventdata)
% get(gcf,'SelectionType')
handles = guidata(src);
if ~test_hit_in_image(handles) || get(handles.listbox_gt_names,'Value') == 1
    return;
end
handles.mouse_left_pressed = 1;
handles = delete_ui_handles(handles, 'prepare_circle');
handles = perform_modification(handles);
guidata(src,handles);

function my_button_motion_fcn(src,eventdata)
handles = guidata(src);
if ~test_hit_in_image(handles)
    return;
end

curPt = get(handles.axes_image, 'CurrentPoint');
x = curPt(1,1);
y = curPt(1,2);
pos = [round(x),round(y)];

% show spectra
spectra = squeeze(handles.I(pos(2),pos(1),:));
wl = handles.wl';
plot(handles.axes_spectra,wl,spectra);
ylim(handles.axes_spectra,[0 1]);
% update status
curr_gt = get_gt_name_by_position(handles, pos);
curr_pos = ['(',num2str(x,'% 10.1f'),', ',num2str(y,'% 10.1f'),')'];
set(handles.text_status, 'string', [curr_gt, ' ',curr_pos]);

if isfield(handles,'mouse_left_pressed') && handles.mouse_left_pressed && ...
        get(handles.listbox_gt_names,'Value') > 1;
    handles = perform_modification(handles);
else
    handles = draw_prepare_circle(handles);
end
guidata(src,handles);

function in = test_hit_in_image(handles)
curPt = get(handles.axes_image, 'CurrentPoint');
% Get changed pixels
x = round(curPt(1,1));
y = round(curPt(1,2));
if x >= 1 && x <= size(handles.I_gt,2) && y >= 1 && y <= size(handles.I_gt,1)
    in = 1;
else
    in = 0;
end

function handles = perform_modification(handles)
curPt = get(handles.axes_image, 'CurrentPoint');
% Get changed pixels
x = curPt(1,1);
y = curPt(1,2);
radius = get_pen_radius(handles.popupmenu_modify_size);
[X,Y] = meshgrid([round(x-radius):round(x+radius)], ...
    [round(y-radius):round(y+radius)]);
X = [X(:),Y(:)];
d = sqrt(sum((X - repmat([x,y],size(X,1),1)).^2, 2));
X1 = X(d <= radius, :);
X1(X1(:,1) < 1 | X1(:,1) > size(handles.I_gt,2), :) = [];
X1(X1(:,2) < 1 | X1(:,2) > size(handles.I_gt,1), :) = [];
I_gt = handles.I_gt_current;
ind = sub2ind(size(I_gt),X1(:,2),X1(:,1));

% draw new gt
gt_ind = get(handles.listbox_gt_names,'Value') - 1;

colors = handles.gt_colors;
tick_labels = handles.tick_labels;

if gt_ind == 0
    errordlg('Select one kind of ground truth in the listbox to modify pixels');
end

if ~isempty(ind) && gt_ind > 0
    if get(handles.radiobutton_add_gt,'Value')
        I_gt(ind) = gt_ind;
        show_gt_image(I_gt,colors,handles.axes_gt,tick_labels);
    elseif get(handles.radiobutton_remove_gt,'Value')
        I_gt(ind) = 0;
        show_gt_image(I_gt,colors,handles.axes_gt,tick_labels);
    elseif get(handles.radiobutton_change_gt,'Value')
        change_to_ind = get(handles.popupmenu_change_gt,'Value');
        if  change_to_ind ~= gt_ind
            selected_pixels = I_gt(ind);
            ind = ind(selected_pixels ~= 0);
            I_gt(ind) = 0;
            A_gt1 = handles.A_gt(:,:,change_to_ind);
            A_gt1(ind) = 1;
            handles.A_gt(:,:,change_to_ind) = A_gt1;
            show_gt_image(I_gt,colors,handles.axes_gt,tick_labels);
        end
    end
    handles.gt_modified = 1;
end
handles.I_gt_current = I_gt;

handles = draw_modify_circle(handles);

function radius = get_pen_radius(radius_h)
radius_ind = get(radius_h,'Value');
radius_strs = get(radius_h, 'String');
radius = str2num(radius_strs{radius_ind});

function handles = draw_modify_circle(handles)
curPt = get(handles.axes_image, 'CurrentPoint');
x = curPt(1,1);
y = curPt(1,2);

radius = get_pen_radius(handles.popupmenu_modify_size);

handles = delete_ui_handles(handles, 'modify_circle');
handles.modify_circle = draw_circle(handles.axes_image,x,y,radius,'r');

handles = delete_ui_handles(handles, 'reference_circle');
handles.reference_circle = draw_circle(handles.axes_gt,x,y,radius,'r');

function handles = draw_prepare_circle(handles)
curPt = get(handles.axes_image, 'CurrentPoint');
x = curPt(1,1);
y = curPt(1,2);

radius = get_pen_radius(handles.popupmenu_modify_size);

handles = delete_ui_handles(handles, 'prepare_circle');
handles.prepare_circle = draw_circle(handles.axes_image,x,y,radius,'g');

handles = delete_ui_handles(handles, 'reference_circle');
handles.reference_circle = draw_circle(handles.axes_gt,x,y,radius,'g');

function circle_h = draw_circle(axes_h,x,y,radius,color)
hold(axes_h,'on');
circle_h = rectangle('Position', [x-radius,y-radius,2*radius,2*radius], ...
    'Curvature',[1,1],'FaceColor',color,'Parent',axes_h);
hold(axes_h,'off');

function my_button_up_fcn(src,eventdata)
handles = guidata(src);
if ~handles.mouse_left_pressed || ~handles.gt_modified || ~test_hit_in_image(handles)
    return;
end

set(gcf,'Pointer','watch');
drawnow;

handles.mouse_left_pressed = 0;
handles.gt_modified = 0;
handles = delete_ui_handles(handles, 'modify_circle');
handles = draw_prepare_circle(handles);

handles = update_gt(handles);

set(gcf,'Pointer','arrow');
guidata(src,handles);

function handles = update_gt(handles)
I = handles.I;
wl = handles.wl;
I_gt = handles.I_gt;
A_gt = handles.A_gt;
colors = handles.gt_colors;
tick_labels = handles.tick_labels;
M = size(A_gt,3);
gt_ind = get(handles.listbox_gt_names,'Value') - 1;

I_gt_current1 = (handles.I_gt_current ~= 0);
A_gt(:,:,gt_ind) = double(I_gt_current1);
for j = 1:M
    if j ~= gt_ind
        A_gt1 = A_gt(:,:,j);
        A_gt1(I_gt_current1) = 0;
        A_gt(:,:,j) = A_gt1;
    end
end

I_gt = A_gt2I_gt(A_gt);

[R_gt,index_to_be_removed] = get_gt_mean_spectra(I,A_gt);
show_gt_spectra(R_gt,wl,colors,handles.axes_gt_spectra,tick_labels);
handles.A_gt = A_gt;
handles.R_gt = R_gt;
handles.I_gt = I_gt;

% --------------------------------------------------------------------
function uitoggletool_probe_OffCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool_probe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles = delete_ui_handles(handles,'other_cursor');
guidata(hObject,handles);

% --- Executes on selection change in popupmenu_change_gt.
function popupmenu_change_gt_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_change_gt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_change_gt contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_change_gt

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

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit_gt_name_Callback(hObject, eventdata, handles)
% hObject    handle to edit_gt_name (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_gt_name as text
%        str2double(get(hObject,'String')) returns contents of edit_gt_name as a double

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

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton_add_gt_name.
function pushbutton_add_gt_name_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_add_gt_name (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
gt_name = get(handles.edit_gt_name,'string');
if isempty(gt_name)
    errordlg('Can not add an empty ground truth name');
    return;
end

idx = get(handles.listbox_gt_names,'value');
selected_str = get_selected_string_from_listbox(handles.listbox_gt_names);

R_gt = handles.R_gt;
A_gt = handles.A_gt;
gt_names = handles.gt_names;
I_gt = handles.I_gt;
gt_colors = handles.gt_colors;
tick_labels = handles.tick_labels;

% Modify the background data
gt_names = insert_by_dim(gt_names, {gt_name}, idx, 2);
R_gt = insert_by_dim(R_gt, zeros(1,size(R_gt,2)), idx, 1);
A_gt = insert_by_dim(A_gt, zeros(size(A_gt,1),size(A_gt,2)), idx, 3);
I_gt = A_gt2I_gt(A_gt);
tick_labels = insert_by_dim(tick_labels, {gt_name}, idx, 2);
M = size(A_gt,3);

colors = distinguishable_colors(M);
for j = 1:M
    candidate_color = colors(j,:);
    find_matched_color = 0;
    for k = 1:size(gt_colors,1)
        if all(candidate_color == gt_colors(k,:))
            find_matched_color = 1;
            break;
        end
    end
    if ~find_matched_color
        break;
    end
end
gt_colors = insert_by_dim(gt_colors, candidate_color, idx, 1);

handles.R_gt = R_gt;
handles.A_gt = A_gt;
handles.I_gt = I_gt;
handles.gt_colors = gt_colors;
handles.tick_labels = tick_labels;
handles.gt_names = gt_names;

% Change UI display
listbox_strs = [{'All'} gt_names];
for j = 1:length(listbox_strs)
    if strcmp(listbox_strs{j},selected_str)
        break;
    end
end
refresh_gt_names_display(handles, gt_names, j);

guidata(hObject,handles);

function refresh_gt_names_display(handles, gt_names, idx)
set(handles.listbox_gt_names,'value',idx);
listbox_strs = [{'All'} gt_names];
set(handles.listbox_gt_names,'string',listbox_strs);
set(handles.popupmenu_change_gt,'string',gt_names);
show_gt_spectra(handles.R_gt, handles.wl, handles.gt_colors, ...
    handles.axes_gt_spectra, handles.tick_labels);

function selected_str = get_selected_string_from_listbox(listbox)
idx = get(listbox,'value');
listbox_strs = get(listbox,'string');
selected_str = listbox_strs{idx};

% --- Executes on button press in pushbutton_remove_gt_name.
function pushbutton_remove_gt_name_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_remove_gt_name (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selected_str = get_selected_string_from_listbox(handles.listbox_gt_names);
idx = get(handles.listbox_gt_names,'value');
idx = idx - 1;

if strcmp(selected_str,'All') || idx == 0
    errordlg('Must select one specific ground truth to delete.');
    return;
end

% Modify background data
R_gt = handles.R_gt;
A_gt = handles.A_gt;
gt_names = handles.gt_names;
I_gt = handles.I_gt;
gt_colors = handles.gt_colors;
tick_labels = handles.tick_labels;

R_gt(idx,:) = [];
A_gt(:,:,idx) = [];
gt_names(idx) = [];
gt_colors(idx,:) = [];
tick_labels(idx) = [];
I_gt = A_gt2I_gt(A_gt);

handles.R_gt = R_gt;
handles.A_gt = A_gt;
handles.I_gt = I_gt;
handles.gt_colors = gt_colors;
handles.tick_labels = tick_labels;
handles.gt_names = gt_names;

% refresh display
refresh_gt_names_display(handles, gt_names, idx);

guidata(hObject,handles);

listbox_gt_names_Callback(handles.listbox_gt_names, [], handles);

% --- Executes on button press in pushbutton_change_gt_name.
function pushbutton_change_gt_name_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_change_gt_name (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
gt_name = get(handles.edit_gt_name,'string');
if isempty(gt_name)
    errordlg('Can not change the selected ground truth to an empty name.');
    return;
end

idx = get(handles.listbox_gt_names,'value');
idx = idx - 1;
if idx == 0
    errordlg('Must select one specific ground truth to change name.');
    return;
end

% Modify background data
R_gt = handles.R_gt;
gt_colors = handles.gt_colors;
gt_names = handles.gt_names;
tick_labels = handles.tick_labels;

gt_names{idx} = gt_name;
tick_labels{idx} = gt_name;

handles.gt_names = gt_names;
handles.tick_labels = tick_labels;

% refresh display
refresh_gt_names_display(handles, gt_names, idx+1);

guidata(hObject,handles);

% --------------------------------------------------------------------
function menu_view_Callback(hObject, eventdata, handles)
% hObject    handle to menu_view (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function menu_image_Callback(hObject, eventdata, handles)
% hObject    handle to menu_image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
figure;
imshow(handles.rgb);

if isfield(handles,'crop_pos') && ~isempty(handles.crop_pos);
    draw_roi_rectangle(gca, handles.crop_pos);
end

% --------------------------------------------------------------------
function menu_gt_image_Callback(hObject, eventdata, handles)
% hObject    handle to menu_gt_image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
figure;
show_gt_image(handles.I_gt, handles.gt_colors, gca, handles.tick_labels);
M = length(handles.tick_labels);
% show colorbar
cbh = colorbar;
set(cbh,'Location','West');
% pos = get(cbh,'Position');
% pos(1) = 0.9;
% set(cbh,'Location','manual');
% set(cbh,'Position',pos);
set(cbh,'YTickLabel',handles.tick_labels);
set(cbh,'YDir','reverse');

s = version;
if str2double(s(1)) <= 7
    set(cbh,'YTick',(1:M)');
    set(cbh,'YLim',[0.5 M+0.5]);
else
    set(cbh,'ticks',(0.5:1:M+0.5)');
    set(cbh,'YLim',[0 M]);
end

% --------------------------------------------------------------------
function menu_gt_spectra_Callback(hObject, eventdata, handles)
% hObject    handle to menu_gt_spectra (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
figure;
subplot(2,2,1);
show_gt_spectra(handles.R_gt, handles.wl, handles.gt_colors, ...
    gca, handles.tick_labels);
lines = findobj(gca,'type','line');
for line = lines
    set(line,'linewidth',2);
end

xlabel('Wavelength (micrometer)','fontsize',12);
ylabel('Reflectance','fontsize',12);
lgh = legend(gca, handles.gt_names);
set(lgh,'fontsize',12);

% --------------------------------------------------------------------
function menu_gt_Callback(hObject, eventdata, handles)
% hObject    handle to menu_gt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function menu_gt_hist_Callback(hObject, eventdata, handles)
% hObject    handle to menu_gt_hist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[Y,A,rows,cols] = reshape_hsi(handles.I, handles.A_gt);
hist_end_var(Y, A, handles.gt_names);

% --------------------------------------------------------------------
function menu_reset_colors_Callback(hObject, eventdata, handles)
% hObject    handle to menu_reset_colors (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
M = length(handles.gt_names);
colors2 = distinguishable_colors(M);

rgb = im2double(handles.rgb);
if 1
    [colors1,index_to_be_removed] = get_gt_mean_spectra(rgb, handles.A_gt);
    [P,colors] = permute_endmembers(colors1, colors2);
elseif 0
    [colors,index_to_be_removed] = get_gt_mean_spectra(rgb, handles.A_gt);
else
    colors = colors2;
end

handles.gt_colors = colors;

show_gt_spectra(handles.R_gt, handles.wl, colors, ...
    handles.axes_gt_spectra, handles.tick_labels);

guidata(hObject,handles);

listbox_gt_names_Callback(handles.listbox_gt_names, [], handles);

% --------------------------------------------------------------------
function menu_script_Callback(hObject, eventdata, handles)
% hObject    handle to menu_script (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename,pathname] = uigetfile('*.m','Select the load script file');
if isequal(filename,0)
    return;
end
filepath = fullfile(pathname,filename);
[pathstr,name,ext] = fileparts(filepath);
% current_dir = pwd;
% cd(pathstr);
rgb = [];
eval(['[I,R_gt,A_gt,names,wl,rgb] = ',name,';']);
% cd(current_dir);

[rgb, R_gt, A_gt, names, I_gt, gt_colors, tick_labels] = ...
    add_missing_info_for_loading_image(I, wl, R_gt, A_gt, rgb);

% load image
handles = load_image(rgb,I,R_gt,A_gt,names,wl,I_gt,gt_colors,tick_labels,handles);
guidata(hObject,handles);

function [rgb, R_gt, A_gt, names, I_gt, gt_colors, tick_labels] = ...
    add_missing_info_for_loading_image(I, wl, R_gt, A_gt, rgb)
% If no ground truth, set default one
if isempty(R_gt) && isempty(A_gt)
    % set default number of endmembers
    default_num_endmembers = 1;

    [Y,A_gt,rows,cols] = reshape_hsi(I,A_gt);
    [idx,c] = kmeans(Y,default_num_endmembers);
    R_gt = c;
    A_gt = I_gt2A_gt(uint8(reshape(idx, rows, cols)));
    for i = 1:size(R_gt,1)
        names{i} = ['endmember',num2str(i)];
    end
end

% set other missing information
if isempty(rgb)
    rgb = sqrt(retrieve_rgb(I,wl));
end
I_gt = A_gt2I_gt(A_gt);
M = size(A_gt,3);
gt_colors = distinguishable_colors(M);
tick_labels = names;

author: zhouyuanzxcv

repo: Hyperspectral


text:
% http://www.mathworks.com/matlabcentral/fileexchange/33381

function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
%    or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%            date: 2011/09/09
%         Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
%            date: 2009/11/02
%         Fran�ois Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
%            date: 2009/03/22
%         Joel Feenstra:
%         http://www.mathworks.com/matlabcentral/fileexchange/20565
%            date: 2008/07/03
%
% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
%      fname: input file name, if fname contains "{}" or "[]", fname
%             will be interpreted as a JSON string
%      opt: a struct to store parsing options, opt can be replaced by
%           a list of ('param',value) pairs. The param string is equivallent
%           to a field in opt.
%
% output:
%      dat: a cell array, where {...} blocks are converted into cell arrays,
%           and [...] are converted to arrays
%
% license:
%     BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

global pos inStr len  esc index_esc len_esc isoct arraytoken

if(regexp(fname,'[\{\}\]\[]','once'))
   string=fname;
elseif(exist(fname,'file'))
   fid = fopen(fname,'rt');
   string = fscanf(fid,'%c');
   fclose(fid);
else
   error('input file does not exist');
end

pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\','  ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);

% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);

opt=varargin2struct(varargin{:});
jsoncount=1;
while pos <= len
    switch(next_char)
        case '{'
            data{jsoncount} = parse_object(opt);
        case '['
            data{jsoncount} = parse_array(opt);
        otherwise
            error_pos('Outer level structure must be an object or an array');
    end
    jsoncount=jsoncount+1;
end % while

jsoncount=length(data);
if(jsoncount==1 && iscell(data))
    data=data{1};
end

if(~isempty(data))
      if(isstruct(data)) % data can be a struct array
          data=jstruct2array(data);
      elseif(iscell(data))
          data=jcell2array(data);
      end
end
end

function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
      if(isstruct(data{i}))
          newdata{i}=jstruct2array(data{i});
      elseif(iscell(data{i}))
          newdata{i}=jcell2array(data{i});
      end
end
end

function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
    for j=1:len
        if(isstruct(getfield(data(j),fn{i})))
            newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
        end
    end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
  newdata=cell(len,1);
  for j=1:len
    ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
    iscpx=0;
    if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
        if(data(j).x0x5F_ArrayIsComplex_)
           iscpx=1;
        end
    end
    if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
        if(data(j).x0x5F_ArrayIsSparse_)
            if(iscpx && size(ndata,2)==4)
                ndata(:,3)=complex(ndata(:,3),ndata(:,4));
            end
            if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
                dim=data(j).x0x5F_ArraySize_;
                ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
            else
                ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
            end
        end
    elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
        if(iscpx && size(ndata,2)==2)
             ndata=complex(ndata(:,1),ndata(:,2));
        end
        ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
    end
    newdata{j}=ndata;
  end
  if(len==1)
      newdata=newdata{1};
  end
end
end

function object = parse_object(varargin)
    parse_char('{');
    object = [];
    if next_char ~= '}'
        while 1
            str = parseStr(varargin{:});
            if isempty(str)
                error_pos('Name of value at position %d cannot be empty');
            end
            parse_char(':');
            val = parse_value(varargin{:});
            eval( sprintf( 'object.%s  = val;', valid_field(str) ) );
            if next_char == '}'
                break;
            end
            parse_char(',');
        end
    end
    parse_char('}');
end

function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
    parse_char('[');
    object = cell(0, 1);
    dim2=[];
    if next_char ~= ']'
        [endpos e1l e1r maxlevel]=matching_bracket(inStr,pos);
        arraystr=['[' inStr(pos:endpos)];
        arraystr=regexprep(arraystr,'"_NaN_"','NaN');
        arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
        arraystr(find(arraystr==sprintf('\n')))=[];
        arraystr(find(arraystr==sprintf('\r')))=[];
        %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
        if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
            astr=inStr((e1l+1):(e1r-1));
            astr=regexprep(astr,'"_NaN_"','NaN');
            astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
            astr(find(astr==sprintf('\n')))=[];
            astr(find(astr==sprintf('\r')))=[];
            astr(find(astr==' '))='';
            if(isempty(find(astr=='[', 1))) % array is 2D
                dim2=length(sscanf(astr,'%f,',[1 inf]));
            end
        else % array is 1D
            astr=arraystr(2:end-1);
            astr(find(astr==' '))='';
            [obj count errmsg nextidx]=sscanf(astr,'%f,',[1,inf]);
            if(nextidx>=length(astr)-1)
                object=obj;
                pos=endpos;
                parse_char(']');
                return;
            end
        end
        if(~isempty(dim2))
            astr=arraystr;
            astr(find(astr=='['))='';
            astr(find(astr==']'))='';
            astr(find(astr==' '))='';
            [obj count errmsg nextidx]=sscanf(astr,'%f,',inf);
            if(nextidx>=length(astr)-1)
                object=reshape(obj,dim2,numel(obj)/dim2)';
                pos=endpos;
                parse_char(']');
                return;
            end
        end
        arraystr=regexprep(arraystr,'\]\s*,','];');
        try
           if(isoct && regexp(arraystr,'"','once'))
                error('Octave eval can produce empty cells for JSON-like input');
           end
           object=eval(arraystr);
           pos=endpos;
        catch
         while 1
            val = parse_value(varargin{:});
            object{end+1} = val;
            if next_char == ']'
                break;
            end
            parse_char(',');
         end
        end
    end
    try
        object=cell2mat(object')';
        if(size(object,1)>1 && ndims(object)==2)
            object=object';
        end
    catch
    end
    parse_char(']');
end

function parse_char(c)
    global pos inStr len
    skip_whitespace;
    if pos > len || inStr(pos) ~= c
        error_pos(sprintf('Expected %c at position %%d', c));
    else
        pos = pos + 1;
        skip_whitespace;
    end
end

function c = next_char
    global pos inStr len
    skip_whitespace;
    if pos > len
        c = [];
    else
        c = inStr(pos);
    end
end

function skip_whitespace
    global pos inStr len
    while pos <= len && isspace(inStr(pos))
        pos = pos + 1;
    end
end

function str = parseStr(varargin)
    global pos inStr len  esc index_esc len_esc
 % len, ns = length(inStr), keyboard
    if inStr(pos) ~= '"'
        error_pos('String starting with " expected at position %d');
    else
        pos = pos + 1;
    end
    str = '';
    while pos <= len
        while index_esc <= len_esc && esc(index_esc) < pos
            index_esc = index_esc + 1;
        end
        if index_esc > len_esc
            str = [str inStr(pos:len)];
            pos = len + 1;
            break;
        else
            str = [str inStr(pos:esc(index_esc)-1)];
            pos = esc(index_esc);
        end
        nstr = length(str); switch inStr(pos)
            case '"'
                pos = pos + 1;
                if(~isempty(str))
                    if(strcmp(str,'_Inf_'))
                        str=Inf;
                    elseif(strcmp(str,'-_Inf_'))
                        str=-Inf;
                    elseif(strcmp(str,'_NaN_'))
                        str=NaN;
                    end
                end
                return;
            case '\'
                if pos+1 > len
                    error_pos('End of file reached right after escape character');
                end
                pos = pos + 1;
                switch inStr(pos)
                    case {'"' '\' '/'}
                        str(nstr+1) = inStr(pos);
                        pos = pos + 1;
                    case {'b' 'f' 'n' 'r' 't'}
                        str(nstr+1) = sprintf(['\' inStr(pos)]);
                        pos = pos + 1;
                    case 'u'
                        if pos+4 > len
                            error_pos('End of file reached in escaped unicode character');
                        end
                        str(nstr+(1:6)) = inStr(pos-1:pos+4);
                        pos = pos + 5;
                end
            otherwise % should never happen
                str(nstr+1) = inStr(pos), keyboard
                pos = pos + 1;
        end
    end
    error_pos('End of file while expecting end of inStr');
end

function num = parse_number(varargin)
    global pos inStr len isoct
    currstr=inStr(pos:end);
    numstr=0;
    if(isoct~=0)
        numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
        [num, one] = sscanf(currstr, '%f', 1);
        delta=numstr+1;
    else
        [num, one, err, delta] = sscanf(currstr, '%f', 1);
        if ~isempty(err)
            error_pos('Error reading number at position %d');
        end
    end
    pos = pos + delta-1;
end

function val = parse_value(varargin)
    global pos inStr len
    true = 1; false = 0;

    switch(inStr(pos))
        case '"'
            val = parseStr(varargin{:});
            return;
        case '['
            val = parse_array(varargin{:});
            return;
        case '{'
            val = parse_object(varargin{:});
            return;
        case {'-','0','1','2','3','4','5','6','7','8','9'}
            val = parse_number(varargin{:});
            return;
        case 't'
            if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
                val = true;
                pos = pos + 4;
                return;
            end
        case 'f'
            if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
                val = false;
                pos = pos + 5;
                return;
            end
        case 'n'
            if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
                val = [];
                pos = pos + 4;
                return;
            end
    end
    error_pos('Value expected at position %d');
end

function error_pos(msg)
    global pos inStr len
    poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
    if poShow(3) == poShow(2)
        poShow(3:4) = poShow(2)+[0 -1];  % display nothing after
    end
    msg = [sprintf(msg, pos) ': ' ...
    inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
    error( ['JSONparser:invalidFormat: ' msg] );
end

function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
    pos=regexp(str,'^[^A-Za-z]','once');
    if(~isempty(pos))
        if(~isoct)
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
        end
    end
    if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return;  end
    if(~isoct)
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        pos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(pos)) return; end
        str0=str;
        pos0=[0 pos(:)' length(str)];
        str='';
        for i=1:length(pos)
            str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
        end
        if(pos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end
    %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
end

function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
    if(str(pos)=='"')
        if(~(pos>1 && str(pos-1)=='\'))
            endpos=pos;
            return;
        end
    end
    pos=pos+1;
end
error('unmatched quotation mark');
end

function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
    c=tokens(pos);
    if(c==']')
        level=level-1;
        if(isempty(e1r)) e1r=bpos(pos); end
        if(level==0)
            endpos=bpos(pos);
            return
        end
    end
    if(c=='[')
        if(isempty(e1l)) e1l=bpos(pos); end
        level=level+1;
        maxlevel=max(maxlevel,level);
    end
    if(c=='"')
        pos=matching_quote(tokens,pos+1);
    end
    pos=pos+1;
end
if(endpos==0)
    error('unmatched "]"');
end
end

function opt=varargin2struct(varargin)
%
% opt=varargin2struct('param1',value1,'param2',value2,...)
%   or
% opt=varargin2struct(...,optstruct,...)
%
% convert a series of input parameters into a structure
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2012/12/22
%
% input:
%      'param', value: the input parameters should be pairs of a string and a value
%       optstruct: if a parameter is a struct, the fields will be merged to the output struct
%
% output:
%      opt: a struct where opt.param1=value1, opt.param2=value2 ...
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

len=length(varargin);
opt=struct;
if(len==0) return; end
i=1;
while(i<=len)
    if(isstruct(varargin{i}))
        opt=mergestruct(opt,varargin{i});
    elseif(ischar(varargin{i}) && i<len)
        opt=setfield(opt,varargin{i},varargin{i+1});
        i=i+1;
    else
        error('input must be in the form of ...,''name'',value,... pairs or structs');
    end
    i=i+1;
end

end

author: goGPS-Project


text:
function out = DK_crinkle(x)
% DK_crinkle  Computes James Theiler's crinkle statistic
%
% Calculates the "crinkle statistic" on a vector x
% 	<(x_{t-1}-2*x_t+x_{t+1})^4> / < ( x_t^2 ) >^2
%	as proposed by James Theiler
%
% ------------------------------------------------------------------------------
% Copyright (C) 1996, D. Kaplan <kaplan@macalester.edu>
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

% Subtract out the mean
x = x - mean(x);
x2 = mean(x.*x)^2;

if x2 == 0
	out = 0;
	return
end

d2 = 2*x(2:end-1) - x(1:end-2) - x(3:end);
out = mean(d2.^ 4)/x2;

end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function selectors = sequence_tag_selectors(experiment, sequences, tags) %#ok<INUSL>
% sequence_tag_selectors Create per-tag selector
%
% Create a set of selectors for a set of tags upon a set of sequences.
%
% Input:
% - experiment (structure): A valid experiment descriptor.
% - sequences (cell): A cell array of valid sequence descriptors.
% - tags (cell): A cell array of tag names.
%
% Output:
% - selectors (cell): A cell array of selector structures, one for each tag.
%

    selectors = cellfun(@(tag) struct('name', sprintf('tag_%s', tag), ...
        'title', tag, ...
        'groundtruth', @(sequences) groundtruth_for_tag(sequences, tag), ...
        'groundtruth_values', @(sequences, value) groundtruth_value_for_tag(sequences, tag, value), ...
        'results', @(experiment, tracker, sequences) results_for_tag(experiment, tracker, sequences, tag), ...
        'results_values', @(experiment, tracker, sequences, value) ...
        result_values_for_tag(experiment, tracker, sequences, tag, value), ...
        'length', @(sequences) count_for_tag(sequences, tag)), ...
        tags, 'UniformOutput', false);

end

function [groundtruth] = groundtruth_for_tag(sequences, tag)

    groundtruth = cell(numel(sequences), 1);

    for s = 1:length(sequences)

        filter = sequence_query_tag(sequences{s}, tag);

        if isempty(filter) || ~any(filter)
            continue;
        end;

        groundtruth{s} = sequences{s}.groundtruth(filter);

    end

end

function [results] = results_for_tag(experiment, tracker, sequences, tag)

    repeat = experiment.parameters.repetitions;

    results = cell(numel(sequences), repeat);

    if ~exist(fullfile(tracker.directory, experiment.name), 'dir')
        print_debug('Warning: Results not available %s', tracker.identifier);
        return;
    end;

    for s = 1:length(sequences)

        filter = sequence_query_tag(sequences{s}, tag);

        if isempty(filter) || ~any(filter)
            continue;
        end;

        groundtruth = sequences{s}.groundtruth;

        directory = fullfile(tracker.directory, experiment.name, sequences{s}.name);

        for j = 1:repeat

            result_file = fullfile(directory, sprintf('%s_%03d.txt', sequences{s}.name, j));

            try
                trajectory = read_trajectory(result_file);

                if (size(results{s, j}, 1) < size(groundtruth, 1))
                    %print_debug('Warning: Trajectory too short. Expanding with empty frames.');
                    trajectory(end+1:length(groundtruth)) = {0};
                end;

                results{s, j} = trajectory(filter);

            catch
                continue;
            end;

        end;

    end

end

function [results] = result_values_for_tag(experiment, tracker, sequences, tag, value)

    repeat = experiment.parameters.repetitions;

    results = cell(numel(sequences), repeat);

    if ~exist(fullfile(tracker.directory, experiment.name), 'dir')
        print_debug('Warning: Results not available %s', tracker.identifier);
        return;
    end;

    for s = 1:length(sequences)

        filter = sequence_query_tag(sequences{s}, tag);

        if isempty(filter) || ~any(filter)
            continue;
        end;

        directory = fullfile(tracker.directory, experiment.name, sequences{s}.name);

        for j = 1:repeat

            values_file = fullfile(directory, sprintf('%s_%03d_%s.value', sequences{s}.name, j, value));

            data = nan(sequences{s}.length, 1);

            i = 0;

            try
                fp = fopen(values_file, 'r');

                while true
                     line = fgets(fp);

                     if line == -1
                         break;
                     end

                     [v, numeric] = str2num(line(1:end-1)); %#ok<ST2NM>

                     if ~numeric
                        v = line(1:end-1);
                     end

                     i = i + 1;

                     if isempty(v)
                         continue;
                     end;

                     data(i) = v;

                end;

                fclose(fp);

                results{s, j} = data(filter);

            catch
                results{s, j} = nan(numel(filter), 1);
                continue;
            end;

        end;

    end

end

function [count, partial] = count_for_tag(sequences, tag)

	count = 0;

    partial = zeros(1, length(sequences));

    for s = 1:length(sequences)

        filter = sequence_query_tag(sequences{s}, tag);

        if isempty(filter)
            continue;
        end;

		count = count + numel(filter);

        partial(s) = numel(filter);

    end
end

function values = groundtruth_value_for_tag(sequences, tag, value)

    values = cell(numel(sequences), 1);

    for s = 1:length(sequences)

        filter = sequence_query_tag(sequences{s}, tag);

        if isempty(filter)
            continue;
        end;

        values{s} = sequence_get_frame_value(sequences{s}, value, filter);

    end;

end

author: votchallenge

repo: toolkit-legacy


text:
function [Detect] = cfar_ca1D_square(Xcube,noiseWin,guardLen,Pfa,wrapMode,ord_stat)
N = noiseWin*2;
alpha = N*(Pfa^(-1/N)-1);
alpha_oneside = noiseWin*(Pfa^(-1/noiseWin)-1);
Xcube = Xcube.^2;
Xlength = length(Xcube);
Detect = [];
numOfDet = 0;
% ord_stat = 0.7;
% if not CAOS-CFAR, set ord_stat = 1

if wrapMode == 0    %%% disabled warpped mode
    for i = 1:Xlength
        if i < noiseWin+guardLen+1  %%% one-sided comparision for left section
            Xcube_select = sort(Xcube(i+guardLen+1:i+guardLen+noiseWin), 'descend');
            num_filter = round(length(Xcube_select) * (1-ord_stat));
            noiseWin_len = noiseWin - num_filter;
            if num_filter > 0
                Xcube_select(1:num_filter) = 0;
            end
            noise_estimate = sum(Xcube_select)/noiseWin_len;
            if Xcube(i) > alpha_oneside*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end
        elseif i < Xlength-noiseWin-guardLen+1  %%% two-sided comparison for middle section
            Xcube_select = sort(Xcube(i+guardLen+1:i+guardLen+noiseWin), 'descend');
            Xcube_select2 = sort(Xcube(i-guardLen-noiseWin:i-guardLen-1), 'descend');
            num_filter = round(length(Xcube_select) * (1-ord_stat));
            noiseWin_len = noiseWin - num_filter;
            if num_filter > 0
                Xcube_select(1:num_filter) = 0;
                Xcube_select2(1:num_filter) = 0;
            end
            noise_estimate = (sum(Xcube_select) + sum(Xcube_select2))/(2*noiseWin_len);
            if Xcube(i) > alpha*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end
        else     %%%  one-sided comparision for right section
            Xcube_select = sort(Xcube(i-guardLen-noiseWin:i-guardLen-1), 'descend');
            num_filter = round(length(Xcube_select) * (1-ord_stat));
            noiseWin_len = noiseWin - num_filter;
            if num_filter > 0
                Xcube_select(1:num_filter) = 0;
            end
            noise_estimate = sum(Xcube_select)/noiseWin_len;
            if Xcube(i) > alpha_oneside*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end
        end
    end
else       %%% enabled wrapped mode
    for i = 1:Xlength
        if i < noiseWin+guardLen+1  %%% two-sided comparision for left section with wrap
            %%% discuss the wrap scenario
            if i <= guardLen
                noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...
                    + sum(Xcube(Xlength+i-guardLen-noiseWin:Xlength+i-guardLen-1)))/N;
            else
                noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...
                    + sum(Xcube(Xlength+i-guardLen-noiseWin:Xlength))+sum(Xcube(1:i-1-guardLen)))/N;
            end

            if Xcube(i) > alpha*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end

        elseif i < Xlength-noiseWin-guardLen+1  %%% two-sided comparison for middle section
            noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...
                + sum(Xcube(i-guardLen-noiseWin:i-guardLen-1)))/N;
            if Xcube(i) > alpha*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end

        else     %%%  two-sided comparision for right section with wrap
            if i >= Xlength-guardLen+1
                noise_estimate = (sum(Xcube(i-guardLen-noiseWin:i-guardLen-1))...
                    + sum(Xcube(guardLen+i-Xlength+1:guardLen+i-Xlength+noiseWin)))/N;
            else
                noise_estimate = (sum(Xcube(i-guardLen-noiseWin:i-guardLen-1))...
                    + sum(Xcube(guardLen+i+1:Xlength))+sum(Xcube(1:noiseWin-Xlength+i+guardLen)))/N;
            end

            if Xcube(i) > alpha*noise_estimate
                numOfDet = numOfDet + 1;
                Detect(1,numOfDet) = i; %%% index
                Detect(2,numOfDet) = Xcube(i);  %%% object power
                Detect(3,numOfDet) = noise_estimate;  %%% estimated noise
            end
        end
    end
end
end

author: Xiangyu-Gao


text:
function [ objectsCV, files ] = loadCV( file )

    %% Load files
    files = dir([file '/Cross*.mat' ]);

%     nFiles = length(files);
%     count_imgs = 0;
%     for i = 1:nFiles
%         disp(['Reading file ' files(i).name]);
%         load([file '/' files(i).name]); % objectsCV
%         nImgs = length(objectsCV);
%         for j = 1:nImgs
%             objectsCV_aux(count_imgs+1) = objectsCV(j);
%             count_imgs = count_imgs+1;
%         end
%     end
%
%     objectsCV = objectsCV_aux;

    if(length(files) > 1)
        load([file '/' files(1).name]); % objectsCV
    else
        error('No CV files found.');
    end

end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
 function scArc(Point, LinCol)
 %scArc : Draws an arc (a circle) on the smith chart passing through a given point
%
%  SYNOPSIS:
%     Draws an arc (a circle) on the smith chart passing through a given point.
%     the point in question is defined as an (r,x) pair. This function should only
%     be called when a smith chart figure is already present.
%
%     See also scDraw, scInv, scMove, scMatchCirc
%
%  SYNTAX:
%     scArc(Point, LinCol)
%
%  INPUT ARGUMENTS:
%     Point  : values of r and x defining a point on the smith chart as a vector [r x]
%     LinCol : color of the arc (or circle)
%
%  OUTPUT ARGUMENT:
%     none
%
%  EXAMPLE:
%         The Command sequence
%         scDraw;
%         scArc([2 3]);
%         will draw a blank smith chart and draw a circle having center at the
%         smith chart center [1 0] and passing through the point [2 3]
%         in the smith chart corresponding to an impedance (2+j3)*Z_L. This
%         may be thought of as the locus of impedance along the lossless
%         line of line impedance Z_L.
%
%
%     Mohammad Ashfaq - (31-05-2000)
%     Mohammad Ashfaq - (13-04-2006) Modified (example included)
%

 if nargin == 1
     LinCol = 'm';
 end

 r1 = Point(1);
 x1 = Point(2);

 %x2 = to(2);
 %r2 = to(1);

 [u1, v1] = scPOI(r1, x1);
 %[u2,v2]=point_of_intersection(r2,x2);
 x = linspace(-sqrt(u1^2+v1^2),sqrt(u1^2+v1^2),500);

 plot(x,sqrt(u1^2+v1^2-x.^2),LinCol);
 plot(x,-sqrt(u1^2+v1^2-x.^2),LinCol);

 % MARK POINT
 plot(u1,v1,'r*')


text:
 function a = loss(comp,par,spr)

%============================================================================
% Loss object - for calculating loss functions
%============================================================================
% a=loss(lossType,param)
%
%   calculates the difference between the input X and the ouput Y depending
%   on the specified loss type (for further information see below).
%   The loss can be calculated in two ways. The first is to it by training,
%   the second is to call the function with a data object as first
%   parameter (loss(d,loss_type,param)). The results are stored in the Y
%   part of the data object.
%
%   Attributes (with defaults):
%       type='class_loss'  -- type of loss (class_loss,linear_loss...)
%       param=[]           -- used parameters (can also be empty)
%
%   Methods:
%       train,test,calc
%
%   LOSS              |   PARAMETERS & DESCRIPTION
%   -------------------------------------------------------------------
%   class_loss        -- zero/one loss, L(x,y)=1 if x=y, 0 otherwise
%   confusion_matrix  -- matrix of [true-pos, false-pos; false-neg, true-neg]
%   epsilon_loss      -- L(x,y)= |x-y|, if |x-y|>epsilon, 0 otherwise
%   linear_loss       -- 1-norm, L(x,y)=|x-y|
%   one_class_loss    -- for one-class, e.g novelty detection, etc.
%   quadratic_loss    -- 2-norm, L(x,y)=|x-y|_2^2
%   roc               -- receiver/operator characteristic
%   roc50             -- receiver/operator characteristic, first n fps
%   sensitivity       -- tp/(tp+fn)
%   specificity       -- tn/(fp+tn)
%   kernel            -- loss derived from kernel matrix (param)
%                     -- inner products in 'loss' space between examples.
%   alignment         -- L(x,y)= sum(sum( (x*x') .* (y*y'))) / normalization
%===================================================================================
% Reference :
% Author    :
% Link      :
%===================================================================================

  %% <<--calculate loss like function (no objects is created)------>>
  if nargin>0 & isa(comp,'algorithm')
    a.type='class_loss';
    if nargin>1
        a.type=par;
    end;

    a.param=[];
    if nargin==3,
        a.param=spr;
    end;

    algoTemp=algorithm(a.type);
    a= class(a,'loss',algoTemp);
    a=train(a,comp);
    return;
  end
  %% --------------------------------------------------------------------

   if nargin==0
     a.type='class_loss';
   else
     a.type=comp;
   end

   a.param=[];

   if nargin==2
     a.param=par;
   end;

   algoTemp=algorithm(a.type);
   a= class(a,'loss',algoTemp);

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [ vX ] = ConsensusAdmm( cProxFun, numElements, paramRho, numIterations, stopThr )
% ----------------------------------------------------------------------------------------------- %
% [ vX ] = ConsensusAdmm( cProxFun, numElements, paramRho, numIterations, stopThr )
%   Solves the Consensus ADMM problem given the set of Proximal Operators.
% Input:
%   - cProxFun      -   Set of Proximal Operators.
%                       Each cell elemnts is the i-th proximal operator.
%                       Each function handler input is a (vV, paramLambda).
%                       The implementation is for the prox in its lambda
%                       form: 0.5 * || x - v ||^2 + paramLamba * g(x).
%                       Structure: Cell Array (numSets x 1).
%                       Type: Function Handler.
%                       Range: NA.
% Output:
%   - vX            -   Solution Vector.
%                       The solution to the optimization problem..
%                       Structure: Vector (m x 1).
%                       Type: 'Single' / 'Double'.
%                       Range: (-inf, inf).
% References
%   1.  ELE 522 - Large Scale Optimization for Data Science - Alternating Direction Method of Multipliers.
% Remarks:
%   1.  Pay attention that the references are using (1 / paramLambda) form
%       of the Prox. Hence the adaptation in the code.
%   2.  This is ultra efficient way to solve the Orthogonal Projection
%       Problem in case having projection onto sets which the intersection
%       is the objective set.
% TODO:
%   1.  C
% Release Notes:
%   -   1.0.000     25/03/2020  Royi Avital
%       *   First release version.
% ----------------------------------------------------------------------------------------------- %

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;

numSets     = size(cProxFun, 1);
% numElements = size(vX, 1);

paramRhoInv = 1 / paramRho;

mX      = zeros(numElements, numSets);
vZ      = mean(mX, 2);
mLambda = zeros(numElements, numSets);

for ii = 1:numIterations
    for jj = 1:numSets
        mX(:, jj) = cProxFun{jj}(vZ - (paramRhoInv * mLambda(:, jj)), paramRhoInv);
    end

    vZ = mean(mX + (paramRhoInv * mLambda), 2);

    for jj = 1:numSets
        mLambda(:, jj) = mLambda(:, jj) + (paramRho * (mX(:, jj) - vZ)); %<! Can be done mLambda = mLambda + (paramRho * (mX - vZ));
    end

    % To calculate the difference from the previous iteration.
    stopCond = max(abs(mX - vZ), [], 'all') < stopThr;

    if(stopCond)
        break;
    end
end

vX = mean(mX, 2);

end

author: RoyiAvital

repo: StackExchangeCodes


text:
function [ranks, sortingInds, isTied] = prtUtilRank(ds)
% prtUtilRank - Ranks the vector in increasing magnitude
%   Ties have a rank of the middle of the tied ranks
%   NaNs have a rank of NaN
%
% prtUtilRank([1 2 2 4 5 inf nan nan]')

if ~isnumeric(ds)
    if isa(ds,'prtDataSetBase')
        ds = ds.getObservations();
    else
        error('prt:prtUtilRank','Input must be either a numerical vector or a prtDataSet containing 1 feature.')
    end
end

if isvector(ds)
    ds = ds(:);
end

assert(size(ds,2)==1,'prtUtilRank is only for 1 dimensional data');

[sortedDS, sortingInds] = sort(ds);

ranks = (1:length(sortedDS))';

if length(sortedDS) > 1
    isTiedWithNext = cat(1,sortedDS(1:(end-1)) == sortedDS(2:end),false);
else
    isTiedWithNext = false;
end

% If there are any ties we need to figure out the tied regions and set each
% of the ranks to the average of the tied ranks.
tieRegions = [];
if any(isTiedWithNext)
    diffIsTiedWithNext = diff(isTiedWithNext);

    if isTiedWithNext(1) % First one is tied
        diffIsTiedWithNext = cat(1,1,diffIsTiedWithNext);
    else
        diffIsTiedWithNext = cat(1,0,diffIsTiedWithNext);
    end

    % Start and stop regions of the ties
    tieRegions = cat(2,find(diffIsTiedWithNext==1),find(diffIsTiedWithNext==-1));

    for iRegion = 1:size(tieRegions,1);
        cInds = tieRegions(iRegion,1):tieRegions(iRegion,2);

        ranks(cInds) = mean(ranks(cInds));
    end
end

ranks(isnan(sortedDS)) = nan;

ranks(sortingInds) = ranks;

if nargout > 2
    % We asked for the isTied vector
    isTied = false(size(ds));
    for iRegion = 1:size(tieRegions,1);
        isTied(tieRegions(iRegion,1):tieRegions(iRegion,2)) = true;
    end
    isTied(sortingInds) = isTied;
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function colornames_view(palette,order)
% View the COLORNAMES palettes in an interactive figure. Sort colors by name/color space.
%
% (c) 2014-2019 Stephen Cobeldick
%
%%% Syntax:
%  colornames_view
%  colornames_view(palette)
%  colornames_view(palette,sortorder)
%
% Create a figure displaying all of the colors from any palette supported
% by the function COLORNAMES. The palette and sort order can be selected
% by drop-down menu or by optional inputs. The colors can be sorted:
% - alphabetically by color name.
% - by color space parameters: Lab, LCh, XYZ, YUV, HSV, or RGB.
%
% The figure is resizeable (the colors flow to fit the axes) with a vertical
% scrollbar provided to view all of the colors (if required). A rudimentary
% zoom ability has also been implemented... but this is rather experimental!
%
% Note: Requires the function COLORNAMES and its associated MAT file (FEX 48155).
%
%% Input and Output Arguments %%
%
%%% Inputs (all inputs are optional):
%  palette   = CharRowVector, the name of a palette supported by COLORNAMES.
%  sortorder = CharRowVector, the color space sort parameters in the desired order,
%              eg: 'RGB', 'BRG', 'GRB', 'Lab', 'abL', etc, OR 'Alphabetical'.
%
%%% Outputs:
% none
%
% See also COLORNAMES COLORNAMES_CUBE COLORNAMES_DELTAE MAXDISTCOLOR COLORMAP

%% Figure Parameters %%
%
persistent fgh axh slh pah srh txh txs rgb coh prv
%
% Text lightness threshold:
thr = 0.54;
%
% Text margin, uicontrol and axes gap (pixels):
mrg = 5;
gap = 4;
sid = 20;
%
% Slider position:
yid = 0;
ymx = 0;
%
% Handle of outlined text:
prv = [];
%
pmt = 'Click on a colorname...';
%
%% Get COLORNAME Palettes %%
%
[fnm,csf] = colornames();
%
if nargin<1
	pnm = fnm{1+rem(round(now*1e7),numel(fnm))};
else
	assert(ischar(palette)&&isrow(palette),'First input <palette> must be a 1xN char.')
	idz = strcmpi(palette,fnm);
	assert(any(idz),'Palette ''%s'' is not supported. Call COLORNAMES() to list all palettes.',palette)
	pnm = fnm{idz};
end
%
%% Color Sorting List %%
%
% List of color spaces for sorting:
lst = {'Alphabetical','Lab','XYZ','LCh','YUV','HSV','RGB'};
[tsl,idt] = cellfun(@sort,lst,'UniformOutput',false);
% Get every permutation of the color spaces:
trs = cellfun(@(s)perms(s(end:-1:1)),lst(2:end),'UniformOutput',false);
trs = [lst(1);cellstr(vertcat(trs{:}))];
%
if nargin<2
	srt = lst{1};
else
	assert(ischar(order)&&isrow(order),'Second input <sort> must be a 1xN char.')
	idz = strcmpi(order,trs);
	assert(any(idz),'Second input must be one of:%s\b.',sprintf(' %s,',trs{:}))
	srt = trs{idz};
end
%
% Intial color sorting index:
idx = 1:numel(colornames(pnm));
%
%% Create a New Figure %%
%
if isempty(fgh)||~ishghandle(fgh)
	% Figure with zoom and pan functions:
	fgh = figure('HandleVisibility','callback', 'IntegerHandle','off',...
		'NumberTitle','off', 'Name','ColorNames View', 'Color','white',...
		'Toolbar','figure', 'Units','pixels', 'Tag',mfilename, 'Visible','on');
	%
	fgp = get(fgh,'Position');
	inh = uicontrol(fgh, 'Units','pixels', 'Style','text', 'HitTest','off',...
		'Visible','on',	'String','Initializing the figure... please wait.');
	inx = get(inh,'Extent');
	set(inh,'Position',[fgp(3:4)/2-inx(3:4)/2,inx(3:4)])
	%
	% Axes and scrolling slider:
	slh = uicontrol('Parent',fgh, 'Style','slider', 'Visible','off',...
		'Enable','on', 'Value',1, 'Min',0, 'Max',1,...
		'FontUnits','pixels', 'Units','pixels', 'Callback',@cnvSldClBk);
	axh = axes('Parent',fgh, 'Visible','off', 'Units','pixels',...
		'YDir','reverse', 'XTick',[], 'YTick',[], 'XLim',[0,1], 'YLim',[0,1]);
	% Palette and color sorting method drop-down menus:
	pah = uicontrol('Parent',fgh, 'Style','popupmenu', 'String',fnm,...
		'ToolTip','Color Scheme', 'Units','pixels',...
		'Visible','off', 'Callback',@cnvPalClBk);
	srh = uicontrol('Parent',fgh, 'Style','popupmenu', 'String',trs,...
		'ToolTip','Sort Colors', 'Units','pixels',...
		'Visible','off', 'Callback',@cnvSrtClBk);
	coh = uicontrol('Parent',fgh, 'Style','edit', 'String',pmt,...
		'ToolTip','RGB Value',   'Units', 'pixels', 'Visible','off',...
		'HorizontalAlignment','left', 'Enable','inactive');
else
	set(coh,'String',pmt)
end
set(pah,'Value',find(strcmpi(pnm,fnm)));
set(srh,'Value',find(strcmpi(srt,trs)));
%
fgo = get(fgh, 'Pointer');
set(fgh, 'Pointer','watch')
drawnow()
%
%% Callback Functions %%
%
	function cnvPalClBk(h,~) % Palette Menu CallBack
		% Select a new palette.
		pnm = fnm{get(h,'Value')};
		set(slh, 'Value',1)
		set(coh, 'String',pmt)
		set(fgh, 'Pointer','watch')
		drawnow()
		cnvTxtDraw()
		cnvSortBy()
		cnvResize()
		set(fgh, 'Pointer',fgo)
	end
%
	function cnvSrtClBk(h,~) % Sort-Order Menu CallBack
		% Select the color sorting method.
		srt = trs{get(h,'Value')};
		set(fgh, 'Pointer','watch')
		drawnow()
		cnvSortBy()
		cnvResize()
		set(fgh, 'Pointer',fgo)
	end
%
	function cnvSldClBk(h,~) % Slider CallBack
		% Scroll the axes by changing the axes limits.
		tmp = diff(get(axh,'Ylim'));
		set(axh, 'Ylim',[0,tmp] + (ymx-tmp)*(1-get(h,'Value')));
	end
%
	function cnvZoomClBk(~,~) % Zoom CallBack
		% Change the font and margin sizes.
		tmp = diff(get(axh,'Ylim'));
		set(txh, 'FontSize',txs/tmp);
		set(txh, 'Margin',mrg/tmp);
	end
%
	function cnvPanClBk(~,~) % Pan CallBack
		% Move the scroll-bar to match panning of the axes.
		tmp = get(axh,'Ylim');
		set(slh, 'Value',max(0,min(1,1-tmp(1)/(ymx-diff(tmp)))))
	end
%
%% Color Sorting %%
%
	function cnvSortBy()
		[tmp,ids] = sort(srt);
		idc = strcmp(tmp,tsl);
		ids = ids(idt{idc});
		switch lst{idc}
			case 'Alphabetical'
				idx = 1:numel(txh);
				return
			case 'RGB'
				mat = rgb;
			case 'HSV'
				mat = csf.rgb2hsv(rgb);
			case 'XYZ'
				mat = csf.rgb2xyz(rgb);
			case 'Lab'
				mat = csf.xyz2lab(csf.rgb2xyz(rgb));
			case 'LCh'
				mat = csf.lab2lch(csf.xyz2lab(csf.rgb2xyz(rgb)));
			case 'YUV' % BT.709
				mat = csf.invgamma(rgb) * [...
					+0.2126, -0.19991, +0.61500;...
					+0.7152, -0.33609, -0.55861;...
					+0.0722, +0.43600, -0.05639];
			otherwise
				error('Colorspace "%s" is not supported. How did this happen?',srt)
		end
		[~,idx] = sortrows(mat,ids);
	end
%
%% Re/Draw Text Strings %%
%
txf = @(s,b,c)text('Parent',axh, 'String',s, 'BackgroundColor',b,...
	'Color',c,'Margin',mrg, 'Units','data', 'Interpreter','none',...
	'VerticalAlignment','bottom', 'HorizontalAlignment','right',...
	'Clipping','on', 'ButtonDownFcn',{@txtClBk,s,b},'LineWidth',3);
%
	function txtClBk(hnd,~,s,bgd)
		try %#ok<TRYNC>
			set(prv, 'EdgeColor','none')
		end % setting one object is much faster than setting all objects.
		prv = hnd;
		%
		hxs = sprintf('%02X',round(bgd*255));
		dcs = sprintf(',%.5f',bgd);
		set(coh, 'String',sprintf('#%s [%s] %s',hxs,dcs(2:end),s));
		set(hnd, 'EdgeColor',max(0,min(1,1-bgd)))
		uistack(hnd,'top')
	end
%
	function cnvTxtDraw()
		% Delete any existing colors:
		delete(txh(ishghandle(txh)))
		% Get new colors:
		[cnc,rgb] = colornames(pnm);
		% Calculate the text color:
		baw = (rgb*[0.298936;0.587043;0.114021])<thr;
		% Draw new colors in the axes:
		txh = cellfun(txf,cnc,num2cell(rgb,2),num2cell(baw(:,[1,1,1]),2),'Uni',0);
		txh = reshape([txh{:}],[],1);
		txs = get(txh(1),'FontSize');
		prv = txh(1);
	end
%
%% Resize the Axes and UIControls, Move the Colors %%
%
	function cnvResize(~,~)
		%
		zoom(fgh,'out')
		%
		if nargin
			set(fgh, 'Pointer','watch')
			drawnow()
		end
		%
		ecv = get(prv, 'EdgeColor');
		set(prv, 'EdgeColor','none');
		%
		set(axh, 'Ylim',[0,1])
		set(txh, 'Units','pixels', 'FontSize',txs, 'Margin',mrg)
		txe = cell2mat(get(txh(:),'Extent'));
		top = get(slh,'FontSize')*2;
		fgp = get(fgh,'Position'); % [left bottom width height]
		hgt = round(fgp(4)-3*gap-top);
		wid = fgp(3)-3*gap-sid;
		pos = [gap,gap,wid,hgt];
		%
		% Calculate color lengths from text and margins:
		txw = 2*mrg+txe(idx,3);
		txc = cumsum(txw);
		% Preallocate position array:
		txm = mean(txw);
		out = zeros(ceil(1.1*[txc(end)/pos(3),pos(3)/txm]));
		% Split colors into lines that fit the axes width:
		idb = 1;
		idr = 0;
		tmp = 0;
		while idb<=numel(txc)
			idr = idr+1;
			idp = max([idb,find((txc-tmp)<=pos(3),1,'last')]);
			out(idr,1:1+idp-idb) = txc(idb:idp)-tmp;
			tmp = txc(idp);
			idb = idp+1;
		end
		% Calculate X and Y positions for each color:
		[~,txy,txx] = find(out.');
		yid = txy(end);
		txy = txy*(2*mrg+max(txe(idx,4)));
		ymx = txy(end)/pos(4);
		%
		% Resize the scrollbar, adjust scroll steps:
		nwp = [2*gap+wid,gap,sid,hgt];
		if ymx>1
			set(slh, 'Position',nwp, 'Enable','on', 'Value',1,...
				'SliderStep',max(0,min(1,[0.5,2]/(yid*(ymx-1)/ymx))))
		else
			set(slh, 'Position',nwp, 'Enable','off')
		end
		% Resize the axes and drop-down menus:
		set(axh, 'Position',pos)
		uiw = (fgp(3)-gap)/4-gap;
		txw = 2*uiw+gap;
		lhs = gap+(0:2)*(uiw+gap);
		bot = fgp(4)-top-gap;
		set(pah, 'Position',[lhs(1),bot,uiw,top])
		set(srh, 'Position',[lhs(2),bot,uiw,top])
		set(coh, 'Position',[lhs(3),bot,txw,top])
		% Move text strings to the correct positions:
		arrayfun(@(h,x,y)set(h,'Position',[x,y]),txh(idx),txx-mrg,pos(4)-txy+mrg);
		set(txh, 'Units','data')
		%
		set(prv, 'EdgeColor',ecv);
		%
		if nargin
			set(fgh, 'Pointer',fgo)
		end
		drawnow()
	end
%
%% Initialize the Figure %%
%
cnvTxtDraw()
cnvSortBy()
cnvResize()
set([pah,srh,coh,slh], 'Visible','on')
set(fgh, 'Pointer',fgo, 'ResizeFcn',@cnvResize)
set(zoom(fgh), 'ActionPostCallback',@cnvZoomClBk);
set(pan(fgh),  'ActionPostCallback',@cnvPanClBk);
try %#ok<TRYNC>
	delete(inh)
end
%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%colornames_view

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
% Script to find valve actuator parameters that match frequency response
% using the direct method (time domain).
% Copyright 2010 MathWorks, Inc.

% This script file is designed to find three parameters of the
% valve actuator: Gain, Time Constant, and Saturation, by directly
% measuring its frequency response to sinusoidal signal at frequency
% at which the phase shift of the real actuator equals -90 deg.
% The script analyzes the valve actuator at two input signals: 100% and
% The script invokes the optimization procedure which is set to find match
% between the required and actual frequency characteristics. The
% characteristics are compared by the phase shift values at specified
% frequencies.
% After the optimization is completed, the check of the
% obtained parameters is performed with the same direct measurement method.

% Specifying required frequencies at which -90 deg phase shift occurs
frequency_20 = 25;      % Frequency (Hz) at -90 deg shift angle and 20% input
frequency_100 = 10;     % Frequency (Hz) at -90 deg shift angle and 100% input

% Set initial value. x0 =[gain, time_const, saturation]
x0 = [300, 0.01, 0.8];

[x,fval,exitflag,output] = ...
    fminsearch(@obj_actuator_param_direct_method,x0, ...
    optimset('Tolx',1e-3,'Display','iter'),frequency_20,frequency_100);

check_frequency_response(x,frequency_20,frequency_100,'Direct');


text:
% Digital Video Stabilization and Rolling Shutter Correction using Gyroscopes
% Copyright (C) 2011 Alexandre Karpenko
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

function [dth, dths] = frame_rotations(gyro, gyro_time, frame_time, t0, ts)

dgt = diff(gyro_time);
theta = ((gyro(1:end-1,:) + gyro(2:end,:)) / 2) .* dgt(:,[1 1 1]);
theta = [0 0 0; cumsum(theta, 1)];
dths = lininterp(gyro_time + t0 + ts, theta, frame_time) - lininterp(gyro(:,4) + t0, theta, frame_time);

dth = diff(lininterp(gyro_time + t0, theta, frame_time));
%dth = diff(lininterp(gyro_time + t0 + ts/2, theta, frame_time));

author: alex-golts

repo: Video-Stabilization