text:
function varargout = configManager(varargin)
% CONFIGMANAGER MATLAB code for configManager.fig
%      CONFIGMANAGER, by itself, creates a new CONFIGMANAGER or raises the existing
%      singleton*.
%
%      H = CONFIGMANAGER returns the handle to a new CONFIGMANAGER or the handle to
%      the existing singleton*.
%
%      CONFIGMANAGER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CONFIGMANAGER.M with the given input arguments.
%
%      CONFIGMANAGER('Property','Value',...) creates a new CONFIGMANAGER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before configManager_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to configManager_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 configManager
% Last Modified by GUIDE v2.5 21-Jul-2013 15:10:10
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Doyen Sahoo
% Contributors: Bin LI, Steven C.H. Hoi
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    load config/config;
    handles.config.algorithmList = algorithmList;
    handles.config.algorithmName = algorithmName;
    handles.config.algorithmParameters = algorithmParameters;
    handles.config.dataList = dataList;
    handles.config.dataName = dataName;
    handles.config.defaultParameters = defaultParameters;
    handles.config.dataFrequency = dataFrequency;

    % The list of data and algorithm names for menu
    set(handles.dataList,'String',handles.config.dataList);
    set(handles.algorithmList,'String',handles.config.algorithmList);

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = configManager_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 pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

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

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

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

    set(handles.deleteDataMessage, 'String', '');
    set(handles.deleteAlgorithmMessage, 'String', '');

    [r c] = size(handles.config.dataList);
    fileName = get(handles.dataFileName, 'string');
    handles.config.dataList(r+1,c) = {get(handles.dataNameString, 'string')};
    handles.config.dataName(r+1,c) = {fileName};
    handles.config.dataFrequency(r+1,c) = str2num(get(handles.frequency, 'string'));

    % Check if file exists
    fullPath = strcat('..\Data\',fileName, '.mat');
    if ~(exist(fullPath) == 2)
        errorMessage('File does not exist. Please create the file before running the tool box to avoid errors. If the file exists, please enter file name without the .mat extension to avoid this warning. Data has been added.');
    end

    set(handles.dataList,'String',handles.config.dataList);

    set(handles.addDataMessage, 'String', 'Added!');
    pause(1);
    set(handles.addDataMessage, 'String', '');

    guidata(hObject, handles);

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

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

    set(handles.deleteDataMessage, 'String', '');
    set(handles.deleteAlgorithmMessage, 'String', '');

    [r c] = size(handles.config.dataList);
    if r > 1
        % Delete the selected data set from config
        dataId = get(handles.dataList, 'Value');
        toBeDeleted = handles.config.dataList(dataId);
        handles.config.dataList(dataId) = [];
        handles.config.dataName(dataId) = [];
        handles.config.dataFrequency(dataId) = [];

        % Update data list
        if dataId == r
            set(handles.dataList, 'value', r-1);
        end
        set(handles.dataList,'String',handles.config.dataList);
        guidata(hObject, handles);

        % print an updated message for 1 second that something got deleted
        set(handles.deleteDataMessage, 'String', 'Deleted!');
        message = ['Deleted the following data set:' ' ' toBeDeleted];
        deletedMessage(message);

    else
        set(handles.deleteDataMessage, 'String', 'Cannot delete all the data from config');
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

% --- Executes during object creation, after setting all properties.
function d6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to d6 (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 algorithmList.
function algorithmList_Callback(hObject, eventdata, handles)
% hObject    handle to algorithmList (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 algorithmList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from algorithmList
    set(handles.deleteDataMessage, 'String', '');
    set(handles.deleteAlgorithmMessage, 'String', '');

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

    set(handles.deleteDataMessage, 'String', '');
    set(handles.deleteAlgorithmMessage, 'String', '');

    [r c] = size(handles.config.algorithmList);
    if r > 1

        % Delete the selected algorithm from config
        algorithmId = get(handles.algorithmList, 'Value');
        toBeDeleted = handles.config.algorithmList(algorithmId);
        handles.config.algorithmList(algorithmId) = [];
        handles.config.algorithmName(algorithmId) = [];
        handles.config.algorithmParameters(algorithmId,:) = [];
        handles.config.defaultParameters(algorithmId,:) = [];

        % Update data list
        if algorithmId == r
            set(handles.algorithmList, 'value', r-1);
        end
        set(handles.algorithmList,'String',handles.config.algorithmList);
        guidata(hObject, handles);

        % print an updated message for 1 second that something got deleted
        set(handles.deleteAlgorithmMessage, 'String', 'Deleted!');
        message = ['Deleted the following algorithm:' ' ' toBeDeleted];
        deletedMessage(message);
        guidata(hObject, handles);
    else
        set(handles.deleteAlgorithmMessage, 'String', 'Cannot delete all algorithms from config');
    end

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

    [r c] = size(handles.config.algorithmList);
    fileName = get(handles.algorithmFileName, 'string');

    % Check if file exists, else return
    fullPath = strcat('..\Strategy\',fileName, '.m');
    if ~(exist(fullPath) == 2)
        errorMessage('File does not exist. Please create the file before running the tool box to avoid errors. If the file exists, please enter file name without the .m extension to avoid this warning. Algortihm has been added.');
    end

    handles.config.algorithmList(r+1,c) = {get(handles.algorithmName, 'string')};
    handles.config.algorithmName(r+1,c) = {fileName};

    % Construct input vectors before adding them to config
    newParameters = {};
    newDefault = {};

    temp = get(handles.p1,'string');
    if strcmp(temp ,'-') == 0
        newParameters{1} = (temp);
        newDefault{1} = str2double(get(handles.d1,'string'));
    else
        newParameters{1} = [];
        newDefault{1} = [];
    end
    temp = get(handles.p2,'string');
    if strcmp(temp ,'-') == 0
        newParameters{2} = (temp);
        newDefault{2} = str2double(get(handles.d1,'string'));
    else
        newParameters{2} = [];
        newDefault{2} = [];
    end
    temp = get(handles.p3,'string');
    if strcmp(temp ,'-') == 0
        newParameters{3} = (temp);
        newDefault{3} = str2double(get(handles.d1,'string'));
    else
        newParameters{3} = [];
        newDefault{3} = [];
    end
    temp = get(handles.p4,'string');
    if strcmp(temp ,'-') == 0
        newParameters{4} = (temp);
        newDefault{4} = str2double(get(handles.d1,'string'));
    else
        newParameters{4} = [];
        newDefault{4} = [];
    end
    temp = get(handles.p5,'string');
    if strcmp(temp ,'-') == 0
        newParameters{5} = (temp);
        newDefault{5} = str2double(get(handles.d1,'string'));
    else
        newParameters{5} = [];
        newDefault{5} = [];
    end
    temp = get(handles.p6,'string');
    if strcmp(temp ,'-') == 0
        newParameters{6} = (temp);
        newDefault{6} = str2double(get(handles.d1,'string'));
    else
        newParameters{6} = [];
        newDefault{6} = [];
    end

    % Update the parameters in config
    if length(newParameters) > 0
        handles.config.algorithmParameters(r+1,:) = newParameters;
        handles.config.defaultParameters(r+1,:) = newDefault;
    else
        handles.config.algorithmParameters(r+1,:) = {[]};
        handles.config.algorithmParameters(r+1,:) = {[]};
    end

    set(handles.algorithmList,'String',handles.config.algorithmList);

    set(handles.addAlgorithmMessage, 'String', 'Added!');
    pause(1);
    set(handles.addAlgorithmMessage, 'String', '');

    guidata(hObject, handles);

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

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

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

    % Save the new preferences to config
    try

        chosenFileName = (get(handles.configFileName,'string'));
        if strcmp (chosenFileName, 'config')
            errorMessage('File cannot be named "config"! "config" saves the active preferences.');
            return;
        end

        n = handles.config;
        algorithmList = n.algorithmList;
        algorithmName = n.algorithmName;
        algorithmParameters = n.algorithmParameters;
        dataFrequency = n.dataFrequency;
        dataList = n.dataList;
        dataName = n.dataName;
        defaultParameters = n.defaultParameters;

        filePath = strcat('config/',chosenFileName);

        if ~(exist(strcat(filePath,'.mat')) == 2)

            save(filePath, 'algorithmList','algorithmName', 'algorithmParameters', 'dataFrequency','dataList','dataName','defaultParameters');

            % If the user wants to make this the active configuration
            if get(handles.activeConfigCheck, 'Value')
                filePath = strcat('config/','config');
                save(filePath, 'algorithmList','algorithmName', 'algorithmParameters', 'dataFrequency','dataList','dataName','defaultParameters');
            end

            %display saved message
            set(handles.configSave, 'String', 'Saved this configuration!');

        else
            errorMessage('This configuration file name already exists!');
            return;
        end
    catch exception
        errorMessage('Error in naming config file! Please enter a valid file name.');
    end

author: OLPS

repo: OLPS

save_path: github-repos/MATLAB/OLPS-OLPS


text:
function score =dmapMetricRel(dmap1,gtdmap,mask)

    dmap1(isinf(dmap1)) = nan;
    gtdmap(isinf(gtdmap)) = nan;
    mask = logical(mask);
    x = dmap1(mask);
    y = gtdmap(mask);
    nanMask = ~isnan(y); % Keep points present in gt depth
    x = x(nanMask); y = y(nanMask);
    x(isnan(x)) = median(x(~isnan(x)));
    b = median(x-y);
    score = abs(x-y-b)./y;
    score = mean(score);
end

repo: CategoryShapes


text:
function shadedTimeSeries(X, Ydata, indicator, Xlabel, Ylabels, colour, Yspacing)
% SHADEDTIMESERIES(X, Ydata, indicator, Xlabel, Ylabels, colour, Yspacing)
%
% Plot time series one above the other with coloured strips highlighting
% interesting features.
%
% All data is in columns.
%
% X is the time vector.
% Each column of Ydata will be plotted in a separate subplot, one beneath
% the other.
% Indicator is a logical array where the ones indicate the areas of
% interest that will be shaded.
% Xlabel is a string for labeling the bottom horizontal axis.
% Ylabels is a cell array of strings used for labeling the Y axes.
% Colour is an RGB colour array that will be used for shading.
% Yspacing is the percentage of vertical padding to leave above and below
% each plot so that they don't touch the top and bottom of their respective
% plots.
%
% If Ydata has only one column then the function will draw in the current
% plot or subplot; this is useful if you want to organise your own plots
% and subplots but still use the shading feature. If Ydata has more than
% one column then the function will create a new figure with a subplot for
% each column of Ydata.
%
% Example 1 - same indicator for all subplots:
%           time = [1:50]';
%           acceleration = rand(50,1);
%           velocity = cumtrapz(acceleration, time);
%           position = cumtrapz(velocity, time);
%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5)]';
%           shadedTimeSeries(time, [acceleration velocity position], indicator, 'Time', {'Acceleration' 'Velocity' 'Position'}, [0 0.8 0.3], 10);
%
%
% Example 2 - different indicators for each subplot:
%           time = [1:50]';
%           acceleration = rand(50,1);
%           velocity = cumtrapz(acceleration, time);
%           position = cumtrapz(velocity, time);
%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5); ones(1,3) zeros(1,10) ones(1,30) zeros(1,7); zeros(1,20) ones(1,20) zeros(1,10)]';
%           shadedTimeSeries(time, [acceleration velocity position], indicator, 'Time', {'Acceleration' 'Velocity' 'Position'}, [0 0.8 0.3], 10);
%
%
%
% Example 3 - single plot at a time for full control:
%           time = [1:50]';
%           acceleration = rand(50,1);
%           velocity = cumtrapz(acceleration, time);
%           position = cumtrapz(velocity, time);
%           indicator = [zeros(1,10) ones(1,10) zeros(1,25) ones(1,5)]';
%           figure;
%           subplot(3,1,1);
%           shadedTimeSeries(time, acceleration, indicator, 'Time', {'Acceleration'}, [1 .7 1], 10);
%           hold on
%           text(10,1,'Custom text.');
%           subplot(3,1,2);
%           shadedTimeSeries(time, velocity, indicator, 'Time', {'Velocity'}, [1 .7 1], 10);
%           xlabel('');
%           subplot(3,1,3);
%           shadedTimeSeries(time, position, indicator, 'Time', {'Position'}, [1 .7 1], 10);
%           grid on;
%
% Carl Fischer. March 2011.
% http://eis.comp.lancs.ac.uk/~carl/blog/

if nargin < 3
    error('Please provide at least X, Ydata and indicator parameters.');
end
% Check consistency of compulsory parameters first.
if length(X) ~= size(Ydata,1)
    if length(X) == size(Ydata,2)
        Ydata = Ydata';
    else
        error('X and Ydata must have the same length.');
    end
end
if length(X) ~= size(indicator,1)
    if length(X) == size(indicator,2)
        indicator = indicator';
    else
        error('X and indicator must have the same length.');
    end
end
if nargin < 4
    Xlabel = '';
end
if nargin < 5
    Ylabels = cell(1,size(Ydata,2));
end
if nargin < 6 || isempty(colour)
    colour = [0 .7 .7];
end
if nargin < 7 || isempty(Yspacing)
    Yspacing = 5;
end

if length(Ylabels) ~= size(Ydata,2)
    error('The number of Ylabels should match the number of data traces in Ydata.');
end
if size(indicator,2) > 1 && size(indicator,2) ~= size(Ydata,2)
    error('If there is more than one column in indicator, their number must match the number of columns in Ydata.');
end

for column_idx = 1:size(indicator,2)
    start_marks{column_idx} = find(diff(indicator(:,column_idx)) > 0);
    end_marks{column_idx} = find(diff(indicator(:,column_idx)) < 0);
    if start_marks{column_idx}(1) > end_marks{column_idx}(1) % plot is shaded from start
        start_marks{column_idx} = [1; start_marks{column_idx}];
    end
    if start_marks{column_idx}(end) > end_marks{column_idx}(end) % plot is shaded until end
        end_marks{column_idx} = [end_marks{column_idx}; length(X)];
    end
end
if size(Ydata,2) > 1
    figure;
end
for i = 1:size(Ydata,2)
    if size(indicator,2) == 1
        plot_partial(X, Ydata(:,i), start_marks{1}, end_marks{1}, i, Ylabels{i}, size(Ydata,2));
    else
        plot_partial(X, Ydata(:,i), start_marks{i}, end_marks{i}, i, Ylabels{i}, size(Ydata,2));
    end
    if i ~= size(Ydata,2)
        set(gca,'xticklabel',[]) % remove x label for all except bottom plot
    end
end
xlabel(Xlabel);

    function plot_partial(x, ydata, start_marks, end_marks, number, name, total)
        if size(Ydata,2) > 1
            subplot(total,1,number);
        end
        hold on;
        ylabel(name);
        xlim([x(1) x(end)]);% force plot to go from edge to edge
        padding = Yspacing/100*(max(ydata)-min(ydata));% spacing at top and bottom of plotted line
        ylim([min(ydata)-padding max(ydata)+padding]); % default leaves too much space around graph

        for j = 1:min(length(start_marks), length(end_marks)) % create all the shaded areas
            % This patch line was ripped from ShadePlotForEmphasis.m by
            % Michael Robbins on Matlab Central.
            patch([repmat( x(start_marks(j)),1,2) repmat( x(end_marks(j)),1,2)], ...
                [get(gca,'YLim') fliplr(get(gca,'YLim'))], ...
                [0 0 0 0],colour,'EdgeColor', 'none');
        end
        plot(x, ydata, 'LineWidth', 3); % plot data line on top of colour patch
        set(gca, 'layer', 'top'); % put ticks back on top of colour patch
        hold off;
    end
end

author: Sable

repo: mcbench-benchmarks


text:
function equalizedData = dfe_frac(data, trainingSymbols, nFTaps, nBTaps, SamplesPerSymbol, Constellation, channelDelay)

inputBuffer = zeros(nFTaps,1);
decisionBuffer = zeros(nBTaps,1);

forwardTaps = [1; zeros(nFTaps-1,1)];
backwardTaps = [zeros(nBTaps,1)];

numTrainingSymbols = length(trainingSymbols);

ind = 0;
equalizedData = complex(zeros(length(data),1));
mu = 0.001;

for s=1:SamplesPerSymbol:length(data)
    ind = ind + 1;

    % Add data to buffer
    inputBuffer = [data(s:s+SamplesPerSymbol-1); inputBuffer(1:end-SamplesPerSymbol)];

    % Fill equalizer
    if s<=channelDelay
        continue
    end

    % Apply equalizer
    eqOut = forwardTaps'*inputBuffer - backwardTaps'*decisionBuffer;

    % Make decision
    [~,i] = min(abs(Constellation - eqOut));
    d = Constellation(i);

    % Determine error
    if s<=numTrainingSymbols
        e = trainingSymbols(ind-channelDelay/SamplesPerSymbol) - eqOut;
    else
        e = d - eqOut;
    end
    e = conj(e);

    % Update taps
    forwardTaps  = forwardTaps  + mu*e*inputBuffer;
    %backwardTaps = backwardTaps - mu*e*decisionBuffer;

    % Update decision buffer
    decisionBuffer = [d; decisionBuffer(1:end-1)];

    % Output
    equalizedData(ind) = eqOut;
end
%s = channelDelay/SamplesPerSymbol+1;
%[equalizedData(s:s+100-1), trainingSymbols(1:100), data(s:s+100-1)]

end

author: analogdevicesinc


text:
function marker = extractScatterhistogramMarker(patch_data, t)

% EXTRACTS THE MARKER STYLE USED FOR MATLAB OBJECTS
% OF TYPE "PATCH". THESE OBJECTS ARE USED IN AREASERIES
% BARSERIES, CONTOURGROUP, SCATTERGROUP.

%-------------------------------------------------------------------------%

%-AXIS STRUCTURE-%
axis_data = get(ancestor(patch_data.Parent,'axes'));

%-FIGURE STRUCTURE-%
figure_data = get(ancestor(patch_data.Parent,'figure'));

%-INITIALIZE OUTPUT-%
marker = struct();

%-------------------------------------------------------------------------%

%-MARKER SIZE (STYLE)-%
marker.size = patch_data.MarkerSize(t)*0.20;

%-------------------------------------------------------------------------%

%-MARKER SYMBOL (STYLE)-%
if ~strcmp(patch_data.MarkerStyle(t),'none')

    switch patch_data.MarkerStyle(t)
        case '.'
            marksymbol = 'circle';
        case 'o'
            marksymbol = 'circle';
        case 'x'
            marksymbol = 'x-thin-open';
        case '+'
            marksymbol = 'cross-thin-open';
        case '*'
            marksymbol = 'asterisk-open';
        case {'s','square'}
            marksymbol = 'square';
        case {'d','diamond'}
            marksymbol = 'diamond';
        case 'v'
            marksymbol = 'triangle-down';
        case '^'
            marksymbol = 'triangle-up';
        case '<'
            marksymbol = 'triangle-left';
        case '>'
            marksymbol = 'triangle-right';
        case {'p','pentagram'}
            marksymbol = 'star';
        case {'h','hexagram'}
            marksymbol = 'hexagram';
    end

    marker.symbol = marksymbol;
end

%-------------------------------------------------------------------------%

%-MARKER LINE WIDTH (STYLE)-%
marker.line.width = patch_data.LineWidth(t);

%-------------------------------------------------------------------------%

%--MARKER COLOR--%

%-figure colormap-%
colormap = figure_data.Colormap;

% marker face color
MarkerColor = patch_data.Color(t, :);

filledMarkerSet = {'o','square','s','diamond','d',...
    'v','^', '<','>','hexagram','pentagram'};

filledMarker = ismember(patch_data.MarkerStyle(t), filledMarkerSet);

if filledMarker && strcmp(patch_data.MarkerFilled, 'on')

    if isnumeric(MarkerColor)
        markercolor = sprintf('rgb(%f,%f,%f)', 255*MarkerColor);
    else

        switch MarkerColor

            case 'none'

                markercolor = 'rgba(0,0,0,0)';

            case 'auto'

                if ~strcmp(axis_data.Color,'none')
                    col = 255*axis_data.Color;
                else
                    col = 255*figure_data.Color;
                end

                markercolor  = ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')'];

            case 'flat'

                for n = 1:length(patch_data.CData)

                    capCD = max(min(patch_data.CData(n),axis_data.CLim(2)),axis_data.CLim(1));
                    scalefactor = (capCD - axis_data.CLim(1))/diff(axis_data.CLim);
                    col =  255*(colormap(1 + floor(scalefactor*(length(colormap)-1)),:));

                    markercolor{n} = ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')'];

                end
        end
    end

    marker.color = markercolor;

end

if filledMarker
    marker.line.color = markercolor;
end

%-------------------------------------------------------------------------%

end

author: plotly


text:
function varargout = input_medit(V,F,C)
  % INPUT_MEDIT  Display input mesh using medit, highlighting boundary
  % edges and non-manifold edges
  %
  % C = input_medit(V,F,C)
  %
  % Inputs:
  %   V  #V by 3 list of mesh positions
  %   F  #F by 3 list of triangle indices
  %   Optional:
  %     C  #C connected component IDs
  %

  % Gather boundary and non-manifold edges
  NME = nonmanifold_edges(F);
  BE = outline(F);
  BE = setdiff(BE,NME,'rows');
  E = [NME 1+0*NME(:,1); ...
        BE 2+0*BE(:,1);];
  if ~exist('C') || isempty(C)
    C = randcycle(connected_components(F));
    C = C(:);
    % hack so that not all equal (medit doesn't like that)
    if all(C==C(1))
      C(ceil(rand*size(C,1))) = C(1)+1;
    end
  end
  if size(C,1)<size(V,1)
      C(size(V,1)) = 0;
      C(C==0) = max(C(:))+1;
  end
  % Gather self-intersecting faces
  ND = doublearea(V,F)>0;
  [~,~,IF] = selfintersect(V,F(ND,:),'DetectOnly',true);
  bad = false(size(F,1),1);
  bad(ND) = full(0<sparse(IF(:),1,1,sum(ND),1));
  F = [F bad];
  medit(V,[],F,'Data',C,'Edges',E,'Wait',false);
  if nargout>0
    varargout{1} = C;
  end
end

author: alecjacobson

repo: gptoolbox


text:
function order = r8poly_order ( na, a )

%*****************************************************************************80
%
%% R8POLY_ORDER returns the order of a polynomial in power sum form.
%
%  Discussion:
%
%    The order of a constant polynomial is 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NA, the number of coefficients.
%
%    Input, real A(1:NA), the coefficients of the polynomials.
%
%    Output, integer ORDER, the order of the polynomial.
%
  order = na;

  while ( 1 < order )

    if ( a(order) ~= 0.0 )
      return
    end

    order = order - 1;

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function fx = ln_cordic ( x, n )

%*****************************************************************************80
%
%% LN_CORDIC evaluates the natural logarithm function using the CORDIC method.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 June 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Frederick Ruckdeschel,
%    BASIC Scientific Subroutines,
%    Volume II,
%    McGraw-Hill, 1980,
%    ISBN: 0-07-054202-3,
%    LC: QA76.95.R82.
%
%  Parameters:
%
%    Input, real X, the argument.
%
%    Input, integer N, the number of steps to take.
%
%    Output, real FX, the logarithm of X.
%
%  Local Parameters:
%
%    Local, real A(1:25) = exp ( (1/2)^(1:25) );
%
  a_length = 25;

  a = [ ...
    1.648721270700128, ...
    1.284025416687742, ...
    1.133148453066826, ...
    1.064494458917859, ...
    1.031743407499103, ...
    1.015747708586686, ...
    1.007843097206488, ...
    1.003913889338348, ...
    1.001955033591003, ...
    1.000977039492417, ...
    1.000488400478694, ...
    1.000244170429748, ...
    1.000122077763384, ...
    1.000061037018933, ...
    1.000030518043791, ...
    1.0000152589054785, ...
    1.0000076294236351, ...
    1.0000038147045416, ...
    1.0000019073504518, ...
    1.0000009536747712, ...
    1.0000004768372719, ...
    1.0000002384186075, ...
    1.0000001192092967, ...
    1.0000000596046466, ...
    1.0000000298023228 ];
  e = 2.718281828459045;

  if ( x <= 0.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'LN_CORDIC - Fatal error!\n' );
    fprintf ( 1, '  Input argument X <= 0.0\n' );
    error ( 'LN_CORDIC - Fatal error!' );
  end

  k = 0;

  while ( e <= x )
    k = k + 1;
    x = x / e;
  end

  while ( x < 1.0 )
    k = k - 1;
    x = x * e;
  end
%
%  Determine the weights.
%
  for i = 1 : n

    w(i) = 0.0;

    if ( i <= a_length )
      ai = a(i);
    else
      ai = 1.0 + ( ai - 1.0 ) / 2.0;
    end

    if ( ai < x )
      w(i) = 1.0;
      x = x / ai;
    end

  end

  x = x - 1.0;
  x = x ...
    * ( 1.0 - ( x / 2.0 ) ...
    * ( 1.0 + ( x / 3.0 ) ...
    * ( 1.0 -   x / 4.0 )));
%
%  Assemble.
%
  poweroftwo = 0.5;
  for i = 1 : n
    x = x + w(i) * poweroftwo;
    poweroftwo = poweroftwo / 2.0;
  end

  fx = k + x;

  return
end


text:
function vec_out = struct2array(struct_in)
% SYNTAX:
%   [vec_out] = struct2array(struct_in);
%
% INPUT:
%   struct_in = structure with fields of the same type
%
% OUTPUT:
%   vec_out = vectorized content of the struct
%
% DESCRIPTION:
%   Convert to a vector the fields of the structure in input
%   Note: It works only when the fields are of the same type

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

tmp = struct2cell(struct_in);
vec_out = [tmp{:}];

author: goGPS-Project


text:
classdef TREE3 < PROBLEM
% <multi> <real> <large/none> <constrained> <expensive/none>
% The time-varying ratio error estimation problem
% T --- 1000 --- Length of data (related to the number of variables)

%------------------------------- Reference --------------------------------
% C. He, R. Cheng, C. Zhang, Y. Tian, Q. Chen, and X. Yao, Evolutionary
% large-scale multiobjective optimization for ratio error estimation of
% voltage transformers, IEEE Transactions on Evolutionary Computation,
% 2020, 24(5): 868-881.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    properties(Access = private)
        Data;   % Dataset
        Mean;   % Mean values of the dataset
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            % Load data
            T = obj.ParameterSet(1000);
            CallStack = dbstack('-completenames');
            load(fullfile(fileparts(CallStack(1).file),'Dataset_TREE.mat'),'Dataset');
            obj.Data = Dataset.TREE3(1:min(max(T,10),end),:);
            % Set the numbers of objectives and decision variables
            K = 6;
            obj.M = 2;
            obj.D = T*K;
            % Set the upper and lower boundaries
            Lower    = zeros(T,K);
            Upper    = zeros(T,K);
            obj.Mean = zeros(T,K);
            for i = 1 : 3
                Lower(:,i)      = min(obj.Data(:,i:3:end*0.5),[],2)/1.01;
                Upper(:,i)      = max(obj.Data(:,i:3:end*0.5),[],2)/0.99;
                Lower(:,i+3)    = min(obj.Data(:,end*0.5+i:3:end),[],2)/1.01;
                Upper(:,i+3)    = max(obj.Data(:,end*0.5+i:3:end),[],2)/0.99;
                obj.Mean(:,i)   = mean(obj.Data(:,i:3:end*0.5),2);
                obj.Mean(:,i+3) = mean(obj.Data(:,end*0.5+i:3:end),2);
            end
            % The decision variables are the offset of the mean values of
            % the dataset
            obj.lower    = reshape(Lower-obj.Mean,1,[]);
            obj.upper    = reshape(Upper-obj.Mean,1,[]);
            obj.encoding = ones(1,obj.D);
        end
        %% Generate initial solutions
        function Population = Initialization(obj,N)
            if nargin < 2; N = obj.N; end
            PopDec = obj.Mean(:)'.*(rand(N,obj.D)*0.008-0.004);
            PopDec = min(max(PopDec,repmat(obj.lower,N,1)),repmat(obj.upper,N,1));
            Population = obj.Evaluation(PopDec);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            N      = size(PopDec,1);
            KP     = size(obj.Data,2);
            [T,K]  = size(obj.Mean);
            PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);
            PopObj = zeros(N,obj.M);
            % First objective
            eA1 = abs(repmat(reshape(obj.Data(:,1:end*0.5),1,T,KP/2),N,1,1)./repmat(PopDec(:,:,1:3),1,1,KP/6)-1);
            eA2 = abs(repmat(reshape(obj.Data(:,end*0.5+1:end),1,T,KP/2),N,1,1)./repmat(PopDec(:,:,4:6),1,1,KP/6)-1);
            eA  = cat(3,eA1,eA2);
            PopObj(:,1) = sum(sum(eA,3),2);
            % Second objective
            Delta = std(eA(:,2:end,:)-eA(:,1:end-1,:),0,2);
            PopObj(:,2) = sum(reshape(Delta,N,[]),2);
        end
        %% Calculate constraint violations
        function PopCon = CalCon(obj,PopDec)
            N      = size(PopDec,1);
            [T,K]  = size(obj.Mean);
            PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);
            PopCon = TREE_CalCon(PopDec,2);
        end
        %% Generate a point for hypervolume calculation
        function R = GetOptimum(obj,~)
            X = zeros(1,obj.D);
            X(1:2:end) = obj.lower(1:2:end);
            X(2:2:end) = obj.upper(2:2:end);
            R = obj.CalObj(X);
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
 function xs = wls_pscd(x, G, yi, dqi, wi, dj, niter)
% Runs one iteration of coordinate descent in the style suitable
% for the inner part of paraboloidal surrogates coordinate descent updates
% cost function: J(x) = ?
% Output
%	x [np,1]	updated image
%
% This is for TESTING ONLY.
% IT IS NOT USEFUL because it is unregularized and slow
%
% Copyright Aug 2000, Jeff Fessler, The University of Michigan

NOT DONE!

if nargin < 3, ir_usage, end

if ~isvar('wi') || isempty(wi)
	wi = ones(size(yi));
end
if ~isvar('niter') || isempty(niter)
	niter = 1;
end

% backproject curvatures for denominator
if ~isvar('dj') || isempty(dj)
	dj = wi(:)' * G.^2;
end

%
% now we are minimizing the quadratic function:
% J(x) = \sum_k q_i([Gx]_i)
%	where q_i(l) = doth' (l-l0) - 1/2 (l-l0)' D(n) (l-l0)
% ?
% d/dli P(l;l0) = dothi - ni (li-l0i)
% Q(x) == doth' G (x-x0) - 1/2 (x-x0)' G' D(n) G (x-x0)
% ??? d/dx_j Q(x) = \sumi \gij \dothi - \sumi \gij \ni [G(x-x0)]_i
% d/dx_j Q(x) = \sumi \gij [d/dli P(l;l0)]
% -d^2/dx_j^2 Q(x) = \sumi \gij^2 \ni
%
dqi = doth(:);	% initial surrogate derivatives

xs = zeros(length(x), nsubiter);
xs(:,1) = x;

%
% loop over subiterations of paraboloid
%
for it=1:niter

	%
	% loop over pixels
	%
	for jj=1:numel(x)
		g = G(:,jj);
		x0j = x(jj);
		x(jj) = x0j + (dqi' * g) / dj(jj);
		x(jj) = max(x(jj),0);
		dqi = dqi - wi .* (g * (x(jj) - x0j));

	end
	xs(:,it) = x;
end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
vidObj = VideoReader('f9-29_ne_twr.mov');
save vidfile.mat vidObj
%%
% Specify that reading should start at 0.5 seconds from the
% beginning.
%vidObj.CurrentTime = 0.5;

% Create an axes
currAxes = axes;
figure
fnum = 1;
while hasFrame(vidObj)
    vidFrame = readFrame(vidObj);
    %image(vidFrame, 'Parent', currAxes);
    fnum
    imagesc(vidFrame)
    %stop
    %currAxes.Visible = 'off';
    pause(2.0/vidObj.FrameRate);
    fnum=fnum+1;
end

author: geoscience-community-codes

repo: GISMO


text:
function q=qrdivide(q1,q2)
%QRDIVIDE divdes two real quaternions q=[q1,q2]
%
% Inputs:
%
%     q1(4,1), q2(4,1)  Two real quaternions in the form [r, i, j, k]' where i^2=j^2=k^2=ijk=-1
%
% Outputs:
%
%     q(4,1)   Quotient of q1/q2 such that q1=q*q2.
%              Note that q*q2 ~= q2*q since quaternion multiplication does not commute.

%      Copyright (C) Mike Brookes 2000-2008
%      Version: $Id: qrdivide.m,v 1.1 2008/12/03 10:07:53 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent a b c d
if isempty(a)
    a=[5 8 9 10 15 13];
    b=[6 7 11 12 14 16];
    c=[1 2 3 4 6 7 11 12 16 14];
    d=[1 2 3 4 5 8 9 10 13 15];
end
if nargin<2
    %    just take the inverse of the only input argument
    q=q1/(q1'*q1);
    q(2:4)=-q(2:4);
else
    %    invert q2 and do a multiply
    q=q2/(q2'*q2);
    q(2:4)=-q(2:4);
    t=q1*q.';
    s=zeros(4,4);
    s(a)=-t(b);
    s(c)=t(d);
    q=sum(s,2);
end

author: decouples


text:
function [IM doseV_SUM indV sampleParticles] = generateDPMdose_aavc (IM, Energy, nhist, OutputError, planC, indBeam, w_field, saveIM, sourceModel, fillWater, useWedge, Softening, UseFlatFilter, K)
%"generateMCInfluence"
%   Given an IM structure, begin/continue calculating montecarlo influence
%   data.
%
%   Based on code by P. Lindsay.
%
%JRA, 26 Aug 04
%
%------------- test file by APA, VC

% JC Feb 27 06
% JC Jun 06 06
% Use stream of the doseV, do not put every dose inside IM struct.
% Use sum(10*clock) as the random seeds in DPMInfluenceJing.m

%
%Usage:
%   function IM = generateMCInfluence(IM, Energy);
%JC, July 28, 2005
%Put the photon spectrum into the DPMIN struct
%IM := IM structure
%Energy := the name of the energy specturm file.
%nhist := the number of history per cm^2
%The first two lines are just information.

%JC Nov 16, 2006, Use the most up-to-date DPM.
% Add more input to DPMIN.

%JC Nov 27, 2006,
% DPMIN.Prefix = 'pre4phot' for photon.
% Correct the distance from target/source to the jaw is 40cm, not 50cm;
% So scale the DPMIN.ClmCorner[1-3].

%JC Jan 04 2006
% According to Virgil's suggestions, use 1.15 as cutoff between Water and
% Bone, instead of 0.5*(Bone+Water) == 1.425

%JC Jan 30 2007
% Turn on FF calc.

% LM: JC Mar 26, 2007
% Add more variables in DPMIN: DoseNormFlag, HornCoef, OpenField.

% LM: JC Aug 06 2007
% Add "Softening" flag in DPMIN, default == 1
% Remove scaling of the dose by "sum(spectrum(:2))" for SourceModel == 0;
% thus no scaling of the dose.

% LM: JC Feb 29 08
% Add one more input, "K". To change the dose from per particle to Gy/MU.

%load DPM_10beams
% global planC
% global stateS
indexS=planC{end};
numBeams = length(IM.beams);

%Create all path parameters.
%JC Feb 10, 06 Turn "getCERRPath" off, in order to run stand-along, without
%CERR.

%DPMPath         = fullfile(getCERRPath, 'planCheck', 'MC', '');
%runsPath        = fullfile(DPMPath, 'runs', '')
%energyPath      = fullfile('.', 'spectrum', '');

% Added to get the bounding box of  the skin structure
% In order to reduce size of the interested CTscan

% In "DPM_test.mat", skin is number 9 structure.
% In planCheck, skin is number 1 structure.
%! skin structure is the last one, #21 in planC(4)
j = find(strcmpi({planC{indexS.structures}.structureName}, 'Skin'));

if isempty(j)
    j = find(strcmpi({planC{indexS.structures}.structureName}, 'Body'));
end

if isempty(j)
    j = find(strcmpi({planC{indexS.structures}.structureName}, 'External'));
end

if isempty(j)
    error('Skin/Body/External structure must be defined to input to DPM.');
else
    j = j(1);
end

for i=1:length(IM.goals)
    structROIV(i) = find(strcmpi(IM.goals(i).strUID,...
        {planC{indexS.structures}.strUID}));
    sampleRateV(i) = IM.goals(i).xySampleRate;
end
[sampleRateV,indSort] = sort(sampleRateV);
structROIV = structROIV(indSort);
% Precalc voxel indices for all structures
scanIndV=cell(max(structROIV),1);
for i = 1 : length(structROIV)
    if sampleRateV(i) ~= 1
        %Ensures that interpolative downsampling won't miss edge points:
        maskSingle3D = getSurfaceExpand(structROIV(i),0.5,1);
        if rem(log2(sampleRateV(i)),1) ~= 0
            error('Sample factor must (currently) be a power of 2.')
        end
        maskSample3D = getDown3Mask(maskSingle3D, sampleRateV(i), 1);
        %Get a mask of where to sample points
        tmpM = logical(maskSample3D) & maskSingle3D;
        clear maskSample3D maskSingle3D;
    else
        tmpM = getUniformStr(structROIV(i));
    end
    scanIndV{i} = find(tmpM);  %Indices with respect to the uniformized scan.
    clear tmpM
end

skinMask=getUniformStr(j,planC);

bbox=boundingBox(skinMask);
% bbox =     61   183    17   240     1    90
% They're yini, yfin, xini, xfin, zini, zfin

scandr = bbox(2) - bbox(1) + 1;
scandc = bbox(4) - bbox(3) + 1;
scands = bbox(6) - bbox(5) + 1;

% Get the Uniformized CT dataset.
scanNum = 1;
scan = getUniformizedCTScan(0, scanNum);

if fillWater   % Assign everything of skinMask to water
    scan = 1000*ones(size(scan));
end

scan(~skinMask) = 0;
inSkinDensity = scan(skinMask);
inSkinDensity(inSkinDensity < 1) = 1;
scan(skinMask) = inSkinDensity;

% xV = the x in the middle of the voxel, in the x direction.
% x1, x2, ..., xmax.
%[xV, yV, zV] = getUniformizedXYZVals(planC);
[xV, yV, zV] = getUniformizedXYZVals_plnChk(planC);
% Get x,y,z resolution: dx, dy, dz
xres = abs(xV(2) - xV(1));
yres = abs(yV(2) - yV(1));
zres = abs(zV(2) - zV(1));
indV = 1:(scandr*scandc*scands);
[c,r,s] = ind2sub([scandc,scandr,scands], indV);
r = r + bbox(1) - 1;
c = c + bbox(3) - 1;
s = s + bbox(5) - 1;
indV = sub2ind(getUniformizedSize(planC), r, c, s);

% Set options from IM.params.DPM
% Need to porpulate all the field of DPMIN struct.
%

% scan = planC{indexS.scan}.scanArray;
size_scan = size(scan)
% Assign the values to CTscan, which is the input structure for dpm.

% Probably need to make CTscan sturc a part of IM structure.
% unless it's only used locally, in this function.
% However, the solution/output of dpm has to be accessable for other
% functions/files.
CTscan.Num_y_vox = size_scan(1);
CTscan.Num_x_vox = size_scan(2);
CTscan.Num_z_vox = size_scan(3);

CTscan.dxvox = xres;
CTscan.dyvox = yres;
CTscan.dzvox = zres;

% Change the 3D array to a vector, used as DPM input

scan = double(scan)/1000;
CTscan.density = zeros(size_scan(1)*size_scan(2)*size_scan(3), 1);
CTscan.material = CTscan.density;
%CTscan.material (CTscan.material == 0) = -1;

% Need to convert the array to a vector, need to know the order of changing
% x, y, and z. which is first?
% rwo: x; col: y; slice: z

% scan1 is the changed order of the original scan (z y x)
%
scan1 = permute(scan, [3 1 2]);
CTscan.density = scan1(:);
clear scan1 scan r c s

% The following part comes from genvoxel.in
% Which specify the number & order of the material in CT scan.

% %Number of materials:
% % 5
% %Material densities (g/cm^3), in the order corresponding to PENELOPE .geo file:
% % 1.00        Water
% % 0.3         LungICRP
% % 1.85        CorticalBone
% % 2.6989      Al
% % 4.54        Ti

% % % % According to the density value, get the material number.
% % % Lung = 0.3                          % #2
% % % Water = 1.0                         % #1
% % % Bone = 1.85                         % #3
% % % Al = 2.6989                         % #4
% % % Ti = 4.54                           % #5
% % %
% % % CTscan.material(CTscan.density < 0.5*(Lung+Water)) = 2;
% % % % According to Virgil's suggestions, use 1.15 as cutoff between Water and
% % % % Bone, instead of 0.5*(Bone+Water) == 1.425
% % % %CTscan.material(0.5*(Lung+Water) <= CTscan.density  & CTscan.density < 0.5*(Water+Bone)) = 1;
% % % %CTscan.material(0.5*(Water+Bone) <= CTscan.density & CTscan.density < 0.5*(Bone+Al)) = 3;
% % % CTscan.material(0.5*(Lung+Water) <= CTscan.density  & CTscan.density < 1.15) = 1;
% % % CTscan.material(1.15 <= CTscan.density & CTscan.density < 0.5*(Bone+Al)) = 3;
% % % CTscan.material(0.5*(Bone+Al) <= CTscan.density & CTscan.density < 0.5*(Al+Ti)) = 4;
% % % CTscan.material(0.5*(Al+Ti)<= CTscan.density) = 5;
% For now
load materialMap materialMap
[CTscan.material materialNames] = generateMaterialMap(CTscan.density, materialMap);

% Feb 29, 2008
% To treat everything above the maximum density (which is bone now) as
% bone.
CTscan.density(find(CTscan.density > materialMap(end).defaultDensity)) ...
    = materialMap(end).defaultDensity;
CTscan.material(find(CTscan.material == 0)) = length(materialMap);

% Find the upper left corner of the CTscan
% Need to check dpm.f to see whether it can handle x, y, z less than zero.
% Actually need to get the region of the intereted structures, not the
% whole CT scan, to eliminate the uncessary calculation.

% Initialize IM.params.DPM struct
IM.params.DPM = struct(...
    'NumParticles', [50], ...      % Number of particles
    'AlctTime', [-9e+008], ...       % Allocated CPU Time
    'ParticleType', [0], ...         % Particle Type, choice: -1, 0. -1 for electron; 0 for photon
    'SourceEnergy', [2e+007], ...    % Beam source energy, in(eV)
    'SqBeamSize', [1.5], ...         % Parallel Square Beam size (cm)
    'ElctAbsEnergy', [2.0e+005], ... % Electron Absorption Energy, in (eV)
    'PhotAbsEnergy', [5.0e+004], ... % Photon Absorption Energy, in (eV)
    'Prefix', 'pre4elec', ...        % Perfix files: pre4elec.*
    'MinCTscanCorner', [0 0 0], ...          % minimum [x y z] of the interested field
    'MaxCTscanCorner', [20 10 15], ...       % maximum [x y z] of the interested field
    'RandSeeds', [0 0], ...          % Random seeds [x1 x2], integer
    'TypeSource',[2], ...            % Type of source, choice: 0, 1, 2. 0 for parallel beam; 1 for disk source; 2 for rectangular collimator
    'SourceXYZ', [10 5 100], ...       % Source location, [x y z]
    'ClmtCorner1', [9.8 4.9 95], ...   % Corner 1 of the collimator: [x y z]
    'ClmtCorner2', [10.2 4.9 95], ...  % Corner 2 of the collimator: [x y z]
    'ClmtCorner3', [10.2 5.1 95], ...  % Corner 3 of the collimator: [x y z]
    'DiameterClmt', [1.5], ...         % The diameter of the disk collimator
    'PhotSpectrum', 'test.spectrum', ... % Photon energy spectrum n*2 matrix
    'OutputError', [0], ...              % Choice: 1 ='Yes', or 0 = 'No'.
    'IsoVector', [0 1 0], ...            % The unit vector from source to the iso-center
    'BinEnergy', [-1 -1], ...            % During commissing, the low bound and upper bound for each energy bin.
    'UsePhotSpectrum', 1, ...            % If it's 1, use DPMIN.PhotSpectrum; if it's 0, use "BinEnergy".
    'UseFlatFilter', 0, ...              % If it's 1, use FlatFilter.
    'FlatFilterA', -0.213, ...           % Coefficient A, to determine the distribution of particles on FlatFilter
    'FlatFilterB', -0.1, ...             % Coefficient B, to determine the distribution of particles on FlatFilter
    'FlatFilterDist', 9.5, ...           % The distance from the source/target to the FlatFilter, cm
    'IsoDistance', 100, ...              % Iso Distance, in cm
    'IncreaseFluence', 0, ...            % How rapid to increase fluence when off-axis angle increase.
    'OnlyHorn', 0, ...                   % Only model the "Horn" effect, used when commissioning.
    'DoseNormFlag', 1, ...               % 1:Use # of succesfully sampled particles to normalize dose;
    ...  % 2:Use # of total sampled particles to normalize dose;
    'HornCoef', [1.0 0; 9.9253e-01   4.3309e-02; 9.8507e-01   4.8225e-02;   9.7761e-01   4.7987e-02;  9.7014e-01   4.7750e-02], ...
    ... % Use lateral dose profile as the increase of fluence.
    'OpenField', 0, ...                  % OpenField == 0; Don't sample isotropic source. 'uniformly' sample
    'Softening', 1, ...                   % Softening == 0; Don't use off-axi-softening.
    'maxSampleAngle', 0.36, ...                   % For OpenField (==1), the max sampling angle for primary source.
    'maxSampleAngleFF', 0.245 ...                   % For OpenField (==1), the max sampling angle for FF source.
    );

% Above is from "initIMRTProblem.m".

% Loop for every beam.
beamletCount = 1;

%for beamIndex=1:numBeams,
%for beamIndex=1:1,
beamIndex = indBeam; % was =1

% Initialize DPMIN struct
DPMIN = IM.params.DPM;

DPMIN.NumParticles = 10000000;
DPMIN.AlctTime = IM.params.DPM.AlctTime;
%DPMIN.ParticleType = IM.params.DPM.ParticleType;
DPMIN.ParticleType = 0;
% Dec 04, 2006
% No need to convert from MeV to eV
%DPMIN.SourceEnergy = IM.beams(beamIndex).beamEnergy*1000000; %MeV->eV
DPMIN.SourceEnergy = IM.beams(beamIndex).beamEnergy;
DPMIN.SqBeamSize = IM.params(1).DPM.SqBeamSize;
DPMIN.ElctAbsEnergy = IM.params(1).DPM.ElctAbsEnergy;
DPMIN.PhotAbsEnergy = IM.params(1).DPM.PhotAbsEnergy;
DPMIN.Prefix = IM.params(1).DPM.Prefix;
DPMIN.MinCTscanCorner = [(bbox(3)-1)*xres (bbox(1)-1)*yres (bbox(5)-1)*zres];
%DPMIN.MaxCTscanCorner = [(bbox(4)-0.95)*xres (bbox(2)-1)*yres (bbox(6)-1)*zres];
DPMIN.MaxCTscanCorner = [(bbox(4)-0.95)*xres (bbox(2)-0.95)*yres (bbox(6)-0.95)*zres];
DPMIN.RandSeeds = IM.params(1).DPM.RandSeeds;
DPMIN.TypeSource = IM.params(1).DPM.TypeSource;
%Just to initialize DPMIN order.
DPMIN.SourceXYZ = [0 0 0];
% Collimators info need to be determined by pencil beam info.
DPMIN.ClmtCorner1 = IM.params(1).DPM.ClmtCorner1;
DPMIN.ClmtCorner2 = IM.params(1).DPM.ClmtCorner2;
DPMIN.ClmtCorner3 = IM.params(1).DPM.ClmtCorner3;
DPMIN.DiameterClmt = IM.params(1).DPM.DiameterClmt;
% Get the photon spectrum file.
fid = fopen(Energy);
if (fid == -1),
    disp('Can not Open photon spectrum file for the primary source');
end
tline = fgetl(fid);
tline = fgetl(fid);
photon_spectrum = fscanf(fid,'%g %g',[2 inf]); % It has two rows now.
PhotSpectrumPrimary = photon_spectrum';
DPMIN.PhotSpectrum = PhotSpectrumPrimary;
fclose(fid);

if (sourceModel == 1)  % Use source model, version 1.
    % Get the photon spectrum file for the Flatteing Filter.
    % Get the correct filename
    inds = max(strfind(Energy, '.'));
    fid = fopen([Energy(1:inds-1), '_FF', Energy(inds:end)]);
    if (fid == -1),
        disp('Can not Open photon spectrum file for the flattening filter');
    end
    tline = fgetl(fid);
    tline = fgetl(fid);
    photon_spectrum = fscanf(fid,'%g %g',[2 inf]); % It has two rows now.
    PhotSpectrumFF = photon_spectrum';

    % Get all the other parameters for the whole source model
    % Fluence weight of Flattening Filter, Horn, and Electron contamination
    inds = max(strfind(Energy, '.'));
    fid = fopen([Energy(1:inds-1), '_Params', Energy(inds:end)]);
    if (fid == -1),
        disp('Can not Open photon spectrum file for the flattening filter');
    end
    tline = fgetl(fid);
    tline = fgetl(fid);
    SourceModelParams = fscanf(fid,'%g',[1 inf]); % It has two rows now.

    % Oct 26, 2007
    % Add the "CosHorn
    fid = fopen([Energy(1:inds-1), '_CosHorn', Energy(inds:end)]);
    % Here, the file extension ".spectrum" is only for the purpose of being
    % consistent with other source model parameters files.
    if (fid == -1),
        disp(['Can not Open CosHorn file',[Energy(1:inds-1), '_CosHorn', Energy(inds:end)]]);
    end
    tline = fgetl(fid);
    tline = fgetl(fid);
    CosHorn = fscanf(fid,'%g',[2 inf]); % It has two rows now.
    CosHorn = CosHorn';
    cosOffAxisAngle = IM.beams(beamIndex).isodistance ./ ...
        (sqrt((IM.beams(beamIndex).RTOGPBVectorsM_MC(:,1).^2 +IM.beams(beamIndex).RTOGPBVectorsM_MC(:,2).^2+ IM.beams(beamIndex).RTOGPBVectorsM_MC(:,3).^2)));
    Horn = interp1(CosHorn(:,1), CosHorn(:,2), cosOffAxisAngle, 'linear');

end

DPMIN.OutputError = IM.params(1).DPM.OutputError;
DPMIN.IsoVector = IM.params.DPM.IsoVector;
DPMIN.BinEnergy = IM.params.DPM.BinEnergy;
DPMIN.UsePhotSpectrum = IM.params.DPM.UsePhotSpectrum;
%JC Feb 09 2005. Make sure OutputError is changed based on input.
DPMIN.OutputError = OutputError;
%JC Nov 16, 2006, Use the most up-to-date DPM.
% Add more input to DPMIN.
DPMIN.UseFlatFilter = IM.params.DPM.UseFlatFilter;          % If it's 1, use FlatFilter.

% Define the FlatFilter Parameters based on the Source Energy
% If 6MV: -0.213 -0.1 9.5

if (DPMIN.SourceEnergy == 6)
    DPMIN.FlatFilterA = -0.213;              % Coefficient A, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterB = -0.1;               % Coefficient B, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterDist = 9.5;        % The distance from the source/target to the FlatFilter, cm
    % If 18MV: -0.774 -0.00508 9.5
elseif (DPMIN.SourceEnergy == 18)
    DPMIN.FlatFilterA = -0.774;              % Coefficient A, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterB = -0.00508;               % Coefficient B, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterDist = 9.5;        % The distance from the source/target to the FlatFilter, cm
else
    DPMIN.FlatFilterA = -0.213;              % Coefficient A, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterB = -0.1;               % Coefficient B, to determine the distribution of particles on FlatFilter
    DPMIN.FlatFilterDist = 9.5;        % The distance from the source/target to the FlatFilter, cm
    warndlg('BE AWARE! Beam Energy is not 6MV or 18MV, using settings for 6MV for flatteing filter')
end

DPMIN.IsoDistance = IM.params.DPM.IsoDistance';             % Iso Distance, in cm
DPMIN.IncreaseFluence = IM.params.DPM.IncreaseFluence;      % How rapid to increase fluence when off-axis angle increase.
DPMIN.OnlyHorn = IM.params.DPM.OnlyHorn;                    % Only model the "Horn" effect, used when commissioning.
DPMIN.DoseNormFlag = IM.params.DPM.DoseNormFlag;               % 1:Use # of succesfully sampled particles to normalize dose;
DPMIN.HornCoef = IM.params.DPM.HornCoef;
DPMIN.OpenField = IM.params.DPM.OpenField;

% Aug 06, 2007
DPMIN.Softening = Softening;
'maxSampleAngle', 0.36, ...                   % For OpenField (==1), the max sampling angle for primary source.
    'maxSampleAngleFF', 0.245 ...                   % For OpenField (==1), the max sampling angle for FF source.

% IM.beams(beamIndex).x is the x coordinate of the beam source.
% IM.beams.RTOGPBVectorsM_MC are the vectors from the source to the center
% of every pencil beam on the plane of the isocenter.
% So pb(:,1:3) are the locations of the center of every pencile beam on the
% plane passing the isocenter.

%nhist_time = zeros(2, length(IM.beams(beamIndex).beamletDelta_x));
rand('state',sum(100*clock));

%currentDIR=pwd;
%cd(DPMPath);
if(exist('local')~= 7)
    dos('mkdir local')
end

%h = waitbar(0,['Generating Monte Carlo Dose for Beam ',num2str(indBeam)]);

% JC Mar 29, 2007
if (useWedge == 1)
    %Energy       mu over rho        mu e n over rho
    %      (MeV)      (cm2/g)     (cm2/g)
    %____________________________________
    [wedge_data wedge_density] = wedge();
    [rayWedgeLength] = rayWedgeIntersect(IM, 1, 18.6);
end
attenuation = ones(size(IM.beams(beamIndex).xPBPosV));

% Since this function is called by DPMpc*OneBeam*.m, so IM always has
% one beams field.

%Calculate isocenter if required.
IM = checkAutoIsocenter(IM);

IM.beams(beamIndex).beamlets = [];
%for i= 1:length(IM.beams(beamIndex).beamletDelta_x), %APA
for i= 1:length(IM.beams(beamIndex).xPBPosV), %APA
    % Every time to call a Beam calculation, set the rand to a different
    % initial state.

    %for i = str2num(imin):str2num(imax)

    %Need to scale NumParticles based on the area of the pencil beam.
    %10Million particles per cm^2
    dx=IM.beams(beamIndex).beamletDelta_x(i);  %APA was (i)
    dy=IM.beams(beamIndex).beamletDelta_y(i);  %APA was (i)
    %DPMIN.NumParticles = str2num(nhist)*dx*dy;
    DPMIN.NumParticles = nhist*dx*dy;
    DPMIN.RandSeeds = rand(1,2)*1000;

    pb(i,1)=IM.beams(beamIndex).RTOGPBVectorsM_MC(i,1)+IM.beams(beamIndex).x;
    pb(i,2)=IM.beams(beamIndex).RTOGPBVectorsM_MC(i,2)+IM.beams(beamIndex).y;
    pb(i,3)=IM.beams(beamIndex).RTOGPBVectorsM_MC(i,3)+IM.beams(beamIndex).z;

    IC=[IM.beams(beamIndex).isocenter.x IM.beams(beamIndex).isocenter.y  IM.beams(beamIndex).isocenter.z];
    th=IM.beams(beamIndex).gantryAngle*pi/180;
    cA=IM.beams(beamIndex).couchAngle*pi/180;
    clA=IM.beams(beamIndex).collimatorAngle*pi/180;
    IsDist = IM.beams(beamIndex).isodistance;

    % coordinates of beams from perspectives of beam's eye view. z = const.
    coll3V(i,:) = scan2Collimator(pb(i,:), th, cA, clA, IC,IM.beams(beamIndex).isodistance);

    %%%%Find corners of the pencil beams.
    %%%%What order should it be?
    %%%% Previously, we had corner3, corner2, corner1, now

    %% JC Nov 27 2006
    %% Use 0.4 instead of 0.5 to scale.

    corner1 = [coll3V(i,1)-0.5*dx   coll3V(i,2)-0.5*dy      coll3V(i,3)];
    corner2 = [coll3V(i,1)+0.5*dx   coll3V(i,2)-0.5*dy      coll3V(i,3)];
    corner3 = [coll3V(i,1)+0.5*dx   coll3V(i,2)+0.5*dy      coll3V(i,3)];
    %   project back towards the plane 40cm from the source
    corner1_new = corner1/IsDist*40;
    corner2_new = corner2/IsDist*40;
    corner3_new = corner3/IsDist*40;

    % Project back to orginal coordinates.
    corner1_final = collimator2Scan(corner1_new, th, cA, clA, IC,IM.beams(beamIndex).isodistance);
    corner2_final = collimator2Scan(corner2_new, th, cA, clA, IC,IM.beams(beamIndex).isodistance);
    corner3_final = collimator2Scan(corner3_new, th, cA, clA, IC,IM.beams(beamIndex).isodistance);

    corner1_final = corner1_final-[xV(1)-xres/2 yV(end)-yres/2 zV(1)-zres/2];
    corner2_final = corner2_final-[xV(1)-xres/2 yV(end)-yres/2 zV(1)-zres/2];
    corner3_final = corner3_final-[xV(1)-xres/2 yV(end)-yres/2 zV(1)-zres/2];

    corner1_final(2) = yres*CTscan.Num_y_vox - corner1_final(2);
    corner2_final(2) = yres*CTscan.Num_y_vox - corner2_final(2);
    corner3_final(2) = yres*CTscan.Num_y_vox - corner3_final(2);

    % DPMIN.SourceXYZ = [IM.beams(beamIndex).x-xV(1)   yres*CTscan.Num_y_vox - (IM.beams(beamIndex).y-yV(end))  IM.beams(beamIndex).z-zV(1)];
    DPMIN.SourceXYZ = [IM.beams(beamIndex).x-(xV(1)-xres/2)   yres*CTscan.Num_y_vox - (IM.beams(beamIndex).y-(yV(end)-yres/2))  IM.beams(beamIndex).z-(zV(1)-zres/2)];
    DPMIN.ClmtCorner1 = corner1_final;
    DPMIN.ClmtCorner2 = corner2_final;
    DPMIN.ClmtCorner3 = corner3_final;
    clear corner1 corner2 corner3 corner1_new corner2_new corner3_new corner1_final corner2_final corner3_final

    % In DPM, the y direction is the opposite of the y of CERR coordinates.
    DPMIN.IsoVector = [IC(1) - IM.beams(beamIndex).x, -(IC(2) - IM.beams(beamIndex).y),IC(3) - IM.beams(beamIndex).z]/IsDist;

    disp(i);

    % run DPM for the primary photon spectrum
    DPMIN.ParticleType = 0;
    DPMIN.NumParticles = nhist*dx*dy;
    DPMIN.Prefix = 'pre4phot';
    DPMIN.PhotSpectrum = PhotSpectrumPrimary;

    % Mar 31, 2007

    if (useWedge ==1)
        mu_en = interp1(wedge_data(:,1), wedge_data(:,2), PhotSpectrumPrimary(:,1));
        % figure; loglog(softPhotSpectrumPrimary(:,1),mu_en, '.');
        % hold on; loglog(wedge_data(:,1), wedge_data(:,2), '+r');
        sampledAttenuation = exp(-rayWedgeLength(i).*mu_en.*wedge_density);
        %figure; plot(PhotSpectrumPrimary(:,1), sampledAttenuation);
        attenSpectrum = sampledAttenuation.*(PhotSpectrumPrimary(:,2)/sum(PhotSpectrumPrimary(:,2)));
        attenuation(i) = sum(attenSpectrum);
        DPMIN.PhotSpectrum = [PhotSpectrumPrimary(:,1) attenSpectrum];
    end

    % The current approach should be: Modify the spectrum for each beamlet,
    % based on the rayWedgeLength.
    % And the scale the total dose by the attentuation.

    DPMIN.UseFlatFilter = 0;
    DPMIN.OnlyHorn = 0;
    DPMIN.RandSeeds = [rand*1000 rand*10000];
    tic; [dosePrimary sampleParticles] = dpm(DPMIN, CTscan); toc

    if (sourceModel ==1)    % Use source model, version 1.

        % run DPM for the Horn effect; Use the Primary Photon Spectrum
        % Will Apply Horn into the fluence map, i.e. PB weight: w_field.
        % Not Applicable here.
        %     DPMIN.OnlyHorn = 1;
        %     DPMIN.NumParticles = nhist*dx*dy*SourceModelParams(7);
        %     DPMIN.RandSeeds = [rand*1000 rand*10000];
        %     doseHorn = dpm(DPMIN, CTscan);

        % run DPM for the flattening filter spectrum
        DPMIN.OnlyHorn = 0;
        DPMIN.UseFlatFilter = UseFlatFilter;
        if (UseFlatFilter == 2 & DPMIN.SourceEnergy == 6)
            DPMIN.FlatFilterA = [0.0332 0.0517 0.032];
            DPMIN.FlatFilterB = [0.65 1.33 4.52];
            % Need to add other combinations of SourceEnergy and UseFlatFilter.
        end

        DPMIN.NumParticles = nhist*dx*dy*SourceModelParams(6);
        DPMIN.RandSeeds = [rand*1000 rand*10000];
        DPMIN.PhotSpectrum = PhotSpectrumFF;
        tic; [doseFF sampleParticles]  = dpm(DPMIN, CTscan); toc

        if (SourceModelParams(8) > 0.005) %If the relative fluence of electron contamination is less than 0.5%, then call DPM for electron.
            DPMIN.ParticleType = -1;
            DPMIN.Prefix = 'pre4elec';
            DPMIN.UseFlatFilter = 0;
            DPMIN.NumParticles = nhist*dx*dy*SourceModelParams(8);
            tic; [doseElec  sampleParticles]= dpm(DPMIN, CTscan);
        else
            doseElec= zeros(size(dosePrimary));
        end

        % Sum different components of dose up.
        % JC Sept 20. 2007
        % Remove the scaling of the dose by "sum(PhotSpectrumPrimary(:,2))"
        %        doseV = sum(PhotSpectrumPrimary(:,2))* ...
        %            (dosePrimary*(1+Horn(i)) + SourceModelParams(6)*doseFF + SourceModelParams(8)*doseElec);
        doseV = dosePrimary*(1+Horn(i)) + SourceModelParams(6)*doseFF + SourceModelParams(8)*doseElec;
        % Change the dose from dose / particle to dose in Gy/MU
        doseV = doseV*K;

    else  % No source model, only primary source.
        % Aug 06, 2007, DO NOT scale the dose.
        % doseV = dosePrimary*sum(PhotSpectrumPrimary(:,2));
        % Change the dose from dose / particle to dose in Gy/MU
        doseV = dosePrimary*K;
	end
	toc

    % JC Mar 29, 2007, add wedge
    if (useWedge == 1)
        doseV = attenuation(i)*doseV;
    end

    % Scale Dose, since DPM outputs dose/particle
    % How to deal with the Error ? Since it's STD, so should not be scaled.
    % When output Error, doseV is nx2 matrix. Need not to be scaled
    doseV(:,1) = doseV(:,1) * dx * dy;

    %%% ASK JING about 23.668 factor
    if (i == 1)
        doseV_SUM = doseV * w_field (i);
    else
        doseV_SUM = doseV_SUM + doseV * w_field(i);
    end

    % Do not apply w_field here.
    if(DPMIN.OutputError == 1)
        Error =  dosePrimary(:, 2);
        dosePrimary =  dosePrimary(:, 1);

        if (sourceModel == 1)

            ErrorFF =  doseFF(:, 2);
            doseFF =  doseFF(:, 1);

            ErrorElec =  doseElec(:, 2);
            doseElec =  doseElec(:, 1);

        end

    end

    if (saveIM == 1)
        % z changes first, then y, then x
        % Aug 07, 2007 Compress doseV instead of dosePrimary. Do not apply
        % w_Field here.
        doseV = applyIMRTCompression(IM.params, doseV);
        %beamlet = createIMBeamlet(doseV, indV', beamIndex, 0);

        % build 3D dose matrix
        scanNum = 1;
        doseM = zeros(getUniformScanSize(planC{indexS.scan}(scanNum)));
        if length(indV)==length(doseV)
            doseM(indV) = doseV;
        else
            errorBeamlets = [errorBeamlets beamletCount];
        end

        %-----------Insert dose data into correct beamlet indices---------------------%
        for j = 1 : length(structROIV)
            beamlet = createIMBeamlet(doseM(scanIndV{j}), scanIndV{j}, beamIndex, 0);
            beamlet.structureName = planC{planC{end}.structures}(structROIV(j)).structureName;
            beamlet.sampleRate = sampleRateV(j);
            beamlet.strUID = planC{planC{end}.structures}(structROIV(j)).strUID;
            if isempty(IM.beams(beamIndex).beamlets)
                IM.beams(beamIndex).beamlets = beamlet;
            else
                IM.beams(beamIndex).beamlets(j,beamletCount) = beamlet;
            end
        end
        beamletCount = beamletCount + 1;

        %-------------------- APA commented begins
        %         %  JC Dec 2007
        %         %  Add the field "beamletPrimary" in IM struct. For the calibration of
        %         %       Horn coefficients.
        %         %       Here, all the dose/fluence components are "un-touched", means not
        %         %       scaled by any factor.
        %
        %         if (sourceModel == 1)
        %             % To get the dose in the units of dose/particle
        %             dosePrimary = applyIMRTCompression(IM.params, (dx*dy)*dosePrimary);
        %             beamletPrimary = createIMBeamlet(dosePrimary, indV', beamIndex, 0);
        %             clear dosePrimary
        %
        %             doseFF = applyIMRTCompression(IM.params, (dx*dy)*doseFF);
        %             beamletFF = createIMBeamlet(doseFF, indV', beamIndex, 0);
        %             clear doseFF
        %
        %             doseElec = applyIMRTCompression(IM.params, dx*dy*doseElec);
        %             beamletElec = createIMBeamlet(doseElec, indV', beamIndex, 0);
        %             clear doseElec
        %         end
        %
        %         if(DPMIN.OutputError == 1)
        %             Error = applyIMRTCompression(IM.params, Error);
        %             Error = createIMBeamlet(Error, indV', beamIndex, 0);
        %             if (sourceModel ==1)
        %                 ErrorFF = applyIMRTCompression(IM.params, ErrorFF);
        %                 ErrorFF = createIMBeamlet(ErrorFF, indV', beamIndex, 0);
        %                 ErrorElec = applyIMRTCompression(IM.params, ErrorElec);
        %                 ErrorElec = createIMBeamlet(ErrorElec, indV', beamIndex, 0);
        %             end
        %         end
        %         % Need to transpose either doseV or indV, because their dimensions
        %         % don't match.
        %
        %
        %         % 14 Aug 05 JC
        %         % Do not use dissimilarInsert, where "setfield" is called, which causes
        %         % problem with mcc.
        %         %    IM.beamlets = dissimilarInsert(IM.beamlets, beamlet, beamletCount);
        %         % Add "beamlet" to IM.beamlets directory. When beamletCount == 1,
        %         % IM.beamlets = []; all beamlet structs have the same fields/order.
        %         if(beamletCount == 1)
        %             IM.beamlets = beamlet;
        %             if (sourceModel == 1)
        %                 %  JC Dec 2007
        %                 %  Add the field "beamletPrimary" in IM struct. For the calibration of
        %                 IM.beamletsPrimary(beamletCount) = beamletPrimary;
        %                 IM.beamletsFF(beamletCount) = beamletFF;
        %                 IM.beamletsElec(beamletCount) = beamletElec;
        %             end
        %             if(DPMIN.OutputError == 1)
        %                 IM.Errors = struct;
        %                 IM.Errors = Error;
        %
        %                 if (sourceModel == 1)
        %                     IM.ErrorsFF = struct;
        %                     IM.ErrorsFF = ErrorFF;
        %
        %                     IM.ErrorsElec = struct;
        %                     IM.ErrorsElec = ErrorElec;
        %                 end
        %             end
        %         else
        %             IM.beamlets(beamletCount) = beamlet;
        %             if (sourceModel == 1)
        %                 IM.beamletsPrimary(beamletCount) = beamletPrimary;
        %                 IM.beamletsFF(beamletCount) = beamletFF;
        %                 IM.beamletsElec(beamletCount) = beamletElec;
        %             end
        %             if(DPMIN.OutputError == 1)
        %                 IM.Errors(beamletCount) = Error;
        %                 if (sourceModel == 1)
        %                     IM.ErrorsFF(beamletCount) = ErrorFF;
        %                     IM.ErrorsElec(beamletCount) = ErrorElec;
        %                 end
        %             end
        %
        %         end
        %
        %     end
        %     beamletCount = beamletCount + 1;
        %-------------------- APA commented ends

    end

    %waitbar(i/length(IM.beams.beamletDelta_x));
    % filename = ['IM_',num2str(indBeam),'_', num2str(nhist)];
    % save(filename, 'IM');

end

%close(h);

%cd(currentDIR);

function IM = checkAutoIsocenter(IM)
%"checkAutoIsocenter"
%   Examines IM structure for auto-isocenter calculation.  If an auto
%   method is specified, calculates isocenter, stores in IM and returns.
calcCOM = 0;
for i = 1:length(IM.beams);
    if strcmpi(IM.beams(i).isocenter.x, 'COM') | strcmpi(IM.beams(i).isocenter.y, 'COM') | strcmpi(IM.beams(i).isocenter.z, 'COM')
        calcCOM = 1;
    end
end
if calcCOM
    disp('Auto calculating ISOCENTER using center of mass...')
    try
        IMRTPGui('statusbar', 'Auto calculating ISOCENTER using center of mass...');
    end

    %         structNums = [IM.goals.structNum];
    %         targets = structNums(strcmpi({IM.goals.isTarget}, 'yes'));
    indTargetV   = strcmpi({IM.goals.isTarget}, 'yes');
    targetsV     = getAssociatedStr({IM.goals(indTargetV).strUID});
    [xCOM, yCOM, zCOM] = calcIsocenter(targetsV, 'COM');
    disp(['ISOCENTER found at x = ' num2str(xCOM) ' y = ' num2str(yCOM) ' z = ' num2str(zCOM) '.']);
    try
        IMRTPGui('statusbar', ['ISOCENTER found at x = ' num2str(xCOM) ' y = ' num2str(yCOM) ' z = ' num2str(zCOM) '.']);
    end

    for i = 1:length(IM.beams)
        if strcmpi(IM.beams(i).isocenter.x, 'COM')
            IM.beams(i).isocenter.x = xCOM;
        end
        if strcmpi(IM.beams(i).isocenter.y, 'COM')
            IM.beams(i).isocenter.y = yCOM;
        end
        if strcmpi(IM.beams(i).isocenter.z, 'COM')
            IM.beams(i).isocenter.z = zCOM;
        end
    end
end
%-------------------------------------------

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR