text:
function varargout = BrainNetClass(varargin)

%BrainNet construction and classification toolbox (BrainNetClass) GUI by Zhen Zhou
%  Copyright(c) 2019; GNU GENERAL PUBLIC LICENSE
%  Image Display, Enhancement, and Analysis (IDEA) Group
%  Department of Radiology and Biomedical Research Imaging Center,
%  University of North Carolina, Chapel Hill, NC 27599, USA
%  Written by Zhen Zhou, Han Zhang
%  zzstefan@email.unc.edu, hanzhang@med.unc.edu

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

% Choose default command line output for BrainNetClass

Release='V1.1';
%handles.Release = Release; % Will be used in mat file version checking (e.g., in function SetLoadedData)

if ispc
    UserName =getenv('USERNAME');
else
    UserName =getenv('USER');
end
Datetime=fix(clock);
fprintf('Welcome: %s, %.4d-%.2d-%.2d %.2d:%.2d \n', UserName,Datetime(1),Datetime(2),Datetime(3),Datetime(4),Datetime(5));
fprintf('BrainNet construction and classification toolbox (BrainNetClass) GUI. \nRelease = %s\n',Release);
fprintf('Copyright(c) 2019; GNU GENERAL PUBLIC LICENSE\n');
fprintf('Image Display, Enhancement, and Analysis (IDEA) Group, Department of Radiology and Biomedical Research Imaging Center, University of North Carolina, Chapel Hill, NC 27599, USA;\n');
fprintf('Mail to Author:  Zhen Zhou Han Zhang');
fprintf('\n-----------------------------------------------------------\n');
fprintf('Citing Information:\nIf you think BrainNetClass is useful for your work, citing it in your paper would be greatly appreciated!\nReference: Zhou, Z., Chen, X., Zhang, Y., Qiao, L., Yu, R., Pan, G., Zhang, H., Shen, D., 2019. Brain network construction and classification toolbox (BrainNetClass). arXiv:1906.09908.\n');

BrainNetClassPath=fileparts(which('BrainNetClass.m'));

axes(handles.axes_logo);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'./Pics/logo.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

axes(handles.axes_arrow2);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'/Pics/arrow_down.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

axes(handles.axes6);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'/Pics/arrow_left.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

axes(handles.axes7);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'/Pics/arrow_down.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

axes(handles.axes8);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'/Pics/arrow_down2.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

axes(handles.axes9);
axis image;
[A, map, alpha] = imread(fullfile(BrainNetClassPath,'/Pics/arrow_down2.png'));
h = imshow(A, map);
set(h, 'AlphaData', alpha);

set(handles.lambda1,'Enable','off');
set(handles.lambda2,'Enable','off');
set(handles.clusters,'Enable','off');
%set(handles.step,'Enable','off');
set(handles.window_length,'Enable','off');
%set(handles.lasso_lambda,'Enable','off');
set(handles.sensitivity_test,'Enable','off');

% handles.default.lambda_1=[0.01:0.01:0.05];
% handles.default.lambda_2=[0.01:0.01:0.05];
% handles.default.clusters=[100:100:300];
% handles.default.window_length=[20:10:40];

handles.default.lambda_1=[0.01:0.01:0.1];
handles.default.lambda_2=[0.01:0.01:0.1];
handles.default.clusters=[100:100:800];
handles.default.window_length=[50:10:120];
handles.default.k_times=10;

% User can change the value of lasso_lambda and step
handles.default.lasso_lambda=0.05;
handles.default.step=1;

handles.cross_val='loocv';
set(handles.k_times,'Enable','off');
set(handles.k_times,'String',mat2str(handles.default.k_times));

No_parameter={'PC','tHOFC','aHOFC'};
Parameter_needed={'SR','WSR','SGR','WSGR','GSR','SSGSR','SLR','dHOFC'};
%set(handles.net_method,'String','Network Type I:  No Parameter Required');
set(handles.method_choice,'String',No_parameter);
handles.meth_Type='Network Type I:  No Parameter Required';
handles.meth_Net='PC';
% set(handles.pop_choice_fe,'value','Connection coefficients';
% set(handles.pop_choice_fs,'value','')
%set the initial radiobutton being selected

% axes(handles.axes_arrow1);
% arrow_p1=[0.5 1];
% arrow_p2=[0 -1];
% h=annotation('textarrow');
% set(h,'parent','postition',[arrow_p1 arrow_p2]);

% axes(handles.axes_arrow1);
% h_arrow_axis=annotation('textarrow');
% set(h_arrow_axis,'parent',gca,'position',[0.5 1],[0 -1]);

%uicontrol('Style','text','String',sprintf('Set \x3a9'),'units','characters','Position',[62.142857142857140,25.588235294117645,9.714285714285708,1.058823529411765]);

% handles.laxis = axes('parent',hObject,'units','normalized','position',[0 0 1 1],'visible','off');
% Find all static text UICONTROLS whose 'Tag' starts with latex_
%lbls = findobj(hObject,'-regexp','tag','latex_*');
% for i=1:length(lbls)
%       l = lbls(i);
%       % Get current text, position and tag
%       set(l,'units','normalized');
%       s = get(l,'string');
%       p = get(l,'position');
%       t = get(l,'tag');
%       % Remove the UICONTROL
%       delete(l);
%       % Replace it with a TEXT object
%       %handles.(t) = text(p(1),p(2),s,'interpreter','latex');
%       handles.(t) = text('position',p,'interpreter','latex','string','$\lambda$');
% end

% lbls=findobj(hObject,'-regexp','tag','lambda_1');
% p=get(lbls,'position');
% uicontrol('Style','text','Fontname','Calibri','FontSize',10,'String',sprintf('\x3bb_1'),'units','characters','Position',p);
%
% lbls=findobj(hObject,'-regexp','tag','lambda_2');
% p=get(lbls,'position');
% uicontrol('Style','text','Fontname','Calibri','FontSize',10,'String',sprintf('\x3bb_2'),'units','characters','Position',p);

% lbls=findobj(hObject,'-regexp','tag','lambda_lasso');
% p=get(lbls,'position');
% uicontrol('Style','text','Fontname','Calibri','String',sprintf('    \x3bb lasso for \n feature selection'),'units','characters','Position',p);

% Update handles structure
if ~ispc
    if ismac
        ZoomFactor=0.95;  %For Mac
    else
        ZoomFactor=0.8;  %For Linux
    end
    ObjectNames = fieldnames(handles);
    for i=1:length(ObjectNames);
        eval(['IsFontSizeProp=isprop(handles.',ObjectNames{i},',''FontSize'');']);
        if IsFontSizeProp
            eval(['PCFontSize=get(handles.',ObjectNames{i},',''FontSize'');']);
            FontSize=PCFontSize*ZoomFactor;
            eval(['set(handles.',ObjectNames{i},',''FontSize'',',num2str(FontSize),');']);
        end
    end
end

handles.output = hObject;
guidata(hObject, handles);

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

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

% p=[62.142857142857140,25.588235294117645,9.714285714285708,1.058823529411765];
% uicontrol('Style','text','String',sprintf('Set '),'Units','norm','Position',p);
% --- Executes on selection change in net_method.
function net_method_Callback(hObject, eventdata, handles)
% hObject    handle to net_method (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 net_method contents as cell array
%        contents{get(hObject,'Value')} returns selected item from net_method
% contents_net=cellstr(get(hObject,'String'));
% pop_choice_net=contents_net{get(hObject,'Value')};

% if isfield(handles,'meth_Net')
%     set(handles.net_method,'Enable','off');
%     handles=rmfield(handles,'meth_Net');
% end
popStrings_net = cellstr(get(hObject,'String'));
meth_Type=popStrings_net{get(hObject,'Value')};
No_parameter={'PC','tHOFC','aHOFC'};
Parameter_needed={'SR','WSR','SGR','WSGR','GSR','SSGSR','SLR','dHOFC'};
if strcmpi(meth_Type,'Network Type I:  No Parameter Required')

    set(handles.method_choice,'String',No_parameter);
    set(handles.method_choice, 'value', 1);
    set(handles.lambda1,'Enable','off');
    set(handles.lambda2,'Enable','off');
    %set(handles.lasso_lambda,'Enable','off');
    set(handles.clusters,'Enable','off');
    set(handles.window_length,'Enable','off');
    %set(handles.step,'Enable','off');
    set(handles.sensitivity_test,'Enable','off');
    set(handles.fe_method,'Enable','on');
    set(handles.fs_method,'Enable','on');
    set(handles.fe_method,'Value',1);
    set(handles.fs_method,'Value',1);
    meth_Net='PC';
    handles.meth_Net=meth_Net;
    set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf(''));
    set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf(''));
    set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf(''));
elseif strcmpi(meth_Type,'Network Type II: Parameter Required')
    if isfield(handles,'pop_choice_fe')
        handles=rmfield(handles,'pop_choice_fe');
    end
    if isfield(handles,'pop_choice_fs')
        handles=rmfield(handles,'pop_choice_fs');
    end
    set(handles.fs_method,'Value',4);
    set(handles.fe_method,'Value',2);
    set(handles.fe_method,'Enable','off');
    set(handles.fs_method,'Enable','off');
    set(handles.lambda1,'Enable','on','String',mat2str(handles.default.lambda_1));
    set(handles.sensitivity_test,'Value',1);
    %set(handles.method_choice, 'value', 1);
    set(handles.method_choice,'String',Parameter_needed);
    set(handles.sensitivity_test,'Enable','on');
    meth_Net='SR';
    handles.meth_Net=meth_Net;
    set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Lambda controls sparsity'));
    set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
    set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    %guidata(hObject,handles);
    if isfield(handles,'meth_Net')
        switch meth_Net
            case{'SR','WSR','GSR','SLR','SSGSR','WSGR','SGR'}
                set(handles.fs_method,'Value',4);
                set(handles.fe_method,'Value',2);
                set(handles.fe_method,'Enable','off');
                set(handles.fs_method,'Enable','off');
            case 'dHOFC'
                set(handles.fs_method,'Value',3);
                set(handles.fe_method,'Value',3);
                set(handles.fe_method,'Enable','off');
                set(handles.fs_method,'Enable','off');
        end
    end
end

handles.meth_Type=meth_Type;
guidata(hObject,handles);

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

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

% --- Executes on selection change in fs_method.
function fe_method_Callback(hObject, eventdata, handles)
% hObject    handle to fs_method (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 fs_method contents as cell array
%        contents{get(hObject,'Value')} returns selected item from fs_method
contents_fe=cellstr(get(hObject,'String'));
pop_choice_fe=contents_fe{get(hObject,'Value')};
switch pop_choice_fe
    case 'Feature Extraction Method'
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','string',sprintf(''));
        if isfield(handles,'pop_choice_fe')
        handles=rmfield(handles,'pop_choice_fe');
        end
    case 'Connection coefficients'
        tmp='coef';
        %handles.fe_method=tmp;
        handles.fe_display=pop_choice_fe;
        handles.pop_choice_fe=tmp;
        guidata(hObject,handles);
    case 'Local clustering coefficients'
        tmp='clus';
        %handles.fe_method=tmp;
        handles.fe_display=pop_choice_fe;
        handles.pop_choice_fe=tmp;
        guidata(hObject,handles);
end

if isfield(handles,'fe_method')&&~strcmpi(pop_choice_fe,'Feature Extraction Method')
    set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('%s as features',handles.fe_display));
end

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

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

% --- Executes on selection change in fs_method.
function fs_method_Callback(hObject, eventdata, handles)
% hObject    handle to fs_method (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 fs_method contents as cell array
%        contents{get(hObject,'Value')} returns selected item from fs_method
contents_fs=cellstr(get(hObject,'String'));
pop_choice_fs=contents_fs{get(hObject,'Value')};
handles.pop_choice_fs=pop_choice_fs;
guidata(hObject,handles);
if strcmpi(pop_choice_fs,'Feature Selection Method')
    set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','string',sprintf(''));
    if isfield(handles,'pop_choice_fe')
        handles=rmfield(handles,'pop_choice_fe');
    end
elseif isfield(handles,'fs_method')
    set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',...
        sprintf('%s for feature selection',pop_choice_fs));
end

% --- Executes during object creation, after setting all properties.
function fs_method_CreateFcn(hObject, eventdata, handles)
% hObject    handle to fs_method (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 edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

% --- Executes on selection change in method_choice.
function method_choice_Callback(hObject, eventdata, handles)
% hObject    handle to method_choice (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 method_choice contents as cell array
%        contents{get(hObject,'Value')} returns selected item from method_choice
% popStrings_net_2 = handles.method_choice.String;
% selectedIndex_net_2 = handles.method_choice.Value;
% meth_Net = popStrings_net_2{selectedIndex_net_2};
contents=cellstr(get(hObject,'String'));
meth_Net=contents{get(hObject,'Value')};
handles.meth_Net=meth_Net;
guidata(hObject,handles);

switch meth_Net
    case {'SR','WSR'}
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Lambda controls sparsity'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    case 'GSR'
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Lambda controls group sparsity'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    case 'SLR'
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Lambda 1 controls low_rank \nLambda 2 controls sparsity'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    case {'SGR','WSGR'}
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',...
            sprintf('Lambda 1 controls sparsity \nLambda 2 controls group sparsity'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    case 'SSGSR'
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',...
            sprintf('Lambda 1 controls group sparsity \nLambda 2 controls inter-subject LOFC-pattern similarity'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Connection coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('t-test (p<0.05) + LASSO for feature selection'));
    case 'dHOFC'
        set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Step normally set to 1'));
        set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('Local clustering coefficients as features'));
        set(handles.fs_details,'HorizontalAlignment','left','Fontname','Calibri','ForegroundColor',[0.3 0.75 0.93],'string',sprintf('LASSO for feature selection'));
end

if strcmp(meth_Net,'SR')||strcmp(meth_Net,'WSR')||strcmp(meth_Net,'GSR')
    set(handles.lambda2,'Enable','off');
    set(handles.window_length,'Enable','off');
    %set(handles.step,'Enable','off');
    set(handles.clusters,'Enable','off');
    set(handles.lambda1,'Enable','on','String',mat2str(handles.default.lambda_1));
    %set(handles.lasso_lambda,'Enable','on','String',num2str(handles.default.lasso_lambda));
    set(handles.sensitivity_test,'Enable','on');
    %set(handles.sensitivity_test,'ForegroundColor','k');
elseif strcmp(meth_Net,'SLR')||strcmp(meth_Net,'SGR')||strcmp(meth_Net,'WSGR')||strcmp(meth_Net,'SSGSR')
    set(handles.window_length,'Enable','off');
    %set(handles.step,'Enable','off');
    set(handles.clusters,'Enable','off');
    set(handles.lambda1,'Enable','on','String',mat2str(handles.default.lambda_1));
    %set(handles.lasso_lambda,'Enable','on','String',num2str(handles.default.lasso_lambda));
    set(handles.lambda2,'Enable','on','String',mat2str(handles.default.lambda_1));
    set(handles.sensitivity_test,'Enable','on');
    %set(handles.sensitivity_test,'ForegroundColor','k');
elseif strcmp(meth_Net,'dHOFC')
    set(handles.lambda1,'Enable','off');
    set(handles.lambda2,'Enable','off');
    %set(handles.lasso_lambda,'Enable','on','String',num2str(handles.default.lasso_lambda));
    set(handles.clusters,'Enable','on','String',mat2str(handles.default.clusters));
    set(handles.window_length,'Enable','on','String',mat2str(handles.default.window_length));
    %set(handles.step,'Enable','on','String',num2str(handles.default.step));
    set(handles.sensitivity_test,'Enable','on');
    %set(handles.sensitivity_test,'ForegroundColor','k');
end

switch meth_Net
    case{'SR','WSR','SLR','SGR','WSGR','GSR','SSGSR'}
        set(handles.fs_method,'Value',4);
        set(handles.fe_method,'Value',2);
        set(handles.fe_method,'Enable','off');
        set(handles.fs_method,'Enable','off');
    case 'dHOFC'
        set(handles.fs_method,'Value',3);
        set(handles.fe_method,'Value',3);
        set(handles.fe_method,'Enable','off');
        set(handles.fs_method,'Enable','off');
end

% --- Executes during object creation, after setting all properties.
function method_choice_CreateFcn(hObject, eventdata, handles)
% hObject    handle to method_choice (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 run_withparam.
function run_withparam_Callback(hObject, eventdata, handles)
% hObject    handle to run_withparam (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
sign_input=isfield(handles,'BOLD');
sign_output=isfield(handles,'result_dir');
sign_label=isfield(handles,'label');
sign_FEX=isfield(handles,'pop_choice_fe');
sign_FS=isfield(handles,'pop_choice_fs');

switch handles.meth_Type
    case 'Network Type I:  No Parameter Required'
       sign_all_char={'input data','output directory','label','feature extraction method','feature selection method'};
       sign_all_char=string(sign_all_char);

        sign_all=[sign_input,sign_output,sign_label,sign_FEX,sign_FS];
        if sum(sign_all)<5
            index=find(sign_all==0);
            temp='You need to specify: ';
            missing_inputs=length(index);
            i=1;
            while missing_inputs>=i
                if i==missing_inputs
                    temp=strcat(temp,sign_all_char(index(i)),'.');
                else
                    temp=strcat(temp,sign_all_char(index(i)),',',{' '});
                end
                i=i+1;
            end
            uiwait(msgbox(temp,'Warning','modal'));
            return;
        end
    case 'Network Type II: Parameter Required'
        sign_all_char={'input data','output directory','label'};
        sign_all_char=string(sign_all_char);
        sign_all=[sign_input,sign_output,sign_label];
        if sum(sign_all)<3
            index=find(sign_all==0);
            temp='You need to specify: ';
            missing_inputs=length(index);
            i=1;
            while missing_inputs>=i
                if i==missing_inputs
                    temp=strcat(temp,sign_all_char(index(i)),'.');
                else
                    temp=strcat(temp,sign_all_char(index(i)),',',{' '});
                end
                i=i+1;
            end
            uiwait(msgbox(temp,'Warning','modal'));
            return;
        end
end

BOLD=handles.BOLD;
[~,nROI]=size(BOLD{1});
label=handles.label;
nSubj=length(label);

result_dir=handles.result_dir;
if handles.sensitivity_test.Value==1
    para_test_flag=1;
else
    para_test_flag=0;
end

if strcmpi(handles.meth_Type,'Network Type I:  No Parameter Required')
    meth_Net=handles.meth_Net;
    meth_FEX=handles.pop_choice_fe;
    meth_FS=handles.pop_choice_fs;

%     memory_needed=nSubj*nROI*nROI*4/(1024*1024*1024);
%     msg=sprintf('The whole program needs at least %3.4f GB memory to run.',memory_needed);
%     uiwait(msgbox({msg,'If your the RAM of your computer is not enough,','you may change to another computer with larger RAM','or switch to the no-parameter required construction method!'},'modal','warn'));
%
    if strcmpi(handles.cross_val,'loocv')
        switch meth_FS
            case 't-test'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest]=no_param_select(result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_ttest);
            case 'LASSO'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_lasso]=no_param_select(result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                 if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_lasso);
            case 't-test + LASSO'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=no_param_select(result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                 if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_ttest,feature_index_lasso);
        end
    elseif strcmpi(handles.cross_val,'10-fold')
        switch meth_FS
            case 't-test'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest]=no_param_select_kfold(handles.default.k_times,result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                 if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_ttest);
            case 'LASSO'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_lasso]=no_param_select_kfold(handles.default.k_times,result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                 if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_lasso);
            case 't-test + LASSO'
                [AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=no_param_select_kfold(handles.default.k_times,result_dir,meth_Net,meth_FEX,meth_FS,BOLD,label,handles.default.lasso_lambda);
                 if AUC==0
                    uiwait(msgbox('AUC=0,you may need to add more samples or change a different feature extraction method.','Warning','modal'));
                    return;
                end
                [result_features]=back_find_low_node_Nopara(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,meth_FEX,meth_FS,feature_index_ttest,feature_index_lasso);
        end
    end
        write_log(result_dir,meth_Net,handles.cross_val,AUC,SEN,SPE,F1,Acc,Youden,BalanceAccuracy,meth_FEX,meth_FS,handles.default.k_times,handles.default.lasso_lambda);
else

    meth_Net=handles.meth_Net;
    switch meth_Net
        case {'SR','WSR','GSR'}
            memory_needed=nSubj*nROI*nROI*4*length(handles.default.lambda_1)/(1024*1024*1024);
        case {'SLR','SGR','WSGR','SSGSR'}
            memory_needed=nSubj*nROI*nROI*4*length(handles.default.lambda_1)*length(handles.default.lambda_2)/(1024*1024*1024);
        case 'dHOFC'
            memory_needed=sum(nSubj*4*length(handles.default.window_length)*(handles.default.clusters.*handles.default.clusters))/(1024*1024*1024);
    end
    msg=sprintf('The whole program needs at least %3.4f GB memory to run.',memory_needed);
    answer=questdlg({msg,'If the physical memory of your computer is not enough,','you may change to another PC or server/cluster with larger RAM','or switch to a method that does not need parameter tuning.'},...
        'Warning','Continue','Stop','Continue');
    switch answer
        case 'Continue'

        case 'Stop'
            error('Stop by user.');
    end

    if strcmpi(handles.cross_val,'loocv')
        switch meth_Net
            case {'SR','WSR','GSR'}
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=param_select(result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.lambda_1,handles.default.lasso_lambda);
            case {'SLR','SGR','WSGR','SSGSR'}
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=param_select(result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.lambda_1,handles.default.lambda_2,handles.default.lasso_lambda);
            case 'dHOFC'
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_lasso,IDX]=param_select(result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.window_length,handles.default.step,handles.default.clusters,handles.default.lasso_lambda);
        end
    elseif strcmpi(handles.cross_val,'10-fold')
        switch meth_Net
            case {'SR','WSR','GSR'}
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=param_select_kfold(handles.default.k_times,result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.lambda_1,handles.default.lasso_lambda);
            case {'SLR','SGR','WSGR','SSGSR'}
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_ttest,feature_index_lasso]=param_select_kfold(handles.default.k_times,result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.lambda_1,handles.default.lambda_2,handles.default.lasso_lambda);
            case 'dHOFC'
                [opt_paramt,opt_t,AUC,SEN,SPE,F1,Acc,w,Youden,BalanceAccuracy,feature_index_lasso,IDX]=param_select_kfold(handles.default.k_times,result_dir,meth_Net,BOLD,label,para_test_flag,handles.default.window_length,handles.default.step,handles.default.clusters,handles.default.lasso_lambda);
        end
    end

    switch meth_Net
        case {'SR','WSR','GSR'}
            [result_features]=back_find_low_node_para(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,feature_index_ttest,feature_index_lasso);
            write_log(result_dir,meth_Net,handles.cross_val,AUC,SEN,SPE,F1,Acc,Youden,BalanceAccuracy,handles.default.lambda_1,handles.default.lasso_lambda,opt_paramt,handles.default.k_times,opt_t);
        case {'SGR','WSGR','SSGSR','SLR'}
            [result_features]=back_find_low_node_para(result_dir,nSubj,handles.default.k_times,nROI,w,handles.cross_val,feature_index_ttest,feature_index_lasso);
            write_log(result_dir,meth_Net,handles.cross_val,AUC,SEN,SPE,F1,Acc,Youden,BalanceAccuracy,handles.default.lambda_1,handles.default.lambda_2,handles.default.lasso_lambda,opt_paramt,handles.default.k_times,opt_t);
        case 'dHOFC'
            [result_features]=back_find_high_node(handles.default.window_length,handles.default.clusters,nROI,w,feature_index_lasso,IDX,opt_t);
            write_log(result_dir,meth_Net,handles.cross_val,AUC,SEN,SPE,F1,Acc,Youden,BalanceAccuracy,handles.default.window_length,handles.default.step,handles.default.clusters,handles.default.lasso_lambda,opt_paramt,handles.default.k_times,opt_t);
    end
    set(handles.parameter,'string',opt_paramt);
end

save (char(strcat(result_dir,'/result_features.mat')),'result_features');
set(handles.Result_details,'HorizontalAlignment','left','Fontname','Calibri','FontSize',10,...
    'string',sprintf('AUC: %0.4g\nACC: %3.2f%%\nSEN: %3.2f%%\nSPE: %3.2f%%\nF-score: %3.2f%%',AUC,Acc,SEN,SPE,F1));

uiwait(msgbox('All Jobs Completed.','modal'));
% --- Executes on button press in select_dir.

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

folderName = uigetdir();
set(handles.data_dir,'string',folderName);
%
% file_extension=any(size(dir([folderName '/*.mat']),1));
% if file_extension==1
%     dirOutput=dir(fullfile(folderName,'*.mat'));
% else
%     dirOutput=dir(fullfile(folderName,'*.txt'));
% end
% fileName={dirOutput.name}';
% folder={dirOutput.folder}';
% [cs,index]=sort_nat(fileName);
% for i=1:length(fileName)
%     load([folder{i},'/',fileName{index(i)}]);
%     BOLD{i}=ROISignals;
% end
% handles.file_extension=file_extension;

file_extension=any(size(dir([folderName '/*.csv']),1));
if file_extension==1
    dirOutput=dir(fullfile(folderName,'*.csv'));
else
    dirOutput=dir(fullfile(folderName,'*.txt'));
end
fileName={dirOutput.name}';
%folder={dirOutput.folder}';
for i=1:length(fileName)
    BOLD{i,1}=load([folderName,'/',fileName{i}]);
end
handles.file_extension=file_extension;

handles.BOLD=BOLD;
guidata(hObject,handles);

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over parameter.
function parameter_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to parameter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

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

% --- Executes during object creation, after setting all properties.
function label_file_CreateFcn(hObject, eventdata, handles)
% hObject    handle to label_file (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 select_label.
function select_label_Callback(hObject, eventdata, handles)
% hObject    handle to select_label (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% if handles.file_extension ==1
%     [label_fileName,path]=uigetfile('.mat','please select the label file');
% else
%     [label_fileName,path]=uigetfile('.txt','please select the label file');
% end

[label_fileName,path]=uigetfile('.txt','please select the label file');

label=importdata(fullfile(path,label_fileName));

set(handles.label_file,'string',label_fileName);

handles.label=label;
guidata(hObject,handles);

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

% lambda_1=get(hObject,'String');
% temp=strsplit(lambda_1,' ');
% lambda_1=str2double(temp);
% handles.lambda_1=lambda_1;
% guidata(hObject,handles);
lambda_1=get(hObject,'String');
handles.default.lambda_1=eval(['[',lambda_1,']']);
guidata(hObject,handles);

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

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

function lambda2_Callback(hObject, eventdata, handles)
% hObject    handle to lambda2 (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 lambda2 as text
%        str2double(get(hObject,'String')) returns contents of lambda2 as a double
% lambda_2=get(hObject,'String');
% temp=strsplit(lambda_2,' ');
% lambda_2=str2double(temp);
% handles.lambda_2=lambda_2;
% guidata(hObject,handles);

lambda_2=get(hObject,'String');
handles.default.lambda_2=eval(['[',lambda_2,']']);
guidata(hObject,handles);

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

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

function window_length_Callback(hObject, eventdata, handles)
% hObject    handle to window_length (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 window_length as text
%        str2double(get(hObject,'String')) returns contents of window_length as a double
% window_length=get(hObject,'String');
% temp=strsplit(window_length,' ');
% window_length=str2double(temp);
% handles.window_length=window_length;
% guidata(hObject,handles);

window_length=get(hObject,'String');
handles.default.window_length=eval(['[',window_length,']']);
guidata(hObject,handles);

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

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

function clusters_Callback(hObject, eventdata, handles)
% hObject    handle to clusters (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 clusters as text
%        str2double(get(hObject,'String')) returns contents of clusters as a double
% clusters=get(hObject,'String');
% temp=strsplit(clusters,' ');
% clusters=str2double(temp);
% handles.clusters=clusters;
% guidata(hObject,handles);

clusters=get(hObject,'String');
handles.default.clusters=eval(['[',clusters,']']);
guidata(hObject,handles);

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

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

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

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

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

% Hint: place code in OpeningFcn to populate axes1

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

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

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

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

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

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

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

% --- Executes during object creation, after setting all properties.
function output_dir_CreateFcn(hObject, eventdata, handles)
% hObject    handle to output_dir (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 select_outdir.
function select_outdir_Callback(hObject, eventdata, handles)
% hObject    handle to select_outdir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
folderName = uigetdir();
handles.result_dir=folderName;
set(handles.output_dir,'string',folderName);
guidata(hObject,handles);

% --- Executes when selected object is changed in uibuttongroup1.
function uibuttongroup1_SelectionChangedFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uibuttongroup1
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
switch(get(eventdata.NewValue,'Tag'))
    case 'loocv'
        handles.cross_val=get(handles.loocv,'string');
        set(handles.k_times,'Enable','off');
    case 'k_fold'
        handles.cross_val=get(handles.k_fold,'string');
        set(handles.k_times,'Enable','on');
end
guidata(hObject,handles);

function k_times_Callback(hObject, eventdata, handles)
% hObject    handle to k_times (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 k_times as text
%        str2double(get(hObject,'String')) returns contents of k_times as a double
k=get(hObject,'String');
handles.default.k_times=eval(['[',k,']']);
guidata(hObject,handles);

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

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

% function reset_para(handles)
%     set(handles.window_length,'Enable','off');
%     %set(handles.step,'Enable','off');
%     set(handles.clusters,'Enable','off');
%     set(handles.lambda1,'Enable','off');
%     %set(handles.lasso_lambda,'Enable','off');
%     set(handles.lambda2,'Enable','off');
%     set(handles.sensitivity_test,'Enable','off');
%     set(handles.lambda_details,'HorizontalAlignment','left','Fontname','Calibri','string',sprintf(''));
%     set(handles.fe_details,'HorizontalAlignment','left','Fontname','Calibri','string',sprintf(''));
%     set(handles.fe_method,'Enable','on');
%     set(handles.fs_method,'Enable','on');
%     set(handles.fe_method,'Value',1);
%     set(handles.fs_method,'Value',1);

author: zzstefan

repo: BrainNetClass


text:
function complextest_AD3()
% Test AD for a complex optimization problem on a manifold which is stored
% in a particular data structure which is recursively defined by a struct,
% an array and a cell.

    % Verify that Manopt was indeed added to the Matlab path.
    if isempty(which('spherecomplexfactory'))
        error(['You should first add Manopt to the Matlab path.\n' ...
		       'Please run importmanopt.']);
    end

    % Verify that the deep learning tool box was installed
    assert(exist('dlarray', 'file') == 2, ['Deep learning tool box is '...
    'needed for automatic differentiation.\n Please install the'...
    'latest version of the deep learning tool box and \nupgrade to Matlab'...
    ' R2021b if possible.'])

    % Generate the problem data.
    n = 100;
    A = randn(n) + 1i*randn(n);
    A = .5*(A+A');

    % Create the manifold
    S = spherecomplexfactory(n);
    P = powermanifold(S,1); % cell
    X.x = S;
    X.y = P;
    problem.M = productmanifold(X); % struct

    % For Matlab R2021b or later, define the problem cost function as usual
    % problem.cost  = @(X) -real(X.x'*A*X.y{1});

    % For Matlab R2021a or earlier, translate the cost function into a
    % particular format with the basic functions in /functions_AD
    problem.cost  = @(X) -creal(cprod(cprod(ctransp(X.x), A), X.y{1}));

    % Define the gradient and the hessian via automatic differentiation
    problem = manoptAD(problem);

    % Numerically check gradient and Hessian consistency.
    figure;
    checkgradient(problem);
    figure;
    checkhessian(problem);

    % Solve.
    [x, xcost, info] = trustregions(problem);          %#ok<ASGLU>

    % Test
    ground_truth = svd(A);
    distance = abs(ground_truth(1) - (-problem.cost(x)));
    fprintf('The distance between the ground truth and the solution is %e \n',distance);

end

author: NicolasBoumal

repo: manopt


text:
function hFig = view_mri_histogram( MriFile )
% VIEW_MRI_HISTOGRAM: Compute and view the histogram of a brainstorm MRI.
%
% USAGE:  hFig = view_mri_histogram( MriFile );
%
% INPUT:
%    - MriFile : Full path to a brainstorm MRI file
% OUTPUT:
%    - hFig    : Matlab handle to the figure where the histogram is displayed
% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2006-2020

%% ===== COMPUTE HISTOGRAM =====
% Display progress bar
bst_progress('start', 'View MRI historgram', 'Computing histogram...');
% Load full MRI
MRI = load(MriFile);
% Compute histogram
Histogram = mri_histogram(MRI.Cube(:,:,:,1));
% Save histogram
s.Histogram = Histogram;
bst_save(MriFile, s, 'v7', 1);

%% ===== DISPLAY HISTOGRAM =====
% Create figure
hFig = figure('Name',        'MRI Histogram', ...
              'Color',        get(0,'defaultUicontrolBackgroundColor'), ...
              'Pointer',      'arrow', ...
              'NumberTitle',  'off', ...
              'DockControls', 'off', ...
              'Menubar',      'none', ...
              'Toolbar',      'figure');
% Adapt figure size
figPos = get(hFig, 'Position');
set(hFig, 'Position', figPos+[0 0 20 40]);
% Get maximum value
maxVal = max(cat(1,Histogram.max.y));
% If a maximum value was found, used this value to limit the Y axis
if (maxVal<1)
    maxVal = max(Histogram.smoothFncY);
end
bar(Histogram.fncX + 0.5, Histogram.fncY);
% White background
hWndComponents = get(hFig, 'Children');
i = 1;
while (~isequal(get(hWndComponents(i), 'Type'), 'axes') && (i <= length(hWndComponents)))
    i = i + 1;
end
if (i > length(hWndComponents))
    return;
end
hAxes = hWndComponents(i);
set(hAxes, 'Color', [1 1 1]);
hold on;
% Plot all the curves
plot(Histogram.smoothFncX +0.5, Histogram.smoothFncY, 'r');
plot(Histogram.fncX + 0.5, Histogram.cumulFncY .* maxVal.*1.2, 'g');
plot(cat(1,Histogram.max.x), cat(1,Histogram.max.y), 'r^', 'MarkerFaceColor', 'r', 'MarkerSize', 7);
plot(cat(1,Histogram.min.x), cat(1,Histogram.min.y), 'rv', 'MarkerFaceColor', 'g', 'MarkerSize', 7);
% Define axis labels and limits
xlabel('Intensity value');
ylabel('Number of voxels');
yLimits = [0 maxVal*1.3];
ylim(yLimits);
% Display background and white matter thresholds
line([Histogram.bgLevel, Histogram.bgLevel], yLimits, 'Color','b');
line([Histogram.whiteLevel, Histogram.whiteLevel], yLimits, 'Color','y');
h = legend('MRI hist.','Smoothed hist.','Cumulative hist.','Maxima','Minima',...
    'Scalp or grey thresh.','White m thresh.');
set(h, 'FontSize',  bst_get('FigFont'), ...
       'FontUnits', 'points');

% Hide progress bar
bst_progress('stop');

author: brainstorm-tools


text:
%  Figure 7.65      Feedback Control of Dynamic Systems, 6e
%                        Franklin, Powell, Emami
% script to generate Fig. 7.65
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Robust Servo Example
% Example 7.36; Figure 7.65
clf;
F=[0 1; 0 -1];
G=[0;1];
H=[1 0];
J=[0];
omega=1;
a=[0 1 0 0;-omega*omega 0 1 0;0 0 0 1;0 0 0 -1];
b=[0;0;G];

% desired closed-loop poles
pc=[-1+sqrt(3)*j;-1-sqrt(3)*j;-sqrt(3)+j;-sqrt(3)-j];
k=place(a,b,pc);

% form controller matrices
k1=k(:,1:2);
ko=k(:,3:4);
ac=[0 1;-omega*omega 0];
bc=-[k(2);k(1)];;
cc=[1 0];
dc=[0];

% closed-loop system
acl=[F-G*ko G*cc;bc*H ac];
bcl=[0;0;-bc];
ccl=[H 0 0];
dcl=[0];
syscl=ss(acl,bcl,ccl,dcl);
pole(syscl)
tzero(syscl)

% blocking zeros
dcle=-1;
syse=ss(acl,bcl,ccl,dcle);
tzero(syse)

% Closed-loop response
t=0:.01:25;
r=sin(t);
y=lsim(syscl,r,t);

% blocking zeros from w to y
G1=[0;1;0;0];
sysclw=ss(acl,G1,ccl,dcl);
tzero(sysclw)

% closed-loop response from w to y
w=sin(t);
y=lsim(sysclw,w,t);
figure(1)
plot(t,y,t,w);
text(0.5,0.9,'w');
text(1.5,0.1,'y');
xlabel('Time (sec)');
ylabel('Disturbance, output');
title('Fig. 7.65 (a): Disturbance response');
nicegrid;

% control effort
cclu=[-ko cc];
dclu=[0];
sysclu=ss(acl,G1,cclu,dclu);
u=lsim(sysclu,w,t);
figure(2)
plot(t,u);
xlabel('Time (sec)');
ylabel('Control, u');
title('Fig. 7.65 (b): Control effort');
nicegrid;

% error signal
ccle=[-H 0 0];
dcle=[0];
syscle=ss(acl,G1,ccle,dcle);
e=lsim(syscle,w,t);
figure(3)
plot(t,e);
xlabel('Time (sec)');
ylabel('Error, e');
title('Fig. 7.65 (c): Tracking error signal')
nicegrid

author: Sable

repo: mcbench-benchmarks


text:
function TV = compute_total_variation(y, options)

% compute_total_variation - compute the total variation of an image
%
%   TV = compute_total_variation(y, options);
%
%   See also: perform_tv_projection, grad, div.
%
%   Copyright (c) 2007 Gabriel Peyre

options.null = 0;

nbdims = 2;
if size(y,1)==1 || size(y,2)==1
    nbdims = 1;
end
if size(y,1)>1 && size(y,2)>1 && size(y,3)>1
    nbdims = 3;
end

if nbdims==1
    TV = sum( abs(diff(y)) );
    return;
end

weight_tv = getoptions(options, 'weight_tv', ones(size(y)) );
tv_norm = getoptions(options,'tv_norm', 'l2');

% options.bound = 'per';
g = grad(y, options);

switch tv_norm
    case 'l2'
        TV = sqrt( sum(g.^2,nbdims+1) );
    case 'l1'
        TV = sum( abs(g),nbdims+1);
    case 'linf'
        TV = max( abs(g),[],nbdims+1);
    otherwise
        error('Unknown norm.');
end
TV = TV .* weight_tv;
TV = sum(TV(:));

author: gpeyre

repo: matlab-toolboxes


text:
function [report_data] = report_convergence(report_data, state)
% Report convergence of the algorithm

% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$

if ~isfield(report_data, 'report_interval')
  report_data.report_interval = 5;
  dss_message(state, 2, sprintf('Setting default report interval to %d (report_data.report_interval)\n', report_data.report_interval));
end

% deflation
if state.iteration==1
  % -- first iteration
  if state.algorithm=='defl'
    % deflation
    report_data.change(state.component,1)=0;
    report_data.deltaw_old=state.w;
  else
    % symmetric
    report_data.change = zeros(size(state.W, 1),1);
    report_data.dW_old = zeros(size(state.W));
    report_data.W_old = state.W;
  end
else
  % -- iterations 2->
  if (mod(state.iteration, report_data.report_interval)==0)
    if state.algorithm=='defl'
      % deflation
      change = acos(state.w' * state.w_old/norm(state.w)/norm(state.w_old)) / pi * 180;
    else
      % symmetric
      change = abs(angle(state.W, state.W_old)) / pi * 180;
    end
    message(state,1,sprintf('Change (angles): %d\n', change));
  end
end

% -----------------------------------
function rad = angle(A, B)

sum_cross = sum(A .* B, 2);
sum_A = sum(A .* A, 2);
sum_B = sum(B .* B, 2);
rad = acos(sum_cross ./ sum_A.^(-1/2) ./ sum_B.^(-1/2));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function writePOLY_triangle(varargin)
  % WRITEPOLY_TRIANGLE prints a vertices to a .poly file, with E connecting
  % those vertices OR triangels made from F. Suitable for use with TRIANGLE
  %
  % writePOLY_triangle(filename,poly_struct)
  % writePOLY_triangle(filename,V,E,H)
  %
  % Input
  %   filename:  name of output file as string (caution! will clobber
  %                    existing)
  %   poly:      struct array where each element contains fields:
  %                    x,y,hole
  %     OR
  %   V  #V by dim=2 list of vertex positions
  %   E  #E by 2 list of edges E
  %   H  #H by dim list of hole positions
  %     OR
  %   V  #V by dim list of vertex positions
  %   F  #F struct containing polygon information arrays
  %     .facets  a #facets list of facets, each facet is a again a list of
  %       polygons (currently all polygons of a facet must be same valence)
  %     .boundary_markers a #facets list of boundary_markers
  %     .holes  a #facets list of holes, each holes entry is again a list for
  %       each facet
  %   H  #H by dim list of hole positions
  %
  % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)
  %
  % See also: png2objandtga, png2poly, writePOLY_tetgen
  %

  if(nargin == 4)
    filename = varargin{1};
    V = varargin{2};
    E = varargin{3};
    H = varargin{4};
  elseif(nargin == 2)
    filename = varargin{1};
    poly = varargin{2};
    [V,E,H] = poly2VEH(poly);
  else
    error('Wrong number of inputs');
  end
  % open file for writing
  poly_file_handle = fopen(filename,'w');

  % dimensions in V, should be 2: triangle format
  dim = size(V,2);
  if isempty(V)
    if isstruct(E)
      % min polygon size
      ms = min(cell2mat(cellfun(@size,E.facets,'UniformOutput',false)),[],1);
      dim = ms(2);
    else
      dim = size(E,2);
    end
    if isempty(E)
        dim = 2;
    end
  end

  if dim ~= 2
    error('writePOLY_triangle is for 2d meshes. Try writePOLY_tetgen etc.');
  end

  % vertices section
  format = '%d %.17g %.17g\n';

  fprintf(poly_file_handle,'# Part 1 - node list\n');
  fprintf(poly_file_handle,'%d %d 0 0\n', size(V,1),size(V,2));
  if ~isempty(V)
    fprintf(poly_file_handle,format,[1:size(V,1);V']);
  end
  % The following became convoluted because of ancient merge and unmerge with
  % writePOLY_tetgen.m
  if isstruct(E)
    F = E;
  else
    F = [];
    F.facets = mat2cell(E,ones(size(E,1),1),size(E,2));
    F.boundary_marker = ones(size(E,1),1);
    F.holes = cell(numel(F.facets),1);
  end
  fprintf(poly_file_handle,'# Part 2 - facet list\n');
  % for now, always include boundary markers
  % [num facets] [boundary markers]
  assert(isempty(F.facets) || iscell(F.facets));
  fprintf(poly_file_handle,'%d %d\n',numel(F.facets),1);
  % the triangle .poly format is slightly different
  fprintf(poly_file_handle,'%d %d %d %d\n', ...
    [1:numel(F.facets); [cell2mat(F.facets) F.boundary_marker]']);
  % [num holes]
  fprintf(poly_file_handle,'# Part 3 - hole list\n');
  fprintf(poly_file_handle,'%d\n',size(H,1));
  if ~isempty(H)
    assert(isempty(V) || size(H,2) == size(V,2));
    fprintf(poly_file_handle,format,[1:size(H,1);H']);
  end
  % not supported
  fprintf(poly_file_handle,'# Part 4 - region list\n');
  fprintf(poly_file_handle,'0\n');

  fprintf(poly_file_handle,'\n');
  fclose(poly_file_handle);
end

author: alecjacobson

repo: gptoolbox


text:
%% Spherical Harmonics
%
%%
% The spherical harmonics are special functions on the 2-sphere $\mathbb S^2$.
% In terms of polar coordinates
% ${\bf \xi} = (\sin \theta \cos \rho, \sin \theta \sin \rho, \cos \theta)$ the
% spherical harmonic of degree $m$ and order $l$ is defined by
%
% $$ Y_m^l({\bf \xi}) = \sqrt{\frac{2m+1}{4\pi}}P_m^{|l|}(\cos\rho)\mathrm e^{\mathrm i l\theta} $$
%
% where $P_m^{|l|}$, $m \in {\bf N_0}$, and $ l = -m, \ldots m$ denote the
% associated Legendre-Polynomials.
%
% We get the function values of the spherical harmonics of degree 1 in a
% point v by the command |sphericalY|, i.e.

v = vector3d.X
sphericalY(1,v)

%%
% The spherical harmonics form an orthonormal basis in $L_2(\mathbb S^2)$.
% Hence we describe functions on the 2-sphere by there harmonic
% representation using the class <S2FunHarmonicRepresentation.html
% S2FunHarmonic>.
%
% With that we define the spherical harmonic $Y_1^1$ by

Y = S2FunHarmonic([0;0;0;1])
Y.eval(v)

%%
% Various normalizations for the sperical harmonics are common in the
% literature.
%
% Here we define the $L_2$-norm by
%
% $$ \| f \|_2 = \left(\int_{\mathrm{sphere}} |f(\xi)|^2 \,\mathrm d\xi\right)^{1/2} $$
%
% such that $ \| 1 \|_2^2 = 1$. Take a look on the section
% <S2FunOperations.html#5 Integration of S2Fun's>.
%
% Using that definition the spherical harmonics in MTEX fulfill
%
% $$\| Y_m^l \|_2 = 1$$ for all $m,l$.
%

norm(Y)

%%
% To concluse this section we plot the first ten spherical harmonics

surf(S2FunHarmonic(eye(10)))

author: mtex-toolbox

repo: mtex

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


text:
function plotFTresult(u,x);
%
%  Plots the piecewise constant function u with discontinuities at x
%
[nc n]=size(u);   % nc = number of components
dp=0.8/nc;dpp=0.05;
for j=1:nc
  yhigh=max(u(j,:)); ylow=min(u(j,:));
  if ylow==yhigh,
    ylow=yhigh-0.5;
    yhigh=ylow+1;
  end;
  dy=0.05*(yhigh-ylow);
  if x(1)==x(n-1),
    xlow=x(1)-0.5;
    xhigh=xlow+1.0;
  else
    xhigh=x(n-1);
    xlow=x(1);
  end;
  dx=0.025*(xhigh-xlow);
  axis([xlow-dx,xhigh+dx,ylow-dy,yhigh+dy]);
  set(gca,'Box','on');
  x1=xlow-dx;
  for i=1:n-1
    line([x1 x(i)],[u(j,i) u(j,i)]);
    x1=x(i);
    line([x1 x1],[u(j,i) u(j,i+1)]);
  end;
  line([x1 xhigh+dx],[u(j,n),u(j,n)]);
end;

repo: Aero-matlab


text:
%POSTANIMATE Plot and animate solution.
%
%   [ M ] = POSTANIMATE( PROB, VARARGIN ) Postprocessing function to
%   plot and animate FEATool solutions. PROB is a valid finite element
%   problem struct. If an IMGNAME is given video or frames will be
%   saved in the corresponding IMGFMT (images will be appended with
%   the frame number before the image file extension). Optionally also
%   returns image frames in the struct M that can be played with the
%   movie command. Accepts the following property/value pairs as for
%   postplot and the following additional properties
%
%       Property    Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       start       integer/{1}               Solution to start animation
%       step        integer/{1}               Step size (positive/negative integer)
%       end         integer/{end}             Solution to end animation
%       pause       scalar/{0}                Pause between frame generation (seconds)
%       imgname     string/{}                 Image/video base filename
%       imgfmt      png,mp4,avi/{jpeg}        Output image/video format
%
% See also POSTPLOT, MOVIE, VIDEOWRITER, PRINT

% Copyright 2013-2022 Precise Simulation, Ltd.

author: precise-simulation

repo: featool-multiphysics


text:
% Load Alan
x=imread('Alan.jpg','jpg');

% Crop Alan
startx=100;
starty=300;

N=256;
xg=double(x(startx:startx+N-1,starty:starty+N-1,2));
xg=xg-mean(mean(xg));

% Maximum latent space dimension
q=100;
pca=spm_vpca(xg,q);

figure; imagesc(pca.M_w); colormap gray; title('Bayes estimate');
figure; imagesc(pca.ml.W(:,1:q)); colormap gray; title('ML estimate');

figure
plot(pca.Fm_evol);
xlabel('Iterations');
ylabel('Neg. Free Energy');

figure
plot(pca.ml.lambda);
title('Eigenspectrum');

figure
plot(pca.mean_alpha);
title('Prior precision of factors');

author: spm


text:
function p = pscale(p,alpha,var)
%PSCALE       scale of argument by alpha
%
%For a polynomial p and scalar alpha, scaling with repect to "var".
%
%  call:     q = pscale(p,alpha,var)
%  result:   q{x} = p{alpha*x}    for x denoting the dependent variable (or var).
%
%For univariate polynomial p the parameter "var" is optional (default: dependent variable).
%
%If p does not depend on var, function is executed, possibly with warning, or an error message
%  is given depending on setting of 'AccessVariable', see polynominit
%
%Execution with error bounds in case p or alpha of type intval
%

% written  07/17/02     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  if size(p.e,2)<=1                               % univariate polynomial
    if ( nargin==3 ) & ~isequal(var,p.v)          % polynomial not depending on specified variable
      INTLAB_POLYNOM_ACCESS_VARIABLE = getappdata(0,'INTLAB_POLYNOM_ACCESS_VARIABLE');
      switch INTLAB_POLYNOM_ACCESS_VARIABLE
        case 1, warning('polynomial does not depend on specified variable')
        case 2, error('polynomial does not depend on specified variable')
      end
      if rndold
        setround(rndold)
      end
      return
    end
    n = p.e;                                      % degree of polynomial
    p.c = ( alpha.^(n:-1:0) ) .* p.c ;
  else                                            % multivariate polynomial
    if ~ischar(var)                               % dependent variable must be string
      error('dependent variable must be string')
    end
    index = find(strcmp(p.v,var));                % index of dependent variable
    if isempty(index)                             % polynomial not depending on specified variable
      INTLAB_POLYNOM_ACCESS_VARIABLE = getappdata(0,'INTLAB_POLYNOM_ACCESS_VARIABLE');
      switch INTLAB_POLYNOM_ACCESS_VARIABLE
        case 1, warning('polynomial does not depend on specified variable')
        case 2, error('polynomial does not depend on specified variable')
      end
      if rndold
        setround(rndold)
      end
      return
    end
    p.c = ( alpha.^p.e(:,index) ) .* p.c;
  end

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
% -*- INTERNAL UNDOCUMENTED FUNCTION -*-
function sp = sp_nurbs_2d (varargin)

warning ('geopdes:obsolete', 'The class SP_NURBS_2D is obsolete. Using SP_NURBS instead')

sp = sp_nurbs (varargin{:});

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
function f=loglikGaPExp(x, varargin)
% f=loglikGaP(x, varargin)
% complete log likellihood of the GaP model
% Vxt = varargin{1};      %data
% sigpsf = varargin{2};  %std deviation of the PSF gaussian approx
% alpha = varargin{3}; %parameters of the Gamma prior on the blinking
% beta = varargin{4}; %parameters of the Gamma prior on the blinking
% peval = varargin{5}; %parameters
% x(1:end-2*peval.ncomp) is Hkt

Vxt = varargin{1};      %data
sigpsf = varargin{2};  %std deviation of the PSF gaussian approx
alpha = varargin{3}; %parameters of the Gamma prior on the blinking
beta = varargin{4}; %parameters of the Gamma prior on the blinking
peval = varargin{5}; %parameters

[Hkt_r, cx, cy, Wxk] = loglikGaPreadparam(x,varargin);
Hkt=exp(Hkt_r); %nonnegativity constrains

[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);
P=Wxkbg*Hktbg; %current approximation

%Poisson contribution
t1=Vxt.*log(P) - P;
%Gamma contribution
t2=(alpha-1)*log(Hkt)-1/beta*Hkt-alpha*log(beta)-log(gamma(alpha));

f=sum(t1(:))+sum(t2(:));
f=-f; %conjugate gradient is mimimizing!
end

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function tests = test_spm_dcm_identify
% Unit Tests for test_spm_dcm_identify
%__________________________________________________________________________
% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging

% $Id: test_spm_dcm_identify.m 7479 2018-11-09 14:17:33Z peter $

tests = functiontests(localfunctions);

% -------------------------------------------------------------------------
function test_identify_dcm_fmri(testCase)

data_path = get_data_path();

DCM = load(fullfile(data_path,'DCM_fMRI.mat'));
DCM = DCM.DCM;

model = spm_dcm_identify(DCM);

testCase.assertEqual(model,'fMRI');

% -------------------------------------------------------------------------
function test_identify_dcm_fmri_csd(testCase)

data_path = get_data_path();

DCM = load(fullfile(data_path,'DCM_fMRI_CSD.mat'));
DCM = DCM.DCM;

model = spm_dcm_identify(DCM);

testCase.assertEqual(model,'fMRI_CSD');

% -------------------------------------------------------------------------
function test_identify_erp(testCase)

data_path = get_data_path();

DCM = load(fullfile(data_path,'DCM_IMG_ERP_CMC.mat'));
DCM = DCM.DCM;

model = spm_dcm_identify(DCM);

testCase.assertEqual(model,'ERP');

% -------------------------------------------------------------------------
function test_identify_csd(testCase)

data_path = get_data_path();

DCM = load(fullfile(data_path,'DCM_LFP_CSD_CMC.mat'));
DCM = DCM.DCM;

model = spm_dcm_identify(DCM);

testCase.assertEqual(model,'CSD');

% -------------------------------------------------------------------------
function test_identify_ind(testCase)

data_path = get_data_path();

DCM = load(fullfile(data_path,'DCM_IND.mat'));
DCM = DCM.DCM;

model = spm_dcm_identify(DCM);

testCase.assertEqual(model,'IND');

% -------------------------------------------------------------------------
function data_path = get_data_path()

data_path = fullfile( spm('Dir'), 'tests', ...
    'data', 'test_spm_dcm_identify');


text:
function lit = haslight(axish)
%HASLIGHT Check if axis handle has a light attached
%
%Syntax
% lit = haslight(axish);
%
%Description
% LIT = HASLIGHT(AXISH) sets LIT to true if the axis specified by axis
% handle AXISH has a child of type 'light', and sets LIT to false otherwise.
%
%Examples
% > lit=haslight(gca)
% lit =
%      1

% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.
% $Revision 1.10 $ $Date 2005-06-01 $
% Documentation files renamed
% $Revision 1.00 $ $Date 2005-02-12 $
%
% For licensing, see COPYING.
% For references, see AUTHORS.
% For revision history, see CHANGELOG.

lit = false;
ch = get(axish,'Children');

for k = 1:length(ch)
    type = get(ch(k),'Type');
    if strcmp(type,'light')
        lit = true;
        return;
    end
end
%
%end function

repo: gspbox


text:
function expmat = MatrixLog6(T)
% *** CHAPTER 3: RIGID-BODY MOTIONS ***
% Takes a transformation matrix T in SE(3).
% Returns the corresponding se(3) representation of exponential
% coordinates.
% Example Input:
%
% clear; clc;
% T = [[1, 0, 0, 0]; [0, 0, -1, 0]; [0, 1, 0, 3]; [0, 0, 0, 1]];
% expmat = MatrixLog6(T)
%
% Output:
% expc6 =
%         0         0         0         0
%         0         0   -1.5708    2.3562
%         0    1.5708         0    2.3562
%         0         0         0         0

[R, p] = TransToRp(T);
omgmat = MatrixLog3(R);
if isequal(omgmat, zeros(3))
    expmat = [zeros(3), T(1: 3, 4); 0, 0, 0, 0];
else
    theta = acos((trace(R) - 1) / 2);
    expmat = [omgmat, (eye(3) - omgmat / 2 ...
                      + (1 / theta - cot(theta / 2) / 2) ...
                        * omgmat * omgmat / theta) * p;
              0, 0, 0, 0];
end
end

author: ShuoYangRobotics

repo: QuadrupedSim


text:
function [ n_data_new, x, fx ] = gud_values ( n_data )

%*****************************************************************************80
%
%% GUD_VALUES returns some values of the Gudermannian function.
%
%  Definition:
%
%    The Gudermannian function relates the hyperbolic and trigonomentric
%    functions.  For any argument X, there is a corresponding value
%    GAMMA so that
%
%      SINH(X) = TAN(GAMMA).
%
%    This value GAMMA(X) is called the Gudermannian of X and symbolized
%    GD(X).  The inverse Gudermannian function is given as input a value
%    GAMMA and computes the corresponding value X.
%
%    GD(X) = 2 * arctan ( exp ( X ) ) - PI / 2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Stephen Wolfram,
%    The Mathematica Book,
%    Fourth Edition,
%    Wolfram Media / Cambridge University Press, 1999.
%
%    Daniel Zwillinger, editor,
%    CRC Standard Mathematical Tables and Formulae,
%    30th Edition,
%    CRC Press, 1996.
%
%  Parameters:
%
%    Input, integer N_DATA, indicates the index of the previous test data
%    returned, or is 0 if this is the first call.  For repeated calls,
%    set the input value of N_DATA to the output value of N_DATA_NEW
%    from the previous call.
%
%    Output, integer N_DATA_NEW, the index of the test data.
%
%    Output, real X, the argument of the function.
%
%    Output, real FX, the value of the function.
%
  n_max = 13;
  fx_vec = [ ...
    -1.301760336E+00,  -0.8657694832E+00, 0.0000000000E+00, ...
     0.09983374879E+00, 0.1986798470E+00, 0.4803810791E+00, ...
     0.8657694832E+00,  1.131728345E+00,  1.301760336E+00,  ...
     1.406993569E+00,   1.471304341E+00,  1.510419908E+00,  ...
     1.534169144E+00 ];
  x_vec = [ ...
    -2.0E+00, -1.0E+00,  0.0E+00, ...
     0.1E+00,  0.2E+00,  0.5E+00, ...
     1.0E+00,  1.5E+00,  2.0E+00, ...
     2.5E+00,  3.0E+00,  3.5E+00, ...
     4.0E+00  ];

  n_data_new = n_data;

  if ( n_data_new < 0 )
    n_data_new = 0;
  end

  n_data_new = n_data_new + 1;

  if ( n_max < n_data_new )
    n_data_new = 0;
    x = 0.0E+00;
    fx = 0.0E+00;
  else
    x = x_vec(n_data_new);
    fx = fx_vec(n_data_new);
  end

  return
end

author: johannesgerer

repo: jburkardt-m