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

% Last Modified by GUIDE v2.5 10-Feb-2023 16:27:47

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

% Choose default command line output for DQ_Spectra_GUI
handles.output = [];

% check input EEG
EEG = varargin{1};
avg_fft = varargin{2};
fft_labels = varargin{3};
yout = varargin{4};
yout_lab = varargin{5};
chanArray = varargin{6};
%guiwin_num = varargin{4};
guiwin_num = 1;

%GUI positions (for multiple DQ tables)

if guiwin_num ~= 1
    offset_GUI = 25 * randi([1 10],1); %offset by
    % %set(hObject, 'Units', 'normalized');
    figureposition = get(handles.figure1, 'Position');
    set(hObject, 'Position', ...
        [ figureposition(1)-offset_GUI figureposition(2)-offset_GUI  ...
        figureposition(3) figureposition(4)])
end

%check contents

% Update GUI with ERPSET info
%n_erp = numel(ALLERP);

%for the case of continuous EEG
eeg_names = EEG.setname;
handles.text_EEGSET_title.String = 'Selected EEG Dataset:';
handles.text_EEGSET_title.FontSize = 12;
handles.active_eegset.Style = 'text';
if numel(eeg_names) > 15
   handles.active_eegset.FontSize = 12;
   set(handles.active_eegset,'FontUnits', 'normalized');
end
%update handles
guidata(hObject, handles);

%ERPSET_title_str = ['ERPSET - ' erp_names(current_ERP)];
handles.active_eegset.String = eeg_names;
handles.active_eegset.Value = 1;

%AMS: Multiple EEGset options
handles.newerpwin.String = eeg_names;
handles.newerpwin.Value = 1;

%n_dq = 2; %power or amplitude
typenames = {'Power', 'Amplitude'};
n_dq = length(typenames);

handles.popupmenu_DQ_type.String = typenames;
%Amplitude first by default
handles.popupmenu_DQ_type.Value = n_dq;
[n_elec, n_bands] = size(avg_fft);
selected_DQ_type = handles.popupmenu_DQ_type.Value;

if selected_DQ_type == 1
    table_data = (avg_fft)^2; %Power

else
    table_data = avg_fft;

end

handles.dq_table.Data = table_data;
handles.orig_data = table_data;

nchan = EEG.nbchan;
chanArray = chanArray(chanArray<=nchan);
handles.chanArray = chanArray;

% electrode labels from EEGset(rows)
for i=1:length(chanArray)
    elec_labels{i} = EEG.chanlocs(chanArray(i)).labels;
end
listch = elec_labels;
handles.dq_table.RowName = elec_labels;
handles.orig_RowName = elec_labels;

%selections
handles.sel_row = n_elec; % set to max on load
handles.sel_col = n_bands; % set to max on load
handles.listch = listch;
handles.indxlistch = chanArray;
%set(handles.edit_channels,'String', vect2colon(chanArray, 'Delimiter', 'off'));

% frequency band column labels
handles.dq_table.ColumnName = fft_labels;
handles.orig_ColName = fft_labels;

% Set font size of DQ Table
desired_fontsize = erpworkingmemory('fontsizeGUI');
handles.dq_table.FontSize = desired_fontsize;
handles.heatmap_on = 0;

% Set outliers text window off
set(handles.stdwindow,'Enable','Off');

%set outliers value in handles off initially
handles.outliers_on = 0;

% Update handles structure
handles.EEG = EEG;
handles.avg_fft = avg_fft;
handles.yout = yout;
handles.yout_lab = yout_lab;
%
% if n_erp == 0
%     %case of aSME preavg
%     handles.ALLERP = ERP;
% else
%     handles.ALLERP = ALLERP;
% end

guidata(hObject, handles);

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_DQ_type contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_DQ_type
% handles.popupmenu_DQ_type.Value saves the indx of the selected DQ Measure
selected_DQ_type = handles.popupmenu_DQ_type.Value;
avg_fft = handles.avg_fft;
%selected_bin = handles.popupmenu_bin.Value;

if strcmp(handles.popupmenu_DQ_type.String{selected_DQ_type},'Amplitude')
    table_data = avg_fft;
else
    table_data = (avg_fft).^2; %power
end

handles.dq_table.Data = table_data;
handles.orig_data = table_data;

if handles.heatmap_on
    redraw_heatmap(hObject, eventdata, handles);
end

if handles.outliers_on
   clear_heatmap(hObject, eventdata, handles);
   handles.heatmap_on = 0;

   redraw_outliers(hObject, eventdata, handles);
   set(handles.checkbox_outliers,'Value',1);
end

% Update handles structure
guidata(hObject, handles);

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

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_bin contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_bin
% handles.popupmenu_DQ_type.Value saves the indx of the selected DQ Measure
% selected_DQ_type = handles.popupmenu_DQ_type.Value;
% selected_bin = handles.popupmenu_bin.Value;
%
% % Check data exists, plot
% if isempty(handles.ERP.dataquality(selected_DQ_type).data)
%
%     % if pointwise SEM, use ERP.binerror
%     if strcmp(handles.ERP.dataquality(selected_DQ_type).type,'Point-wise SEM') && isempty(handles.ERP.binerror) == 0
%         table_data = handles.ERP.binerror(:,:,selected_bin);
%     else
%
%         % Data empty here.
%         table_data = nan(1);
%         disp('DQ data not found for this DQ type and bin. Perhaps it has been cleared?');
%     end
%
% else
%     % data is present and correct
%     table_data = handles.ERP.dataquality(selected_DQ_type).data(:,:,selected_bin);
% end
%
%
% handles.dq_table.Data = table_data;
% handles.orig_data = table_data;
%
%
% %if user switches bin and both heatmap & outliers on,
% %use shortcircuit to clear outliers and redraw heatmap only
% if handles.heatmap_on %|| handles.outliers_on
%     clear_outliers(hObject, eventdata, handles);
%     redraw_heatmap(hObject, eventdata, handles);
%     %turn outliers off
%     handles.outliers = 0;
%     set(handles.checkbox_outliers,'Value',0);
%
% end
%
% %if only outliers on, then clear heatmap and redraw outliers
% if handles.outliers_on
%    clear_heatmap(hObject, eventdata, handles);
%    handles.heatmap_on = 0;
%
%    redraw_outliers(hObject, eventdata, handles);
%    set(handles.checkbox_outliers,'Value',1);
% end
%
%
% % Update handles structure
% guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function popupmenu_bin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_bin (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 checkbox_text_labels.
% function checkbox_text_labels_Callback(hObject, eventdata, handles)
% % hObject    handle to checkbox_text_labels (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 checkbox_text_labels
% %selected_DQ_type = handles.popupmenu_DQ_type.Value;
% %selected_bin = handles.popupmenu_bin.Value;
%
% % if strcmp(handles.ERP.dataquality(selected_DQ_type).type,'SD Across Trials') && isempty(handles.ERP.binerror) == 0
% %     table_data = handles.ERP.dataquality(selected_DQ_type).data.SD_bias(:,:,selected_bin);
% % else
% %     table_data = handles.ERP.dataquality(selected_DQ_type).data(:,:,selected_bin);
% %
% % end
% % handles.dq_table.Data = table_data;
% % handles.orig_data = table_data;
%
% % Time-window labels
% clear tw_labels
% ERP = handles.ERP;
% n_dq = numel(ERP.dataquality);
% %[n_elec, n_tw, n_bin] = size(ERP.dataquality(selected_DQ_type).data);
% if strcmp(handles.ERP.dataquality(selected_DQ_type).type,'SD Across Trials') && isempty(handles.ERP.binerror) == 0
%     [n_elec, n_tw, n_bin] = size(ERP.dataquality(selected_DQ_type).data.SD_bias);
% else
%     [n_elec, n_tw, n_bin] = size(ERP.dataquality(selected_DQ_type).data);
% end
% if isfield(ERP.dataquality(selected_DQ_type),'time_window_labels') && isempty(ERP.dataquality(selected_DQ_type).time_window_labels) == 0 && handles.checkbox_text_labels.Value == 1
%     tw_labels = ERP.dataquality(selected_DQ_type).time_window_labels;
% elseif isempty(ERP.dataquality(selected_DQ_type).times)
%     tw_labels = [];
% elseif n_tw == 0  % some data problem, no tw here
%     tw_labels{1} = 'No data here - measure cleared?';
% else
%     for i=1:n_tw
%         tw_labels{i} = [num2str(ERP.dataquality(selected_DQ_type).times(i,1)) ' : ' num2str(ERP.dataquality(selected_DQ_type).times(i,2))];
%     end
% end
% handles.dq_table.ColumnName = tw_labels;
%
% if handles.heatmap_on
%     redraw_heatmap(hObject, eventdata, handles);
% end
%
%
%  % Update handles structure
%  guidata(hObject, handles);

% --- Executes on button press in pushbutton_xls.
function pushbutton_xls_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_xls (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
empty_filename = [];
selected_DQ_type = handles.popupmenu_DQ_type.Value;
avg_fft = handles.avg_fft; %only the average across frequencies within band
chans_per_row = handles.orig_RowName;
band_per_col = handles.orig_ColName;

%sd_correction = handles.sdcorrection.Value;
save_spectral_dq(avg_fft,chans_per_row, band_per_col, selected_DQ_type, empty_filename,'xlsx')

% --- Executes on button press in pushbutton_mat.
function pushbutton_mat_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_mat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
empty_filename = [];
selected_DQ_type = handles.popupmenu_DQ_type.Value;
avg_fft = handles.avg_fft; %only the average across frequencies within band
chans_per_row = handles.orig_RowName;
band_per_col = handles.orig_ColName;

%sd_correction = handles.sdcorrection.Value;
save_spectral_dq(avg_fft,chans_per_row, band_per_col, selected_DQ_type, empty_filename,'mat')

% --- Executes on button press in pushbutton_help.
function pushbutton_help_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web https://github.com/lucklab/erplab/wiki/Spectral-Data-Quality-(continuous-eeg) -browser

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

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
delete(hObject);

% --- Executes on button press in checkbox_heatmap.
function checkbox_heatmap_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_heatmap (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 checkbox_heatmap
heatmap_on = get(hObject,'Value');

if heatmap_on == 1

    %if heatmap_on, then outliers not possible so clear outliers
    clear_outliers(hObject, eventdata, handles);
    handles.outliers_on = 0;
    set(handles.checkbox_outliers, 'Value', 0);

    redraw_heatmap(hObject, eventdata, handles);
    handles.heatmap_on = 1;
else
    clear_heatmap(hObject, eventdata, handles);
    handles.heatmap_on = 0;

    %if outliers is on, then keep outliers active
    if handles.outliers_on == 1
        redraw_outliers(hOBject, eventdata,handles);
    end

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

function redraw_heatmap(hObject, eventdata, handles)

color_map = viridis;
data = handles.dq_table.Data;

if any([isnan(data(1,:))])
    disp('Cannot create heatmap if NaN is present')
    return
end

data_min = min(data(:));
range_val = max(data(:)) - data_min;
range_colormap = size(color_map,1); % as in, 256 shades?
val_increase_per_shade = range_val / range_colormap;

% Use this @ anonymous function to make HTML tag in box in loop below
colergen = @(color,text) ['

',text,'

'];

for cell = 1:numel(data)
    data_here = data(cell);
    shades_up_here = round((data_here - data_min) / val_increase_per_shade);
    if shades_up_here < 1
        shades_up_here = 1;
    end
    if shades_up_here > range_colormap
        shades_up_here = range_colormap;
    end
    RGB_here = color_map(shades_up_here,:);
    hex_color_here = ['#' dec2hex(round(255*RGB_here(1)),2) dec2hex(round(255*RGB_here(2)),2) dec2hex(round(255*RGB_here(3)),2)];
    data2{cell} = colergen(hex_color_here,num2str(data_here));
end

data2 = reshape(data2,size(data));

handles.dq_table.Data = data2;

function clear_heatmap(hObject, eventdata, handles)
handles.dq_table.Data = handles.orig_data;

% --- Executes when entered data in editable cell(s) in dq_table.
function dq_table_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to dq_table (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.CONTROL.TABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)

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

% --- Executes during object creation, after setting all properties.
function newerpwin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to newerpwin (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 pushbutton_selERP.
function pushbutton_selERP_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_selERP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selected_erpset = handles.newerpwin.Value;
sel_ERP = handles.ALLERP(selected_erpset);
DQ_Table_GUI(sel_ERP, handles.ALLERP, selected_erpset,2);

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

% Hint: get(hObject,'Value') returns toggle state of checkbox_heatmap
outliers_on = get(hObject,'Value'); % this is not the same as handles.outliers_on

if outliers_on == 1
    set(handles.stdwindow,'Enable','On');
%     set(handles.chwindow,'Enable','On');
%     set(handles.chbutton,'Enable','On');
else
    set(handles.stdwindow,'Enable','Off');
%     set(handles.chwindow,'Enable','Off');
%     set(handles.chbutton,'Enable','Off');
end

%updated the handles object for outliers to be in sync with hObject
if outliers_on == 1
    handles.outliers_on = 1;
else
    handles.outliers_on = 0;
end

if handles.outliers_on == 1

    %if heatmap is currently on, stop it and turn its states off
    %before applying outliers fxn

    if handles.heatmap_on == 1
        clear_heatmap(hObject, eventdata, handles);
        handles.heatmap_on = 0;
        set(handles.checkbox_heatmap, 'Value', 0);

        %handles.outliers_on = 1;
        redraw_outliers(hObject, eventdata, handles);

    else
        %handles.outliers_on = 1;
        clear_outliers(hObject, eventdata, handles);
        %guidata(hObject, handles);
        redraw_outliers(hObject, eventdata, handles);

    end

else %but if outliers is off, and heatmap is wanted, you can do it

%     if handles.heatmap_on ==1
%
%         clear_outliers(hObject, eventdata, handles);
%         redraw_heatmap(hObject, eventdata, handles);
%         handles.outliers_on = 0;
%
%     else
%         clear_outliers(hObject, eventdata, handles);
%         handles.outliers_on = 0;
%
%     end

    %also, redraw initial data/channels without outliers
    clear_outliers(hObject, eventdata, handles)

end

% %if heatmap is currently on, stop it and turn its states off
% %before applying outliers fxn
% if handles.heatmap_on == 1
%
%     clear_heatmap(hObject, eventdata, handles);
%     handles.heatmap_on = 0;
%     set(handles.checkbox_heatmap, 'Value', 0);
%
%     if outliers_on == 1
%         handles.outliers_on = 1;
%         redraw_outliers(hObject, eventdata, handles);
%     else
%
%         set(handles.stdwindow,'Enable','Off');
%         set(handles.chwindow,'Enable','Off');
%         set(handles.chbutton,'Enable','Off');
%         clear_outliers(hObject, eventdata, handles);
%         handles.outliers_on = 0;
%
%     end
%
% else
%
%      if outliers_on == 1
%         handles.outliers_on = 1;
%         redraw_outliers(hObject, eventdata, handles);
%      else
%         set(handles.stdwindow,'Enable','Off');
%         set(handles.chwindow,'Enable','Off');
%         set(handles.chbutton,'Enable','Off');
%         clear_outliers(hObject, eventdata, handles);
%         handles.outliers_on = 0;
%
%      end
%
% end
% Update handles structure
guidata(hObject, handles);

function redraw_outliers(hObject, eventdata, handles)
handles = guidata(hObject); %get the most updated handles struct
data = handles.dq_table.Data;

if iscell(data)
    %in case of new std from stdwindow
    data = handles.orig_data;
end
%
% %either default(all) or from chbutton
% chans_to_use = handles.indxlistch;
% data = data(chans_to_use,:);
% n_elec = length(chans_to_use);
% ERPtouse = handles.ERP.chanlocs;
%
% for i=1:n_elec
%     curr_chanInd = chans_to_use(i);
%     elec_labels{i} = ERPtouse(curr_chanInd).labels;
% end

%save new labels to handles
% handles.dq_table.RowName = elec_labels;

%compute outliers as X standard deviations from mean across channels

col_means = mean(data,1);
col_std = std(data,0,1);
chosen_std = str2double((handles.stdwindow.String));

% Use this @ anonymous function to make HTML tag in box in loop below
colergen = @(color,text) ['

',text,'

'];

for cell = 1:numel(data)

    data_here = data(cell);
    [d_row,d_col] = ind2sub(size(data),cell);

    neg_thresh = col_means(d_col) - (chosen_std*col_std(d_col));
    pos_thresh = col_means(d_col) + (chosen_std*col_std(d_col));

    if data_here < neg_thresh || data_here > pos_thresh
        hex_color_here = ['#' dec2hex(255,2) dec2hex(0,2) dec2hex(0,2)];
        data2{cell} = colergen(hex_color_here,num2str(data_here));
    else
        data2{cell} = num2str(data_here);

    end

end

data2= reshape(data2,size(data));
handles.dq_table.Data = data2;

function clear_outliers(hObject, eventdata, handles)
%handles = guidata(hObject);
handles.dq_table.Data = handles.orig_data;
handles.dq_table.RowName = handles.orig_RowName;
%handles.indxlistch = handles.orig_indxlistch;

% Re-Prepare List of current Channels
%chanArray = handles.orig_indxlistch; %default
%handles.indxlistch = chanArray; %default
%set(handles.chwindow, 'String', vect2colon(chanArray, 'Delimiter', 'off'));
 % Update handles structure
guidata(hObject, handles);

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

newstd = get(hObject,'String');
handles.stdwindow.String= newstd;
redraw_outliers(hObject, eventdata, handles);

guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function stdwindow_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stdwindow (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 chwindow_Callback(hObject, eventdata, handles)
% % hObject    handle to chwindow (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 chwindow as text
% %        str2double(get(hObject,'String')) returns contents of chwindow as a double
%
% ch = get(hObject,'string');
% nch = length(handles.listch);
%
% ch_val = eval(ch);
%
% if ~isempty(ch)
%
% %     testch = regexpi(ch,':') ;
% %
% %     if isempty(testch)
% %
% %         try
% %             ch_val = eval(ch);
% %             handles.listch(ch_val); %attempt to index
% %
% %         catch
% %             msgboxText =  'Invalid channel input: please enter channels as integers, with a space between each number, or ch1:chN array syntax';
% %             title = 'ERPLAB: channel GUI input';
% %             errorfound(msgboxText, title);
% %
% %         end
% %     else
% %         ch_val = eval(ch);
% %
% %     end
% %
%
%     tf = checkchannels(ch_val, nch, 1);
%
%     if tf
%         return
%     end
%
%
% %     if length(ch_val) > length(handles.orig_indxlistch)
% %         msgboxText =  'Exceeded Number of Available Channels';
% %         title = 'ERPLAB: channel GUI input';
% %         errorfound(msgboxText, title);
% %         return
% %     end
% %
%     set(handles.chwindow, 'String', vect2colon(ch_val, 'Delimiter', 'off'));
%     handles.indxlistch = ch_val;
%     % Update handles structure
%     guidata(hObject, handles);
%     redraw_outliers(hObject, eventdata, handles);
%     guidata(hObject, handles);
%
% else
%     msgboxText =  'Not valid channel';
%     title = 'ERPLAB: channel GUI input';
%     errorfound(msgboxText, title);
%     return
% end
%

% --- Executes during object creation, after setting all properties.
function chwindow_CreateFcn(hObject, eventdata, handles)
% hObject    handle to chwindow (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 chbutton.
function chbutton_Callback(hObject, eventdata, handles)
% hObject    handle to chbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
listch = handles.listch; %true channels list as labels
indxlistch = handles.indxlistch; %true array of channel indexs
indxlistch = indxlistch(indxlistch<=length(listch)); % true array of channel index if less than expected labels
titlename = 'Select Channel(s)';
if get(hObject, 'Value')
        if ~isempty(listch)
                ch = browsechanbinGUI(listch, indxlistch, titlename);
                if ~isempty(ch)
                        set(handles.chwindow, 'String', vect2colon(ch, 'Delimiter', 'off'));
                        handles.indxlistch = ch;
                        % Update handles structure
                        guidata(hObject, handles);
                        redraw_outliers(hObject, eventdata, handles);
                        guidata(hObject, handles);

                else
                        disp('User selected Cancel')
                        return
                end
        else
                msgboxText =  'No channel information was found';
                title = 'ERPLAB: ploterp GUI input';
                errorfound(msgboxText, title);
                return
        end
end

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

newactive = get(hObject,'Value');
ERPs = handles.ALLERP;
ERP = ERPs(newactive);

n_dq = numel(ERP.dataquality);
for i=1:n_dq
    type_names{i} = ERP.dataquality(i).type;
end

handles.popupmenu_DQ_type.String = type_names;
handles.popupmenu_DQ_type.Value = n_dq;

[n_elec, n_tw, n_bin] = size(ERP.dataquality(n_dq).data);

if n_elec == 0
    % if the dq data is of zero size, then the 3rd dim may be mis-sized.
    % So set to default of ERP.nbin instead.
    n_bin = ERP.nbin;
end

n_bin_names = numel(ERP.bindescr);
if n_bin_names == n_bin

    for i=1:n_bin
        bin_names{i} = ['BIN ' num2str(i) ' - ' ERP.bindescr{i}];
    end
else
    % if not every bin has a bin description, leave then off
    for i=1:n_bin
        bin_names{i} = ['BIN ' num2str(i)];
    end
end

handles.popupmenu_bin.String = bin_names;

% handles.popupmenu_DQ_type.Value saves the indx of the selected DQ Measure
selected_DQ_type = handles.popupmenu_DQ_type.Value;
selected_bin = handles.popupmenu_bin.Value;

table_data = ERP.dataquality(selected_DQ_type).data(:,:,selected_bin);
handles.dq_table.Data = table_data;
handles.orig_data = table_data;

% electrode labels from ERPset, iff present and number matches
if isfield(ERP.chanlocs,'labels') && numel(ERP.chanlocs) == n_elec
    for i=1:n_elec
        elec_labels{i} = ERP.chanlocs(i).labels;
    end
else

    for i=1:ERP.nchan
        elec_labels{i} = i;
    end
end
handles.dq_table.RowName = elec_labels;

% Time-window labels
if isfield(ERP.dataquality(selected_DQ_type),'time_window_labels') && isempty(ERP.dataquality(selected_DQ_type).time_window_labels) == 0  && handles.checkbox_text_labels.Value == 1
    tw_labels = ERP.dataquality(selected_DQ_type).time_window_labels;
elseif isempty(ERP.dataquality(selected_DQ_type).times)
    tw_labels = [];
else
    for i=1:n_tw
        tw_labels{i} = [num2str(ERP.dataquality(selected_DQ_type).times(i,1)) ' : ' num2str(ERP.dataquality(selected_DQ_type).times(i,2))];
    end
end
if n_tw == 0
    tw_labels = 'No data here. Perhaps it was cleared?';
end
handles.dq_table.ColumnName = tw_labels;

% Set font size of DQ Table
desired_fontsize = erpworkingmemory('fontsizeGUI');
handles.dq_table.FontSize = desired_fontsize;
handles.heatmap_on = 0;

%
% Prepare List of current Channels
%
nchan  = ERP.nchan; % Total number of channels
if ~isfield(ERP.chanlocs,'labels')
        for e=1:nchan
                ERP.chanlocs(e).labels = ['Ch' num2str(e)];
        end
end
listch = {''};
for ch =1:nchan
        listch{ch} = [num2str(ch) ' = ' ERP.chanlocs(ch).labels ];
end
handles.listch     = listch;

chanArray = 1:ERP.nchan; %default
handles.indxlistch = chanArray; %default
set(handles.chwindow, 'String', vect2colon(chanArray, 'Delimiter', 'off'));

% Set outliers text window off
set(handles.stdwindow,'Enable','Off');
set(handles.chwindow,'Enable','Off');
set(handles.chbutton,'Enable','Off');

% Update handles structure
handles.ERP = ERP;
handles.ALLERP = ERPs;

%clear all perviously set options
set(handles.checkbox_outliers,'Value',0);
set(handles.checkbox_heatmap,'Value',0);
set(handles.checkbox_text_labels,'Value',0);
set(handles.stdwindow,'Enable','Off');
set(handles.chwindow,'Enable','Off');
set(handles.chbutton,'Enable','Off');

%check to see if outliers is on prior to switching active erpset?
%checkbox_outliers_Callback(hObject, eventdata, handles)

% outliers_on = get(handles.checkbox_outliers,'Value');
%
% if outliers_on == 1
%     handles.outliers_on = 1;
%     set(handles.stdwindow,'Enable','On');
%     set(handles.chwindow,'Enable','On');
%     set(handles.chbutton,'Enable','On');
%     redraw_outliers(hObject, eventdata, handles);
%
% else
%     handles.heatmap_on = 0;
%     set(handles.stdwindow,'Enable','Off');
%     set(handles.chwindow,'Enable','Off');
%     set(handles.chbutton,'Enable','Off');
%     clear_outliers(hObject, eventdata, handles);
%
%
% end

guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function active_eegset_CreateFcn(hObject, eventdata, handles)
% hObject    handle to active_eegset (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 tf = checkchannels(chx, nchan, showmsg)

if nargin<3
        showmsg = 1;
end
tf = 0; % no problem by default

if ~mod(chx, 1) == 0
    if showmsg
        msgboxText =  'Invalid channel indexing.';
        title = 'ERPLAB: basicfilterGUI() error:';
        errorfound(msgboxText, title);
    end
    tf = 1; %

end

if isempty(chx)
        if showmsg
                msgboxText =  'Invalid channel indexing.';
                title = 'ERPLAB: basicfilterGUI() error:';
                errorfound(msgboxText, title);
        end
        tf = 1; %
        return
end
if ~isempty(find(chx>nchan))
        if showmsg
                msgboxText =  ['You only have %g channels,\n'...
                        'so you cannot specify indices greater than this.'];
                title = 'ERPLAB: basicfilterGUI() error:';
                errorfound(sprintf(msgboxText, nchan), title);
        end
        tf = 1; %
        return
end
if ~isempty(find(chx<1))
        if showmsg
                msgboxText =  'You cannot use zero or a negative number as a channel indexing';
                title = 'ERPLAB: basicfilterGUI() error:';
                errorfound(msgboxText, title);
        end
        tf = 1; %
        return
end
if length(chx)>length(unique_bc2(chx))
        if showmsg
                msgboxText =  ['Repeated channels are not allowed.\n'...
                        'Therefore, ERPLAB will get rid of them.'];
                title = 'ERPLAB: basicfilterGUI() error:';
                errorfound(sprintf(msgboxText), title, [1 1 0], [0 0 0], 0)
        end
        tf = 0; %
        return
end

% --- Executes on button press in sdcorrection.
function sdcorrection_Callback(hObject, eventdata, handles)
% hObject    handle to sdcorrection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selected_DQ_type = handles.popupmenu_DQ_type.Value;
selected_bin = handles.popupmenu_bin.Value;

if handles.sdcorrection.Value == 1
    table_data = handles.ERP.dataquality(selected_DQ_type).data.SD_unbias(:,:,selected_bin); %SD (Gurland & Tripathi, 1971)
else
    table_data = handles.ERP.dataquality(selected_DQ_type).data.SD_bias(:,:,selected_bin); %SD (N-1)
end
handles.dq_table.Data = table_data;
handles.orig_data = table_data;

%update handles struct
guidata(hObject, handles);

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

% --- Executes when selected cell(s) is changed in dq_table.
function dq_table_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to dq_table (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.CONTROL.TABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
if numel(eventdata.Indices)
    row_here = eventdata.Indices(:,1);
    col_here = eventdata.Indices(:,2);
    old_row = handles.sel_row;
    old_col = handles.sel_col;
    handles.sel_row = row_here;
    handles.sel_col = col_here;
%     if isequal(row_here,old_row) == 0
%         row_text = ['Row number ' num2str(row_here) ' now selected'];
%         col_text = ['Column Number' num2str(col_here) ' now selected'];
%         disp(row_text)
%     end
    guidata(hObject, handles);

% catch
%    eventdata = handles.ch;
%    guidata(hObject,handles);
%

end

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

chans_to_plot = handles.sel_row;
labels_to_plot = handles.sel_col;
yout = handles.yout;
yout_lab = handles.yout_lab;
msgn = 'whole';

if numel(unique_bc2(labels_to_plot)) > 1

    msgboxText =  'Sorry, you may only plot one frequency band at a time!';
    title_header = 'ERPLAB: pop_continuousFFT() error';
    errorfound(msgboxText, title_header);

    return

elseif any(isnan(yout{unique_bc2(labels_to_plot)}))
    msgboxText =  'Sorry, you cannot plot this frequency band due to NaNs';
    title_header = 'ERPLAB: pop_continuousFFT() error';
    errorfound(msgboxText, title_header);

else

    dq_selected = handles.popupmenu_DQ_type.Value;

    if (strcmp(handles.popupmenu_DQ_type.String{dq_selected},'Amplitude'))

        fname = handles.EEG.setname;
        h = figure('Name',['<< ' fname ' >>  ERPLAB Amplitude Spectrum'],...
            'NumberTitle','on', 'Tag','Plotting Spectrum',...
            'Color',[1 1 1]);
        p_yout = yout{unique_bc2(labels_to_plot)};

        if numel(chans_to_plot) == 1
            p_yout_sel = p_yout(:,chans_to_plot); %only use selected channels
            p_yout_lab = yout_lab{unique_bc2(labels_to_plot)}';
            lege = sprintf('EEG Channel: ');
        else
            p_yout_sel = p_yout(:,chans_to_plot); %only use selected channels
            p_yout_sel = mean(p_yout_sel,2); %average across selected channels;
            p_yout_lab = yout_lab{unique_bc2(labels_to_plot)}';
            lege = sprintf('EEG Channel Average: ');
        end

        if numel(p_yout_lab) == 1 %impulse at one frequency/ create impulse
            plot([p_yout_lab p_yout_lab], [0 p_yout_sel]);
        else
            plot(p_yout_lab,p_yout_sel);
        end

        try
            axis([min(p_yout_lab)  max(p_yout_lab)  min(p_yout_sel)*0.9 max(p_yout_sel)*1.1])
        catch % in the case of impulse
            axis([min(p_yout_lab)*0.99  max(p_yout_lab)*1.01  min(p_yout_sel)*0.99 max(p_yout_sel)*1.01])
        end

        if isfield(handles.EEG.chanlocs,'labels')
           % lege = sprintf('EEG Channel Average: ');
            for i=1:length(chans_to_plot)
                lege =   sprintf('%s %s', lege, handles.EEG.chanlocs(chans_to_plot(i)).labels);
            end
            lege = sprintf('%s *%s', lege, msgn);
            legend(lege)
        else
            legend(['EEG Channel: ' vect2colon(chanArray,'Delimiter', 'off') '  *' msgn])
        end

        title('Single-Sided Amplitude Spectrum of y(t)')
        xlabel('Frequency (Hz)')
        ylabel('Amplitude - absolute single-sided (original units)')

        %     if plot_type == 1
        %         set(gca,'XScale','log')
        %         set(gca,'XTick',[1 10 60 100])
        %         if f1 == 0
        %             xstart = 0.1
        %         else
        %             xstart = f1;
        %         end
        %         xlim = [xstart f2];
        %         xlabel('Frequency (Hz) - log scale')
        %
        %     end
    else %choose power

        fname = handles.EEG.setname;
        h = figure('Name',['<< ' fname ' >>  ERPLAB Power Spectrum'],...
            'NumberTitle','on', 'Tag','Plotting Spectrum',...
            'Color',[1 1 1]);
        p_yout = yout{unique_bc2(labels_to_plot)};

        if numel(chans_to_plot) == 1
            p_yout_sel = (p_yout(:,chans_to_plot)).^2; %only use selected channels
            p_yout_lab = yout_lab{unique_bc2(labels_to_plot)}';
            lege = sprintf('EEG Channel: ');
        else
            p_yout_sel = (p_yout(:,chans_to_plot)).^2; %only use selected channels
            p_yout_sel = mean(p_yout_sel,2); %average across selected channels;
            p_yout_lab = yout_lab{unique_bc2(labels_to_plot)}';
            lege = sprintf('EEG Channel Average: ');
        end

%         plot(p_yout_lab,p_yout_sel);
%         axis([min(p_yout_lab)  max(p_yout_lab)  min(p_yout_sel)*0.9 max(p_yout_sel)*1.1])
%
        if numel(p_yout_lab) == 1 %impulse at one frequency/ create impulse
            plot([p_yout_lab p_yout_lab], [0 p_yout_sel]);
        else
            plot(p_yout_lab,p_yout_sel);
        end

        try
            axis([min(p_yout_lab)  max(p_yout_lab)  min(p_yout_sel)*0.9 max(p_yout_sel)*1.1])
        catch % in the case of impulse
            axis([min(p_yout_lab)*0.99  max(p_yout_lab)*1.01  min(p_yout_sel)*0.99 max(p_yout_sel)*1.01])
        end

        if isfield(handles.EEG.chanlocs,'labels')
            %lege = sprintf('EEG Channel Average: ');
            for i=1:length(chans_to_plot)
                lege =   sprintf('%s %s', lege, handles.EEG.chanlocs(chans_to_plot(i)).labels);
            end
            lege = sprintf('%s *%s', lege, msgn);
            legend(lege)
        else
            legend(['EEG Channel: ' vect2colon(chanArray,'Delimiter', 'off') '  *' msgn])
        end

        title('Single-Sided Power Spectrum of y(t)')
        xlabel('Frequency (Hz)')
        ylabel('Power - absolute single-sided (original units)')

        %     if plot_type == 1
        %         set(gca,'XScale','log')
        %         set(gca,'XTick',[1 10 60 100])
        %         if f1 == 0
        %             xstart = 0.1
        %         else
        %             xstart = f1;
        %         end
        %         xlim = [xstart f2];
        %         xlabel('Frequency (Hz) - log scale')
        %
        %     end

    end

end

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

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

ch = get(hObject,'string');
nch = length(handles.listch);

ch_val = eval(ch);

if ~isempty(ch)

    tf = checkchannels(ch_val, nch, 1);

    if tf
        return
    end

%     if length(ch_val) > length(handles.orig_indxlistch)
%         msgboxText =  'Exceeded Number of Available Channels';
%         title = 'ERPLAB: channel GUI input';
%         errorfound(msgboxText, title);
%         return
%     end
%
    set(handles.edit_channels, 'String', vect2colon(ch_val, 'Delimiter', 'off'));
    handles.listch = ch_val;
    %

    % Update handles structure
    guidata(hObject, handles);

else
    msgboxText =  'Not valid channel';
    title = 'ERPLAB: channel GUI input';
    errorfound(msgboxText, title);
    return
end

% --- Executes during object creation, after setting all properties.
function edit_channels_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_channels (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 browse_button.
function browse_button_Callback(hObject, eventdata, handles)
% hObject    handle to browse_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
listch     = handles.listch;
nchan = length(listch);
for ch =1:nchan
        listch{ch} = [num2str(ch) ' = ' listch{ch}];
end

indxlistch = handles.indxlistch;
indxlistch = indxlistch(indxlistch<=length(listch));
titlename  = 'Select Channel(s)';

if get(hObject, 'Value')
        if ~isempty(listch)
                ch = browsechanbinGUI(listch, indxlistch, titlename);
                if ~isempty(ch)
                        set(handles.edit_channels, 'String', vect2colon(ch, 'Delimiter', 'off'));
                        handles.indxlistch = ch;
                        handles.sel_row = ch;

                        %dq table callback = eventdata.Indices(:,1);
                        test.Indices(:,1) = ch;

                        jUIscrollPane = findobj(handles.dq_table);
                        jUITable = jUIscrollPane.getViewport.getView;

%                         %dq_table_CellSelectionCallback(hObject, eventdata, handles)
%                         dataTB = handles.dq_table;
%                         dataTB.Selection = [ch];

                        dq_table_CellSelectionCallback(hObject, test, handles);

                        % Update handles structure
                        guidata(hObject, handles);
                else
                        disp('User selected Cancel')
                        return
                end
        else
                msgboxText =  'No channel information was found';
                title = 'ERPLAB: fourieeg GUI input';
                errorfound(msgboxText, title);
                return
        end
end

% --- Executes on button press in all_button.
function all_button_Callback(hObject, eventdata, handles)
% hObject    handle to all_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
listch     = handles.listch; %original list
nChan = 1:length(listch);
handles.indxlistch = nChan;
set(handles.edit_channels, 'String', vect2colon(nChan, 'Delimiter', 'off'));
guidata(hObject,handles);

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

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
%  Checks whether the fitness is too low
%
%  ::
%
%    flag=is_violation(f,penalty)
%
%  Args:
%
%     - **f** [numeric]: fitness
%     - **penalty** [numeric]: lowest possible fitness
%
%  Returns:
%     :
%
%     - **flag** [true|false]:
%
%

author: jmaih


text:
function frequency = Frequency(timestamps,varargin)

%Frequency - Compute instantaneous frequency for a point process (e.g. a spike train).
%
% Compute instantaneous frequency either by smoothing the point process using a fixed
% or adaptive Gaussian kernel, or by simply taking the inverse of the interevent intervals.
% Adaptive kernel smoothing is described in Richmond et al. (1990).
%
%  USAGE
%
%    frequency = Frequency(timestamps,<options>)
%
%    timestamps     list of timestamps
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'method'      convolute with a fixed ('fixed', default) or adaptive
%                   ('adaptive') Gaussian kernel, or compute inverse inter-
%                   event intervals ('inverse')
%     'limits'      [start stop] in seconds (default = approx. first and last
%                   timestamps)
%     'binSize'     bin size in seconds (default = 0.050)
%     'smooth'      Gaussian kernel width in number of samples (default = 2)
%     'show'        plot results (default = 'off')
%    =========================================================================
%
%  NOTE
%
%    While the convolution method returns a Mx2 matrix (time bins in column 1,
%    frequencies in column 2), the inverse interspike intervals method returns
%    a Nx2 matrix (original spike timestamps in column 1, frequencies in column 2)

% Copyright (C) 2004-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

% Defaults
method = 'fixed';
binSize = 0.05;
smooth = 2;
limits = [];
show = 'off';

% Check number of parameters
if nargin < 1,
  error('Incorrect number of parameters (type ''help Frequency'' for details).');
end

% Check parameter sizes
if size(timestamps,2) ~= 1,
	error('Parameter ''timestamps'' is not a vector (type ''help Frequency'' for details).');
end

% Parse parameter list
for i = 1:2:length(varargin),
	if ~ischar(varargin{i}),
		error(['Parameter ' num2str(i+2) ' is not a property (type ''help Frequency'' for details).']);
	end
	switch(lower(varargin{i})),

		case 'method',
			method = lower(varargin{i+1});
			if ~isstring_FMAT(method,'fixed','adaptive','inverse','iisi'),
				error('Incorrect value for property ''method'' (type ''help Frequency'' for details).');
			end

		case 'binsize',
			binSize = varargin{i+1};
			if ~isdscalar(binSize,'>=0'),
				error('Incorrect value for property ''binSize'' (type ''help Frequency'' for details).');
			end

		case 'limits',
			limits = varargin{i+1};
			if ~isdvector(limits,'#2'),
				error('Incorrect value for property ''limits'' (type ''help Frequency'' for details).');
			end

		case 'smooth',
			smooth = varargin{i+1};
			if ~isdscalar(smooth,'>=0'),
				error('Incorrect value for property ''smooth'' (type ''help Frequency'' for details).');
			end

		case 'show',
			show = varargin{i+1};
			if ~isstring_FMAT(show,'on','off'),
				error('Incorrect value for property ''show'' (type ''help Frequency'' for details).');
			end

		otherwise,
			error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help Frequency'' for details).']);

  end
end

if isempty(limits),
	limits = [timestamps(1)-10*binSize timestamps(end)+10*binSize];
end

if strcmp(method,'inverse') | strcmp(method,'iisi'),
	% Inter-spike intervals
	ds = diff(timestamps);
	f1 = 1./ds;
	t = timestamps(1:end-1) + ds/2;
	f2 = Interpolate([t f1],timestamps(2:end-1));
	f2 = [timestamps(1) 0;f2;timestamps(end) 0];
	frequency = f2;
else
	% Smoothing
	% 1) Fixed-kernel
	t = (limits(1):binSize:limits(2))';
	T = Bin(timestamps,t);
	binned = Accumulate(T,1,size(t));
	f = Smooth(binned/binSize,smooth);
	frequency = [t f];
	if strcmp(method,'adaptive'),
		% 2) Variable-kernel (requires the above 'pilot' fixed-kernel estimate)
		% Compute variable-kernel sigma
		N = length(t);
		mu = exp(1/N*sum(log(f(f~=0)))); % Correction: geometric mean is computed using only non-zero values
		lambda = sqrt(f/mu);
		sigma = (smooth*binSize)./lambda;
		sigma = Clip(sigma,0,N*binSize/3);
		% Perform variable-kernel smoothing
		binned = [flipud(binned);binned;flipud(binned)];
		for i = 1:N,
			% Gaussian
			x = (0:binSize:3*sigma(i))';
			x = [flipud(-x);x(2:end)];
			kernel = exp(-x.^2/sigma(i)^2);
			kernel = kernel/sum(kernel);
			% 'Pointwise' convolution
			n = (length(kernel)-1)/2;
			bins = N + i + (-n:n);
			S2(i) = sum(binned(bins).*kernel)/binSize;
		end
		frequency = [t S2'];
	end
end

if strcmp(lower(show),'on'),
	PlotXY(frequency);
	hold on;
	PlotTicks(timestamps,'size',10,'k');
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function [image_roidb, bbox_means, bbox_stds] = rfcn_prepare_image_roidb(conf, imdbs, roidbs, bbox_means, bbox_stds)
% [image_roidb] = rfcn_prepare_image_roidb(conf, imdbs, roidbs, cache_img)
% --------------------------------------------------------
% R-FCN implementation
% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)
% Copyright (c) 2016, Jifeng Dai
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    if ~exist('bbox_means', 'var')
        bbox_means = [];
        bbox_stds = [];
    end

    if ~iscell(imdbs)
        imdbs = {imdbs};
        roidbs = {roidbs};
    end

    imdbs = imdbs(:);
    roidbs = roidbs(:);

    image_roidb = cellfun(@(x, y) ... // @(imdbs, roidbs)
                    arrayfun(@(z) ... //@([1:length(x.image_ids)])
                        struct('image_path', x.image_at(z), 'image_id', x.image_ids{z}, 'im_size', x.sizes(z, :), 'imdb_name', x.name, ...
                        'overlap', y.rois(z).overlap, 'boxes', y.rois(z).boxes, 'class', y.rois(z).class, 'image', [], 'bbox_targets', []), ...
                        [1:length(x.image_ids)]', 'UniformOutput', true), imdbs, roidbs, 'UniformOutput', false);

    image_roidb = cat(1, image_roidb{:});

    % enhance roidb to contain bounding-box regression targets
    [image_roidb, bbox_means, bbox_stds] = append_bbox_regression_targets(conf, image_roidb, bbox_means, bbox_stds);
end

function [image_roidb, means, stds] = append_bbox_regression_targets(conf, image_roidb, means, stds)
    % means and stds -- (k+1) * 4, include background class

    num_images = length(image_roidb);
    % Infer number of classes from the number of columns in gt_overlaps
    if conf.bbox_class_agnostic
        num_classes = 1;
    else
        num_classes = size(image_roidb(1).overlap, 2);
    end

    valid_imgs = true(num_images, 1);
    for i = 1:num_images
       rois = image_roidb(i).boxes;
       [image_roidb(i).bbox_targets, valid_imgs(i)] = ...
           compute_targets(conf, rois, image_roidb(i).overlap);
    end
    if ~all(valid_imgs)
        image_roidb = image_roidb(valid_imgs);
        num_images = length(image_roidb);
        fprintf('Warning: rfcn_prepare_image_roidb: filter out %d images, which contains zero valid samples\n', sum(~valid_imgs));
    end

    if ~(exist('means', 'var') && ~isempty(means) && exist('stds', 'var') && ~isempty(stds))
        % Compute values needed for means and stds
        % var(x) = E(x^2) - E(x)^2
        class_counts = zeros(num_classes, 1) + eps;
        sums = zeros(num_classes, 4);
        squared_sums = zeros(num_classes, 4);
        for i = 1:num_images
           targets = image_roidb(i).bbox_targets;
           for cls = 1:num_classes
              cls_inds = find(targets(:, 1) == cls);
              if ~isempty(cls_inds)
                 class_counts(cls) = class_counts(cls) + length(cls_inds);
                 sums(cls, :) = sums(cls, :) + sum(targets(cls_inds, 2:end), 1);
                 squared_sums(cls, :) = squared_sums(cls, :) + sum(targets(cls_inds, 2:end).^2, 1);
              end
           end
        end

        means = bsxfun(@rdivide, sums, class_counts);
        stds = (bsxfun(@minus, bsxfun(@rdivide, squared_sums, class_counts), means.^2)).^0.5;

        % add background class
        means = [0, 0, 0, 0; means];
        stds = [0, 0, 0, 0; stds];
    end

    % Normalize targets
    for i = 1:num_images
        targets = image_roidb(i).bbox_targets;
        for cls = 1:num_classes
            cls_inds = find(targets(:, 1) == cls);
            if ~isempty(cls_inds)
                image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
                    bsxfun(@minus, image_roidb(i).bbox_targets(cls_inds, 2:end), means(cls+1, :));
                image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
                    bsxfun(@rdivide, image_roidb(i).bbox_targets(cls_inds, 2:end), stds(cls+1, :));
            end
        end
    end
end

function [bbox_targets, is_valid] = compute_targets(conf, rois, overlap)

    overlap = full(overlap);

    [max_overlaps, max_labels] = max(overlap, [], 2);

    % ensure ROIs are floats
    rois = single(rois);

    bbox_targets = zeros(size(rois, 1), 5, 'single');

    % Indices of ground-truth ROIs
    gt_inds = find(max_overlaps == 1);

    if ~isempty(gt_inds)
        % Indices of examples for which we try to make predictions
        ex_inds = find(max_overlaps >= conf.bbox_thresh);

        % Get IoU overlap between each ex ROI and gt ROI
        ex_gt_overlaps = boxoverlap(rois(ex_inds, :), rois(gt_inds, :));

        assert(all(abs(max(ex_gt_overlaps, [], 2) - max_overlaps(ex_inds)) < 10^-4));

        % Find which gt ROI each ex ROI has max overlap with:
        % this will be the ex ROI's gt target
        [~, gt_assignment] = max(ex_gt_overlaps, [], 2);
        gt_rois = rois(gt_inds(gt_assignment), :);
        ex_rois = rois(ex_inds, :);

        [regression_label] = rfcn_bbox_transform(ex_rois, gt_rois);

        if conf.bbox_class_agnostic
            bbox_targets(ex_inds, :) = [max_labels(ex_inds)>0, regression_label];
        else
            bbox_targets(ex_inds, :) = [max_labels(ex_inds), regression_label];
        end
    end

    % Select foreground ROIs as those with >= fg_thresh overlap
    is_fg = max_overlaps >= conf.fg_thresh;
    % Select background ROIs as those within [bg_thresh_lo, bg_thresh_hi)
    is_bg = max_overlaps < conf.bg_thresh_hi & max_overlaps >= conf.bg_thresh_lo;

    % check if there is any fg or bg sample. If no, filter out this image
    is_valid = true;
    if ~any(is_fg | is_bg)
        is_valid = false;
    end
end

repo: R-FCN


text:
function ndx = merge(param1,param2)
% ndx = merge(ndx_obj_array)
% ndx = merge(ndx1,ndx2)
% Merges Ndx objects.  The function can be called in two ways: with
% two ndxs or with an object array of ndxs.
% Inputs:
%   Either:
%   ndx1: An Ndx object.
%   ndx2: Another Ndx object.
%   Or:
%   ndx_obj_array: An array of Ndx objects.
% Outputs:
%   ndx: An Ndx object that contains the information from the input ndxs.

assert(nargin<3)
if nargin==2
    ndx1 = param1;
    ndx2 = param2;
    assert(isa(ndx1,'Ndx'))
    assert(isa(ndx2,'Ndx'))
    assert(ndx1.validate())
    assert(ndx2.validate())

    ndx_obj_arr = Ndx.empty(2,0);
    ndx_obj_arr(1) = ndx1;
    ndx_obj_arr(2) = ndx2;

    ndx = Ndx.merge(ndx_obj_arr);
else
    % the output ndx must have all models and segment in the input
    % ndxs (only once).  A trial in any ndx becomes a trial in the
    % output ndx.
    assert(nargin==1)
    obj_array = param1;
    assert(isa(obj_array,'Ndx'))
    numndxs = length(obj_array);
    ndx = Ndx();
    for ii=1:numndxs
	ndx_new = Ndx();
	ndx1 = ndx;
	ndx2 = obj_array(ii);

	% create new ndx with empty masks
	ndx_new.modelset = union(ndx1.modelset, ndx2.modelset);
	ndx_new.segset = union(ndx1.segset, ndx2.segset);

	% expand ndx1 mask
	trials_1 = false(length(ndx_new.modelset), length(ndx_new.segset));
	[dummy,model_index_a,model_index_b] = intersect(ndx_new.modelset,ndx1.modelset);
	[dummy,seg_index_a,seg_index_b] = intersect(ndx_new.segset,ndx1.segset);
	trials_1(model_index_a,seg_index_a) = ndx1.trialmask(model_index_b,seg_index_b);

	% expand ndx2 mask
	trials_2 = false(length(ndx_new.modelset), length(ndx_new.segset));
	[dummy,model_index_a,model_index_b] = intersect(ndx_new.modelset,ndx2.modelset);
	[dummy,seg_index_a,seg_index_b] = intersect(ndx_new.segset,ndx2.segset);
	trials_2(model_index_a,seg_index_a) = ndx2.trialmask(model_index_b,seg_index_b);

	% merge masks
	trials = trials_1 | trials_2;

	% build new ndx
	ndx_new.trialmask = trials;
	ndx = ndx_new;
    end
end

assert(ndx.validate())

author: nesl


text:
%% Author: epokh
%% Website: www.epokh.org/drupy
%% This software is under GPL

%%This function plan a trajectory passing in N
%% points using N-1 3th order polynomial:
%% the user must choose: intial,final and intermediate points
%% timePoints is a matrix [2,N] where first row is the time,second row
%% is the position points
%% the velocities this time are computed as a linear interpolation between
%% the position points
%% Output: a matrix [N-1,4] whose columns are the polynomail coefficients

function [TJ]=trajectory3VelComputed(timePoints)
N=length(timePoints);

if(N<2)
fprintf('Error: you defined only 1 point');
return;
end
TJ=[];

for k=1:N-1
    tk=timePoints(1,k);
    tk1=timePoints(1,k+1);
    qk=timePoints(2,k);
    qk1=timePoints(2,k+1);
    if(k==1)
        velk=0;
    else
        velk=(qk-timePoints(2,k-1))/(tk-timePoints(1,k-1));
    end

    if(k==N-1)
        velk1=0;
    else
       velk1=( timePoints(2,k+1)- timePoints(2,k))/(timePoints(1,k+1)-timePoints(1,k));
    end

    if(sign(velk)~=sign(velk1))
        velk=0;
        velk1=0;
    else
        velk=0;
        velk1=(velk+velk1)/2;

    end

    coeffs=pol3interpol(tk,tk1,qk,qk1,velk,velk1);
    TJ=[TJ;coeffs'];
end

end

author: Sable

repo: mcbench-benchmarks


text:
% rsadjust() - adjust l-values (Ramberg-Schmeiser distribution)
%                with respect to signal mean and variance
%
% Usage: p = rsadjust(l3, l4, m, var, skew)
%
% Input:
%   l3   - value lambda3 for Ramberg-Schmeiser distribution
%   l4   - value lambda4 for Ramberg-Schmeiser distribution
%   m    - mean of the signal distribution
%   var  - variance of the signal distribution
%   skew - skewness of the signal distribution (only the sign of
%          this parameter is used).
%
% Output:
%   l1  - value lambda3 for Ramberg-Schmeiser distribution
%   l2  - value lambda4 for Ramberg-Schmeiser distribution
%   l3  - value lambda3 for Ramberg-Schmeiser distribution (copy
%         from input)
%   l4  - value lambda4 for Ramberg-Schmeiser distribution (copy
%         from input)
%
% Author: Arnaud Delorme, SCCN, 2003
%
% See also: rsfit(), rsget()
%
% Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F.
%            A probability distribution and its uses in fitting data.
%            Technimetrics, 1979, 21: 201-214.

% Copyright (C) 2003 Arnaud Delorme, SCCN, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [l1,l2,l3,l4] = rsadjust( l3, l4, mu, sigma2, m3);

    % swap l3 and l4 for negative skewness
    % ------------------------------------
    if m3 < 0
        ltmp = l4;
        l4   = l3;
        l3   = ltmp;
    end;

    A = 1/(1 + l3) - 1/(1 + l4);
    B = 1/(1 + 2*l3) + 1/(1 + 2*l4) - 2*beta(1+l3, 1+l4);
    C = 1/(1 + 3*l3) - 1/(1 + 3*l4) ...
             - 3*beta(1+2*l3, 1+l4) + 3*beta(1+l3, 1+2*l4);

    % compute l2 (and its sign)
    % ------------------------
    l2 = sqrt( (B-A^2)/sigma2 );
    if m3 == 0, m3 = -0.000000000000001; end;
    if (m3*(C - 2*A*B + 2*A^3)) < 0, l2 = -l2; end;
    %l22 = ((C - 2*A*B + 2*A^3)/m3)^(1/3) % also equal to l2

    % compute l1
    % ----------
    l1 = mu - A/l2;

    return;

    % fitting table 1 of
    % ---------------
    [l1 l2]  = pdffitsolv2(-.0187,-.0388, 0, 1, 1)
    [l1 l2]  = pdffitsolv2(-.1359,-.1359, 0, 1, 0)

    % sign problem
    [l1 l2]  = pdffitsolv2(1.4501,1.4501, 0, 1)

    % numerical problem for l1
    [l1 l2]  = pdffitsolv2(-.00000407,-.001076, 0, 1, 2)
    [l1 l2]  = pdffitsolv2(0,-.000580, 0, 1, 2)

author: PatternRecognition

repo: OpenBMI


text:
% Script to test actuator at current parameter values using frestimate
% Copyright 2010 MathWorks, Inc.

mdl = 'actuator_freq_resp';

amplitude_100 = 0.2;
frequency_100 = 43;
amplitude_40  = amplitude_100*0.4;
frequency_40  = 55;

ios = getlinio(mdl);
in_2pts = frest.Sinestream(...
   'Frequency',[20, 20.1, 43, 57], ...
   'Amplitude', [amplitude_100, amplitude_40, amplitude_100, amplitude_40], ...
   'SimulationOrder', 'Sequential', ... %Set to OneAtATime to restart simuation for each frequency
   'FreqUnits', 'Hz');

sys = frestimate(mdl,ios,in_2pts);
R = sys.ResponseData(:);
Lag = angle(R)/pi*180;
%disp('');
%disp(['Desired Phase: -59 -50 -90 -90']);
%disp(['Actual Phase:  ' sprintf('%3.0f %3.0f %3.0f %3.0f',Lag(1),Lag(2),Lag(3),Lag(4))]);


text:
function jtwgft = gsp_jtwgft(G, w, s, param)
%GSP_JTWGFT Compute the joint vertex-time windowed graph fourier transform
%   Usage:  jtwgft = gsp_jtwgft(G, w, s)
%           jtwgft = gsp_jtwgft(G, w, s, param)
%
%   Input parameters:
%         G          : Graph structure
%         w          : windows
%         s          : vertex-time signal
%         param      : structure of optional parameters
%   Output parameters:
%         jtwgft     : Joint vertex-time windowed graph Fourier transform
%
%   Additional parameters
%   ---------------------
%   * *param.boundary*    : 'periodic' or 'reflecting' (default 'periodic')
%   * *param.a*           : hop size in time (default 1)
%   * *param.M*           : number of frequencies (default size(s,2))
%

% Author : Nathanael Perraudin
% Date   : 30 April 2016

if nargin<4
    param=struct;
end
if ~isfield(param,'boundary'), param.boundary = 'periodic'; end
if ~isfield(param,'a'), param.a = 1; end
if ~isfield(param,'M'), param.M = size(s,2); end

switch param.boundary
    case 'periodic'
        % 1) perform DGT
        S = dgt(transpose(s),w,param.a,param.M);
        % 2) Reshape
        S = reshape(S,[],G.N);
        % 3) GFT
        Shat = transpose(gsp_gft(G,transpose(S)));
        % 4) Reshape
        jtwgft = reshape(Shat,param.M,[],G.N);
    case 'reflecting'
        % 1) perform DGT
        S = wmdct(transpose(s),w,param.M,size(s,2));
        % 2) Reshape
        S = reshape(S,[],G.N);
        % 3) GFT
        Shat = transpose(gsp_gft(G,transpose(S)));
        % 4) Reshape
        jtwgft = reshape(Shat,param.M,[],G.N);
    otherwise
        error('Unknown boundary condition');
end

end

repo: gspbox


text:
function [S,a,t] = normalizeS(S)

t = mean(S,2);
S = S - t*ones(1,size(S,2));
a = mean(std(S, 1, 2));
S = S / a;

author: geopavlakos


text:
function [ t ] = net_establishConnection( ip )
%% This function is used to establish a connection with the server on KUKA

%% Syntax:
% function [ t ] = net_establishConnection( ip )
% This function is used to establish a connection with the server on KUKA.

%% Arregument:
% ip: a string variable, the IP of the robot, example '172.31.1.147',
% To figure out your robot IP, do the following:
% from the teach pendant, click on 'Station' button, then the 'information'
% button, from the information page check out your KUKA iiwa IP.

%% Return value:
% t: is a TCP/IP object, this object is empty when the connection could not be established.

% Copy right, Mohammad SAFEEA, 3rd of May 2017

t=[];
if ~exist('ip','var') || isempty(ip)
  warning('Connection could not be establised');
  return;
else
    try
            port=30001;
            % Connect to server
            t= tcpip(ip, port, 'NetworkRole', 'client');
            t.TransferDelay='off';
            t.Timeout=3.0;
            fopen(t);
            pause(1);
    catch exception
       warning('Connection could not be establised');
    end

end

end

repo: KST-Kuka-Sunrise-Toolbox


text:
classdef C10MOP5 < EvoXBenchProblem
% <multi> <real> <large/none> <expensive/none>

%------------------------------- Reference --------------------------------
% Z. Lu, R. Cheng, Y. Jin, K. C. Tan, and K. Deb, Neural architecture
% search as multiobjective optimization benchmarks: Problem formulation and
% performance assessment, IEEE Transactions on Evolutionary Computation,
% 2023.
%--------------------------------------------------------------------------

    methods
        %% Default settings of the problem
        function Setting(obj)
            config.name = 'nb201';
            config.args.fidelity = 200;
            config.args.objs = ['err&params&flops&edgegpu_latency&' ...
                'edgegpu_energy'];
            config.args.dataset = 'cifar10';
            config.args.normalized_objectives = true;
            obj.Setting@EvoXBenchProblem(config);
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function determ = pascal1_determinant ( n )

%*****************************************************************************80
%
%% PASCAL1_DETERMINANT returns the determinant of the PASCAL1 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real DETERM, the determinant.
%
  determ = 1.0;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function fs_retinotopicTemplate(subject, out_path, subjects_dir)
%
% function fs_retinotopicTemplate(subject, out_path, subjects_dir)
%
% Parameters
% ----------
% subject : str
%    The subject ID in the Freesurfer context
% out_path : str
%    Full path to the location where output files will be generated
% subjects_dir : str (optional)
%    Full path to the Freesurfer SUBJECTS_DIR. Per default this will be set
%    to the environment-defined $SUBJECTS_DIR variable
%
% Notes
% -----
% Based on the work of Benson et al. (2012). The requirements
% for this to work are:
% 1. The data should have been processed using the cross-sectional stream
% in FreeSurfer (i.e. recon-all -s subjid -autorecon-all). Preferably using
% Freesurfer version 5.1
% 2. The scripts (surfreg) and atlas (fsaverage_sym), which are not part of
% the standard FreeSurfer 5.1 distribution, should be installed
% 3. surfreg should be installed in $FREESURFER_HOME/bin/
% 4. fsaverage_sym should be copied to the FreeSufer subject data directory
%
% The 'fsaverage_sym' subject used to be abvailable at:
%
% ftp://surfer.nmr.mgh.harvard.edu/transfer/outgoing/flat/greve/
%
% Until it returns to this location, you can copy it from, or symlink to:
%
% /home/arokem/data/freesurfer_subjects/fsaverage_sym/
%
%
% References
% ----------
% NC Benson, OH Butt, R Datta, PD Radoeva, DH Brainard, GK Aguirre (2012)
% The retinotopic organization of striate cortex is well predicted by
% surface topology. Current Biology 22: 2081-2085.
%
% Greve, Douglas N., Lise Van der Haegen, Qing Cai, Steven Stufflebeam, Mert
% R. Sabuncu, Bruce Fischl, and Marc Bysbaert. "A surface-based analysis of
% language lateralization and cortical asymmetry." (2013). Journal of
% Cognitive Neuroscience. In press.

% To accomodate user set SUBJECTS_DIR system variable:
if notDefined('subjects_dir')
    subjects_dir = getenv('SUBJECTS_DIR');
else
    syscall(sprintf('export SUBJECTS_DIR=%s', subjects_dir));
end

maps = {'ecc', 'pol'};
hemis = {'lh', 'rh'};
for map_idx = 1:length(maps)
    template = fullfile(vistaRootPath, 'fileFilters', 'freesurfer', ...
        sprintf('mh.V1.%stmp.sym.mgh', maps{map_idx}));
    for hemi_idx = 1:length(hemis)
        file_root = fullfile(out_path, sprintf('%s_%s_%s', subject, ...
                             hemis{hemi_idx} , maps{map_idx}));
        % These commands differ slightly for the two hemispheres (xhemi):
        if strcmp(hemis{hemi_idx}, 'lh')
            % If the registration file is not there, we'll have to make it:
            if ~(exist(fullfile(subjects_dir, subject, ...
                    '/surf/lh.fsaverage_sym.sphere.reg'), 'file') == 2)
                fprintf('[%s]: Registering... This might take a while... \n',...
                    mfilename);

                cmd_str1 = sprintf('surfreg --s %s --t fsaverage_sym --lh', subject);
            else
                cmd_str1 = '';
            end
            cmd_str2 = ['mri_surf2surf --srcsubject fsaverage_sym --trgsubject ' ...
                sprintf('%s --sval %s --tval ', subject, template) ...
                sprintf('%s.mgh --hemi lh', file_root)];
        else
            if ~(exist(fullfile(subjects_dir, subject, ...
                    'xhemi/surf/lh.fsaverage_sym.sphere.reg'), 'file') == 2)
                fprintf('[%s]: Registering... This might take a while... \n',...
                    mfilename);

                % Yep - the following line is with 'lh':
                cmd_str1 = sprintf('surfreg --s %s --t fsaverage_sym --lh --xhemi', subject);
            else
                cmd_str1 = '';
            end
            cmd_str2 = ['mri_surf2surf --srcsubject fsaverage_sym --trgsubject ' ...
                sprintf('%s/xhemi --sval %s --tval ', subject, template) ...
                sprintf('%s.mgh --srcsurfreg sphere.reg --trgsurfreg ', file_root, subject) ...
                'fsaverage_sym.sphere.reg --hemi lh'];
        end
        syscall(cmd_str1);
        syscall(cmd_str2);

        cmd_str = [sprintf('mri_surf2vol --surfval %s.mgh --projfrac 1 ', file_root) ...
            sprintf('--identity %s --o %s.mgz --hemi %s ', subject, file_root, hemis{hemi_idx}) ...
            sprintf('--template %s/%s/mri/orig.mgz', subjects_dir, subject)];
        syscall(cmd_str);

        % Convert to volume:
        outfile = [file_root '.nii'];
        cmd_str = [sprintf('mri_convert  %s.mgz ', file_root), outfile];
        syscall(cmd_str);
        gzip(outfile);
        delete(outfile);

    end
end
end

% Helper function: throw an error if the system call doesn't work as
% expected:
    function [status, result] = syscall(cmd_str)
        % Allow for noops:
        if strcmp(cmd_str, '')
            return
        end
        fprintf('[%s]: Executing "%s" \n', mfilename, cmd_str);
        [status, result] = system(cmd_str);
        if status~=0
            error(result);
        end
    end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
% VBRFA2010_DEMO - A simple comparison of VB PCA and two robust extensions.
%
% The algorithms do not use ARD prior for the loadings W in order to keep
% the visualizations of the subspaces more clear. In addition, it helps
% avoiding pruning out relevant components too easily.
%
% NOTE: The robust algorithms might be less sensitive to the initialization
% if they estimate many components. With only one estimated component, they
% might kill all the components.
%
% This demo doesn't always show good results for robust algorithms. You may
% want to run a few times. In addition, sometimes there are several good
% interpretations of the data and the robust algorithms pick one.

% Last modified 2010-06-10
% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)

function Q = vbrfa2010_demo

n = 50;
m = 2;
d = 1;
dh = d + 0; % number of components to estimate

randn('state', 6);
rand('state', 6);

mu = [0;0];
W = [2; 1];
X = orth(randn(d,n)')' * sqrt(n);
s2 = 0.2;

% Generate normal data
Y = W*X + repmat(mu,1,n);

% Add noise
Yn = Y + sqrt(s2)*randn(m,n);

% Generate some outliers
Yno = Yn;
p = (rand(m,n) < 0.05);
Yno(p) = 5 + 8 * rand(sum(p(:)),1);

% Generate some missing values
Ynom = Yno;
pmv = (rand(m,n) < 0.0);
Ynom(pmv) = NaN;

% Run different algorithms
options.init.tau = 1e2*ones(m,1); % the initialization of this can be crucial..
options.init.nu = 1;
options.prior.aw = 1e10*ones(d,1); % fix w by setting strong prior
options.prior.bw = 1e15*ones(d,1); % fix w by setting strong prior
options.update_nu = 1;
options.update_w = 1;
options.rotate = 0;
options.common_nu = false;
options.common_tau = true
options.maxiter = 50;

% PCA
disp('Run PCA')
options.robustness = 'none';
results_p = vbrfa(Ynom, dh, options);
W_p = results_p.W;
X_p = results_p.X;
S_p = results_p.Sv;
mu_p = results_p.mu;
nu_p = results_p.nu;

% Robust PCA with multivariate Student-t
disp('Run robust PCA with multivariate Student-t')
options.robustness = 'multivariate-t';
results_rp = vbrfa(Ynom, dh, options);
W_rp = results_rp.W;
X_rp = results_rp.X;
S_rp = results_rp.Sv;
mu_rp = results_rp.mu;
nu_rp = results_rp.nu;

% Robust PCA with independent Student-t
disp('Run robust PCA with independent Student-t')
options.robustness = 'independent-t';
results_rvb = vbrfa(Ynom, dh, options);
W_rvb = results_rvb.W;
X_rvb = results_rvb.X;
S_rvb = results_rvb.Sv;
mu_rvb = results_rvb.mu;
nu_rvb = results_rvb.nu;

% Reconstruct
Y_p = W_p*X_p + repmat(mu_p,1,n);
Y_rp = W_rp*X_rp + repmat(mu_rp,1,n);
Y_rvb = W_rvb*X_rvb + repmat(mu_rvb,1,n);

plot_results(Ynom, []);
%print('-depsc2', '/home/jluttine/papers/vbrfa/figures_journal/fig_demo_data.eps');
plot_results(Ynom, Y_p)
%print('-depsc2', '/home/jluttine/papers/vbrfa/figures_journal/fig_demo_pca.eps');
plot_results(Ynom, Y_rp)
%print('-depsc2', '/home/jluttine/papers/vbrfa/figures_journal/fig_demo_multi-t.eps');
plot_results(Ynom, Y_rvb)
%print('-depsc2', '/home/jluttine/papers/vbrfa/figures_journal/fig_demo_indep-t.eps');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
function plot_results(Y, Yh)
%subspace2d(Yh, [], Y)
figure
plot(Y(1,:), Y(2,:), 'x', 'markersize', 5, 'color', [.2 .2 .2]);
if ~isempty(Yh)
  hold on
  plot(Yh(1,:), Yh(2,:), 'ko', 'markersize', 3);
  nans = nan*ones(1,size(Y,2));
  plot([Y(1,:);Yh(1,:);nans], [Y(2,:);Yh(2,:);nans], ':', 'color', [.0 .0 .0]);
end
set(gca, 'DataAspectRatioMode', 'manual');
set(gca, 'DataAspectRatio', [1 1 1]);
set(gca, 'XTick', [], 'YTick', []);
set(gcf, 'units', 'centimeters');
pos = get(gcf, 'position');
set(gcf, 'position', [pos(1), pos(2), 5 5])
set(gcf, 'PaperPositionMode', 'auto', 'paperunits', 'centimeters', 'PaperSize', [5 5]);

xmg = 0.05 * (max(Y(1,:)) - min(Y(1,:)));
ymg = 0.05 * (max(Y(2,:)) - min(Y(2,:)));
xl = [min(Y(1,:))-xmg, max(Y(1,:))+xmg];
yl = [min(Y(2,:))-ymg, max(Y(2,:))+ymg];
set(gca, 'xlim', xl, 'ylim', yl);

% $$$ % Mark outliers
% $$$ hold on
% $$$ indeces = sum(p,1)>0;
% $$$ plot(VYno(1,indeces), VYno(2, indeces), 'go', 'MarkerSize', 8);

% $$$ % Mark observations with missing values
% $$$ indeces = sum(pmv,1)>0;
% $$$ scatter(VYno(1,indeces), VYno(2, indeces), 'yo');

return

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
function frame = FrameFromEvents(polarity, contrast, dims)

%{
Polarity is a structure containing at least the fields x, y, and polarity,
column vectors of equal lengths where polarity is boolean
and x and y are zero-based coordinates.
returns 'frame'(uint8) a matrix of plus/minus plots of polarity data a la jAER.
Encoding is from 0 (full scale OFF events)
to contrast * 2 (full scale ON events, with contrast representing the
neutral value.
dims is the expected dimension of the output - a tuple of [X Y]

Note that the frame returned accords to the maximum size of the x and y
events.
%}

% Output class is double, because the numerical operation on polarity
% results in a double
if exist('dims', 'var')
    frame = accumarray([polarity.y polarity.x] + 1, polarity.polarity * 2 - 1, dims(end : -1 : 1));
else
    frame = accumarray([polarity.y polarity.x] + 1, polarity.polarity * 2 - 1);
end

% Clip the values according to the contrast
frame(frame > contrast) = contrast;
frame(frame < - contrast) = -contrast;
frame = uint8(frame + contrast + 1);

author: panpanfei


text:
function transfo = createBasisTransform(source, target)
%CREATEBASISTRANSFORM Compute matrix for transforming a basis into another basis.
%
%   TRANSFO = createBasisTransform(SOURCE, TARGET)
%   Both SOURCE and TARGET represent basis, in the following form:
%   [x0 y0  ex1 ey1  ex2 ey2]
%   [y0 y0] is the origin of the basis, [ex1 ey1] is the first direction
%   vector, and [ex2 ey2] is the second direction vector.
%
%   The result TRANSFO is a 3-by-3 matrix such that a point expressed with
%   coordinates of the first basis will be represented by new coordinates
%   P2 = transformPoint(P1, TRANSFO) in the target basis.
%
%   TRANSFO = createBasisTransform(TARGET)
%   Assumes the source is the standard (Oij) basis, with origin at (0,0),
%   first direction vector equal to (1,0) and second direction  vector
%   equal to (0,1).
%
%
%   Example
%     % define source and target bases
%     src = [ 0 0   1  0    0  1];
%     tgt = [20 0  .5 .5  -.5 .5];
%     trans = createBasisTransform(src, tgt);
%     % create a polygon in source basis
%     poly = [10 10;30 10; 30 20; 20 20;20 40; 10 40];
%     figure;
%     subplot(121); drawPolygon(poly, 'b'); axis equal; axis([-10 50 -10 50]);
%     hold on; drawLine([0 0 1 0], 'k'); drawLine([0 0 0 1], 'k');
%     drawLine([20 0 1 1], 'r'); drawLine([20 0 -1 1], 'r');
%     t = -1:5; plot(t*5+20, t*5, 'r.'); plot(-t*5+20, t*5, 'r.');
%     % transform the polygon in target basis
%     poly2 = transformPoint(poly, trans);
%     subplot(122); drawPolygon(poly2, 'b'); axis equal; axis([-10 50 -10 50]);
%     hold on; drawLine([0 0 1 0], 'r'); drawLine([0 0 0 1], 'r');
%     t = -1:5; plot(t*10, zeros(size(t)), 'r.'); plot(zeros(size(t)), t*10, 'r.');
%
%   See also
%   transforms2d
%

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2010-12-03, using Matlab 7.9.0.529 (R2009b)
% Copyright 2010-2022 INRA - Cepia Software Platform

% init basis transform to identity
t1 = eye(3);
t2 = eye(3);

if nargin == 2
    % from source to reference basis
    t1(1:2, 1) = source(3:4);
    t1(1:2, 2) = source(5:6);
    t1(1:2, 3) = source(1:2);
else
    % if only one input, use first input as target basis, and leave the
    % first matrix to identity
    target = source;
end

% from reference to target basis
t2(1:2, 1) = target(3:4);
t2(1:2, 2) = target(5:6);
t2(1:2, 3) = target(1:2);

% compute transform matrix
transfo = zeros(3, 3);
maxSz = 1;
for i = 1:maxSz
    % coordinate of three reference points in source basis
    po = t1(1:2, 3, i)';
    px = po + t1(1:2, 1, i)';
    py = po + t1(1:2, 2, i)';

    % express coordinates of reference points in the new basis
    t2i = inv(t2(:,:,i));
    pot = transformPoint(po, t2i);
    pxt = transformPoint(px, t2i);
    pyt = transformPoint(py, t2i);

    % compute direction vectors in new basis
    vx = pxt - pot;
    vy = pyt - pot;

    % concatenate result in a 3-by-3 affine transform matrix
    transfo(:,:,i) = [vx' vy' pot' ; 0 0 1];
end

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function plotranking(scores, X, dims)
% PLOTRANKING(DAT)
% PLOTRANKING(SCORES, X)
%
% DAT is a data object returned by the MRANK method TEST.
%
% SCORES may be one column [scores], two columns [indices, scores] or three
% columns [indices, scores, ranks] (the latter is the format returned by
% READRANKING or in the result field of an MRANK algorithm).
%
% SCORES may also be a string, in which case it is automatically passed
% through READRANKING (to plot the contents of an output file).
%
% Use NaN in the scores column to mark labelled points.
%
% X may be a string: if so, a variable X is loaded from the named file.
% If X is omitted, 'twomoons' is assumed. The first two columns of X
% provide the coordinates for the plotted data points.

if nargin < 3, dims = [1 2]; end
if nargin < 2, X = ''; end
if nargin < 1, scores = ''; end

if nargin == 1 & (isa(scores, 'data') | isa(scores, 'data_global'))
	X = get_x(scores);
	scores = get_y(scores);
end

if isempty(X), X = 'twomoons'; end
if isstr(X), load(X, 'X'); end
if isa(X, 'data') | isa(X, 'data_global'), X = get_x(X); end
X = X(:, dims);

if isstr(scores), scores = readranking(scores); end

m = size(X, 1);

if isempty(scores), scores = [1:m]'; end

if size(scores, 2) == 1
	if size(scores, 1) ~= m, error('SCORES must have one element per data point unless indices are supplied in the first column'), end
	scores = [[1:m]' scores];
end
if size(scores, 2) == 2
	labelled = isnan(scores(:, 2));
	scores(labelled, 3) = nan;
	t = compute_ranks(-scores(~labelled, 2));
	scores(~labelled, 3) = t(:);
end

X = X(scores(:, 1), :);
ranks = scores(:, 3);
scores = scores(:, 2);

labelled = isnan(scores);

plotpoints(X(~labelled, :), ranks(~labelled))
plot(X(labelled, 1), X(labelled, 2), 'marker', 'o', 'color', [1 0 0], 'markerfacecolor', [0 1 0], 'markersize', 10, 'linestyle', 'none')
axis square
figure(gcf)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotpoints(X, ranks)

fullcolour = 0;
m = size(X, 1);
cmap = jet(m);
[ranks i] = sort(max(ranks)-ranks);
X = X(i, :);
s = 10 + 90*ranks/m;
c = [1:m]';
if ~fullcolour, c = round(m/4)+round(m/2)*(c<m/2); end
c = cmap(c, :);
washeld = ishold;
plot(X(:, 1), X(:, 2), 'color', [1, 0,0])
hold on
if fullcolour
	scatter(X(:, 1), X(:, 2), 20, c, 'filled')
else
	scatter(X(:, 1), X(:, 2), s, c)
end
if ~washeld, hold off, end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rm = compute_ranks(am)

rm = zeros(size(am));
for j = 1:size(am, 2)
    a = am(:, j);
    [sorted r] = sort(a);
    r(r) = 1:length(r);
    while 1
        tied = sorted(min(find(diff(sorted) == 0)));
        if isempty(tied), break, end
        sorted(sorted==tied) = nan;
        r(a==tied) = mean(r(a==tied));
    end
    rm(:, j) = r;
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function f = filterBinomial1d( r, show )
% 1D binomial filter (approximation to Gaussian filter)
%
% Creates a binomial filter of size 2*r+1 x 1.  This can be used to
% approximate the Gaussian distribution with sigma=sqrt((2*r+1)/4). For
% large r, should give same output as:
%  g = fspecial( 'Gaussian', [2*r+1,1],sqrt((2*r+1)/4) );
% Given sigma, use r ~= 2*sigma^2.
%
% Use F = f*f' to get the equivalent 2d filter.
%
% USAGE
%  f = filterBinomial1d( r, [show] )
%
% INPUTS
%  r       - mask will have length 2r+1 and var=(2*r+1)/4
%  show    - [0] figure to use for optional display
%
% OUTPUTS
%  f       - 1D binomial filter
%
% EXAMPLE
%  r = 10;
%  fbinom = filterBinomial1d( r, 1 );
%  fgauss = filterGauss( 2*r+1, [], (2*r+1)/4, 2);
%
% See also FILTERGAUSS
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.0
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<2 ); show=0; end;
if( mod(r,1)~=0 ); error( 'r must be an integer'); end;

f = diag(fliplr(pascal(2*r+1))) / 4^r;

% display
if(show); filterVisualize( f, show ); end;

author: pdollar

repo: toolbox

save_path: github-repos/MATLAB/pdollar-toolbox


text:
function e = ExplorationNoise(t)
%% LocalExploration
% Generate exploratoion noise
  e = (0.01*sin(10*t)+0.01*sin(3*t)+0.01*sin(100*t));
end

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
function Show_EWT2D_Curvelet(ewtc)

%==========================================================================
% function Show_EWT2D_Curvelet(ewtc)
%
% This function displays the curvelet coefficient obtained by the Empirical
% Curvelet Transform (one figure per scale)
%
% Inputs:
%   -ewtc: output of the empirical curvelet transform
%
% Author: Jerome Gilles
% Institution: UCLA - Department of Mathematics
% Year: 2013
% Version: 1.0
%==========================================================================

Ns=length(ewtc);

% Show the low pass filter
figure;
imshow(ewtc{1},[]);

for s=2:Ns
   Nt=length(ewtc{s});
   figure;
   for t=1:Nt
      subplot(1,Nt,t);
      imshow(ewtc{s}{t},[]);
   end
end


text:
function mesh = spm_eeg_inv_spatnorm(mesh)
% Spatial Normalisation (using Unified Segmentation)
% Transforms individual sMRI into MNI space and save the [inverse]
% deformations that will be needed for computing the individual mesh
%
% FORMAT mesh = spm_eeg_inv_spatnorm(mesh)
%
% mesh        - input data struct
%
% mesh        - same data struct including the inverse deformation .mat file
%               and filename of normalised (bias corrected) sMRI
%__________________________________________________________________________
% Copyright (C) 2009-2014 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_eeg_inv_spatnorm.m 6217 2014-09-29 17:54:33Z guillaume $

spm('Pointer','Watch');

%-Initialise
%--------------------------------------------------------------------------
sMRI = mesh.sMRI;

%-Spatial Transformation into MNI space
%--------------------------------------------------------------------------
[pth,nam] = spm_fileparts(sMRI);
def       = fullfile(pth,['y_' nam '.nii']);
mat       = fullfile(pth,[nam '_seg8.mat']);

if ~(exist(def, 'file') && exist(mat, 'file'))
    % Assume it is an image, so derive deformation field.
    T = fullfile(spm('dir'),'tpm','TPM.nii,');
    p = struct('channel',struct('vols',     {{sMRI}},...
        'biasreg',  0.0001,...
        'biasfwhm', 60,...
        'write',    [0 0]),...
        'tissue', struct('tpm',   {{[T,'1']},{[T,'2']},{[T,'3']},{[T,'4']},{[T,'5']},{[T,'6']}},...
        'ngaus', {2,2,2,3,4,2},...
        'native',{[0 0],[0 0],[0 0],[0 0],[0 0],[0 0]},...
        'warped',{[0 0],[0 0],[0 0],[0 0],[0 0],[0 0]}),...
        'warp',   struct('reg',[0 0.001 0.5 0.05 0.2], 'affreg', 'mni', 'samp', 3, 'write', [0 1],'mrf',0));

    spm_preproc_run(p);
end

mesh.def    = def;
mesh.Affine = getfield(load(mat, 'Affine'), 'Affine');

%-Clean up
%--------------------------------------------------------------------------
spm('Pointer','Arrow');

author: spm


text:
function res = nsamples(obj)
% Method for getting the number of samples per trial
% FORMAT res = nsamples(obj)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: nsamples.m 1373 2008-04-11 14:24:03Z spm $

res = obj.Nsamples;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function alpha = angle3d(varargin)
%ANGLE3D compute angle between 2 3D points
%
%   ALPHA = anglePoints3d(P1, P2)
%   compute angle (P1, O, P2), in radians, between 0 and PI.
%
%   ALPHA = anglePoints3d(P1, P2, P3)
%   compute angle (P1, P2, P3), in radians, between 0 and PI.
%
%   ALPHA = anglePoints3d(PTS)
%   PTS is a 3x3 or 2x3 array containing coordinate of points.
%
%
%   ---------
%
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 21/02/2005.
%

%   HISTORY
%   20/09/2005 : add case of single argument for all points

p2 = [0 0 0];
if length(varargin)==1
    pts = varargin{1};
    if size(pts, 1)==2
        p1 = pts(1,:);
        p0 = [0 0 0];
        p2 = pts(2,:);
    else
        p1 = pts(1,:);
        p0 = pts(2,:);
        p2 = pts(3,:);
    end
elseif length(varargin)==2
    p1 = varargin{1};
    p0 = [0 0 0];
    p2 = varargin{2};
elseif length(varargin)==3
    p1 = varargin{1};
    p0 = varargin{2};
    p2 = varargin{3};
end

% normalized points
p1 = normalize3d(p1-p0);
p2 = normalize3d(p2-p0);
alpha = acos(dot(p1, p2, 2));

function vn = normalize3d(v)
%NORMALIZE3D normalize a 3D vector, such that its norm equals 1.

n = sqrt(v(:,1).*v(:,1) + v(:,2).*v(:,2) + v(:,3).*v(:,3));
vn = v./[n n n];

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
% Change to your downloaded location
clear
addpath('C:\liblinear\matlab')
addpath('../training_code')
addpath('../utilities')

%% load shared definitions and AU data
shared_defs;

% Set up the hyperparameters to be validated
hyperparams.c = 10.^(-7:1:1);
hyperparams.e = 10.^(-3);

hyperparams.validate_params = {'c', 'e'};

% Set the training function
svr_train = @svm_train_linear;

% Set the test function (the first output will be used for validation)
svr_test = @svm_test_linear;

%%
for a=1:numel(aus)

    au = aus(a);

    rest_aus = setdiff(all_aus, au);

    % make sure validation data's labels are balanced
    [users_train, users_valid] = get_balanced_fold(DISFA_dir, users, au, 1/3, 1);

    % need to split the rest
    [train_samples, train_labels, valid_samples, valid_labels, ~, PC, means, scaling, valid_ids, valid_success] = Prepare_HOG_AU_data_generic(users_train, users_valid, au, rest_aus, DISFA_dir, hog_data_dir);

    train_labels(train_labels > 1) = 1;
    valid_labels(valid_labels > 1) = 1;

    train_samples = sparse(train_samples);
    valid_samples = sparse(valid_samples);

    %% Validate here
    hyperparams.success = valid_success;

    [ best_params, ~ ] = validate_grid_search_no_par(svr_train, svr_test, false, train_samples, train_labels, valid_samples, valid_labels, hyperparams);

    model = svr_train(train_labels, train_samples, best_params);

    [~, prediction] = svr_test(valid_labels, valid_samples, model);

    name = sprintf('classifiers/AU_%d_stat.mat', au);

    [ accuracies, F1s, corrs, ccc, rms, classes ] = evaluate_regression_results( prediction, valid_labels );

    save(name, 'model', 'accuracies', 'F1s', 'corrs', 'rms', 'ccc', 'prediction', 'valid_labels');

    name = sprintf('classifiers/AU_%d_stat.dat', au);

    pos_lbl = model.Label(1);
    neg_lbl = model.Label(2);

    w = model.w(1:end-1)';
    b = model.w(end);

    svs = bsxfun(@times, PC, 1./scaling') * w;
    write_lin_svm(name, means, svs, b, pos_lbl, neg_lbl);

end

author: TadasBaltrusaitis

repo: OpenFace