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

% Last Modified by GUIDE v2.5 11-Apr-2018 18:59:36

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

% Choose default command line output for plot_controller
handles.output = hObject;
if ~sum(size(varargin))
    error('OpenBMI: No data input');
elseif ~isfield(varargin{1},'x')
    error('OpenBMI: Data must have fields named ''x''');
else
    handles.data=varargin{1};
end
% Update handles structure
guidata(hObject, handles);
initialize_gui(hObject, handles, false);
% UIWAIT makes plot_controller wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = plot_controller_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 initialize_gui(hObject, handles, isreset)
% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
% set(handles.time_seg_start, 'String', handles.data.ival(1));
% set(handles.time_seg_end, 'String', handles.data.ival(end));
set(handles.time_seg, 'String', sprintf('%d ~ %d', handles.data.ival(1), handles.data.ival(end)));
set(handles.sampling_rate,'String',handles.data.fs);
set(handles.num_class,'String',size(handles.data.class, 1));
set(handles.chan_num,'String',length(handles.data.chan));

chan=handles.data.chan(1);
for i=2:length(handles.data.chan)
    chan=strcat(chan,{', '},handles.data.chan(i));
end
set(handles.chan_info,'String',chan);

% Update handles structure
guidata(hObject, handles);
RESET(hObject,handles);

function RESET(hObject, handles, isreset)
% handles     structure with handles and user data (see GUIDATA)
% init        initialization
% Initialize plot type
set(handles.check_ERP,'Value',false);
set(handles.check_SSVEP, 'Value', false);
set(handles.check_MI,'Value',false);
set(handles.check_Topo,'Value',false);

% Initialize channel
handles.selected_chan={'Cz','Oz'};
str={};
for i=1:length(handles.selected_chan)
    str=[str; sprintf('%s',handles.selected_chan{i})];
end
% sprintf('%s',selected_chan{1});
set(handles.chan_listbox, 'String', str);

% Initialize interval
str ={};

ival = handles.data.ival([1, end]);
if ival(1) < 0, ival(1) = 0; end
selected_ival = linspace(ival(1), ival(2), 6);
handles.selected_ival=[selected_ival(1),selected_ival(2);...
    selected_ival(2),selected_ival(3);selected_ival(3),selected_ival(4);...
    selected_ival(4),selected_ival(5); selected_ival(5),selected_ival(6)];
ival=handles.selected_ival;
for i = 1:size(ival,1)
    str = [str; sprintf('%d ~ %d',ival(i,1), ival(i,2))];
end
set(handles.ival_listbox, 'String', str);

% Initialize num_class
str = {};
handles.selected_class=handles.data.class(:,2);

for i=1:length(handles.selected_class)
    str = [str; sprintf('%s', handles.selected_class{i})];
end

set(handles.inputToggle, 'Value', false);
set(handles.inputToggle, 'String', 'Direct');
set(handles.pop_range, 'Visible', 'on');
set(handles.maxTopo, 'Visible', 'off');
set(handles.minTopo, 'Visible', 'off');
set(handles.maxTopo, 'String', '0');
set(handles.minTopo, 'String', '0');
set(handles.tildeTopo, 'Visible', 'off');
set(handles.selToggle, 'Value', false);
set(handles.selToggle, 'String', 'Select');
set(handles.maxSelect, 'Enable', 'off');%
set(handles.minSelect, 'Enable', 'off');
set(handles.maxSelect, 'String', '0');
set(handles.minSelect, 'String', '0');
set(handles.ylimToggle, 'Value', false);
set(handles.ylimToggle, 'String', 'Select');
set(handles.maxYlim, 'Enable', 'off');
set(handles.minYlim, 'Enable', 'off');
set(handles.maxYlim, 'String', '0');
set(handles.minYlim, 'String', '0');

set(handles.class_listbox,'String', str);

set(handles.pop_range, 'Value', 1);
set(handles.pop_color, 'Value', 1);
set(handles.pop_quality, 'Value', 1);
set(handles.pop_orient, 'Value', 1);

% Initialize baseline
set(handles.baseline_start, 'String', string(handles.data.ival(1)));
set(handles.baseline_end, 'String', '0');

set(handles.note_txt,'String', {'';'';'Welcome'});

% Update handles structure
guidata(hObject, handles);

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

% --- Executes on button press in select_chan_btn.
function select_chan_btn_Callback(hObject, eventdata, handles)
% hObject    handle to select_chan_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    [~,selected_chan]=GUI_selectChannels(handles.data.chan,handles.selected_chan);
    if length(selected_chan) > 5
        set(handles.note_txt, 'String', {'';'';'Don''t you think that selected channels are too many?'});
        return;
    else
        handles.selected_chan = selected_chan;
    end
catch
    return;
end
str={};
for i=1:length(handles.selected_chan)
    str=[str; sprintf('%s',handles.selected_chan{i})];
end
set(handles.chan_listbox, 'String', str);
set(handles.note_txt, 'String', {'';'';'Channels are selected'});

clear tmp;
% Update handles structure
guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function chan_listbox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to chan_listbox (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 select_ival_btn.
function select_ival_btn_Callback(hObject, eventdata, handles)
% hObject    handle to select_ival_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    ival = select_interval(handles.selected_ival);
    if ~isempty(ival)&&(min(ival(:)) < handles.data.ival(1) || max(ival(:)) > handles.data.ival(end))
        set(handles.note_txt,'String', {'';'';'Please select intervals between segmented data'});
        return;
    end
    if ~isempty(ival)
        ival = sort(ival,2);
        [~, sort_] = sort(ival,1);
        ival = ival(sort_(:,1),:);
    else
        ival = handles.data.ival([1, end]);
%         if ival(1) < 0, ival(1) = 0; end % ival 0 to max -> min to max
    end
catch
    return;
end
handles.selected_ival=ival;
% str=sprintf('%d ~ %d',handles.selected_ival(1,1), handles.selected_ival(1,2));
% for i=2:length(handles.selected_ival(:,1))
%     str=sprintf('%s\n%d ~ %d',str,handles.selected_ival(i,1), handles.selected_ival(i,2));
% end
str = {};
for i = 1:size(ival,1)
    str = [str; sprintf('%d ~ %d', ival(i,1), ival(i,2))];
end

set(handles.ival_listbox, 'String',str);
set(handles.note_txt, 'String', {'';'';'Itervals are selected'});

% Update handles structure
guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function ival_listbox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ival_listbox (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 select_class_btn.
function select_class_btn_Callback(hObject, eventdata, handles)
% hObject    handle to select_class_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    handles.selected_class=select_class(handles.data.class(:,2),handles.selected_class);
catch
    return;
end
str={};
for i=1:length(handles.selected_class)
    str=[str; sprintf('%s',handles.selected_class{i});];
end
set(handles.class_listbox, 'String', str);
clear tmp;
set(handles.note_txt, 'String', {'';'';'Classes are selected'});

% Update handles structure
guidata(hObject, handles);

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

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

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

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

%% Update baseline range
baseline=[str2double(get(handles.baseline_start,'String')), str2double(get(handles.baseline_end,'String'))];
if baseline(1) > baseline(2)
    baseline = flip(baseline);
    set(handles.baseline_start,'String', baseline(1));
    set(handles.baseline_end, 'String', baseline(2));
end
%% Select time
if get(handles.selToggle, 'Value')
    selTime = [str2double(get(handles.minSelect, 'String')), str2double(get(handles.maxSelect, 'String'))];
    if selTime(1) > selTime(2)
        selTime = flip(selTime);
        set(handles.minSelect, 'String', selTime(1));
        set(handles.maxSelect, 'String', selTime(2));
    end
else
    selTime = [handles.data.ival(1), handles.data.ival(end)];
end
%% Ylim range
if get(handles.ylimToggle, 'Value')
    ylimRange = [str2double(get(handles.minYlim, 'String')), str2double(get(handles.maxYlim, 'String'))];
else
    ylimRange = [];
end
%% Get plots
if get(handles.check_ERP,'Value'), ERPPlot = 'on'; else ERPPlot = 'off'; end
if get(handles.check_SSVEP,'Value'), SSVEPPlot = 'on'; else SSVEPPlot = 'off'; end
if get(handles.check_MI,'Value'), MIPlot = 'on'; else MIPlot = 'off'; end
if get(handles.check_Topo,'Value'), TopoPlot = 'on'; else TopoPlot = 'off'; end
if ~sum(ismember({ERPPlot, MIPlot, SSVEPPlot, TopoPlot}, 'on'))
    set(handles.note_txt, 'String', {'';'';'Choose at least one plot type'});
    return;
end
%% Patch
if get(handles.check_patch,'Value'), Patch = 'on'; else Patch = 'off'; end
%% Topography range
if get(handles.inputToggle, 'Value')
    p_range = [str2double(get(handles.minTopo, 'String')), str2double(get(handles.maxTopo, 'String'))];
    if p_range(1) > p_range(2)
        p_range = flip(p_range);
        set(handles.minTopo,'String', p_range(1));
        set(handles.maxTopo,'String', p_range(2));
    end
else
    switch get(handles.pop_range, 'Value')
        case 1
            p_range = 'sym';
        case 2
            p_range = '0tomax';
        case 3
            p_range = 'minto0';
        case 4
            p_range = 'mintomax';
        case 5
            p_range = 'mean';
    end
end
%% Topography color
switch get(handles.pop_color, 'Value')
    case 1
        cm = 'parula';
    case 2
        cm = 'jet';
    case 3
        cm = 'hsv';
end
%% Topography quality
switch get(handles.pop_quality, 'Value')
    case 1
        quality = 'high';
    case 2
        quality = 'medium';
    case 3
        quality = 'low';
end

%% Interval check
if sum(handles.selected_ival(:,1) < selTime(1)) || sum(handles.selected_ival(:,2) > selTime(2))
    set(handles.note_txt, 'String', {'';'';'Choose intervals between selected time'});
    return;
end

%% Start visualization
set(handles.note_txt, 'String', {'';'';'Wait for Drawing'}); drawnow;
try
    options = {'Interval', handles.selected_ival;...
        'Channels',handles.selected_chan;'Class',handles.selected_class;...
        'TimePlot', ERPPlot; 'TopoPlot', TopoPlot; 'ErdPlot', MIPlot;...
         'Range', p_range; 'baseline', baseline;...
        'Colormap', cm; 'Patch', Patch; 'Quality', quality; ...
        'SelectTime', selTime; 'TimeRange', ylimRange};
    [avSMT, rSMT] = untitled_function(handles.data);
    output = vis_plotController(avSMT, rSMT, options);
catch error
    close gcf;
    output = {'';'Unexpected Error Occurred in';...
        sprintf('%s (line: %d)', error.stack(1).name, error.stack(1).line);...
        error.message};
end
set(handles.note_txt, 'String', output);
% visual_scalpPlot_fin(handles.data, {'Interval', handles.selected_ival;'Channels',{'Cz', 'POz','Oz'};'num_class',{'target','non-target'}});
% visual_scalpPlot_fin(handles.data, {'Interval', [-100 0 150 250 400];'Channels',{'Cz', 'POz','Oz'}});
% Update handles structure
% guidata(hObject, handles);

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

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

% --- Executes during object creation, after setting all properties.
function time_seg_start_CreateFcn(hObject, eventdata, handles)
% hObject    handle to time_seg_start (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 time_seg_end_Callback(hObject, eventdata, handles)
% hObject    handle to time_seg_end (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 time_seg_end as text
%        str2double(get(hObject,'String')) returns contents of time_seg_end as a double

% --- Executes during object creation, after setting all properties.
function time_seg_end_CreateFcn(hObject, eventdata, handles)
% hObject    handle to time_seg_end (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 freq_band_start_Callback(hObject, eventdata, handles)
% hObject    handle to freq_band_start (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 freq_band_start as text
%        str2double(get(hObject,'String')) returns contents of freq_band_start as a double

% --- Executes during object creation, after setting all properties.
function freq_band_start_CreateFcn(hObject, eventdata, handles)
% hObject    handle to freq_band_start (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 freq_band_end_Callback(hObject, eventdata, handles)
% hObject    handle to freq_band_end (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 freq_band_end as text
%        str2double(get(hObject,'String')) returns contents of freq_band_end as a double

% --- Executes during object creation, after setting all properties.
function freq_band_end_CreateFcn(hObject, eventdata, handles)
% hObject    handle to freq_band_end (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 baseline_start_Callback(hObject, eventdata, handles)
% hObject    handle to baseline_start (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 baseline_start as text
%        str2double(get(hObject,'String')) returns contents of baseline_start as a double
input = get(handles.baseline_start, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.baseline_start, 'String', string(handles.data.ival(1)));
    return;
end
if str2double(input) < handles.data.ival(1) || str2double(input) > handles.data.ival(end)
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input between the segmentation range'});
    set(handles.baseline_start, 'String', string(handles.data.ival(1)));
    return;
end

% --- Executes during object creation, after setting all properties.
function baseline_start_CreateFcn(hObject, eventdata, handles)
% hObject    handle to baseline_start (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 baseline_end_Callback(hObject, eventdata, handles)
% hObject    handle to baseline_end (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 baseline_end as text
%        str2double(get(hObject,'String')) returns contents of baseline_end as a double
input = get(handles.baseline_end, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.baseline_end, 'String', '0');
    return;
end
if str2double(input) < handles.data.ival(1) || str2double(input) > handles.data.ival(end)
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input between the segmentation range'});
    set(handles.baseline_end, 'String', string(handles.data.ival(end)));
    return;
end

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

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

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

% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

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

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

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

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

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

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

% --- Executes during object creation, after setting all properties.
function pop_range_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pop_range (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 popupmenu10.
function popupmenu10_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu10 (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 popupmenu10 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu10

% --- Executes during object creation, after setting all properties.
function popupmenu10_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu10 (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 popupmenu11.
function popupmenu11_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu11 (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 popupmenu11 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu11

% --- Executes during object creation, after setting all properties.
function popupmenu11_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu11 (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 pop_color.
function pop_color_Callback(hObject, eventdata, handles)
% hObject    handle to pop_color (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 pop_color contents as cell array
%        contents{get(hObject,'Value')} returns selected item from pop_color

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

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

% --- Executes during object creation, after setting all properties.
function pop_quality_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pop_quality (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 minYlim_Callback(hObject, eventdata, handles)
% hObject    handle to minYlim (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 minYlim as text
%        str2double(get(hObject,'String')) returns contents of minYlim as a double
input = get(handles.minYlim, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.minYlim, 'String', '0');
    return;
end
% --- Executes during object creation, after setting all properties.
function minYlim_CreateFcn(hObject, eventdata, handles)
% hObject    handle to minYlim (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 maxYlim_Callback(hObject, eventdata, handles)
% hObject    handle to maxYlim (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 maxYlim as text
%        str2double(get(hObject,'String')) returns contents of maxYlim as a double
input = get(handles.maxYlim, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.maxYlim, 'String', '0');
    return;
end

% --- Executes during object creation, after setting all properties.
function maxYlim_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxYlim (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 inputToggle.
function inputToggle_Callback(hObject, eventdata, handles)
% hObject    handle to inputToggle (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 inputToggle
if get(handles.inputToggle, 'Value')
    set(handles.pop_range, 'Visible', 'off');
    set(handles.maxTopo, 'Visible', 'on');
    set(handles.minTopo, 'Visible', 'on');
    set(handles.tildeTopo, 'Visible', 'on');
    set(handles.inputToggle, 'String', 'Options');
else
    set(handles.pop_range, 'Visible', 'on');
    set(handles.maxTopo, 'Visible', 'off');
    set(handles.minTopo, 'Visible', 'off');
    set(handles.tildeTopo, 'Visible', 'off');
    set(handles.inputToggle, 'String', 'Direct');
end

function minTopo_Callback(hObject, eventdata, handles)
% hObject    handle to minTopo (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 minTopo as text
%        str2double(get(hObject,'String')) returns contents of minTopo as a double
input = get(handles.minTopo, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.minTopo, 'String', '0');
    return;
end

% --- Executes during object creation, after setting all properties.
function minTopo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to minTopo (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 maxTopo_Callback(hObject, eventdata, handles)
% hObject    handle to maxTopo (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 maxTopo as text
%        str2double(get(hObject,'String')) returns contents of maxTopo as a double
input = get(handles.maxTopo, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.maxTopo, 'String', '0');
    return;
end

% --- Executes during object creation, after setting all properties.
function maxTopo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxTopo (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 minSelect_Callback(hObject, eventdata, handles)
% hObject    handle to minSelect (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 minSelect as text
%        str2double(get(hObject,'String')) returns contents of minSelect as a double
input = get(handles.minSelect, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.minSelect, 'String', string(handles.data.ival(1)));
    return;
end
if str2double(input) < handles.data.ival(1) || str2double(input) > handles.data.ival(end)
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input between the segmentation range'});
    set(handles.minSelect, 'String', string(handles.data.ival(1)));
    return;
end

% --- Executes during object creation, after setting all properties.
function minSelect_CreateFcn(hObject, eventdata, handles)
% hObject    handle to minSelect (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 maxSelect_Callback(hObject, eventdata, handles)
% hObject    handle to maxSelect (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 maxSelect as text
%        str2double(get(hObject,'String')) returns contents of maxSelect as a double
input = get(handles.maxSelect, 'String');
[~, len] = regexp(input, '^-?[0-9]+');

if ~isequal(len, length(input))
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input the number'});
    set(handles.maxSelect, 'String', string(handles.data.ival(end)));
    return;
end
if str2double(input) < handles.data.ival(1) || str2double(input) > handles.data.ival(end)
    set(handles.note_txt, 'String',{'';sprintf('[%s] is not acceptable', input);'please input between the segmentation range'});
    set(handles.maxSelect, 'String', string(handles.data.ival(end)));
    return;
end

% --- Executes during object creation, after setting all properties.
function maxSelect_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxSelect (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 selToggle.
function selToggle_Callback(hObject, eventdata, handles)
% hObject    handle to selToggle (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 selToggle
if get(handles.selToggle, 'Value')
    set(handles.maxSelect, 'Enable', 'on');
    set(handles.minSelect, 'Enable', 'on');
    set(handles.selToggle, 'String', 'Deselect');
else
    set(handles.maxSelect, 'Enable', 'off');
    set(handles.minSelect, 'Enable', 'off');
	set(handles.selToggle, 'String', 'Select');
end

% --- Executes on button press in ylimToggle.
function ylimToggle_Callback(hObject, eventdata, handles)
% hObject    handle to ylimToggle (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 ylimToggle
if isequal(get(handles.ylimToggle, 'String'), 'Select')
    set(handles.maxYlim, 'Enable', 'on');
    set(handles.minYlim, 'Enable', 'on');
    set(handles.ylimToggle, 'String', 'Deselect');
    set(handles.ylimToggle, 'Value', true);
else
    set(handles.maxYlim, 'Enable', 'off');
    set(handles.minYlim, 'Enable', 'off');
    set(handles.ylimToggle, 'String', 'Select');
    set(handles.ylimToggle, 'Value', false);
end

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

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

author: PatternRecognition

repo: OpenBMI


text:
function ret = optiSolver(instr,err)
%OPTISOLVER  See if a solver is installed on your PC and details about it
%
%   optiSolver() prints a list of OPTI interfaced solvers, their version
%   numbers and and whether they are available on your PC.
%
%   optiSolver('matrix') prints a solver vs problem type matrix for
%   determining which solvers and setup for which problems.
%
%   optiSolver('config') prints a solver vs config matrix for
%   determining which options are configured for which solvers.
%
%   optiSolver(type) prints a list of solvers for a given problem, 'type',
%   together with a table of constraint and derivative information. See
%   below for heading information. Examples are 'lp', 'milp', etc.
%
%   ok = optiSolver(solver) returns true if the passed solver is available
%   on your PC. Examples are 'clp', 'ipopt', etc.
%
%   optiSolver(solver) displays information about the solver (if
%   available) and configuration specifics (no output args).
%
%   solver = optiSolver(bestSolver) returns the best available solver as a
%   string for a given problem type. Examples are 'best_lp', 'best_milp',
%   etc.
%
%   Problem Type table headings are as follows:
%
%   BD - Bounds
%   LI - Linear Inequality (* indicates a conversion will take place)
%   LE - Linear Equality   (* indicates a conversion will take place)
%   QI - Quadratic Inequality
%   SS - Special Ordered Set
%   NI - Nonlinear Inequality
%   NE - Nonlinear Equality
%   SP - Supports Sparse Matrices
%   D1 - Requires First Derivatives (Gradient) (* indicates optional)
%   D2 - Requires Second Derivatives (Hessian) (* indicates optional)
%   GL - Global Solver

%   Copyright (C) 2011-2015 Jonathan Currie (IPL)

global SLE LP MILP BILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP DESC PTYPES

%Ordered lists of 'best' solvers
SLE = {'matlab','MUMPS'};
LP = {'CPLEX','clp','mosek','scip','ooqp','glpk','lp_solve','MATLAB','csdp','dsdp','SeDuMi'};
MILP = {'CPLEX','cbc','mosek','scip','glpk','lp_solve','MATLAB'};
BILP = {'CPLEX','cbc','mosek','scip','glpk','lp_solve','MATLAB'};
QP = {'CPLEX','ooqp','clp','mosek','scip','ipopt','MATLAB'};
QCQP = {'CPLEX','mosek','scip','ipopt'};
MIQP = {'CPLEX','mosek','scip','bonmin'};
MIQCQP = {'CPLEX','mosek','scip','bonmin'};
SDP = {'csdp','dsdp','SeDuMi'}; %mosek?
MISDP = {}; %'scip'
SNLE = {'nl2sol','hybrj','mkltrnls','lmder','levmar','MATLAB','IPOPT','nomad','nlopt'};
SCNLE = {'nl2sol','mkltrnls','levmar','IPOPT','nomad','pswarm','nlopt'};
NLS = {'nl2sol','mkltrnls','lmder','levmar','gsl','MATLAB','IPOPT','nomad','pswarm','nlopt'};
UNO = {'IPOPT','matlab','m1qn3','NLOPT','nomad','scip','GMATLAB'};
NLP = {'IPOPT','MATLAB','FILTERSD','NLOPT','LBFGSB','nomad','PSwarm','baron','scip','GMATLAB'};
MINLP = {'BONMIN','nomad','baron','scip','GMATLAB'};
%Description List
DESC = containers.Map({'cplex','glpk','lp_solve','clp','matlab','mumps','ooqp','ipopt','nlopt','cbc','bonmin','lbfgsb','levmar','lmder','nl2sol','hybrj',...
                       'mkltrnls','pswarm','gmatlab','nomad','scip','m1qn3','filtersd','dsdp','csdp','sedumi','baron','mosek','gsl'},...
                      {'IBM ILOG CPLEX','GNU Linear Programming Kit','LP_Solve','COIN-OR Linear Programming',...
                       'Optimization Toolbox: ','a MUltifrontal Massively Parallel sparse direct Solver','Object-Orientated Quadratic Programming',...
                       'Interior-Point Optimization','Nonlinear Optimization','COIN-OR Branch and Cut',...
                       'Basic Open-source Nonlinear Mixed INteger programming','Limited Memory Broyden-Fletcher-Goldfarb-Shanno Bounded Optimization',...
                       'Levenberg-Marquardt Nonlinear Least Squares in C/C++','MINPACK Levenberg-Marquardt','Adaptive Nonlinear Least Squares','MINPACK Powell Hybrid',...
                       'Intel MKL Trust Region Nonlinear Least Squares','Pattern and Particle Swarm Global Optimizer','Global Optimization Toolbox: ',...
                       'Nonlinear Optimization with the MADS algorithm','Solving Constraint Integer Programs','Large-Scale Unconstrained L-BFGS Minimization',...
                       'FilterSD: Filter & Trust Region Nonlinear Optimization','Dual Scaling Interior Point SDP Solver','Predictor-Corrector Primal-Dual SDP Solver',...
                       'Self-Dual-Minimization','Branch And Reduce Optimization Navigator','MOSEK Optimization Software','GNU Scientific Library'});
%Problem Type List
PTYPES = {'sle','lp','milp','bilp','qp','qcqp','miqp','miqcqp','sdp','misdp','snle','scnle','nls','uno','nlp','minlp'};

%Default Input Args
if(nargin < 2), err = 1; end %default to create an error
if(nargin < 1), instr = []; end
%Default Internal Args
ret = [];

if(isempty(instr))
    printSolvers();     %print a list of solvers and availability
else
    %Check if we have a known solver
    allS = getAllSolvers();
    for i = 1:length(allS)
        if(strcmpi(instr,allS{i}))
            ret = check(instr,err);
            if(nargout == 0 && ret), printSolverInfo(instr); end
            return;
        end
    end

    % if 'DNLS' - change to nls
    if (strcmpi(instr,'dnls'))
        instr = 'nls';
    end

    %If we got here, check for a known problem type
    for i = 1:length(PTYPES)
        if(strcmpi(instr,PTYPES{i}))
            ret = findAllForProb(instr,nargout);
            return;
        end
    end

    %Still not found, check standard options and alternative names for solvers
    switch(lower(instr))
        %Options
        case 'matrix'
            printSolverMatrix;
        case 'config'
            printConfigMatrix;
        case 'ptypes'
            ret = PTYPES;
        case 'ver'
            ret = genSolverList();
        %Alternative Solver Names
        case 'auto'
            ret = 1; %assume we can find a solver
        case 'optim'
            ret = check('matlab',err);
            if(nargout == 0 && ret), printSolverInfo('matlab'); end
        case {'mldivide','fminsearch'}
            ret = 1; %base matlab
        case 'l-bfgs-b'
            ret = check('lbfgsb',err);
            if(nargout == 0 && ret), printSolverInfo('lbfgsb'); end
        case 'lpsolve'
            ret = check('lp_solve',err);
            if(nargout == 0 && ret), printSolverInfo('lp_solve'); end
        case {'lmdif','lm_der','lm_dif'}
            ret = check('lmder',err);
            if(nargout == 0 && ret), printSolverInfo('lmder'); end
        case 'nl2sno'
            ret = check('nl2sol',err);
            if(nargout == 0 && ret), printSolverInfo('nl2sol'); end
        case 'hybrd'
            ret = check('hybrj',err);
            if(nargout == 0 && ret), printSolverInfo('hybrd'); end
        case 'mkltr'
            ret = check('mkltrnls',err);
            if(nargout == 0 && ret), printSolverInfo('mkltrnls'); end
        case 'baron'
            ret = check('baron',err);

        %Check for all, best
        otherwise
            if(strfind(instr,'best'))
                ret = findBestSolver(instr);
            elseif(strfind(instr,'all'))
                ret = findAllForProb(instr,nargout);
            else
                error('Unknown Solver or Option: %s',instr); %not found
            end
    end
end

function ok = check(name,err,ptype)
%Check a particular solver is installed
if(nargin < 3), ptype = []; end
switch(name)
    case 'MATLAB'
        if(~isempty(ptype) && strcmpi(ptype,'milp'))
            c = which('intlinprog.m'); %only available >= 2014a (8.3)
        elseif(~isempty(ptype) && strcmpi(ptype,'bilp'))
            %bintprog removed in 2014b, used intlinprog instead if available
            if(verLessThan('matlab','8.4')) %2014b
                c = which('bintprog.m');
            else
                c = which('intlinprog.m');
            end
        else
            c = which('fmincon'); %using ver is quite slow
        end
        if(isempty(c))
            if(err)
                error('The MATLAB Optimization Toolbox must be installed');
            else
                ok = 0;
            end
        else
            ok = 1;
        end
        return
    case {'GMATLAB','gmatlab'}
        c = which('patternsearch'); %using ver is quite slow
        if(isempty(c))
            if(err)
                error('The MATLAB Global Optimization Toolbox must be installed');
            else
                ok = 0;
            end
        else
            ok = 1;
        end
        return
    case {'matlab'} %always installed (mldivide)
        ok = 1;
        return
    case {'CPLEX','cplex'} %check cplexlink mex file
        c = which(name);
        %Problems with OPTI + R2013a x64 + Cplex >= v12.5.0.0
        if(~isempty(c) && ~isempty(strfind(computer,'64')))
            if(~isempty(which(['cplexlink1250.' mexext])) || ~isempty(which(['cplexlink1251.' mexext])) || ~isempty(which(['cplexlink1260.' mexext])))
            c = []; %force not available
            end
        end
    case {'MOSEK','mosek'} %find mex file
        c = which(['mosekopt.' mexext]);
    case {'sedumi','SEDUMI','SeDuMi'}
        %Check matlab file
        c = which('sedumi');
        %Check mex file exists as well
        if(isempty(which(['partitA.' mexext])))
            c = [];
        %Check for v1.31 or higher
        elseif(~isempty(c))
            [~,major,minor] = getVerFromVerFile('sedumi');
            if(major == 1 && minor < 31)
                c = [];
            elseif(major < 1)
                c = [];
            end
        end
    case {'BARON','baron'}
        c = which('baron.m');
        if(isempty(c))
            c = which('baron.p');
        end
    case {'LIPSOL','lipsol'}
        c = which(['ls_blkslv.' mexext]);
    otherwise
        c = which([name '.' mexext]); %bug fix 22/2/12
        if(~isempty(c)) %ensure mex file is OK
            try
                a = eval(lower(name)); %#ok<NASGU>
            catch
                c = [];
            end
        end
end

if(isempty(c))
    if(err)
        throwAsCaller(MException('opti:checkSolver','OPTI cannot find a valid version of %s. Ensure it is installed on your system.',name));
    else
        ok = 0;
    end
else
    ok = 1;
end

function str = findBestSolver(prob)
%Find the best available solver for a given problem type

global SLE LP MILP BILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP PTYPES %#ok<NUSED>

s = regexp(prob,'_','split');
if(length(s) < 2)
    error('When requesting the best solver it should be of the form best_xxx, e.g. best_lp');
end

%Remove 'D' from dynamic problems
if(s{2}(1) == 'D')
    s{2} = s{2}(2:end);
end

fnd = 0;
for i = 1:length(PTYPES)
    if(strcmpi(s{2},PTYPES{i}))
        try
            list = eval(upper(s{2}));
            fnd = 1;
        catch %#ok<CTCH>
            fnd = 0; %global var doesn't exist?
        end
        break;
    end
end
%If not found, we don't have a solver for this problem
if(~fnd)
    error('Could not find a problem type match for type %s',upper(s{2}));
%Otherwise return the best solver available
else
    str = [];
    for i = 1:length(list)
        if(check(list{i},0))
            str = list{i};
            break;
        end
    end
    if(isempty(str))
        error('You do not have a solver which can solve a %s explicitly',upper(s{2}));
    end
end

function list = findAllForProb(prob,nout)
%Find all available solvers for a given problem type

global SLE LP MILP BILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP PTYPES %#ok<NUSED>

%Backwards compatibility check
if(strfind(prob,'all_'))
    s = regexp(prob,'_','split');
    prob = s{2};
end

fnd = 0;
for i = 1:length(PTYPES)
    if(strcmpi(prob,PTYPES{i}))
        try
            plist = eval(upper(prob));
            fnd = 1;
        catch %#ok<CTCH>
            fnd = 0; %global var doesn't exist?
        end
        break;
    end
end
%If found keep availale solvers
if(fnd)
    j = 1; list = [];
    for i = 1:length(plist)
        if(check(plist{i},0,prob))
            list{j} = plist{i}; %#ok<AGROW>
            j = j + 1;
        end
    end
%Check if we want all...
else
    if(strcmpi(prob,'all'))
        list = getAllSolvers();
        return;
    else
        error('Unknown problem type: %s\nNote the API has changed in v1.34 to just the problem type, e.g. checkSolver(''lp'')',prob);
    end
end

%If not returning anything, just print
if(~nout)
    printSelSolvers(list,upper(prob))
    list = [];
end

function list = getAllSolvers()
%Create a list of all solvers OPTI is interfaced to (not neccesarily found however).
global SLE LP MILP BILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP

fulllist = [SLE LP MILP BILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP];
%Remove duplicates
fulllist = unique(lower(fulllist));
%Sort & Return
list = sort(upper(fulllist));

function printSolvers()
%Print each solver and if it exists

fprintf('\n------------------------------------------------\n')
fprintf('OPTI AVAILABLE SOLVERS:\n\n');
list = genSolverList();
for i = 1:length(list)
    fprintf('%s\n',list{i});
end

fprintf('------------------------------------------------\n')

function list = genSolverList()
%Generate a display compatible list of all solvers, their availability and version number
solv = getAllSolvers();
list = cell(length(solv),1);
for i = 1:length(solv)
    [avail,solVer] = getSolverVer(solv{i});
    list{i} = sprintf('%-10s       %-13s  %s',[solv{i} ':'],avail,solVer);
end

function printSelSolvers(solv,type)
%Print selected solvers

fprintf('\n------------------------------------------------\n')
fprintf(['OPTI ' upper(type) ' SOLVERS:\n']);
if(isempty(solv))
    fprintf('None Available\n');
else
    [~,hd] = getSolverInfo(solv{1},type);
    len = length(strtrim(hd));
    fprintf(' %s\n',hd); j = 1;
    for i = 1:length(solv)
        if(check(solv{i},0)) %only print if the solver is available
            fprintf(['(%2d) %-10s  %-'  num2str(len+4) 's %s\n'],j,upper(solv{i}),getSolverInfo(solv{i},type),getDesc(solv{i},type));
            j = j + 1;
        end
    end
end
fprintf('------------------------------------------------\n')

function printSolverMatrix()
%Print solver vs problem matrix

global SLE LP BILP MILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP PTYPES

fprintf('\n------------------------------------------------\n')
fprintf('OPTI SOLVER vs PROBLEM MATRIX:\n\n');
fprintf(' %-8s  %-5s %-4s %-5s %-6s %-4s %-5s %-5s %-4s %-4s %-4s %-5s %-6s %-5s %-5s %-4s %-4s\n','Solver','SLE','LP','BILP','MILP','QP','QCQP','MIQP','MIQCQP','SDP','MISDP','SNLE','SCNLE','NLS','UNO','NLP','MINLP');

solv = getAllSolvers();
list = {SLE LP BILP MILP QP QCQP MIQP MIQCQP SDP MISDP SNLE SCNLE NLS UNO NLP MINLP};

%REVERSE LOCATION OF BILP AND MILP TO SUIT ABOVE
probs = PTYPES;
idxm = strcmpi(probs,'milp');
idxb = strcmpi(probs,'bilp');
probs{idxm} = 'bilp';
probs{idxb} = 'milp';

for i = 1:length(solv)
    fprintf('%-8s |',solv{i});
    sok = optiSolver(solv{i},0);
    for j = 1:length(list)
        if(any(strcmpi(solv{i},list{j})))
            if(strcmpi(solv{i},'matlab')) %matlab has optimization toolbox + base packages
                msok = check('MATLAB',0,probs{j});
                if(msok || any(strcmp({'matlab'},list{j})))
                    fprintf('  x  |');
                else
                    fprintf('  o  |');
                end
            else
                if(sok)
                    fprintf('  x  |');
                else
                    fprintf('  o  |');
                end
            end
        else
            fprintf('     |');
        end
    end
    fprintf('\n');
end

fprintf('------------------------------------------------\n')

function printConfigMatrix()
%Print solver vs config matrix

%[miter,meval,mnode,mtime,tolr,tola,tolint,disp,opts,ctrlc,iterf]
fprintf('\n------------------------------------------------\n')
fprintf('OPTI SOLVER vs CONFIG MATRIX:\n\n');
fprintf('   %-11s %-7s %-7s %-7s %-7s %-7s %-6s %-8s %-7s %-7s %-6s %-7s\n','Solver','miter','meval','mnode','mtime','tolr','tola','tolint','disp','sOpts','ctrlc','iterfnc');

solv = getAllSolvers();

for i = 1:length(solv)
    info = optiSolverInfo(solv{i},'');
    %Separate out variables we use
    miter   = getMarker(info.opt.miter);
    meval   = getMarker(info.opt.meval);
    mnode   = getMarker(info.opt.mnode);
    mtime   = getMarker(info.opt.mtime);
    tolr    = getMarker(info.opt.tolr);
    tola    = getMarker(info.opt.tola);
    tolint  = getMarker(info.opt.tolint);
    disp    = getMarker(info.opt.disp);
    sOpts   = getMarker(info.opt.opts);
    ctrlc   = getMarker(info.opt.ctrlc);
    iterf   = getMarker(info.opt.iterf);

    %Print line
    fprintf('%-11s  |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |   %1s   |\n',solv{i},miter,meval,mnode,mtime,tolr,tola,tolint,disp,sOpts,ctrlc,iterf);
end

fprintf('------------------------------------------------\n')

function str = getDesc(solv,type)
%Return solver description
global DESC

str = DESC(lower(solv));
if(strcmp(solv,'MATLAB'))
    str = [str getMatlabDesc(type)];
elseif(strcmp(solv,'GMATLAB'))
    str = [str getGMatlabDesc(type)];
elseif(strcmp(solv,'matlab'))
    str = getMatlabDesc(type);
end

function str = getMatlabDesc(type)
%Return MATLAB solver

switch(lower(type))
    case 'sle'
        str = 'mldivide';
    case 'lp'
        str = 'linprog';
    case 'qp'
        str = 'quadprog';
    case 'bilp'
        if(verLessThan('matlab','8.4')) %2014b
            str = 'bintprog';
        else
            str = 'intlinprog';
        end
    case 'milp'
        str = 'intlinprog';
    case 'nlp'
        str = 'fmincon';
    case 'snle'
        str = 'fsolve';
    case 'nls'
        str = 'lsqnonlin';
    case 'uno'
        str = 'fminsearch';
    otherwise
        str = '';
end

function str = getGMatlabDesc(type)
%Return Global MATLAB Solver

switch(lower(type))
    case {'uno','nlp'}
        str = 'patternsearch';
    case 'minlp'
        str = 'ga';
    otherwise
        str = '';
end

function [avail,solVer] = getSolverVer(solver)
%Return currently installed solver version

ok = check(solver,0);
if(ok)
    avail = 'Available';
    switch(lower(solver))
        %Interfaced solvers
        case 'cplex'
            c = Cplex;
            solVer = ['v' c.getVersion];
            clear c;
        case 'matlab'
            c = ver('optim');
            if(isfield(c,'Version'))
                solVer = ['v' c.Version];
            else
                solVer = '';
            end
            clear c;
        case 'gmatlab'
            c = ver('globaloptim');
            if(isfield(c,'Version'))
                solVer = ['v' c.Version];
            else
                solVer = '';
            end
            clear c;
        case 'mosek'
            solVer = ''; %unknown for the moment
        case 'sedumi'
            solVer = getVerFromVerFile('sedumi');
        case 'lipsol'
            solVer = getVerFromVerFile('lipsol');
        case 'opti'
            c = optiver;
            solVer = ['v' num2str(c)];
        case 'baron' %unknown
            solVer = '';
        %Supplied Solvers
        otherwise
            try
                v = feval(lower(solver));
                if(~strcmp(v,''))
                    solVer = ['v' v];
                else
                    solVer = '';
                end
            catch %#ok<CTCH>
                solVer = '';
            end
    end
else
    avail = 'Not Available';
    solVer = '';
end

function [str,hd] = getSolverInfo(solver,type)
%Generate a string of solver information for a particular solver

%Get Solver Information
info = optiSolverInfo(solver,type);
%Separate out variables we use
bnd     = getMarker(info.con.bnd);
lineq   = getMarker(info.con.lineq);
leq     = getMarker(info.con.leq);
qineq   = getMarker(info.con.qineq);
ss   = getMarker(info.con.sos);
sdp     = getMarker(info.con.sdp);
nlineq  = getMarker(info.con.nlineq);
nleq    = getMarker(info.con.nleq);
der1    = getMarker(info.der1);
der2    = getMarker(info.der2);
glb     = getMarker(info.global);
sp      = getMarker(info.sparse);

lhs = '%-17s';
switch(lower(type))
    case {'lp','qp'}
        hd = sprintf([lhs 'BD LI LE SP'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s',bnd,lineq,leq,sp);
    case {'milp','miqp'}
        hd = sprintf([lhs 'BD LI LE SS SP'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s %-2s',bnd,lineq,leq,ss,sp);
    case 'bilp'
        hd = sprintf([lhs 'LI LE SP'],'');
        str = sprintf(' %-2s %-2s %-2s',lineq,leq,sp);
    case {'qcqp','miqcqp'}
        hd = sprintf([lhs 'BD LI LE QI SP'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s',bnd,lineq,leq,qineq,sp);
    case {'sdp','misdp'}
        hd = sprintf([lhs 'BD LI LE QI SD SP'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s %-2s',bnd,lineq,leq,qineq,sdp,sp);
    case 'nls'
        hd = sprintf([lhs 'BD LI LE D1'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s',bnd,lineq,leq,der1);
    case {'nlp','minlp'}
        hd = sprintf([lhs 'BD LI LE QI NI NE SP D1 D2 GL'],'');
        str = sprintf(' %-2s %-2s %-2s %-2s %-2s %-2s %-2s',bnd,lineq,leq,qineq,nlineq,nleq,sp,der1,der2,glb);
    otherwise %no constraints
        hd = '';
        str = '';
end

function str = getMarker(value)
switch(value)
    case 1
        str = 'x';
    case 0
        str = '';
    case -1
        str = '*';
end

%Print Solver Information
function printSolverInfo(solver)
fprintf('\n-----------------------------------------------------------\n');
%Print heading
[~,solVer] = getSolverVer(solver);
if(strcmpi(solver,'MATLAB'))
    solverstr = 'MATLAB [Optimization Toolbox]';
elseif(strcmpi(solver,'GMATLAB'))
    solverstr = 'GMATLAB [Global Optimization Toolbox]';
else
    solverstr = upper(solver);
end
fprintf('OPTI SOLVER: %s [%s]\n',solverstr,solVer);
fprintf('-----------------------------------------------------------\n');
%Get solver info
info = optiSolverInfo(solver);
%Print Special Info
if(info.der1 || info.der2 || info.sparse || info.global || info.multialg)
   fprintf('Solver Features:\n');
   if(info.parallel == 1), fprintf('\t- Multi-Threaded (Parallel) Solver\n'); end
   if(info.multialg == 1), fprintf('\t- Contains Multiple Algorithms\n'); end
   if(info.whitebox == 1), fprintf('\t- White-Box NL Solver Which Exploits Problem Structure\n'); end
   if(info.global == 1)
       fprintf('\t- Solves Global Optimization Problems\n');
   elseif(info.global == -1)
       fprintf('\t- Some Algorithms Solve Global Optimization Problems\n');
   end
   if(info.con.int), fprintf('\t- Solves Mixed Integer Problems\n'); end
   if(info.sparse), fprintf('\t- Solves Sparse Problems\n'); end
   if(info.der1 == 1)
       fprintf('\t- Requires First Derivatives\n');
   elseif(info.der1 == -1)
       if(info.multialg==1)
            fprintf('\t- Some Algorithms Require First Derivatives\n');
       else
            fprintf('\t- Can Accept First Derivatives (Or Solver Will Approximate)\n');
       end
   end
   if(info.der2 == 1)
       fprintf('\t- Requires Second Derivatives\n');
   elseif(info.der2 == -1)
       fprintf('\t- Can Accept Second Derivatives (Or Solver Will Approximate)\n');
   end
   fprintf('-----------------------------------------------------------\n');
end
%Print Constraint Info
if(info.con.con)
    fprintf('Supported Constraints:\n');
    printCon('Decision Variable Bounds',info.con.bnd);
    printCon('Linear Inequalities',info.con.lineq);
    printCon('Linear Equalities',info.con.leq);
    printCon('Quadratic Inequalities',info.con.qineq);
    printCon('Quadratic Equalities',info.con.qeq);
    printCon('Semidefinite (Linear Matrix Inequalities)',info.con.sdp);
    printCon('Nonlinear Inequalities',info.con.nlineq);
    printCon('Nonlinear Equalities',info.con.nleq);
    printCon('Integer Variables',info.con.int);
    printCon('Special Ordered Sets',info.con.sos);
    fprintf('-----------------------------------------------------------\n');
end
%See if we have any unique info
u=struct2cell(info.unq); uu = 0;
for i = 1:length(u)
    if(ischar(u{i}) || any(u{i} ~= 0))
        uu = 1;
        break;
    end
end
%Print Unique Info
if(uu)
    fprintf('Special Requirements / Options:\n');
    if(info.unq.x0 == 1)
        fprintf('\t- Requires an initial solution guess via x0\n');
    elseif(info.unq.x0 == -1)
        fprintf('\t- Can accept an initial solution guess via x0\n');
    end
    switch(info.unq.qpform)
        case 'sym'
            fprintf('\t- QP H Matrix must be symmetric\n');
        case 'tril'
            fprintf('\t- QP H Matrix must be symmetric lower triangular\n');
        case 'triu'
            fprintf('\t- QP H Matrix must be symmetric upper triangular\n');
    end
    switch(info.unq.hform)
        case 'sym'
            fprintf('\t- Nonlinear Hessian (if supplied) must be symmetric\n');
        case 'tril'
            fprintf('\t- Nonlinear Hessian (if supplied) must be symmetric lower triangular\n');
        case 'triu'
            fprintf('\t- Nonlinear Hessian (if supplied) must be symmetric upper triangular\n');
    end
    if(info.unq.jstr), fprintf('\t- Requires the structure of the Jacobian\n'); end
    if(info.unq.hstr), fprintf('\t- Requires the structure of the Hessian (if supplied)\n'); end
    fprintf('-----------------------------------------------------------\n');
end

%Print info from MEX file
switch(lower(solver))
    case {'cplex','mosek','matlab','gmatlab','sedumi','lipsol','baron'}
        %Nothing
    case {'filtersd'}
        fprintf('MEX FILE DETAILS:');
        eval([lower(solver) 'sp']);
    otherwise
        fprintf('MEX FILE DETAILS:');
        eval(lower(solver));
end

function printCon(con,val)
if(val == 1)
    fprintf('\t- %s\n',con);
elseif(val == -1)
    fprintf('\t- %s (but may be converted internally)\n',con);
end

function [solVer,major,minor] = getVerFromVerFile(solverP)
solVer = ''; major = 0; minor = 0;
%Find sedumi.m and Version .txt
p = which(solverP); p2 = which('Version.txt','-all');
if(~isempty(p) && ~isempty(p2))
    %Find final file sep in solver path
    ind = strfind(p,filesep);
    %For each version path, see if we can find a matching solver path
    for i = 1:length(p2)
        ind2 = strfind(p2{i},filesep);
        %compare paths up to find file sep
        if(strcmp(p(1:ind(end)),p2{i}(1:ind2(end))))
            %open and reading version
            fid = fopen(p2{i});
            if(fid > 0)
                v = fscanf(fid,'%d.%d');
                fclose(fid);
                major = v(1); minor = v(2);
                solVer = sprintf('v%d.%d',v(1),v(2));
            else
                fclose(fid);
            end
            break;
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function [Ytest d C] = kmeanscov(Ctest,Ctrain,Nclass,varargin)

    if isempty(varargin)
        method_mean = 'riemann';
        method_dist = 'riemann';
    else
        method_mean = varargin{1};
        method_dist = varargin{2};
    end

    % initialisation
    Ntrial = size(Ctrain,3);

    Y_old = zeros(Ntrial,1);
    ix = randperm(Ntrial);
    C = cell(Nclass,1);
    for i=1:Nclass
        C{i} = Ctrain(:,:,ix(i));
    end

    d = zeros(Ntrial,Nclass);
    for j=1:Ntrial
        for i=1:Nclass
            d(j,i) = distance(Ctrain(:,:,j),C{i},method_dist);
        end
    end

    [~,Y] = min(d,[],2);

    % iteration
    while sum(Y~=Y_old)>(Ntrial*0.01)
        Y_old = Y;
        [Y,~,C] = mdm(Ctrain,Ctrain,Y,method_mean,method_dist);
    end

    % classification of test data
    Ntesttrial = size(Ctest,3);
    d = zeros(Ntesttrial,Nclass);
    for j=1:Ntesttrial
        for i=1:Nclass
            d(j,i) = distance(Ctest(:,:,j),C{i},method_dist);
        end
    end

    [~,Ytest] = min(d,[],2);

author: alexandrebarachant

repo: covariancetoolbox


text:
function spm_standalone(varargin)
% Gateway function for standalone SPM
%
% References:
%
%   SPM Standalone:  https://en.wikibooks.org/wiki/SPM/Standalone
%   MATLAB Compiler: http://www.mathworks.com/products/compiler/
%
% See also: config/spm_make_standalone.m
%__________________________________________________________________________
% Copyright (C) 2010-2017 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_standalone.m 7372 2018-07-09 16:50:44Z guillaume $

if ~nargin, action = ''; else action = varargin{1}; end

if strcmpi(action,'run')
    warning('"Run" is deprecated: use "Batch".');
    action = 'batch';
end

exit_code = 0;

switch lower(action)

    case {'','pet','fmri','eeg','quit'}
    %----------------------------------------------------------------------
        spm(varargin{:});

    case {'-h','--help'}
    %----------------------------------------------------------------------
        cmd = lower(spm('Ver'));
        fprintf([...
            '%s - Statistical Parametric Mapping\n',...
            'https://www.fil.ion.ucl.ac.uk/spm/\n',...
            '\n'],...
            upper(cmd));
        fprintf([...
            'Usage: %s [ fmri | eeg | pet ]\n',...
            '       %s COMMAND [arg...]\n',...
            '       %s [ -h | --help | -v | --version ]\n',...
            '\n',...
            'Commands:\n',...
            '    batch          Run a batch job\n',...
            '    script         Execute a script\n',...
            '    function       Execute a function\n',...
            '    eval           Evaluate a MATLAB expression\n',...
            '    [NODE]         Run a specified batch node\n',...
            '\n',...
            'Options:\n',...
            '    -h, --help     Print usage statement\n',...
            '    -v, --version  Print version information\n',...
            '\n',...
            'Run ''%s [NODE] help'' for more information on a command.\n'],...
            cmd, cmd, cmd, cmd);

    case {'-v','--version'}
    %----------------------------------------------------------------------
        spm_banner;

    case 'batch'
    %----------------------------------------------------------------------
        inputs = varargin(2:end);
        flg = ismember(inputs,'--silent');
        if any(flg)
            quiet = true;
            inputs = inputs(~flg);
        else
            quiet = false;
        end
        flg = ismember(inputs,'--modality');
        if any(flg)
            idx = find(flg);
            try
                modality = inputs{idx+1};
            catch
                error('Syntax is: --modality <modality>.');
            end
            inputs([idx idx+1]) = [];
        else
            modality = 'fmri';
        end
        flg = ismember(inputs,'--cmdline');
        if any(flg)
            cmdline = true;
            inputs = inputs(~flg);
        else
            cmdline = false;
        end
        spm_banner(~quiet);
        spm('defaults',modality);
        spm_get_defaults('cmdline',cmdline);
        spm_jobman('initcfg');
        if isempty(inputs)
            h = spm_jobman;
            waitfor(h,'Visible','off');
        else
            try
                spm_jobman('run', inputs{:});
            catch
                fprintf('Execution failed: %s\n', inputs{1});
                exit_code = 1;
            end
        end
        spm('Quit');

    case 'script'
    %----------------------------------------------------------------------
        spm_banner;
        assignin('base','inputs',varargin(3:end));
        try
            if nargin > 1
                spm('Run',varargin(2));
            else
                spm('Run');
            end
        catch
            exit_code = 1;
        end

    case 'function'
    %----------------------------------------------------------------------
        spm_banner;
        if nargin == 1
            fcn = spm_input('function name','!+1','s','');
        else
            fcn = varargin{2};
        end
        try
            feval(fcn,varargin{3:end});
        catch
            exit_code = 1;
        end

    case 'eval'
    %----------------------------------------------------------------------
        spm_banner;
        if nargin == 1
            expr = spm_input('expression to evaluate','!+1','s','');
        else
            expr = varargin{2};
        end
        try
            eval(expr);
        catch
            exit_code = 1;
        end

    otherwise % cli
    %----------------------------------------------------------------------
        %spm('defaults','fmri');
        %spm_get_defaults('cmdline',true);
        spm_jobman('initcfg');
        try
            spm_cli(varargin{:});
        catch
            exit_code = 1;
        end

end

%-Display error message and return exit code (or use finish.m script)
%--------------------------------------------------------------------------
if exit_code ~= 0
    err = lasterror;
    msg{1} = err.message;
    if isfield(err,'stack')
        for i=1:numel(err.stack)
            if err.stack(i).line
                l = sprintf(' (line %d)',err.stack(i).line);
            else
                l = '';
            end
            msg{end+1} = sprintf('Error in %s%s',err.stack(i).name,l);
        end
    end
    fprintf('%s\n',msg{:});

    exit(exit_code);
end

%==========================================================================
function spm_banner(verbose)
% Display text banner
if nargin && ~verbose, return; end
[vspm,rspm] = spm('Ver');
tlkt = ver(spm_check_version);
if isdeployed, mcr = ' (standalone)'; else mcr = ''; end
fprintf('%s, version %s%s\n',vspm,rspm,mcr);
fprintf('%s, version %s\n',tlkt.Name,version);
spm('asciiwelcome');

author: spm


text:
function pid2 = pid2pid(pid1,direction)
% PID2PID Convert from Form 2 back to Form 1 of PID controller.
%         PID2PID takes the 3 gains of the Form 1 PID controller and
%         converts them into the gains of the Form 2 PID controller.

% Author: Craig Borghesani
% Date: 11/13/94
% Revised:
% Copyright (c) 1999, Prentice-Hall

if direction == 2,
 Kp = pid1(1);
 Ki = pid1(2);
 Kd = pid1(3);

 KP = max(roots([1, -Kp, Kd*Ki]));
 KI = Ki;
 KD = Kd/KP;

 pid2 = [KP,KI,KD,direction*20];

else

 KP = pid1(1);
 KI = pid1(2);
 KD = pid1(3);

 Kp = KP + KD*KI;
 Ki = KI;
 Kd = KD*KP;

 pid2 = [Kp,Ki,Kd,direction*20];
end

author: Sable

repo: mcbench-benchmarks


text:
%% Create PNG image with alpha transparency
%
% The sample shows how to create an RGBA image and store it as a PNG file.
% It also demonstrates how to set custom PNG compression parameters.
%
% Sources:
%
% * <https://github.com/opencv/opencv/blob/3.4.1/samples/cpp/tutorial_code/snippets/imgcodecs_imwrite.cpp>
%

%%
% create image with alpha channel
sz = [480 640];
img = create_rgba_image(sz);
whos img

%%
% write to PNG file with alpha data
fname = fullfile(tempdir(), 'alpha.png');
if true
    cv.imwrite(fname, img, 'PngCompression',9, 'PngStrategy','RLE');
else
    imwrite(img(:,:,1:3), fname, 'Alpha',img(:,:,4))
end
imfinfo(fname)

%%
% show image (over checkerboard image as background to better see transparency)
bg = create_checkerboard_image(sz);
figure('Menubar','none', 'Color','k', 'Name','RGBA')
if ~mexopencv.isOctave()
    imshow(bg, 'InitialMagnification',100, 'Border','tight')
else
    image(bg), axis image off
    set(gca, 'Units','normalized', 'Position',[0 0 1 1])
end
image('CData',img(:,:,1:3), 'AlphaData',img(:,:,4))

%%
% Helper functions

function img = create_rgba_image(sz)
    %CREATE_RGBA_IMAGE  Create image with transparency, with a gradient effect

    nrows = sz(1);
    ncols = sz(2);
    img = zeros(nrows, ncols, 4, 'uint8');
    [I,J] = ndgrid(1:nrows, 1:ncols);
    img(:,:,1) = uint8(255 * (nrows-I+1)/nrows);     % red
    img(:,:,2) = uint8(255 * (ncols-J+1)/ncols);     % green
    img(:,:,3) = uint8(255);                         % blue
    img(:,:,4) = uint8(0.8 * sum(img(:,:,[1 2]),3)); % alpha
end

function img = create_checkerboard_image(sz)
    %CREATE_CHECKERBOARD_IMAGE  Create checkerboard image

    % n should evenly divide both width and height
    if true
        n = 40;  %HACK: hardcoded for 640x480
    else
        n = gcd(sz(1), sz(2));
    end
    s = sz / n;
    assert(isequal(s, fix(s)));
    img = kron(bsxfun(@xor, mod(1:s(1),2).', mod(1:s(2),2)), ones(n));
    img = repmat(max(img, 0.75), [1 1 3]);
    img = uint8(255 * img);
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function rename(oldfile, newfile)

% RENAME is an overloaded version of the MATLAB rename function.
% This version is faster than the original.

% Copyright (C) 2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

system(sprintf('mv %s %s', oldfile, newfile));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function ht = my_yticklabels(varargin)

%MY_YTICKLABELS replaces YTickLabels with "normal" texts
%   accepting multiline texts and TEX interpreting
%   and shrinks the axis to fit the texts in the window
%
%    ht = my_yticklabels(Ha, ytickpos, ytickstring)
% or
%    ht = my_yticklabels(ytickpos, ytickstring)
%
%  in:    ytickpos     YTick positions [N*1]
%        ytickstring   Strings to use as labels {N*1} cell of cells
%
% Examples:
% plot(randn(20,1))
% ytl = {{'one';'two';'three'} '\alpha' {'\beta';'\gamma'}};
% h = my_yticklabels(gca,[-1 0 1],ytl);
% % vertical
% h = my_yticklabels([-1 0 1],ytl, ...
%     'Rotation',-90, ...
%     'VerticalAlignment','middle', ...
%     'HorizontalAlignment','center');

% Pekka Kumpulainen 5.3.2008

textopts = {};
if length(varargin{1})==1 && ...
        ishandle(varargin{1}) && ...
        strcmpi(get(varargin{1},'Type'),'axes');
    Ha = varargin{1};
    ytickpos = varargin{2};
    ytickstring = varargin{3};
    if nargin > 3
        textopts = varargin(4:end);
    end
else
    Ha = gca;
    %Hfig = get(Ha,'Parent');
    ytickpos = varargin{1};
    ytickstring = varargin{2};
    if nargin > 2
        textopts = varargin(3:end);
    end
end

set(Ha,'YTick',ytickpos, 'YTickLabel','')
h_olds = findobj(Ha, 'Tag', 'MUYTL');
if ~isempty(h_olds)
    delete(h_olds)
end

%% Make XTickLabels
NTick = length(ytickpos);
Xbot = min(get(gca,'XLim'));
ht = zeros(NTick,1);
for ii = 1:NTick
    ht(ii) = text('String',ytickstring{ii}, ...
        'Units','data', ...
        'VerticalAlignment', 'middle', ...
        'HorizontalAlignment', 'center', ...
        'Position',[Xbot ytickpos(ii)], ...
        'Tag','MUYTL');
end
if ~isempty(textopts)
    set(ht,textopts{:})
end

%% shift texts left to fit & squeeze axis if needed

set(Ha,'Units','pixels')
Axpos = get(Ha,'Position');
% set(Hfig,'Units','pixels')
% Figpos = get(Hfig,'Position');

set(ht,'Units','pixels')
TickPos = zeros(NTick,3);
TickExt = zeros(NTick,4);
for ii = 1:NTick
    TickPos(ii,:) = get(ht(ii),'Position');
    tmpext = get(ht(ii),'Extent');
    set(ht(ii),'Position',[TickPos(ii,1)-tmpext(3)/2-5 TickPos(ii,2:end)])
    TickExt(ii,:) = get(ht(ii),'Extent');
end

needmove = -(Axpos(1) + min(TickExt(:,1)));

if needmove>0;
    Axpos(1) = Axpos(1)+needmove+2;
    Axpos(3) = Axpos(3)-needmove+2;
    set(Ha,'Position',Axpos);
end

set(Ha,'Units','normalized')
set(ht,'Units','normalized')