text:
function varargout = p300_paradigm(varargin)
% P300_PARADIGM MATLAB code for p300_paradigm.fig
%      P300_PARADIGM, by itself, creates a new P300_PARADIGM or raises the existing
%      singleton*.
%
%      H = P300_PARADIGM returns the handle to a new P300_PARADIGM or the handle to
%      the existing singleton*.
%
%      P300_PARADIGM('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in P300_PARADIGM.M with the given input arguments.
%
%      P300_PARADIGM('Property','Value',...) creates a new P300_PARADIGM or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before p300_paradigm_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to p300_paradigm_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% % See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help p300_paradigm

% Last Modified by GUIDE v2.5 08-Aug-2017 13:59:53

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @p300_paradigm_OpeningFcn, ...
                   'gui_OutputFcn',  @p300_paradigm_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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if you want to edit, edit from below this line
% Oyeon Kwon, 2017.08
% oy_kwon@korea.ac.kr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Executes just before p300_paradigm is made visible.
function p300_paradigm_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 p300_paradigm (see VARARGIN)
set(gcf,'units','points','position',[500 150 495 460])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialization
set(handles.spellerText,'String','KOREA_UNIVERSITY');
set(handles.NumberOfSeq  ,'String','10');
set(handles.screenNumber ,'String','2');
set(handles.stimulusTime ,'String','0.135');
set(handles.IntervalTime ,'String','0.05');
set(handles.portNumber ,'String','D010');
set(handles.tcpiptxt ,'String','12300');
% set(handles.testText,'text40','off');
% set(handles.testText,'visible','off');
% set(handles.testText,'String','OPENBMI_SPELLER');
set(handles.notiontxt,'String','You have to start with selecting the p300 spller type');
scrPanelOn(handles,'off');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Choose default command line output for p300_paradigm
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
% UIWAIT makes p300_paradigm wait for user response (see UIRESUME)
% uiwait(handles.figure1);

function initialize_gui(fig_handle, handles, isreset)
% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
if isfield(handles, 'metricdata') && ~isreset
    return;
end
% RESET(handles, true);
% Update handles structure
guidata(handles.figure1, handles);

% --- Outputs from this function are returned to the command line.
function varargout = p300_paradigm_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

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

set(handles.notiontxt,'String','Executing paradigm...'); drawnow;
% get offline or online
if get(handles.offbtn,'Value')
    exp_type = -1;
elseif get(handles.onbtn,'Value')
    exp_type = 0;
end

% get screensize info
ScreenSize = cellstr(get(handles.screenSize,'String'));
selectScreenSize = ScreenSize{get(handles.screenSize,'Value')};
if strcmp(cellstr(selectScreenSize),'Full screen')
    selectScreenSizeFirst = 'Full screen';   selectScreenSizeEnd=[];
elseif strcmp(cellstr(selectScreenSize),'1920 x 1200')
    selectScreenSizeFirst = 1920; selectScreenSizeEnd = 1200;
elseif strcmp(cellstr(selectScreenSize),'1920 x 1080')
    selectScreenSizeFirst = 1920; selectScreenSizeEnd = 1080;
elseif strcmp(cellstr(selectScreenSize),'1280 x 1024')
    selectScreenSizeFirst = 1280; selectScreenSizeEnd = 1024;
elseif strcmp(cellstr(selectScreenSize),' 800 x  600')
    selectScreenSizeFirst = 800; selectScreenSizeEnd = 600;
elseif strcmp(cellstr(selectScreenSize),'Write direct')
    selectScreenSizeFirst = str2double(get(handles.writeScreenSizeFirst,'String'));
    selectScreenSizeEnd = str2double(get(handles.writeScreenSizeEnd,'String'));
end

% get parameters info
spellerText = get(handles.spellerText,'String');
NumberOfSeq = str2double(get(handles.NumberOfSeq,'String'));
screenNumber = str2double(get(handles.screenNumber,'String'));
stimulusTime = str2double(get(handles.stimulusTime,'String'));
IntervalTime = str2double(get(handles.IntervalTime,'String'));
portNumber = get(handles.portNumber,'String');

% warning box
if isempty(portNumber), error('No input port information'), end

% play paradigm
if ischar(selectScreenSizeFirst) && strcmp(selectScreenSizeFirst,'Full screen')
    if get(handles.random_sp,'Value')
                 gg =   random_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    elseif get(handles.face_sp,'Value')
                     gg = face_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    elseif get(handles.RC_sp,'Value')
                    gg = rc_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime});
    end
else
    if get(handles.random_sp,'Value')
                 gg =   random_speller({'exp_type',exp_type;  'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    elseif get(handles.face_sp,'Value')
              gg = face_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    elseif get(handles.RC_sp,'Value')
                   gg = rc_speller({'exp_type',exp_type; 'port',portNumber;...
    'text',spellerText;'nSequence',NumberOfSeq;'screenNum',screenNumber;'sti_Times',stimulusTime;...
    'sti_Interval',IntervalTime;'screenSize',[selectScreenSizeFirst,selectScreenSizeEnd]});
    end
end

set(handles.notiontxt,'String',gg);

initialize_gui(hObject, handles, false);

% --- Executes on button press in RC_sp.
function RC_sp_Callback(hObject, eventdata, handles)
% hObject    handle to RC_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.RC_sp,'Value'))
    set(handles.random_sp,'Value',0)
    set(handles.face_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of RC_sp

% --- Executes on button press in random_sp.
function random_sp_Callback(hObject, eventdata, handles)
% hObject    handle to random_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.random_sp,'Value'))
    set(handles.RC_sp,'Value',0)
    set(handles.face_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of random_sp

% --- Executes on button press in face_sp.
function face_sp_Callback(hObject, eventdata, handles)
% hObject    handle to face_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.face_sp,'Value'))
    set(handles.random_sp,'Value',0)
    set(handles.RC_sp,'Value',0)
end
set(handles.notiontxt,'String','Now you should make your p300 paradigm then start');
% Hint: get(hObject,'Value') returns toggle state of face_sp

function scrPanelOn(handles, onoff)
set(handles.writeScreenSizeFirst,'visible',onoff);
set(handles.text29,'visible',onoff);
set(handles.writeScreenSizeEnd,'visible',onoff);
set(handles.screenSizeComplete,'visible',onoff);

% --- Executes on selection change in screenSize.
function screenSize_Callback(hObject, eventdata, handles)
% hObject    handle to screenSize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
switch get(handles.screenSize,'value')
    case 1
        scrPanelOn(handles, 'off');
    case 2
        scrPanelOn(handles, 'off');
    case 3
        scrPanelOn(handles, 'off');
    case 4
        scrPanelOn(handles, 'off');
    case 5
       scrPanelOn(handles, 'off');
    case 6
        scrPanelOn(handles, 'on');
end

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

% --- Executes during object creation, after setting all properties.
function screenSize_CreateFcn(hObject, eventdata, handles)
% hObject    handle to screenSize (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 writeScreenSizeEnd_Callback(hObject, eventdata, handles)
% hObject    handle to writeScreenSizeEnd (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 writeScreenSizeEnd as text
%        str2double(get(hObject,'String')) returns contents of writeScreenSizeEnd as a double
input = get(handles.writeScreenSizeEnd,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen size input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

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

function writeScreenSizeFirst_Callback(hObject, eventdata, handles)
% hObject    handle to writeScreenSizeFirst (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 writeScreenSizeFirst as text
%        str2double(get(hObject,'String')) returns contents of writeScreenSizeFirst as a double
input = get(handles.writeScreenSizeFirst,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen size input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

% --- Executes during object creation, after setting all properties.
function writeScreenSizeFirst_CreateFcn(hObject, eventdata, handles)
% hObject    handle to writeScreenSizeFirst (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 spellerText_Callback(hObject, eventdata, handles)
% hObject    handle to spellerText (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 spellerText as text
%        str2double(get(hObject,'String')) returns contents of spellerText as a double
input = get(handles.spellerText,'string');
if regexp(input, '[^A-Z.,0-9._ ;]')
    set(handles.notiontxt,'String','Text input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

% --- Executes during object creation, after setting all properties.
function spellerText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to spellerText (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 NumberOfSeq_Callback(hObject, eventdata, handles)
% hObject    handle to NumberOfSeq (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 NumberOfSeq as text
%        str2double(get(hObject,'String')) returns contents of NumberOfSeq as a double
input = get(handles.NumberOfSeq,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Sequence input format should be checked');
else
        set(handles.notiontxt,'String','Set');
%         set(handles.NumberOfSeq  ,'String','10');
end

% --- Executes during object creation, after setting all properties.
function NumberOfSeq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NumberOfSeq (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 screenNumber_Callback(hObject, eventdata, handles)
% hObject    handle to screenNumber (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 screenNumber as text
%        str2double(get(hObject,'String')) returns contents of screenNumber as a double
input = get(handles.screenNumber,'string');
if regexp(input, '[^0-9]')
    set(handles.notiontxt,'String','Screen number input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

% --- Executes during object creation, after setting all properties.
function screenNumber_CreateFcn(hObject, eventdata, handles)
% hObject    handle to screenNumber (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 stimulusTime_Callback(hObject, eventdata, handles)
% hObject    handle to stimulusTime (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 stimulusTime as text
%        str2double(get(hObject,'String')) returns contents of stimulusTime as a double
input = get(handles.stimulusTime,'string');
if regexp(input, '[^0-9.,;]')
    set(handles.notiontxt,'String','Stimulus time input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

% --- Executes during object creation, after setting all properties.
function stimulusTime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stimulusTime (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 IntervalTime_Callback(hObject, eventdata, handles)
% hObject    handle to IntervalTime (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 IntervalTime as text
%        str2double(get(hObject,'String')) returns contents of IntervalTime as a double
input = get(handles.IntervalTime,'string');
if regexp(input, '[^0-9.,;]')
    set(handles.notiontxt,'String','Interval time input format should be checked');
else
        set(handles.notiontxt,'String','Set');
end

% --- Executes during object creation, after setting all properties.
function IntervalTime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to IntervalTime (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 portNumber_Callback(hObject, eventdata, handles)
% hObject    handle to portNumber (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 portNumber as text
%        str2double(get(hObject,'String')) returns contents of portNumber as a double
% input = get(handles.IntervalTime,'string');
% if regexp(input, '[!@#$%^&*()-=~+]')
%     set(handles.notiontxt,'String','Interval time input format should be checked');
% else
%         set(handles.notiontxt,'String','Set');
% end

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

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

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

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

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

% --- Executes on button press in offbtn.
function offbtn_Callback(hObject, eventdata, handles)
% hObject    handle to offbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.spellerText,'String','KOREA_UNIVERSITY');

if(get(handles.offbtn,'Value'))
    set(handles.onbtn,'Value',0)
end
set(handles.text41,'visible','off');
set(handles.tcpiptxt,'visible','off');
set(handles.servercheck,'visible','off');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','Set up for offline paradigm');
% Hint: get(hObject,'Value') returns toggle state of offbtn

% --- Executes on button press in onbtn.
function onbtn_Callback(hObject, eventdata, handles)
% hObject    handle to onbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(handles.onbtn,'Value'))
    set(handles.offbtn,'Value',0)
end
set(handles.spellerText,'String','OPENBMI_SPELLER');
% Hint: get(hObject,'Value') returns toggle state of onbtn
set(handles.text41,'visible','on');
set(handles.tcpiptxt,'visible','on');
set(handles.servercheck,'visible','on');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','Set up for online paradigm');

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

% --- Executes during object creation, after setting all properties.
function testText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to testText (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 servercheck.
function servercheck_Callback(hObject, eventdata, handles)
% hObject    handle to servercheck (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global sock IO_LIB IO_ADD

% if isequal(get(handles.pushbutton12, 'string'), 'Brainvision check')
%     set(handles.notiontxt,'String','have to set up brainvision port first...'); drawnow;
%     return;
% end
% set(handles.notiontxt,'String','waiting check connection of TCPIP');
% bbci_acquire_bv('close');
set(handles.notiontxt,'String','Waiting check TCPIP connection...'); drawnow;
port = get(handles.portNumber ,'String');
IO_LIB=which('inpoutx64.dll');
IO_ADD=hex2dec(port);
tcpipp = str2double(get(handles.tcpiptxt,'String'));
% param = struct;
% state = bbci_acquire_bv('Init',param);
sock = tcpip('0.0.0.0',tcpipp ,'NetworkRole','server','timeout',3);  %
fopen(sock);
disp(1);
flushinput(sock);
while(true)
    a = fread(sock,19);
    if ~isempty(a)
        break;
    end
end

ppWrite(IO_ADD,a);  % 19 check
set(handles.notiontxt,'String','Check connection and start paradigm');

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

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

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

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

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

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

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

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

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

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

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

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

% --- Executes during object creation, after setting all properties.
function edit39_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit39 (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 offbtn.
% function offlinebtn_Callback(hObject, eventdata, handles)
% % hObject    handle to offbtn (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 offbtn
% set(handles.text41,'visible','off');
% set(handles.tcpiptxt,'visible','off');
% set(handles.servercheck,'visible','off');
%
%
% % --- Executes on button press in onbtn.
% function onlinebtn_Callback(hObject, eventdata, handles)
% % hObject    handle to onbtn (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 onbtn
% set(handles.text41,'visible','on');
% set(handles.tcpiptxt,'visible','on');
% set(handles.servercheck,'visible','on');
%

% --- Executes on button press in finishbtn.
function finishbtn_Callback(hObject, eventdata, handles)
% hObject    handle to finishbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.notiontxt,'String','Check brainvison port (or TCPIP for online access)');

% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global IO_LIB IO_ADD
% bbci_acquire_bv('close');
port = get(handles.portNumber ,'String');
IO_LIB=which('inpoutx64.dll');
IO_ADD=hex2dec(port);
ppWrite(IO_ADD,19);  % 19 check
set(handles.notiontxt,'String','Check trigger... "19" in your brainvision');

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

function RESET(handles, init)
if ~init
    a = [500 150 495 460];
else
    a = get(handles.figure1,'Position');
end
% a(4) = 450;
set(handles.notiontxt,'String','Reset all parameters...'); drawnow;
pause(2);
set(handles.figure1,'Position',a);
set(handles.spellerText,'String','KOREA_UNIVERSITY');
set(handles.NumberOfSeq  ,'String','10');
set(handles.screenNumber ,'String','2');
set(handles.stimulusTime ,'String','0.135');
set(handles.IntervalTime ,'String','0.05');
set(handles.portNumber ,'String','D010');
set(handles.tcpiptxt ,'String','12300');
% set(handles.testText,'text40','off');
% set(handles.testText,'visible','off');
% set(handles.testText,'String','OPENBMI_SPELLER');
scrPanelOn(handles,'off');
set(handles.RC_sp,'Value',0);
set(handles.random_sp,'Value',0);
set(handles.face_sp,'Value',0);
set(handles.offbtn,'Value',0);
set(handles.onbtn,'Value',0);
set(handles.text41,'visible','on');
set(handles.tcpiptxt,'visible','on');
set(handles.servercheck,'visible','on');
set(handles.pushbutton12,'visible','on');
set(handles.notiontxt,'String','You have to start with selecting the p300 spller type');
set(handles.screenSize,'value',1);

global state sock
bbci_acquire_bv('close');
params = struct;
state = bbci_acquire_bv('init', params);
disp('will close to connection');
try
    fclose(sock);
catch
end

author: PatternRecognition

repo: OpenBMI


text:
% load all images of uiuc
% takes about 2.5 Go of ram
all_img = retrieve_uiuc;

% display all images of class 1
imagesc(display_gscatt_all(all_img{1}));

author: scatnet

repo: scatnet

save_path: github-repos/MATLAB/scatnet-scatnet


text:
function varargout=melbankm(varargin)
%
% For calling details please see v_melbankm.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_melbankm.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: melbankm.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_melbankm(varargin{:});
else
    v_melbankm(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
for model_index=0:0
    caffe.reset_all;
    net=caffe.get_net(param.test_net_file,'test');
%     net.copy_from(strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(65500+model_index*2000),'.caffemodel'));
   net.copy_from(param.fintune_model);
    tic;
    fin=fopen(param.result_save_file,'a');
    str=strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(65500+model_index*2000),'.caffemodel');
    fprintf(fin,'model:%s\n',str);
    fprintf('testing model:%s\n',str);
    fclose(fin);
    net.blobs('data').reshape([224 224 3 param.test_batch_size]);
%     % contrast fix score
%     net.blobs('sig').reshape([1 1 3 param.test_batch_size]);
%     batch_sig=ones(1,1,3,param.test_batch_size,'single');
%     net.blobs('sig').set_data(batch_sig);
%     %
    load(strcat(param.data_path,param.testdata_filename,num2str(split_index),'/test_data.mat'));
    test_script_for_LPW;
    toc;
end

author: liuyuisanai

repo: Quality-Aware-Network


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sh7.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function f = sh7(x)
% Shekel7 function
function f = sh7(x)
a = [4, 1, 8, 6, 3, 2, 5;
     4, 1, 8, 6, 7, 9, 5;
     4, 1, 8, 6, 3, 2, 3;
     4, 1, 8, 6, 7, 9, 3];
c = [0.1 0.2 0.2 0.4 0.4 0.6 0.3];
if size(x,1) == 1
 x = x';
end
for i=1:7
 b = (x - a(:,i)).^2;
 d(i) = sum(b);
end
f = -sum((c+d).^(-1));

author: lacerbi

repo: optimviz

save_path: github-repos/MATLAB/lacerbi-optimviz


text:
function r8mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% R8MAT_WRITE writes an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 August 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real TABLE(M,N), the points.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'R8MAT_WRITE - Error!' );
    return;
  end
%
%  Write the data.
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %24.16f', table(i,j) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, varargin)
%STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, varargin)
%
% PCA-Lasso based prediction on a set of brain images
% Tor Wager, Sept. 2009
%
% Inputs:
%   my_outcomes: a cell array of outcomes for each dataset
%   imgs: a cell array of image names for each dataset
%
%   Alternative: "Object-oriented" mode
%   my_outcomes = [];
%   imgs = an fmri_data object, with imgs.Y = outcomes
%
% Optional inputs:
%     'reversecolors', reversecolors = 1;
%     'skipnonparam', dononparam = 0;
%     'skipsurface', dosurface = 0;
%     {'cov', 'covs', 'covariates'}, covs = varargin{i+1};
%     'mask', mask = varargin{i+1}; varargin{i + 1} = [];
%     'niter', niter = varargin{i+1};
%     'more_imgs', followed by 2nd (or nth) set of
%     images in cell array {}
%     'outcome_name', outcome_name = varargin{i+1}; varargin{i + 1} = [];
%     'covnames', covnames = varargin{i+1}; varargin{i + 1} = [];
%     'save', dosave = 1;
%     'ndims', ndims = varargin{i+1}; varargin{i + 1} = [];
%     'pca', plsstr = 'pca';  % default...
%     'pls', plsstr = 'pls';
%     {'choose_regparams', 'dochoose_regparams', 'optimize_regularization'}, dochoose_regparams_str = 'optimize_regularization';
%     {'holdout_method'} followed by string e.g., 'balanced4'
%     or custom holdout set of integers for each test set; see
%     xval_regression_multisubject
%
% Examples
% -----------------------------------------------------------------------
% mkdir LASSO_xvalidation_frontal
% cd LASSO_xvalidation_frontal/
% mask = '/Users/tor/Documents/Tor_Documents/CurrentExperiments/Combined_sample_2007/newmask_mapped.img';
% load('/Users/tor/Documents/Tor_Documents/CurrentExperiments/Combined_sample_2007/robust0004/robust0001/SETUP.mat')
% imgs = {SETUP.files};
% my_outcomes = {SETUP.X(:, 2)};
% covs = {SETUP.X(:, [3 4 5])};
% outcome_name = 'Placebo Analgesia (C-P)';
% covnames = {'Order' 'Study' 'Study x Placebo'};
% STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, 'mask', mask, 'covs', covs, 'reversecolors', 'skipsurface', 'skipnonparam');
%
% or
%
% STATS_FINAL = xval_lasso_brain(my_outcomes, imgs, 'mask', mask, 'covs', covs, 'reversecolors');
%
% STATS_FINAL = xval_lasso_brain({img_dat_cat_masked.Y}, {imgs}, 'mask', maskname, 'outcome_name', img_dat_cat_masked.Y_names, 'niter', 1000, 'holdout_method', id_numbers, 'save');
%
% For fmri_data object inputs:
% STATS_FINAL = xval_lasso_brain([], img_dat_cat_masked, 'mask', maskname, 'niter', 1000, 'holdout_method', id_numbers, 'save');

% Programmers' notes
% Updated 3/7/2013 tor wager
%   - changed rng to rng from 'twister' (legacy)
%   - documentation
%   - updated to take object-oriented fmri_data file as input

    % -----------------------------------------------------------------------
    % Optional inputs
    % -----------------------------------------------------------------------
    spm_defaults
    covs = [];
    mask = which('brainmask.nii');
    reversecolors = 0;
    dononparam = 1;
    dosurface = 1;
    niter = 200;
    covnames = {'Unknown'};
    outcome_name = 'Unknown';
    verbose = 1;
    imgs2 = {};
    dosave = 0;
    ndims = 'variable';
    plsstr = 'pca';
    dochoose_regparams_str = 'verbose';  % switch to 'optimize_regularization' to do inner xval
    holdout_method = 'loo'; % see xval_regression_multisubject

    if isa(imgs, 'image_vector')
        outcome_name = imgs.Y_names;
        my_outcomes = {imgs.Y};
    end

    inputOptions.all_optional_inputs = varargin;

    for i = 1:length(varargin)
        if ischar(varargin{i})
            switch varargin{i}
                % Process control
                case 'reversecolors', reversecolors = 1;
                case 'skipnonparam', dononparam = 0;
                case 'skipsurface', dosurface = 0;

                    % Covariates and Masking
                case {'cov', 'covs', 'covariates'}, covs = varargin{i+1};
                case 'mask', mask = varargin{i+1}; varargin{i + 1} = [];
                case 'niter', niter = varargin{i+1};

                    % Input images
                case 'more_imgs', imgs2{end+1} = varargin{i+1};
                    fprintf('Found additional image set %3.0f\n', length(imgs2));

                    % Naming output and saving
                case 'outcome_name', outcome_name = varargin{i+1}; varargin{i + 1} = [];
                case 'covnames', covnames = varargin{i+1}; varargin{i + 1} = [];
                case 'save', dosave = 1;

                    % Dimension reduction
                case 'ndims', ndims = varargin{i+1}; varargin{i + 1} = [];
                    if strcmp(ndims, 'all')
                        ndims = size(imgs{1}, 1) - 2;
                        fprintf('Choosing %3.0f dims for PCA/PLS\n', ndims);
                    end

                case 'pca', plsstr = 'pca';  % default...
                case 'pls', plsstr = 'pls';

                    % Shrinkage/regularization parameters

                case {'choose_regparams', 'dochoose_regparams', 'optimize_regularization'}, dochoose_regparams_str = 'optimize_regularization';

                    % Holdout set selection

                case {'holdout_method'}, holdout_method = varargin{i+1}; varargin{i + 1} = [];

                case {'variable', 'verbose'} % do nothing; needed later

                otherwise, warning(['Unknown input string option:' varargin{i}]);
            end
        end
    end

    inputOptions.all_outcomes = my_outcomes;
    inputOptions.outcome_name = outcome_name;
    inputOptions.imgs = imgs;
    inputOptions.covs = covs;
    inputOptions.covnames = covnames;
    inputOptions.mask = mask;
    inputOptions.ndims = ndims;
    inputOptions.plsstr = plsstr;
    inputOptions.reversecolors = reversecolors;
    inputOptions.dochoose_regparams_str = dochoose_regparams_str;
    inputOptions.holdout_method = holdout_method;

    % set up the mask
    % -------------------------------------------------------------------------
    if isempty(mask), error('Mask is empty and/or default mask ''brainmask.nii'' cannot be found on path.'); end

    if isa(imgs, 'image_vector')
        if isa(mask, 'image_vector')

            mask = resample_space(mask, imgs);

        else  % mask is string

            mask = fmri_data(mask);
        end
        maskInfo = mask.volInfo;

    else

        if exist(fullfile(pwd, 'mask.img')) && verbose, disp('''mask.img'' already exists in this directory.  Replacing.'); else disp('Creating mask.img'); end
        scn_map_image(mask, deblank(imgs{1}(1,:)), 'write', 'mask.img');
        maskInfo = iimg_read_img(fullfile(pwd, 'mask.img'), 2);
    end

    inputOptions.maskInfo = maskInfo;

    datasets = length(imgs);  % each Subject would constitute a "dataset" for a multi-level/within-subjects analysis

    % load image data and apply mask
    % -------------------------------------------------------------------------
    % Object-oriented input
    if isa(imgs, 'image_vector')
        fprintf('Loading all datasets and applying mask ');
        imgs = apply_mask(imgs, mask);
        dat{1} = imgs.dat';
        size_orig{1} = [1 imgs.volInfo.n_inmask]; % for reconstruction

        if ~isempty(imgs2) && isa(imgs, 'image_vector')
            imgs2 = apply_mask(imgs2, mask);
            dat{1} = [dat{1} imgs2.dat'];
        elseif ~isempty(imgs2)
            error('imags and imgs2 must both be objects or neither can be an object.');
        end

    else
        % load from image names

        fprintf('Loading all datasets (may be memory-intensive for multi-subject fMRI): ');
        for i = 1:datasets
            fprintf('%02d', i);
            dat{i} =  iimg_get_data(maskInfo, imgs{i});
            size_orig{i} = size(dat{i});

            if ~isempty(imgs2)
                for imgset = 1:length(imgs2)
                    dat{i} = [dat{i} iimg_get_data(maskInfo, imgs2{imgset}{i})];
                end

            end

        end
        fprintf('\n');
    end

    %%

    STATS_FINAL = struct('inputOptions', inputOptions);

    % Run it: covs only
    % -------------------------------------------------------------------------
    STATS_FINAL.covs = [];
    if ~isempty(covs)
        disp('==================================')
        disp('Covariates only: OLS')
        STATS_FINAL.covs = xval_regression_multisubject('ols', my_outcomes, covs, 'holdout_method', holdout_method);
    end

    % Run it: data only
    % -------------------------------------------------------------------------
    if ~isempty(covs)
        disp('==================================')
        disp('Data only: lasso')
        STATS_FINAL.data = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);
    else
        STATS_FINAL.data = 'see .full_model';
    end

    % Run it: combined
    % -------------------------------------------------------------------------

    % My best guess about what will work: Lasso, with as many dims retained as possible
    % * NOTE: all of the main inputs should be cell arrays
    STATS_FINAL.full_model = [];
    if ~isempty(covs)
        disp('==================================')
        disp('Data plus covariates full model: lasso')
        STATS_FINAL.full_model = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, 'cov', covs, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);
    else
        disp('Data only full model: lasso')
        disp('==================================')
        STATS_FINAL.full_model = xval_regression_multisubject('lasso', my_outcomes, dat, 'pca', 'ndims', ndims, plsstr, dochoose_regparams_str, 'holdout_method', holdout_method);
    end

    if dosave
        save STATS_xval_output STATS_FINAL
    end

    %% Figures: Scatterplot plus bars
    % -------------------------------------------------------------------------

    create_figure('Scatterplot: Full model', 1, 2);
    [r,istr,sig,h] = plot_correlation_samefig(STATS_FINAL.full_model.subjfit{1}, STATS_FINAL.inputOptions.all_outcomes{1});
    set(gca,'FontSize', 24)
    xlabel('Cross-validated prediction');
    ylabel('Outcome');
    title('Lasso cross-validation');
    set(h, 'MarkerSize', 10, 'MarkerFaceColor', [.0 .4 .8], 'LineWidth', 2);
    h = findobj(gca, 'Type', 'Text');
    set(h, 'FontSize', 24)

    % bars
    subplot(1, 2, 2)
    set(gca,'FontSize', 24)

    if ~isempty(covs)
        pevals = [std(STATS_FINAL.inputOptions.all_outcomes{1}) ...
            STATS_FINAL.full_model.pred_err_null STATS_FINAL.covs.pred_err ...
            STATS_FINAL.data.pred_err STATS_FINAL.full_model.pred_err];
        penames = {'Var(Y)' 'Mean' 'Covs' 'Brain' 'Full'};
    else
        pevals = [std(STATS_FINAL.inputOptions.all_outcomes{1}) ...
            STATS_FINAL.full_model.pred_err_null STATS_FINAL.full_model.pred_err];
        penames = {'Var(Y)' 'Mean' 'Brain'};
    end

    han = bar(pevals); set(han, 'FaceColor', [.5 .5 .5]);
    set(gca, 'XTick', 1:length(penames), 'XTickLabel', penames);
    axis tight
    ylabel('Prediction error');

    if dosave
        scn_export_papersetup(500); saveas(gcf, 'Pred_Outcome_Scatter', 'png');
    end

    % is accuracy predicted by Y and/or covariates?
    % ****

    %% Get mean Lasso betas
    % -------------------------------------------------------------------------

    bonf_thresh = norminv(1 - .025 ./ size(dat{1}, 2));

    mystd = std(STATS_FINAL.full_model.vox_weights'); % not actual valid threshold because training sets are not independent

    [my_ste,t,n_in_column,p,m] = ste(STATS_FINAL.full_model.vox_weights');
    Z = (m ./ mystd)';

    if isa(mask, 'image_vector')
        not_in_mask = mask.dat == 0;
        my_ste = zeroinsert(not_in_mask, my_ste')';
        t = zeroinsert(not_in_mask, t')';
        n_in_column = zeroinsert(not_in_mask, n_in_column')';
        p = zeroinsert(not_in_mask, p')';
        m = zeroinsert(not_in_mask, m')';
        Z = zeroinsert(not_in_mask, Z);
    end

    i = 1;
    iimg_reconstruct_vols(m(1: size_orig{i}(2))', maskInfo, 'outname', 'xval_lasso_wts_mean.img');
    iimg_reconstruct_vols(Z(1: size_orig{i}(2)), maskInfo, 'outname', 'xval_lasso_Z.img');

    if length(m) > size_orig{i}
        iimg_reconstruct_vols(m(size_orig{i}(2)+1:end)', maskInfo, 'outname', 'xval_lasso_wts_mean_imageset2.img');
        iimg_reconstruct_vols(Z(size_orig{i}(2)+1:end), maskInfo, 'outname', 'xval_lasso_Z_imageset2.img');
    end

    sig_vox = abs(Z) > bonf_thresh;
    Z_thresh = Z;
    Z_thresh(~sig_vox) = 0;
    iimg_reconstruct_vols(Z_thresh(1: size_orig{i}(2)), maskInfo, 'outname', 'xval_lasso_Z_bonf_thresh.img');

    if length(m) > size_orig{i}
        iimg_reconstruct_vols(Z_thresh(size_orig{i}(2)+1:end), maskInfo, 'outname', 'xval_lasso_Z_bonf_thresh.img');
    end

    %% Orthviews
    % -------------------------------------------------------------------------

    if any(Z_thresh)
        cl = mask2clusters('xval_lasso_Z_bonf_thresh.img');
    else
        disp('No significant voxel weights at bonferroni corrected threshold.')
        cl = [];
    end

    poscm2 = colormap_tor([1 .5 0], [1 1 0]);
    negcm2 = colormap_tor([.5 0 1], [0 0 1]);

    cluster_orthviews(cl);

    if reversecolors
        cm = spm_orthviews_change_colormap([1 1 0], [0 0 1], [1 0 .4], [.4 .6 1] );
    else
        cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [.4 .6 1], [1 0 .4]);
    end

    STATS_FINAL.full_model.cl = cl;

    %cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [0 0 1], [0 0 1], [0
    %.5 1], [0 .5 1], [.5 .5 .5], [.5 .5 .5], [.7 0 0], [1 .5 0], [1 .5 0], [1 1 0]);

    % cm = spm_orthviews_change_colormap([0 0 1], [1 1 0], [0 0 1], [0 0 1], [0 .5 1], [0 .5 1], [.5 .5 .5], [.5 .5 .5], [.7 0 0], [1 .5 0], [1 .5 0], [1 1 0]);

    %%  Brain Surface Plot
    % -------------------------------------------------------------------------

    if dosurface

        create_figure('Brain_Surface', 2, 2);

        if reversecolors
            negcm = colormap_tor([1 0 .4], [1 1 0]);
            poscm = colormap_tor([.4 .6 1], [0 0 1]);
        else
            poscm = colormap_tor([1 0 .4], [1 1 0]);
            negcm = colormap_tor([.4 .6 1], [0 0 1]);
        end

        han1 = addbrain('hires');
        cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han1);

        %replace with 'hires' and re-run to do whole cortical surface
        create_figure('Brain_Surface', 2, 2, 1);
        subplot(2, 2, 2);
        han = addbrain('hires right'); set(han, 'FaceAlpha', 1);

        drawnow
        cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);
        set(han, 'FaceAlpha', 1);
        axis image; lightRestoreSingle;
        lighting gouraud

        create_figure('Brain_Surface', 2, 2, 1);
        subplot(2, 2, 3);
        han = addbrain('hires left'); set(han, 'FaceAlpha', 1);
        axis image; lightRestoreSingle;
        lighting gouraud
        drawnow
        cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);

        create_figure('Brain_Surface', 2, 2, 1);
        subplot(2, 2, 4);
        han = addbrain('limbic'); set(han, 'FaceAlpha', 1);
        axis image; lightRestoreSingle;
        lighting gouraud
        drawnow
        cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);

        set(han(end), 'FaceAlpha', .2)
        han2 = addbrain('brainstem');
        cluster_surf(cl, 2, 'heatmap', 'colormaps', poscm, negcm, han);
        view(135, 15)

        create_figure('Brain_Surface', 2, 2, 1);
        subplot(2, 2, 1)
        han = findobj(gca,'Type','patch'); set(han, 'FaceAlpha',1)
        axis image

        if dosave
            scn_export_papersetup(600); saveas(gcf, 'Surface1', 'png');
            subplot(2, 2, 1);
            view(135, 20); lightRestoreSingle;
            saveas(gcf, 'Surface2', 'png');
            view(225, 20); lightRestoreSingle;
            saveas(gcf, 'Surface3', 'png');
            view(90, 3); lightRestoreSingle;
            saveas(gcf, 'Surface4', 'png');
            view(270, 3); lightRestoreSingle;
            saveas(gcf, 'Surface5', 'png');
        end

    end

    %% NONPARAMETRIC TEST

    if dononparam

        disp('PERMUTATION TEST FOR NULL HYPOTHESIS');

        % Permute : covariates only
        % ==============================================
        if ~isempty(covs)
            clear my_outcomesp all_r pe
            ndims =  min(size(covs{1}, 2) - 1, size(covs{1}, 1) - 2); % will not work for multilevel with diff. dimensions per dataset

            fprintf('Covariates only: Running %3.0f iterations\n', niter);

            for i = 1:niter

                %rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...
                try
                    rng('shuffle');
                catch
                    rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...
                end

                my_outcomes = STATS_FINAL.inputOptions.all_outcomes;

                % permute
                for s = 1:datasets
                    ix = randperm(length(my_outcomes{s}));
                    my_outcomesp{s} = my_outcomes{s}(ix);
                end

                %% Do the prediction
                % ------------------------------------------------------------------
                if size(covs, 2) > 1
                    STATSpcovs = xval_regression_multisubject('lasso', my_outcomesp, covs, 'noverbose',  'holdout_method', holdout_method); %,'pca', 'ndims', ndims);
                else
                    STATSpcovs = xval_regression_multisubject('ols', my_outcomesp, covs, 'noverbose',  'holdout_method', holdout_method); %,'pca', 'ndims', ndims);
                end

                fprintf('%3.2f ', STATSpcovs.r_each_subject);

                all_r(i) = STATSpcovs.r_each_subject;
                pe(i) = STATSpcovs.pred_err;

            end

            STATS_FINAL.covs.permuted.pe_values = pe;
            STATS_FINAL.covs.permuted.pe_mean = mean(pe);
            STATS_FINAL.covs.permuted.pe_ci = [prctile(pe, 5) prctile(pe, 95)];
            STATS_FINAL.covs.permuted.r_values = all_r;
            STATS_FINAL.covs.permuted.r_mean = mean(all_r);
            STATS_FINAL.covs.permuted.r_ci = [prctile(all_r, 5) prctile(all_r, 95)];
            if dosave
                save STATS_xval_output -append STATS_FINAL
            end

            fprintf('\n')

        end

        % Permute : random subset of 1000 voxels
        % ==============================================
        n_vox = 1000;
        if size(dat{1}, 2) > n_vox
            clear my_outcomesp my_datp all_r pe
            ndims = size(dat{1}, 1) - 2;

            fprintf('1000 vox subsets: %3.0f iterations: %3.0f', niter, 0);

            for i = 1:niter

                fprintf('\b\b\b%3.0f', i);

                try
                    rng('shuffle');
                catch
                    rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...
                end

                my_outcomes = STATS_FINAL.inputOptions.all_outcomes;

                % permute
                for s = 1:datasets
                    ix = randperm(length(my_outcomes{s}));
                    ix2 = randperm(size(dat{s}, 2));

                    my_outcomesp{s} = my_outcomes{s}(ix);
                    my_datp{s} = dat{s}(:, ix2(1:n_vox));

                end

                %% Do the prediction
                % ------------------------------------------------------------------
                STATSpv= xval_regression_multisubject('lasso', my_outcomesp, my_datp, 'pca', plsstr, 'ndims', ndims, dochoose_regparams_str,  'holdout_method', holdout_method, 'noverbose');

                all_r(i) = STATSpv.r_each_subject;
                pe(i) = STATSpv.pred_err;

            end

            fprintf('%3.2f ', all_r);
            fprintf('\n')

            STATS_FINAL.full_model.permuted.v1000_pe_values = pe;
            STATS_FINAL.full_model.permuted.v1000_pe_mean = mean(pe);
            STATS_FINAL.full_model.permuted.v1000_pe_ci = [prctile(pe, 5) prctile(pe, 95)];
            STATS_FINAL.full_model.permuted.v1000_r_values = all_r;
            STATS_FINAL.full_model.permuted.v1000_r_mean = mean(all_r);
            STATS_FINAL.full_model.permuted.v1000_r_ci = [prctile(all_r, 5) prctile(all_r, 95)];
            if dosave
                save STATS_xval_output -append STATS_FINAL
            end
        end

        % Permute : Full data
        % ==============================================
        clear my_outcomesp all_r pe
        ndims = size(dat{1}, 1) - 2;

        fprintf('1000 vox subsets: %3.0f iterations\n', niter);

        for i = 1:niter

            %rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...
            try
                rng('shuffle');
            catch
                rand('twister',sum(100*clock)) ; % was getting wacky results suggesting randperm is not producing indep. perms...
            end

            my_outcomes = STATS_FINAL.inputOptions.all_outcomes;

            % permute
            for s = 1:datasets
                ix = randperm(length(my_outcomes{s}));
                my_outcomesp{s} = my_outcomes{s}(ix);
            end

            %% Do the prediction
            % ------------------------------------------------------------------
            STATSp = xval_regression_multisubject('lasso', my_outcomesp, dat, 'pca', plsstr, 'ndims', ndims,  dochoose_regparams_str, 'holdout_method', holdout_method);

            fprintf('Iteration %3.0f : r = %3.2f\n', STATSp.r_each_subject);

            all_r(i) = STATSp.r_each_subject;
            pe(i) = STATSp.pred_err;

        end

        STATS_FINAL.full_model.permuted.pe_values = pe;
        STATS_FINAL.full_model.permuted.pe_mean = mean(pe);
        STATS_FINAL.full_model.permuted.pe_ci = [prctile(pe, 5) prctile(pe, 95)];

        STATS_FINAL.full_model.permuted.r_values = all_r;
        STATS_FINAL.full_model.permuted.r_mean = mean(all_r);
        STATS_FINAL.full_model.permuted.r_ci = [prctile(all_r, 5) prctile(all_r, 95)];
        if dosave
            save STATS_xval_output -append STATS_FINAL
        end

    end % if do nonparam

end % main function

% - Extra stuff -

% % %% Bootstrap the covariates
% % %
% % % This is the "Leave one out bootstrap" of Efron and Tibshirani, JASA, 1997
% % % Err(1)
% % % They show that this can be done by taking the error on each point from
% % % bootstrap samples that do not happen to contain that point
% % %
% % % they say that for continuous outcomes and predictors (our case), they
% % % expect the cross-val estimate and the 632+ bootstrap estimate to be more
% % % similar.  the benefit is mainly for discontinuous outcomes (1/0)
% % %
% % % they say that Err(1) is biased upwards compared to the nearly unbiased
% % % CV(1) (leave-one-out cross-validation)
% % % it estimates "half-sample" xval
% %
% % bootfun = @(Y, X) xval_regression_boostrap_wrapper(Y, X);
% % STATS_FINAL.bootstrap.covs_only_r_rsq = bootstrp(200, bootfun, my_outcomes_orig{1}, covs{1});
% % STATS_FINAL.bootstrap.covs_only_summary = [mean(STATS_FINAL.bootstrap.covs_only_r_rsq) std(STATS_FINAL.bootstrap.covs_only_r_rsq) ];
% % STATS_FINAL.bootstrap.covs_only_summary_descrip = 'mean std of bootstrapped values'
% %
% % STATS_FINAL.bootstrap.dat_only_r_rsq = bootstrp(20, bootfun, my_outcomes_orig{1}, dat{1});
% %
% % STATS_FINAL.bootstrap.dat_only_r_rsq = [STATS_FINAL.bootstrap.dat_only_r_rsq; bootstrp(80, bootfun, my_outcomes_orig{1}, dat{1})];
% %
% % STATS_FINAL.bootstrap.dat_only_summary = [mean(STATS_FINAL.bootstrap.dat_only_r_rsq) std(STATS_FINAL.bootstrap.dat_only_r_rsq) ];
% % STATS_FINAL.bootstrap.dat_only_summary_descrip = 'mean std of bootstrapped values'
% %
% % %% Nonparametric test with N variables (voxels) selected at random
% %
% % s = 1;
% %
% %
% % n_vox = [1000:2000:50000];
% % niter = [1 50];
% %
% % if niter(1) == 1,  all_r_perm = zeros(niter(2), length(n_vox + 1)); end
% %
% % for i = 1:length(n_vox)
% %     for j = niter(1):niter(2)
% %
% %         rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...
% %
% %         ix = randperm(length(my_outcomes{s}));
% %         ix2 = randperm(size(dat{s}, 2));
% %
% %         STATSperm= xval_regression_multisubject('lasso', {my_outcomes{1}(ix)}, {dat{1}(:, ix2(1:n_vox(i)))}, 'pca', 'ndims', ndims);
% %
% %         all_r_perm(j, i) = STATSperm.r_each_subject;
% %
% %     end
% %
% %     create_figure('permuted');
% %     plot(n_vox(1:size(all_r_perm, 2)), mean(all_r_perm), 'ko-', 'Linewidth', 3);
% %     xlabel('Number of voxels'); ylabel('Average predicted/actual correlation');
% %     drawnow
% % end
% %
% % % with full sample
% % n_vox(end+1) = size(dat{s}, 2);
% % i = length(n_vox);
% %
% % for j = niter(1):niter(2)
% %
% %     rand('twister',sum(100*clock)) ; % trying this; was getting wacky results suggesting randperm is not producing indep. perms...
% %
% %     ix = randperm(length(my_outcomes{s}));
% %     %ix2 = randperm(size(dat{s}, 2));
% %
% %     STATSperm= xval_regression_multisubject('lasso', {my_outcomes{1}(ix)}, dat(1), 'pca', 'ndims', ndims);
% %
% %     all_r_perm(j, i) = STATSperm.r_each_subject;
% %
% % end
% %
% % create_figure('permuted');
% % plot(n_vox(1:size(all_r_perm, 2)), mean(all_r_perm), 'ko-', 'Linewidth', 3);
% % xlabel('Number of voxels'); ylabel('Average predicted/actual correlation');
% % drawnow

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
 function X = dtft_mex(varargin)

disp('This dtft_mex.m is a dummy m-file that is included to provide')
disp('a reminder that you must have the Mex file "dtft_mex.mex???" that')
disp('is appropriate for your system.  For pc-linux, the mex file is')
disp('called "dtft_mex.mexglx", which is provided in the "mfile"')
disp('subdirectory.  For a sun, the name is "dtft_mex.mexsol", which')
disp('may or may not be provided.  If you have another OS, then you may')
disp('be out of luck, or you may be able to cajole Jeff into compiling a')
disp('mex file for your OS.')
error 'no appropriate mex file!?'

author: thomaskuestner


text:
function s = y_to_s_gregorian ( y )

%*****************************************************************************80
%
%% Y_TO_S_GREGORIAN writes a Gregorian year into a string.
%
%  Format:
%
%    YearNumber BC
%    YearNumber AD
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year.
%
%    Output, string S, a representation of the year.
%
  if ( y < 0 )
    s = sprintf ( 'BC %d', -y );
  elseif ( 0 < y )
    s = sprintf ( 'AD %d', y );
  end

  return
end


text:
function [time_finish, time_table_pen] = cal_time_data(cp_ptp, ts, time_wait)
% Finish Time and Pen Time Table Calculation
%
% [Inputs]
%	cp_ptp			 : CP + PTP trajectory
%   ts				 : sample rate [msec]
%	time_wait		 : time to wait [msec]
% [Outputs]
%	time_finish		 : time to finish tracking trajectory [msec]
%	time_table_pen	 : time table to manipulate pen [msec]

% time_table_pen
num_pen = length(cp_ptp) - 1;
time_table_pen = zeros(1, num_pen);
noe = 0;
for n = 1:num_pen
	noe = noe + max(size(cp_ptp{n}));
	time_table_pen(n) = noe * ts;
end

% time_finish
noe = noe + max(size(cp_ptp{end}));
time_finish = noe * ts + time_wait;

author: Sable

repo: mcbench-benchmarks


text:
function planDB = updatePlanDB(planDB, varargin)
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.
%
%"updatePlanDB"
%   Sync the plan database with contents of <path> and its subdirs.
%
%   Given a planDB (or [] if a new planDB is being created), scan <path>
%   and all subdirectories for .mat/.mat.bz2 files. If .mat files are encountered
%   that did not exist in the planDB or have been modified since the last
%   update, load them and attempt to compile a planC extract.  If files
%   exist in planDB that do not exist in <path>, flag them as not present.
%   .mat files that do not contain planCs have an extract of [] and their
%   isPlanC field is set to 0.
%
%   If a user defined function handle @<fcnName> has been specified,
%   it is executed by passing planC as the only parameter.  Output is
%   stored in the userdata field.  The 'userfiles' field is a list of
%   filenames that, if changed, require the database to recompile. This
%   should be the file(s) containing <fcnName> and its child functions.
%
%   planDB parameters 'path', 'template' and 'function' are stored in the
%   planDB and only need to be referenced after the first update if they
%   need to be changed.
%
%   JRA 11/28/03
%
%  To make new DB:
%     planDB = updateplanDB([],'path', <path>, 'template', makeTemplate, 'addfunction', @<fcnName>, <full path to function file>)
%  Update existing:
%     planDB = updateplanDB(planDB);
%  Update for new template:
%     planDB = updateplanDB(planDB, 'template', makeTemplate);

% Steps to update the database:
%    1. Parse Input Arguments        - gives path, template, and ufs
%    2. Check validity of plan path
%    3. Scan HD path for plans.

%    4. Compare found plans to stored plans:
%         i. add new plans -- keep index of new plans
%         ii. flag missing files -- keep index of missing
%         iii. flag changed files as needing update -- keep index.
%         iv. leave unchanged files alone
%
%    4. check for a template change: if changed, flag all plans to get new template.
%
%    3. Update ufs
%     i. Remove deleted ufs
%     ii. add new userfunctions
%     iii. for functions that must be recalced this run flag all plans to get recalc.
%
%
%    5. loop over plans, loading if user or template.  calc necessary stuff. Update plan timestamp at load time.

%Start timer.
updateStartTime = datestr(now);

%Check arguments.  If no args, use the internal template and path.
[path, template, userfuncts, reusePlanC] = evaluateArgs(planDB, nargin, varargin);

%Check validity of path.
if ~isdir(path)
    disp(['planDB>> ''' path ''' does not exist. All files will be flagged not present.']);
    %No matfiles exist, create empty struct.
    matFiles = struct('name', {}, 'path', {}, 'lastMod', {});
else
	%Find all the .mat and .mat.bz2 files in path.
	disp(['planDB>> Searching for .mat & .mat.bz2 files in ' path]);
	matFiles = findMatFiles(path);
    disp(['planDB>> Found ' num2str(length(matFiles)) ' .mat and .mat.bz2 files.']);
end

%Get list of archived files, get list of files found in HD scan.
[storedFileNames, presentFileNames, planDB] = getFilenameList(planDB, matFiles);

%Find indices of new files, removed files.
[newFiles newIndex] = setdiff(presentFileNames, storedFileNames);
[removedFiles removedIndex] = setdiff(storedFileNames, presentFileNames);

%Add the new files to the planDB.
disp(['planDB>> ADDING ' num2str(length(newIndex)) ' new files.']);
for i=1:length(newIndex)
    plan.extract = [];
    plan.userdata = [];
    plan.info.name = matFiles(newIndex(i)).name;
    plan.info.path = matFiles(newIndex(i)).path;
    %Leave lastMod empty so these matFiles will be updated.
    plan.info.lastMod = '';
    plan.isPlanC = [];
    plan.isPresent = 1;
    planDB.matFiles(end+1) = plan;
end

%set isPresent flag for files that no longer exist, do not remove from db.
disp(['planDB>> FLAGGING ' num2str(length(removedIndex)) ' files as missing.']);
for i=1:length(removedIndex)
    planDB.matFiles(removedIndex(i)).isPresent = 0;
end

%Refresh lists.
[storedFileNames, presentFileNames, planDB] = getFilenameList(planDB, matFiles);

%Find indices of files already existing in the database.
storedPlanInfo = [planDB.matFiles.info];
[bool, ind] = ismember(storedFileNames, presentFileNames);

ind(ind==0) = [];

%Flag modified or new files for updating.
needsFullUpdate = ~strcmp({storedPlanInfo(bool).lastMod}, {matFiles(ind).lastMod});

%set isPresent flag for all found files.
presentFiles = find(bool);
disp(['planDB>> FLAGGING ' num2str(length(presentFiles)) ' files as present.']);
for i=1:length(presentFiles)
    planDB.matFiles(presentFiles(i)).isPresent = 1;
end

%We have a fully updated file list in planDB, and a list of flags to indicate which files
%have changed or been added at this point in needsFullUpdate.

%Find which userfunctions have changed or been added, and need calculation.
[ufChanged, planDB] = userFilesChanged(planDB, userfuncts);
changed = find(ufChanged);

%Some output statements for the kids.
if ~isempty(changed)
    string = [];
    for i = 1:length(changed)
        string = [string ' ' planDB.userfunctions(changed(i)).fHandle];
    end
    if length(changed) == 1
        plural = '';
        verb = ' is';
    else
        plural = 's';
        verb = ' are';
    end
    disp(['planDB>> User function' plural string verb ' new or changed and requires calculation.']);
end

%Create a boolean matrix where each row is a plan and each column a
%userfunction.  If userfunction 3 for matFile 5 is true, calculate that
%user function for matFile 5.  New user functions are flagged true for all
%plans, as all plans need this new function calculated.  For new or changed
%plans, flag all userfunctions as needing calculation.
refreshUD = repmat(ufChanged, length(planDB.matFiles), 1);
refreshUD(needsFullUpdate,:) = 1;

%Create a similar boolean vector to refresh template.
refreshTemplate = zeros(length(planDB.matFiles), 1);
refreshTemplate(needsFullUpdate) = 1;

%If template has changed, all plans need template refreshed.
if isfield(planDB, 'template')
	templateExpired = ~isempty(setxor(template, planDB.template));
else
    templateExpired = 1;
end
if templateExpired
    planDB.template = template;
    refreshTemplate = ones(length(planDB.matFiles),1);
end

%Now iterate over all files in planDB.matFiles.  If a matFile is a plan,
%check if it requires its extract or any userfunctions to be recalculated
%by looking at refreshTemplate and refreshUD.  If so, load the plan and
%calculate only what needs refreshing.
for i=1:length(planDB.matFiles)
    plan = planDB.matFiles(i);
    if plan.isPresent
        %If any changes, load the plan.
        fullfilename = fullfile(planDB.matFiles(i).info.path,planDB.matFiles(i).info.name);
        if any([refreshTemplate(i) refreshUD(i,:)])
            disp(['planDB>> UPDATE ' planDB.matFiles(i).info.name]);

            tic
            if reusePlanC
                global planC
            end
            planC = loadPlan(fullfilename);
            disp(['      >> Loaded in ' num2str(toc) 's']);
        end

        if refreshTemplate(i)
            tic
            plan.extract = compileExtract(planC, template);
            disp(['      >> Extracted in ' num2str(toc) 's']);
        end

        for j=1:size(refreshUD, 2)
            if refreshUD(i, j)
                tic
                plan.userdata{j} = compileUser(planC, str2func(planDB.userfunctions(j).fHandle));
                disp(['      >> User function ' planDB.userfunctions(j).fHandle ' run in ' num2str(toc) 's']);
            end
        end
        info = dir(fullfilename);
        %Set timestamp to detect future modifications.
        plan.info.lastMod = info.date;
        %If no extract, file is not a planC.
        plan.isPlanC = ~isempty(plan.extract);
        planDB.matFiles(i) = plan;
    end
end

%PlanDB is now fully updated.  Stamp.
updateEndTime = datestr(now);

planDB.lastUpdateStart = updateStartTime;
planDB.lastUpdateEnd = updateEndTime;
planDB.template = template;
planDB.path = path;

%Build the index of fieldnames into plans, for database browsing.
planDB.fieldIndex = compileFieldnameIndex(planDB.matFiles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function extract = compileExtract(planC, template)
%Make an extract out of the planC if it is not [].
if isempty(planC)
   extract = [];
   return;
else
   extract = makeExtract(planC, template);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function userdata = compileUser(planC, fHandle);
%Run user function if it exists, store returend data.
if isempty(fHandle) | isempty(planC)
    userdata = [];
    return;
else
    userdata = feval(fHandle, planC);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function planC = loadPlan(filename)
%Load the .mat file and check if a planC exists in the workspace.
%If it does, return planC, else return [].  Also handles .bz2 by extracting
%to a tempfile in the tempDirectory and deleting when finished.
compressed = 0;

oldPathStr = pwd;
newPathStr = getCERRPath;

if strcmpi(filename(end-3:end), '.bz2')
    %Is compressed.  Decompress and load. LEAVE original file.
    cd(newPathStr);
    cd('Compression');
    compressed = 1;
    tempFile = fullfile(tempdir, 'temp.mat');
    if ispc
        dos(['bzip2-102-x86-win32.exe -vdkc "', filename, '">> ' tempFile]);
    elseif isunix
        unix(['bzip2 -dck ', filename, ' > ' tempFile]);
    end
    filename = tempFile;
    cd(oldPathStr);
end

clear planC;
try
    load(filename);
catch
    planC = []; %fileload has failed. return.
    return;
end

if compressed
    try
        delete(tempFile);
    end
end

if ~exist('planC')
    planC = [];
    return;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [path, template, userfunctions, reusePlanC] = evaluateArgs(planDB, nargs, vargs)
% Evaluated passed arguments, returning parameters needed to run update.
ufs = [];
oldfHandle = 0;

%Grab old values if they exist.
try,    path        = planDB.path;                 ,end
try,    template    = planDB.template;             ,end
try,    ufs         = planDB.userfunctions;        ,end

reusePlanC = 0;

i = 1;
while i <= nargs-1
    switch vargs{i}
        case 'path'
            %Overwrite path if a new one is specified.
            path = vargs{i+1};
            i = i + 2;
        case 'template'
            %Overwrite template if a new one is specified.
            template = vargs{i+1};
            i = i + 2;
        case 'delfunction'
            %Scrap the specified user function.
            [jnk, ind] = intersect({ufs.fHandle} , func2str(vargs{i+1}));
            ufs(ind) = [];
            i = i + 2;
        case 'addfunction'
            %Add the new user function and userfiles list.

            %First check if it already exists.
            if isfield(ufs, 'fHandle')
                [jnk, ind] = intersect({ufs.fHandle} , func2str(vargs{i+1}));
            else
                jnk = [];
            end
            if ~isempty(jnk)
                warning(['User function ' func2str(vargs{i+1}) ' already exists. Overwriting old associated userfiles.']);
            else
                ind = length(ufs) + 1;
            end
            ufs(ind).fHandle = func2str(vargs{i+1});
            ufs(ind).files = vargs{i+2};
            if ~iscell(ufs(ind).files)
                ufs(ind).files = {ufs(ind).files};
            end
            ufs(ind).date = [];
            i = i + 3;
        case 'reusePlanC'
            i = i + 1;
            reusePlanC = 1;
        otherwise
            error('Invalid Call');
    end
end
userfunctions = ufs;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [storedFileNames, presentFileNames, planDB] = getFilenameList(planDB, matFiles);
%Returns a list of matfiles on the local HD and a list of matfiles stored in the planDB
if ~isempty(planDB) & isfield(planDB, 'matFiles')
	for i=1:length(planDB.matFiles)
        storedFileNames{i} = fullfile(planDB.matFiles(i).info.path, planDB.matFiles(i).info.name);
	end
else
    planDB.matFiles = struct('extract', {}, 'userdata', {}, 'info', {}, 'isPlanC', {}, 'isPresent', {});
    storedFileNames = {};
end
for i=1:length(matFiles)
    presentFileNames{i} = fullfile(matFiles(i).path,matFiles(i).name);
end
%Filenames/directories are caps insensitive and caps inconsistent on pc.
%Uppercase them for purposes of name comparison.
if (ispc)
    presentFileNames = upper(presentFileNames);
    storedFileNames = upper(storedFileNames);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [changed, planDB] = userFilesChanged(planDB, userfuncts)
%Returns a vector of userFile sets that have been modified. Also returns planDB with
%the userfiletime field changed.

%Array of flags to indicate if any userfiles have changed.
changed = zeros(1,length(userfuncts));

if isfield(planDB, 'userfunctions')
    oldFuncts = planDB.userfunctions;

    %Get indices of userfunctions that has been removed.
    [diff,ind] = setdiff({planDB.userfunctions.fHandle}, {userfuncts.fHandle});

    %Delete old userdata.
    for i=1:length(planDB.matFiles)
        planDB.matFiles(i).userdata(ind) = [];
    end
    planDB.userfunctions(ind) = [];

    %Get indices of new userfunctions, add to planDB.
    [newDiff, newInd] = setdiff({userfuncts.fHandle}, {planDB.userfunctions.fHandle});
    planDB.userfunctions(end+1:end+length(newDiff)) = userfuncts(newInd);

    %Flag these new userfuncs as needing calculation.
    [diff,ind] = setdiff({planDB.userfunctions.fHandle}, {userfuncts.fHandle});
    changed(ind) = 1;
else
    %All userfunctions are new, update all.
    planDB.userfunctions = userfuncts;
    changed = ones(1,length(userfuncts));
end

%Check and update userfile timestamps
for j = 1:length(planDB.userfunctions)
    files = planDB.userfunctions(j).files;
	fileInfo = struct('name', {}, 'date', {}, 'bytes', {}, 'isdir', {});

	for i=1:length(files)
        fileInfo(end+1) = dir(files{i});
	end

	%Has file list changed? If so flag as needing recalculation.
	if ~isfield(planDB.userfunctions, 'files') | ~isfield(planDB.userfunctions, 'date')
        changed(j) = 1;
    elseif ~isequal(length(files), length(planDB.userfunctions(j).files))
        changed(j) = 1;
	elseif ~isempty(setxor(files, planDB.userfunctions(j).files))
        changed(j) = 1;
	elseif ~isequal({fileInfo.date}, planDB.userfunctions(j).date)
        changed(j) = 1;
	end

    %Save current timestamp info.
	if changed(j)
        files = files;
        planDB.userfunctions(j).date = {fileInfo.date};
    end

end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [gd,fnorm]=sgrpdlay(x,fnorm);
%SGRPDLAY Group delay estimation of a signal.
%	[GD,FNORM]=SGRPDLAY(X,FNORM) estimates the group delay of
%	signal X at the normalized frequency(ies) FNORM.
%
%	X     : signal in the time-domain.
%	FNORM : normalized frequency. By default, FNORM is a
%               linearly spaced vector between -0.5 and 0.5 with
%               length(X) elements.
%	GD    : computed group delay. When GD equals zero, it means that
%	 	the estimation of the group delay for this frequency was
%		outside the interval [1 xrow], and therefore meaningless.
%
%	Example :
%	 N=128; x=amgauss(N,64,30).*fmlin(N,0.1,0.4);
%	 fnorm=0.1:0.04:0.38; gd=sgrpdlay(x,fnorm);
%	 t=2:N-1; instf=instfreq(x,t);
%	 plot(t,instf,gd,fnorm); axis([1 N 0 0.5]);

%	F. Auger, March 1994, July 1995.
%	Copyright (c) 1996 by CNRS (France).
%
%  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

if (nargin == 0),
 error('At least one parameter required');
end;

[xrow,xcol] = size(x);
if (xcol~=1),
 error('x must have only one column');
end;
Ex=mean(abs(x).^2);
Threshold=1.0e-6;

if (nargin==1),
 Num=fft(x .* (1:xrow)');
 Den=fft(x);
 ratio=(real(Num./Den) .* (real(Num./Den)>=1) .* (real(Num./Den)<=xrow+3));
 gd=fftshift(ratio);
 if (nargout==2),
  if (rem(xrow,2)==0),
   L=xrow/2;
   fnorm=(-L:L-1)/xrow;
  else
   L=(xrow-1)/2;
   fnorm=(-L:L)/xrow;
  end;
 end;
elseif (nargin==2),
 [fnormrow,fnormcol] = size(fnorm);
 if (fnormrow~=1),
  error('FNORM must have only one row');
 end;
 expo=exp(-j*2.0*pi*fnorm'*(0:xrow-1));
 Num=expo*(x .* (1:xrow)');
 Den=expo*x;
 gd=(real(Num./Den) .* (real(Num./Den)>=1) .* (real(Num./Den)<=xrow+3));
end;

author: HeLiangHIT


text:
%% inv_parbound
% Below is a demonstration of the features of the |inv_parbound| function

%%
clear; close all; clc;

%% Syntax
% |P=inv_parbound(Pb,Ps);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON