function varargout = resultManager2(varargin)
% RESULTMANAGER2 MATLAB code for resultManager2.fig
%      RESULTMANAGER2, by itself, creates a new RESULTMANAGER2 or raises the existing
%      singleton*.
%
%      H = RESULTMANAGER2 returns the handle to a new RESULTMANAGER2 or the handle to
%      the existing singleton*.
%
%      RESULTMANAGER2('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RESULTMANAGER2.M with the given input arguments.
%
%      RESULTMANAGER2('Property','Value',...) creates a new RESULTMANAGER2 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before resultManager2_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to resultManager2_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 resultManager2
% Last Modified by GUIDE v2.5 11-Jul-2013 01:16:29
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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', @resultManager2_OpeningFcn, ...
                   'gui_OutputFcn',  @resultManager2_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 resultManager2 is made visible.
function resultManager2_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 resultManager2 (see VARARGIN)

    handles.returns_daily = varargin{1} - 1;
    handles.returns = cumprod(varargin{1});
    handles.portfolio = varargin{2};
    handles.selectedAlgorithms = varargin{3};
    handles.frequency = varargin{4};
    [handles.r handles.c] = size(handles.portfolio{1});
    rd_cumulativeReturns_Callback(hObject, eventdata, handles);

     % Compute the statsand display the important numbers in table using the
    % library functions
    addpath('./lib');

    cumReturns = handles.returns;
    dailyReturns = handles.returns_daily;

    % Get final Values
    [r c] = size(cumReturns);
    handles.finalValues = cumReturns(r,:);

    % Get the mean returnfor every day - This is a simple average
    handles.meanReturns = mean(dailyReturns);

    % Get annualised returns
    denominator = 252/handles.frequency;
    Y = r/denominator;
    handles.annualisedReturns = handles.finalValues.^(1/Y)-1;

    % Get standard deviation- a measureof risk
    handles.standardDeviation = std(dailyReturns);

    % Get annualised standard deviation
    handles.annualisedStandardDeviation = handles.standardDeviation * sqrt(denominator);

    % Get sharpe ratios
    handles.sharpeRatios = sharpe(dailyReturns, handles.finalValues, handles.frequency);

    % Get Sortino ratios
    handles.sortinoRatios = sortino(dailyReturns, 0);

    % Get Value risks at level 5%
    handles.valueAtRisks = var5(dailyReturns);

    % Get Maximum draw down
    handles.mdds = maxDD_general(cumReturns);

    % Get Calmar ratios
    handles.calmars = calmar(cumReturns, handles.mdds, handles.frequency);

    % Fill up the tables
    set(handles.table,'ColumnName',handles.selectedAlgorithms);
    tableData = [handles.finalValues; handles.meanReturns; handles.annualisedReturns; handles.standardDeviation; handles.annualisedStandardDeviation; handles.sharpeRatios; handles.calmars; handles.sortinoRatios; handles.valueAtRisks; handles.mdds];
    set(handles.table,'Data',tableData);

    rmpath('./lib');

    guidata(hObject, handles);

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

% Update handles structure
guidata(hObject, handles);

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

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

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

function rd_sharpe_Callback(hObject, eventdata, handles)
% hObject    handle to rd_sharpe (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 rd_sharpe
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_sharpe,'Value', 1);

    window = str2double(get(handles.windowSharpe,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);
    addpath('./lib');

    [r c] = size(handles.returns_daily);
    sharpeRatios = zeros(r,c);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        sharpeRatios(i,:) = sharpe(handles.returns_daily(start:finish,:), handles.returns(finish,:)./handles.returns(start,:), handles.frequency);
    end

    rmpath('./lib');

    plot(handles.mainGraph, sharpeRatios);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');

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

% --- Executes during object creation, after setting all properties.
function windowSharpe_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowSharpe (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 rd_calmar.
function rd_calmar_Callback(hObject, eventdata, handles)
% hObject    handle to rd_calmar (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 rd_calmar
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_calmar,'Value', 1);

    window = str2double(get(handles.windowCalmar,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);
    addpath('./lib');

    [r c] = size(handles.returns_daily);
    calmarRatios = zeros(r,c);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        mdd = maxDD_general(handles.returns(start:finish,:));
        calmarRatios(i,:) = calmar(handles.returns(start:finish,:), mdd,  handles.frequency);
    end

    rmpath('./lib');

    plot(handles.mainGraph, calmarRatios);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');

% --- Executes on button press in rd_var.
function rd_var_Callback(hObject, eventdata, handles)
% hObject    handle to rd_var (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 rd_var
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_var,'Value', 1);

    window = str2double(get(handles.windowVar,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);
    addpath('./lib');

    [r c] = size(handles.returns_daily);
    vars = zeros(r,c);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        vars(i,:) = var5(handles.returns_daily(start:finish,:));
    end

    rmpath('./lib');
    plot(handles.mainGraph, vars);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');

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

% --- Executes during object creation, after setting all properties.
function windowCalmar_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowCalmar (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 rd_mdd.
function rd_mdd_Callback(hObject, eventdata, handles)
% hObject    handle to rd_mdd (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 rd_mdd
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_mdd,'Value', 1);

    window = str2double(get(handles.windowMDD,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);
    addpath('./lib');

    [r c] = size(handles.returns_daily);
    mdds = zeros(r,c);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        mdds(i,:) = maxDD_general(handles.returns(start:finish,:));
    end

    rmpath('./lib');

    plot(handles.mainGraph, mdds);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');

% --- Executes on button press in rd_sortino.
function rd_sortino_Callback(hObject, eventdata, handles)
% hObject    handle to rd_sortino (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 rd_sortino
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_sortino,'Value', 1);

    window = str2double(get(handles.windowSortino,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);
    addpath('./lib');

    [r c] = size(handles.returns_daily);
    sortinos = zeros(r,c);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        sortinos(i,:) = sortino(handles.returns_daily(start:finish,:),0);
    end

    rmpath('./lib');

    plot(handles.mainGraph, sortinos);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');

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

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

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

% --- Executes during object creation, after setting all properties.
function windowMDD_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowMDD (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 rd_cumulativeReturns.
function rd_cumulativeReturns_Callback(hObject, eventdata, handles)
% hObject    handle to rd_cumulativeReturns (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 rd_cumulativeReturns
    clearRadio(hObject, eventdata, handles);
    set(handles.rd_cumulativeReturns,'Value', 1);
    if get(handles.logCheck,'Value') ~=1
        plot(handles.mainGraph, handles.returns);
        xlim(handles.mainGraph, [0 handles.r+1]);
        legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');
        grid on;
    else
        logCheck_Callback(hObject, eventdata, handles);
    end

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

    % Check if user wants to see cumulative returns
    selected  = get(handles.rd_cumulativeReturns,'Value');

    % only if user wants to see the cumulative returns
    if selected == 1
        logPlot = get(handles.logCheck,'Value');

        if logPlot == 1
            semilogy(handles.returns);
        else
            plot(handles.returns);
        end
        xlim(handles.mainGraph, [0 handles.r+1]);
        legend(handles.mainGraph , handles.selectedAlgorithms, 'Location', 'Best');
        grid on;
    end

function clearRadio(hObject, eventdata, handles)
% The function is a helper function to uncheck all radio buttons

    set(handles.rd_cumulativeReturns,'Value', 0);
    set(handles.rd_sharpe,'Value', 0);
    set(handles.rd_calmar,'Value', 0);
    set(handles.rd_sortino,'Value', 0);
    set(handles.rd_var,'Value', 0);
    set(handles.rd_mdd,'Value', 0);

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

    first = str2double(get(handles.dailyStart,'string'));
    last = str2double(get(handles.dailyEnd,'string'));

    if isnan(first) || isnan(last) || first < 1 || last - first < 1
        errorMessage('Error in entering start and end days. End day must be greater than start day. Start day must be positive integer.');
        return;
    end
    first = round(first);
    last = round(last);

    [r c] = size(handles.returns_daily);
    last = min(last,r);
    bar(handles.mainGraph, handles.returns_daily(first:last,:));
    xlim([0 last-first+2]);
    legend(handles.mainGraph,handles.selectedAlgorithms, 'Location', 'Best');

% --- Executes on button press in portfolioAllocationButton.
function portfolioAllocationButton_Callback(hObject, eventdata, handles)
% hObject    handle to portfolioAllocationButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    first = str2double(get(handles.portfolioStart,'string'));
    last = str2double(get(handles.portfolioEnd,'string'));

    if isnan(first) || isnan(last) || first < 1 || last - first < 1
        errorMessage('Error in entering start and end days. End day must be greater than start day. Start day must be positive integer.');
        return;
    end
    first = round(first);
    last = round(last);

    [r c] = size(handles.portfolio{1});
    last = min(last,r);

    % Number of algorithms
    [tmp n] = size(handles.portfolio);
    for i = 1:1:n
        portfolio = handles.portfolio{i};
        portfolio = portfolio(first:last,:);
        expected(:,i) = mean(portfolio)';
        deviation(:,i) = std(portfolio)';
    end
    errorbar(handles.mainGraph, expected, deviation,'x');
    xlim([0 c+1]);
    minMean = min(min(expected));
    maxMean = max(max(expected));
    maxDev = max(max(deviation));
    legend(handles.mainGraph, handles.selectedAlgorithms, 'Location', 'Best');

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

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

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

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

% --- Executes during object creation, after setting all properties.
function dailyEnd_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dailyEnd (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 opt= defopt_scalp_r(varargin)
%DEFOPT_SCALP_R - Properties for plot_scalp* functions, optimized for
%visualizing (signed, squared) r values

props= {'Extrapolation'          1
        'ExtrapolateToMean'      0
        'Resolution'             71
        'CLim'                   'sym'
        'ShrinkColorbar'         0.2
        'ColorOrder'             [0 0 0]
        'Colormap'               cmap_posneg(51)
        'LineWidth'              2
        'ChannelLineStyleOrder'  {'thick' 'thin'}
        'IvalColor'              [0.8 0.8 0.8; 0.6 0.6 0.6]
        'Contour'                5
        'ContourPolicy'          'withinrange'
        'ContourLineprop'        {'LineWidth' 0.3}
        'MarkMarkerProperties'   {'MarkerSize' 6, 'LineWidth' 1}
        'ChannelAtBottom'        1
        'GlobalCLim'             1
        'LegendPos'              'NorthWest'};

opt= opt_proplistToStruct(varargin{:});
opt= opt_setDefaults(opt, props);


function ai = r8cvv_rget ( mn, a, m, roff, i )

%*****************************************************************************80
%
%% R8CVV_RGET gets row I from an R8CVV.
%
%  Discussion:
%
%    An R8CVV is a "vector of vectors" of R8's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 November 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer MN, the size of the cell array.
%
%    Input, real A(MN), the cell array.
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer ROFF(M+1), the row offsets.
%
%    Input, integer I, the row.
%    1 <= I <= M.
%
%    Output, real AI(NR(I)), the value of A(I,*).
%
  k1 = roff(i) + 1;
  k2 = roff(i+1);
  nv = k2 + 1 - k1;
  ai(1:nv) = a(k1:k2);

  return
end


function DataSet = prtDataGenProstate(prostateFile)
%   prtDataGenIris Read in data from the UCI PROSTATE data file
%
%   DataSet = prtDataGenIris reads in the data from the classic Prostate.UCI
%   file used in many pattern recognition texts and papers. For more
%   information about this data, see the following URL:
%
%   http://lib.stat.cmu.edu/S/Harrell/data/descriptions/prostate.html
%
%   Example:
%
%   ds = prtDataGenProstate;
%   ds.plot;
%
%   See also: prtDataSetClass, prtDataGenBiModal, prtDataGenIris,
%   prtDataGenMary, prtDataGenNoisySinc, prtDataGenOldFaithful,
%   prtDataGenSpiral, prtDataGenUnimodal, prtDataGenUnimodal, prtDataGenXor

%   prtDataGenProstate Read in data from a CSV formatted PROSTATE-like data file
%
% DataSet = prtDataGenProstate; Read in the data from the Prostate.UCI file
% available with the prt and on the web.
%
% DataSet = prtDataGenProstate(ProstateFile);  Read in the CSV formatted,
% file matching the specifications of ProstateFile
% (see: ProstateFile in <<prtRoot>>\data\)
%
% http://lib.stat.cmu.edu/S/Harrell/data/descriptions/prostate.html

if nargin == 0
    prostateFile = fullfile(prtRoot,'dataGen','dataStorage','prostate','prostate.csv');
end

fid = fopen(prostateFile,'r');
%patno,stage,rx,dtime,status,age,wt,pf,hx,sbp,dbp,ekg,hg,sz,sg,ap,bm,sdate
topLineSpec = repmat('%s ',1,18);
%1,3,0.2 mg estrogen,72,alive,75,76,normal activity,0,15,9,heart strain,13.79882813,2,8,0.299987793,0,2778
dataSpec = '%d %d %s %d %s %d %d %s %d %d %d %s %f %d %d %f %d %f';

varNames = textscan(fid,topLineSpec,1,'whitespace',' \b\t""','Delimiter',',');
cellData = textscan(fid,dataSpec,'whitespace',' \b\t"','Delimiter',',');
fclose(fid);

%handle the data
cellData{3} = prostateFixEstrogen(cellData{3});
cellData{3} = cat(1,cellData{3}{:});
[cellData{5},col5Labels] = prtUtilStringsToClassNumbers(cellData{5});
[cellData{8},col8Labels] = prtUtilStringsToClassNumbers(cellData{8});
[cellData{12},col12Labels] = prtUtilStringsToClassNumbers(cellData{12});

targetInd = 5;
featureInd = setdiff(2:length(cellData),targetInd);
Y = cellData{targetInd};
X = double(cat(2,cellData{featureInd}));  %drop the counting var, and the Y
colNames = varNames(featureInd);

varNames = cellfun(@(c)c{1},varNames,'uniformoutput',false);
colNames = varNames(featureInd);

userData = struct('column6IntegerExplanations',{col8Labels},...
    'column10IntegerExplanations',{col12Labels});

DataSet = prtDataSetClass(X,Y,'name','UCI Prostate Data');
DataSet = DataSet.setFeatureNames(colNames);
DataSet.userData = userData;
DataSet = DataSet.setClassNames(col5Labels);

function cellData = prostateFixEstrogen(cellData)
for i = 1:length(cellData)
    switch lower(cellData{i})
        case 'placebo'
            cellData{i} = 0;
        otherwise
            cellData{i} = str2double(cellData{i}(1:3));
    end
end


classdef NodalFieldPrinter < FieldRepresenterPrinter

    properties (Access = private)
        nodes
    end

    methods (Access = public)

        function obj = NodalFieldPrinter(cParams)
            obj.init(cParams);
            obj.nodes(:,1) = 1:size(obj.fieldValues,1);
        end

        function printResultsLineHeader(obj)
            iD = obj.fileID;
            fN = obj.fieldName;
            sC = obj.simulationStr;
            it = obj.iter;
            fT = obj.fieldType;
            rL = obj.fieldPosition;
            fprintf(iD,'\nResult "%s" "%s" %.0f %s %s\n',fN,sC,it,fT,rL);
        end

        function printFieldLines(obj)
            iD = obj.fileID;
            pformat = ['%6.0f ',repmat('%12.5d ',1,obj.nComp),' \n'];
            printV  = [obj.nodes, obj.fieldValues]';
            fprintf(iD,pformat,printV);
        end

    end

     methods (Access = private)

        function init(obj,d)
            fieldsNames = fieldnames(d);
            for ifield = 1:length(fieldsNames)
                ifieldName = fieldsNames{ifield};
                fieldValue = d.(ifieldName);
                obj.(fieldsNames{ifield}) = fieldValue;
            end
        end

     end

end


%SETFEATSIZE Fixed mapping, (re)set the feature size of a dataset
%
%   A = SETFEATSIZE(A,FEATSIZE)
%   A = A*SETFEATSIZE([],FEATSIZE)
%   A = A*SETFEATSIZE(FEATSIZE)
%
% INPUT
%   A         Dataset
%   FEATSIZE  Feature size vector, default: scalar with actual featsize
%
% OUTPUT
%   A         Dataset
%
% DESCRIPTION
% By default the feature size of a dataset is its number of features, i.e.
% the number of columns in the DATA field of A. If the features are samples
% of a multi-dimensional data item, e.g. the pixels of an image, the
% original size of this data item may be stored in FEATSIZE. The product of
% all elements in FEATSIZE has to be equal to the number of columns in the
% DATA field of A.
%
% This routine is particulary useful as A = A*SETFEATSIZE to remove image
% size settings for the feature size.
%
% There is a low level version of this routine with the same name in the
% PRDATASET directory.
%
% SEE ALSO (PRTools Guide)
% DATASETS, MAPPINGS

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com

function out = setfeatsize(varargin)

  varargin = shiftargin(varargin,'double');
  argin = setdefaults(varargin,[],[]);
  if mapping_task(argin,'definition')
    out = define_mapping(argin,'fixed')
  else
    % this will not happen. prmap directly jumps to @prdataset/setfeatsize
    [a,featsize] = deal(argin{:});
    if isempty(featsize)
      featsize = prod(getfeatsize(a));
    end
    out = setfeatsize(a,featsize);
  end


%% Test Problems for SEDUMI Interface
clc
clear

%Check SEDUMI is available
if(~checkSolver('sedumi',0))
    fprintf(2,'\n\nSEDUMI IS NOT AVAILABLE, NO SEDUMI TESTS CAN BE RUN\n\n');
    return;
end

files = {'sdp_truss1.mat','sdp_truss2.mat','sdp_truss3.mat','sdp_truss4.mat','sdp_hinf01.mat',...
         'sdp_hinf02.mat','sdp_hinf03.mat','sdp_hinf04.mat','sdp_arch0.mat','sdp_arch2.mat',...
         'sdp_arch4.mat','sdp_qap05.mat','sdp_qap06.mat','sdp_qap07.mat','sdp_qap08.mat',...
         'sdp_mcp100.mat','sdp_mcp124-1.mat','sdp_mcp124-2.mat','sdp_mcp124-3.mat','sdp_mcp124-4.mat',...
         'sdp_mcp250-1.mat','sdp_mcp250-2.mat','sdp_mcp250-3.mat','sdp_mcp250-4.mat'};

len = length(files);
cfval = zeros(len,1);
sfval = zeros(len,1);
optsC = optiset('solver','csdp','maxtime',15);
optsS = optiset('solver','sedumi','maxtime',15);

fprintf('SEDUMI SDP Checking\n');
%For each problem
for i = 1:len
    %Read In Problem
    prob = sdpRead(files{i});
    %Solve
    fprintf('Running Problem %s....',files{i});
    [~,cfval(i)] = solve(opti(prob,optsC));
    [~,sfval(i)] = solve(opti(prob,optsS));
    fprintf(' Done\n');
end

%Display fvals
display([cfval sfval])
if(norm(cfval-sfval) > 1e-1)
    error('Failed SeDuMi Checking');
else
    fprintf('Passed SeDuMi Checking\n');
end

% %% Complex Checking
% % Create a positive (semi)definite matrix:
% R=randn(5)+j*randn(5); R=R*R';
% % Make sure it's Hermitian:
% R=(R+R')/2;
%
% % Primal formulation
% clear At b c K
% c=vec(eye(5));
% At=vec(R);
% b=1;
% K.s=5;
% K.scomplex=1;
%
% [x,y,info]=sedumi(At,b,c,K);
%
% % Normed eigenvector:
% e=x(1:5)/norm(x(1:5));
% % Verify the eigenvalue
% [real(e'*R*e), max(eig(R))]


function SavePTS(pts, ptsPath)
fPTS = fopen(ptsPath, 'w');
numPoints = size(pts, 1);
fprintf(fPTS, 'version: 1.0\r\nn_points: %d\r\n{\r\n', numPoints);
for j = 1 : numPoints
    fprintf(fPTS, '%f %f\r\n', pts(j, 1), pts(j, 2));
end
fprintf(fPTS, '}\r\n');
fclose(fPTS);
end


function test_triangulation_test ( )

%*****************************************************************************80
%
%% TEST_TRIANGULATION_TEST tests the TEST_TRIANGULATION library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 April 2009
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_TRIANGULATION_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TEST_TRIANGULATION library.\n' );

  test_triangulation_test01 ( );
  test_triangulation_test02 ( );
  test_triangulation_test03 ( );
% test_triangulation_test04 ( );
  test_triangulation_test05 ( );
  test_triangulation_test06 ( );
  test_triangulation_test07 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_TRIANGULATION_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function p03_default ( dim_num )

%*****************************************************************************80
%
%% P03_DEFAULT sets default values for problem 03.
%
%  Discussion:
%
%    If a problem uses vector parameters, then the spatial dimension
%    DIM_NUM is needed as input, so that the vector parameters can be
%    properly dimensioned.
%
%    Every problem keeps a count of the number of function calls.  Calling
%    this routine causes that count to be reset to 0.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
  i4 = 0;
  p03_i4 ( 'D', '*', i4 );

  return
end


function [wordnet, counts] = findsenses(D, name)
%
% Looks at the wordnet field in D and return all the different senses that
% are returned when using 'name' for query.
%
% Example:
%  wordnet = findsenses(D, 'screen-device');
%    shutter. blind, screen. protective covering, protective cover, protection. covering. artifact, artefact. whole, unit. object, physical object. physical entity. entity.
%    windshield, windscreen. screen. protective covering, protective cover, protection. covering. artifact, artefact. whole, unit. object, physical object. physical entity. entity.
%
%  wordnet = findsenses(D, 'screen+device');
%    computer screen, computer display. screen, CRT screen. display, video display. electronic device. device. instrumentality, instrumentation. artifact, artefact. whole, unit. object, physical object. physical entity. entity.
%    screen, CRT screen. display, video display. electronic device. device. instrumentality, instrumentation. artifact, artefact. whole, unit. object, physical object. physical entity. entity.

if nargin == 2
    D = LMquery(D, 'object.synset', name);
end

Nannotations = length(D);

wordnet = [];
for i = 1:Nannotations
    if isfield(D(i).annotation, 'object')
        if isfield(D(i).annotation.object, 'synset')
            N = length(D(i).annotation.object);
            wordnet = [wordnet {D(i).annotation.object(:).synset}];
        end
    end
end

% Extract unique senses and counts
[wordnet, i, j] = unique(wordnet);
Nsenses = length(wordnet);
[counts, x] = hist(j, 1:Nsenses);


function p=paramsetch(d,q,m,c,t)
%PARAMSETCH update and check parameter values p=(d,q,m,c,t)
% Usage: (1) function x=func(y,q)
%            d=struct('a',1,'b',2,'c',3); % default parameters
%            p=paramsetch(d,q); % update selected parameters
%
%        (2) function x=func(y,q)
%            d=struct('a',1,'b',2,'c',3); % default parameters
%            c={'p.a>0 && p.a<5','p.b>0'};
%            p=paramsetch(d,q,'E',c); % check parameter ranges
%
%        (3) t={'a','description of parameter a';'c','and of parameter c'}
%            p=paramsetch(d,q,'l',c,t); % list values with optional descritions
%
%  Inputs:
%       d  default parameter structure
%       q  new parameter values either a struct or alternatively matrix with
%          each row a different variable in the same order as the fields of d
%       m  mode string: any combination of the following
%           'a' ignore additional fields in q
%           'A' additional fields in q constitute an error
%           'e' print errors but don't exit
%           'E' print errors and exit
%           'l' list fields and their values (default if no output)
%       c  cell array with parameter checking conditions e.g. 'p.a>3' (use p for structure name)
%       t  cell array with descriptive text for each field in a new row. Either in
%          the form t(:,*)={'field' 'description'} or a single column of
%          descriptions in the same order as the fields of d
%
% Outputs:
%       p  output parameter structure
%

%      Copyright (C) Mike Brookes 2017
%      Version: $Id: paramsetch.m 9302 2017-01-18 16:19:20Z dmb $
%
%   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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p=d;   % initialize to the default values
numerr=0; % initialize error count
dn=fieldnames(d);
ndn=length(dn);
dup=zeros(length(dn),1); % update flag for existing fields
% sort out input arguments
if nargin<5
    t={'' ''}; % define an empty description array
    if nargin<4
        c=cell(0); % define an empty check condition array
    end
    if nargin<3
        m='';
        if nargin>=2 && numel(q)>0
        end
    end
end
% now update the selected fields
if nargin>1 && numel(q)>0
    if isstruct(q)
        qn=fieldnames(q);
        addnew=~any(lower(m)=='a');
        adderr=any(m=='A');
        for i=1:length(qn)
            fi=qn{i};
            old=isfield(p,fi);
            if addnew || old
                p.(fi)=q.(fi);
            end
            if old
                dup(find(strcmp(fi,dn),1))=1; % indicate field is updated
            end
            if adderr && ~old
                fprintf(2,'%s is an unknown parameter field\n',fi);
                numerr=numerr+1;
            end
        end

    else
        nq=min(size(q,1),ndn); % number of fields to update
        dup(1:nq)=1; % indicate which fields are updated
        for i=1:nq
            p.(dn{i})=q(i,:);
        end
        if size(q,1)>nq && any(lower(m)=='e')
            fprintf(2,'More than %d parameters specified\n',nq);
            numerr=numerr+1;
        end
    end
end
% Apply parameter checks
if any(lower(m)=='e') && numel(c)>0
    for i=1:numel(c)
        if any(~eval(c{i}))
            numerr=numerr+1;
            fprintf(2,'Parameter check failed: %s\n',c{i});
        end
    end
end
% print out a list of the parameters if requested
if ~nargout || any(m=='l')
    pn=fieldnames(p);
    nf=length(pn);
    st=size(t);
    for i=1:nf
        fi=pn{i};
        vi=p.(fi);
        if i>ndn
            cat='+';
        else
            cat='-'+('*'-'-')*dup(i);
        end
        if st(2)>1
            jti=find(strcmp(fi,t(:,1)),1);
            if ~isempty(jti)
                jti=t{jti,2}; % description string
            end
        elseif i<=st(1)
            jti=t{i,1}; % description string
        else
            jti=[];
        end
        if isnumeric(vi) && length(vi)==numel(vi) && isreal(vi) % can print on one line
            fit=fi;
            if size(vi,1)>1
                fit=[fi ''''];
            end
            fprintf('%3d%c %s =',i,cat,fit);
            fprintf(' %g',vi);
            if isempty(jti)
                fprintf('\n');
            else
                fprintf(' = %s\n',jti);
            end
        else
            fprintf('%3d%c %s =',i,cat,fi);
            if isempty(jti)
                fprintf('\n');
            else
                fprintf(' %s =\n',jti);
            end
            disp(vi);
        end
    end
end
if numerr>0 && any(m=='E')
    error('%d error%c in parameter specification',numerr,(' '+(numerr>1)*('s'-' ')));
end


% pop_crossf() - Return estimates and plots of event-related spectral coherence
%
% Usage:
%       >> pop_crossf(EEG, typeproc, num1, num2, tlimits,cycles,
%                                 'key1',value1,'key2',value2, ... );
% Inputs:
%   INEEG    - Input EEG dataset
%   typeproc - Type of processing:
%                  1 = process two raw-data channels,
%                  0 = process two ICA components
%   num1     - First component or channel number
%   num2     - Second component or channel number
%   tlimits  - [mintime maxtime] Sub-epoch time limits in ms
%   cycles   -   >0 -> Number of cycles in each analysis wavelet
%                 0 -> Use FFTs (with constant window length)
%
% Optional inputs: As for crossf().  See >> help crossf
%
% Outputs: Same as crossf(). No outputs are returned when a
%          window pops-up to ask for additional arguments
%
% Author: Arnaud Delorme, CNL / Salk Institute, 11 March 2002
%
% See also: timef(), eeglab()

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

% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm

function varargout = pop_crossf(EEG, typeproc, num1, num2, tlimits, cycles, varargin );

varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
	help pop_crossf;
	return;
end;
lastcom = [];
if nargin < 3
	popup = 1;
else
	popup = isstr(num1) | isempty(num1);
	if isstr(num1)
		lastcom = num1;
	end;
end;

% pop up window
% -------------
if popup
	[txt vars] = gethelpvar('timef.m');

	geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]};
    uilist = { { 'Style', 'text', 'string', fastif(typeproc, 'First channel number', 'First component number'), 'fontweight', 'bold'  } ...
			   { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ...
			   { 'Style', 'text', 'string', fastif(typeproc, 'Second channel number', 'Second component number'), 'fontweight', 'bold'  } ...
			   { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],'2') } {} ...
			   { 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ...
				 'tooltipstring', 'Sub epoch time limits' } ...
			   { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ...
			   { 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ...
				 'tooltipstring', context('cycles',vars,txt) } ...
			   { 'Style', 'edit', 'string', getkeyval(lastcom,6,[],'3 0.5') } {} ...
			   { 'Style', 'text', 'string',  '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ...
				 'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ...
					'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ...
			   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ...
			   { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ...
				 'tooltipstring', context('alpha',vars,txt) } ...
			   { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ...
			   { 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ...
				 'tooltipstring', 'See crossf() help via the Help button on the right...' } ...
			   { 'Style', 'edit', 'string', '''padratio'', 4' } ...
			   { 'Style', 'pushbutton', 'string', 'Help', 'callback',  'pophelp(''crossf'');' } ...
			   {} ...
			   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...
				 'Plot coherence amplitude', 'tooltipstring', ...
				 'Plot coherence ampltitude image in the upper panel' } ...
			   { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',0), 'string', ...
				 'Plot coherence phase', 'tooltipstring', ...
				 'Plot coherence phase image in the lower panel' } ...
			 };

	result = inputgui( geometry, uilist, 'pophelp(''pop_crossf'');', ...
					   fastif(typeproc, 'Plot channel cross-coherence -- pop_crossf()', ...
							  'Plot component cross-coherence -- pop_crossf()'));
	if length( result ) == 0 return; end;

	num1     = eval( [ '[' result{1} ']' ] );
	num2     = eval( [ '[' result{2} ']' ] );
	tlimits	 = eval( [ '[' result{3} ']' ] );
	cycles	 = eval( [ '[' result{4} ']' ] );
    if result{5}
    	options = [',''type'', ''coher''' ];
    else
		options = [',''type'', ''phasecoher''' ];
    end;

    % add topoplot
    % ------------
	if isfield(EEG.chanlocs, 'theta')
        if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
		if typeproc == 1
			options = [options ', ''topovec'', [' int2str([num1 num2]) ...
                       '], ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
		else % typeproc == 0
			options = [options ', ''topovec'', EEG.icawinv(:, [' int2str([num1 num2]) ...
                       '])'', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
		end;
	end;

    % add title
    % ---------
	if isempty( findstr(  'title', result{7}))
        if ~isempty(EEG.chanlocs) & typeproc
            chanlabel1 = EEG.chanlocs(num1).labels;
            chanlabel2 = EEG.chanlocs(num2).labels;
        else
            chanlabel1 = int2str(num1);
            chanlabel2 = int2str(num2);
        end;
		if result{5}
            options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
					' Coherence'''];
        else
            options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
					' Phase Coherence''' ];
		end;
	end;
	if ~isempty( result{6} )
		options      = [ options ', ''alpha'',' result{6} ];
	end;
	if ~isempty( result{7} )
		  options = [ options ',' result{7} ];
	end;
	if ~result{8}
		options = [ options ', ''plotersp'', ''off''' ];
	end;
	if ~result{9}
		options = [ options ', ''plotphase'', ''off''' ];
	end;
    figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
	options = [ ',' vararg2str(varargin) ];
end;

% compute epoch limits
% --------------------
if isempty(tlimits)
	tlimits = [EEG.xmin, EEG.xmax]*1000;
end;
pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));
pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));
pointrange = [pointrange1:pointrange2];

% call function sample either on raw data or ICA data
% ---------------------------------------------------
if typeproc == 1
	tmpsig1 = EEG.data(num1,pointrange,:);
	tmpsig2 = EEG.data(num2,pointrange,:);
else
	if ~isempty( EEG.icasphere )
        tmpsig1 = eeg_getdatact(EEG, 'component', num1, 'samples', pointrange);
        tmpsig2 = eeg_getdatact(EEG, 'component', num2, 'samples', pointrange);
	else
		error('You must run ICA first');
	end;
end;
tmpsig1 = reshape( tmpsig1, 1, size(tmpsig1,2)*size(tmpsig1,3));
tmpsig2 = reshape( tmpsig2, 1, size(tmpsig2,2)*size(tmpsig2,3));

% outputs
% -------
outstr = '';
if ~popup
    for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
    if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;

% plot the datas and generate output command
% --------------------------------------------
if length( options ) < 2
    options = '';
end;
varargout{1} = sprintf('figure; pop_crossf( %s, %d, %d, %d, [%s], [%s] %s);', ...
          inputname(1), typeproc, num1, num2, int2str(tlimits), num2str(cycles), options);

%options = [ options ', ''ydir'', ''norm''' ];
com = sprintf( '%s crossf( tmpsig1, tmpsig2, length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);
eval(com)

return;

% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
	loc = strmatch( var, allvars);
	if ~isempty(loc)
		txt= alltext{loc(1)};
	else
		disp([ 'warning: variable ''' var ''' not found']);
		txt = '';
	end;


%GOBJ_POINT Create point geometry object.
%
%   [ GOBJ ] = GOBJ_POINT( P, TAG ) Creates a point
%   geometry object. Accepts the following input parameters.
%
%       Parameter   Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       p           array  {[0,0]}            Coordinates of point
%       tag         string {P1}               Geometry object tag/name

% Copyright 2013-2022 Precise Simulation, Ltd.


T_10 = readtable('/Users/lbasek/image-denoising-benchmark/results/final_results_sigma10.csv');
T_10(:,'WNNM') = [];
T_10(:,'NCSR') = [];

T_15 = readtable('/Users/lbasek/image-denoising-benchmark/results/final_results_sigma15.csv');
T_15(:,'WNNM') = [];
T_15(:,'NCSR') = [];

T_20 = readtable('/Users/lbasek/image-denoising-benchmark/results/final_results_sigma20.csv');
T_20(:,'WNNM') = [];
T_20(:,'NCSR') = [];

T_25 = readtable('/Users/lbasek/image-denoising-benchmark/results/final_results_sigma25.csv');
T_25(:,'WNNM') = [];
T_25(:,'NCSR') = [];

T_50 = readtable('/Users/lbasek/image-denoising-benchmark/results/final_results_sigma50.csv');
T_50(:,'WNNM') = [];
T_50(:,'NCSR') = [];

ssim_row_10 = T_10(3,:);
ssim_row_15 = T_15(3,:);
ssim_row_20 = T_20(3,:);
ssim_row_25 = T_25(3,:);
ssim_row_50 = T_50(3,:);

x = [0,10,15,20,25,50];

bm3d_10 = ssim_row_10{1,3};
bm3d_15 = ssim_row_15{1,3};
bm3d_20 = ssim_row_20{1,3};
bm3d_25 = ssim_row_25{1,3};
bm3d_50 = ssim_row_50{1,3};

ksvd_10 = ssim_row_10{1,4};
ksvd_15 = ssim_row_15{1,4};
ksvd_20 = ssim_row_20{1,4};
ksvd_25 = ssim_row_25{1,4};
ksvd_50 = ssim_row_50{1,4};

foe_10 = ssim_row_10{1,5};
foe_15 = ssim_row_15{1,5};
foe_20 = ssim_row_20{1,5};
foe_25 = ssim_row_25{1,5};
foe_50 = ssim_row_50{1,5};

epll_10 = ssim_row_10{1,6};
epll_15 = ssim_row_15{1,6};
epll_20 = ssim_row_20{1,6};
epll_25 = ssim_row_25{1,6};
epll_50 = ssim_row_50{1,6};

y1 = [ssim_row_10{1,2}, bm3d_10,bm3d_15,bm3d_20,bm3d_25,bm3d_50];
y2 = [ssim_row_10{1,2}, ksvd_10,ksvd_15,ksvd_20,ksvd_25,ksvd_50];
y3 = [ssim_row_10{1,2}, foe_10,foe_15,foe_20,foe_25,foe_50];
y4 = [ssim_row_10{1,2}, epll_10,epll_15,epll_20,epll_25,epll_50];

h = figure;
hold on
h1 = plot(x,y1,'-s','MarkerSize',10);
h2 = plot(x,y2,'-s','MarkerSize',10);
h3 = plot(x,y3,'-s','MarkerSize',10);
h4 = plot(x,y4,'-s','MarkerSize',10);
hold off
set([h1,h2,h3,h4],'LineWidth',2)
ylabel('SSIM')
xlabel('Noise Power')
legend('BM3D','KSVD','FOE','EPLL');
grid on
saveas(h,'./graphs/ssim','png');


function [ colptr, rowind ] = hb_structure_read ( input_unit, ncol, mxtype, ...
  nnzero, neltvl, ptrcrd, ptrfmt, indcrd, indfmt )

%*****************************************************************************80
%
%% HB_STRUCTURE_READ reads the structure of an HB matrix.
%
%  Discussion:
%
%    The user should already have opened the file, and positioned it
%    to just after the header records.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 April 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992.
%
%  Parameters:
%
%    Input, integer INPUT_UNIT, the unit from which data is read.
%
%    Input, integer NCOL, the number of columns.
%
%    Input, character ( len = 3 ) MXTYPE, the matrix type.
%    First character is R for Real, C for complex, P for pattern only.
%    Second character is S for symmetric, U for unsymmetric, H for
%      Hermitian, Z for skew symmetric, R for rectangular.
%    Third character is A for assembled and E for unassembled
%      finite element matrices.
%
%    Input, integer NNZERO.  In the case of assembled sparse matrices,
%    this is the number of nonzeroes.  In the case of unassembled finite
%    element matrices, in which the right hand side vectors are also
%    stored as unassembled finite element vectors, this is the total
%    number of entries in a single unassembled right hand side vector.
%
%    Input, integer NELTVL, the number of finite element matrix entries,
%    set to 0 in the case of assembled matrices.
%
%    Input, integer PTRCRD, the number of pointer records.
%
%    Input, character ( len = 16 ) PTRFMT, the format for reading pointers.
%
%    Input, integer INDCRD, the number of index records.
%
%    Input, character ( len = 16 ) INDFMT, the format for reading indices.
%
%    Output, integer COLPTR(NCOL+1), COLPTR(I) points to the location of
%    the first entry of column I in the sparse matrix structure.
%
%    Output, integer ROWIND(NNZERO) or ROWIND(NELTVL), the row index of
%    each item.
%
  [ p, code, w, m ] = s_to_format ( ptrfmt );

  if ( mxtype(3) == 'A' )
    line_num = 1 + floor ( ( ( ncol + 1 ) - 1 ) / p );
  else
    line_num = 1 + floor ( ( ( ncol     ) - 1 ) / p );
  end

  jhi = 0;

  for i = 1 : line_num
    line = fgetl ( input_unit );
    jlo = jhi + 1;
    if ( mxtype(3) == 'A' )
      jhi = min ( jlo + p - 1, ncol + 1 );
    else
      jhi = min (  jlo + p - 1, ncol );
    end

    khi = 0;

    for j = jlo : jhi
      klo = khi + 1;
      khi = min ( klo + w - 1, length ( line ) );
      s = line(klo:khi);
      colptr(j) = s_to_i4 ( s );
    end

  end

  if ( mxtype(3) == 'A' )

    [ p, code, w, m ] = s_to_format ( indfmt );

    line_num = 1 + floor ( ( nnzero - 1 ) / p );

    jhi = 0;

    for i = 1 : line_num
      line = fgetl ( input_unit );
      jlo = jhi + 1;
      jhi = min ( jlo + p - 1, nnzero );

      khi = 0;

      for j = jlo : jhi
        klo = khi + 1;
        khi = min ( klo + w - 1, length ( line ) );
        s = line(klo:khi);
        rowind(j) = s_to_i4 ( s );
      end

    end

  elseif ( mxtype(3) == 'E' )

    [ p, code, w, m ] = s_to_format ( indfmt );
    number = colptr(ncol) - colptr(1);
    line_num = 1 + floor ( ( number - 1 ) / p );

    jhi = 0;

    for i = 1 : line_num
      line = fgetl ( input_unit );
      jlo = jhi + 1;
      jhi = min ( jlo + p - 1, number );

      khi = 0;

      for j = jlo : jhi
        klo = khi + 1;
        khi = min ( klo + w - 1, length ( line ) );
        s = line(klo:khi);
        rowind(j) = s_to_i4 ( s );
      end

    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'HB_STRUCTURE_READ - Fatal error!\n' );
    fprintf ( 1, '  Illegal value of MXTYPE(3).\n' );
    return

  end

  return
end


function p20_default ( dim_num )

%*****************************************************************************80
%
%% P20_DEFAULT sets default values for problem 20.
%
%  Discussion:
%
%    If a problem uses vector parameters, then the spatial dimension
%    DIM_NUM is needed as input, so that the vector parameters can be
%    properly dimensioned.
%
%    Every problem keeps a count of the number of function calls.  Calling
%    this routine causes that count to be reset to 0.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
  i4 = 0;
  p20_i4 ( 'D', '*', i4 );

  r8 = 0.0;
  p20_r8 ( 'D', '*', r8 );

  return
end


function [Conn peaks] = hlp_filterConns(Conn, varargin)
%
% Apply a set of selection rules to a connectivity matrix
%
% Inputs:
%
%   Conn        Connectivity structure with subfields Conn.(connmethod)
%               containing [nchs x nchs x num_freqs x num_times]
%               connectivity matrices
%
% Optional:
%
%       'connThresh'    [real]. Absolute thresholding to apply after
%                               significance thresholding. Can be be a
%                               scalar or a matrix of same size as
%                               EEG.CAT.Conn.(connmethod). Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
%       'prcThresh'     -     [real] The upper percent [1-100] of filtered
%                             connections to keep {def: 100}
%       'method'              cell array of dimensionality reduction methods to apply in a specified order. e.g.,
%                             {'freq','net','time','peak'} will first integrate over freq, then find peak over time.
%                             If method is a string, then this is taken to be the compression global dimension reduction
%                             method applied to all dims in the order {'time','freq',...}.
%                             allowed methods:  'mean', 'net', 'peak', 'getrange'
%        ...
%

% Outputs:
%
%   Conn        filtered connectivity structure
%   peaks       frequency peaks (if method = 'peak')
%
% See Also: est_mvarConnectivity()
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift/
%
%
% Author: Tim Mullen 2008, 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% ----------------------------------------------------------
% TODO:
% need to provide ability to specify order in which dim-compression
% methods are applied. e.g., {3,'net',4,'peak'} would first
% integrate over the third dimension (frequency) and then find the peaks
% over the 4th dim (time)
% ONE OPTION:  allow 'method' = a cell array as above
% ----------------------------------------------------------
% Key point, need to have EEG.CAT.dims = {'chans','chans','freq','times'}
% or some such...
%

if nargin<1
    help hlp_filterConns;
    return;
end

% parse inputs
g = finputcheck(varargin,...
   {'connmethods', ''          {}          {}; ...      % cell array of connectivity method names. If empty, we use all of them
    'connThresh'   ''          []          0; ...       % absolute thresholding to apply after significance thresholding. can be a scalar or a matrix of same size as EEG.CAT.C. Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
    'prcThresh'    'real'      [eps 100]   100;...      % top percentile of connections to keep
    'frange'       'real'      []          [];...       % same units as Conn.freqs
    'trange'       'real'      []          [];...       % same units as EEG.CAT.times
    'sigThresh'    ''          []          [];...       % can be a scalar or a matrix of same size as EEG.CAT.C. Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
    'badchans'     'integer'   []          [];...
    'method'       ''          ''          '';...       % cell array of dimensionality reduction methods to apply in a specified order.
                                                        % e.g. {'freq','net','time','peak'} will first integrate over freq, then find peak over time.
                                                        % If method is a string, then this is taken to be the compression global dimension reduction
                                                        % method applied to all dims in the order {'time','freq',...}
                                                        % Allowed compression methods are:
                                                        % 'net'         (integrate)
                                                        % 'mean'        (average)
                                                        % 'peak'        (1-D peak search along given dim)
                                                        % 'peak2d'      (2-D peak search)
                                                        % 'getrange'    (extract a data range from given dimension)
                                                        % 'maxmag'      (1-D max magnitude (max of absval) along given dimension)
                                                        % 'max'         (1-D max along given dimension)
                                                        % 'min'         (1-D min along given dimension)

    'peakWidth'    'integer'   []          2;...
    'chanlocs'     ''          []          [];...
    'distRad'      'real'      []          [];...
    'strictRad'    'boolean'   []          1;...
    'metric',      'string'    []          'manhattan';...
    'diags',       'string'    {'off','on'} 'on'; ...
    'freqdim',     'real'      []          []; ...
    'timedim',     'real'      []          []; ...
    'verb',        'boolean'   []          1; ...
    },'hlp_filterConns','error','quiet');

if ischar(g)
    error(g);
end

if isempty(g.connmethods)
    g.connmethods = hlp_getConnMethodNames(Conn);
end

nmethods = 3;

if ~isempty(g.timedim)
    timedim = g.timedim;
elseif isfield(Conn,'dims')
    timedim=find(ismember_bc(Conn.dims,'time'));
else
    timedim = [];
end

if ~isempty(g.freqdim)
    freqdim = g.freqdim;
elseif isfield(Conn,'dims')
    freqdim=find(ismember_bc(Conn.dims,'freq'));
else
    freqdim = [];
end

if isempty(freqdim)
    if g.verb
        disp('warning: no ''freq'' entry found in Conn.dims -- assuming dim 3');
    end
    freqdim = 3;
end
if isempty(timedim)
    if g.verb
        disp('warning: no ''time'' entry found in Conn.dims -- assuming dim 4');
    end
    timedim = 4;
end

if ischar(g.method),
    ONEMETHOD = true;
    g.method = {'time',g.method,'freq',g.method};
else
    ONEMETHOD = false;
end

if isempty(g.frange)
    g.frange = [Conn.freqs(1) Conn.freqs(end)];
end

if isempty(g.trange)
    g.trange = [Conn.erWinCenterTimes(1) Conn.erWinCenterTimes(end)];
end

if length(Conn.freqs)==1
    Conn.freqs = repmat(Conn.freqs,1,2);
end

if length(Conn.erWinCenterTimes)==1
    Conn.erWinCenterTimes = repmat(Conn.erWinCenterTimes,1,2);
    Conn.winCenterTimes = repmat(Conn.winCenterTimes,1,2);
end

if isnan(g.frange)
    g.frange = [];
end

if isnan(g.trange)
    g.trange = [];
end

frangeidx = getindex(Conn.freqs,g.frange);
trangeidx = getindex(Conn.erWinCenterTimes,g.trange);

for m=1:length(g.connmethods)
    connmethod = g.connmethods{m};

    if length(size(Conn.(connmethod)))>5
        error('Connectivity Matrix cannot be greater than 4-D!');
    end

    C = Conn.(connmethod);  % make copy of connectivity matrix

    % apply significance thresholding
    if ~isempty(g.sigThresh)
        if islogical(g.sigThresh) && isequal(size(C),size(g.sigThresh))
            C(~g.sigThresh)=0;
        else
            C(C<g.sigThresh) = 0;
        end
    end

    if ~all(cellfun(@isempty,g.method(2:2:end))) && ~strcmpi(g.method{2},'thresh')
        if ~isempty(g.trange) && ~isempty(g.frange) && ONEMETHOD && isequal(g.method{2},'peak2d')
            % apply 2D peak identification
            if g.verb
                fprintf('applying method=%s to dim=%s and %s\n',g.method{2},g.method{1},g.method{3});
            end
            C = collapseDim(C,'dim',4,'range',trangeidx, ...
                'method','getrange');     % extract time range
            C = collapseDim(C,'dim',3,'range',frangeidx, ...
                'method','getrange');     % extract freq range
            [C peaks] = collapseDim(C,'dim',4,'range',[], 'method','peak2d', ...
                'peakWidth',g.peakWidth,'minpeakheight',g.connThresh); % find peaks
        else

            for mm=1:2:length(g.method)

                curmethod = g.method{mm};

                if ~ismember_bc(curmethod,{'time','freq'})
                    error('unknown method %s',curmethod);
                end

                % collapse time dim
                if ~isempty(g.trange) && (isequal(curmethod,'time'))
                    if g.verb
                        fprintf('applying method=%s to dim=%s\n',g.method{mm+1},g.method{mm});
                    end
                    [C peaks.times] = collapseDim(C,'dim',timedim,...
                        'range',trangeidx,'method',g.method{mm+1},...
                        'dx',Conn.erWinCenterTimes(2)-Conn.erWinCenterTimes(1),'peakWidth',g.peakWidth, ...
                        'minpeakheight',g.connThresh);
                end

                % collapse freq dim
                if ~isempty(g.frange) && (isequal(curmethod,'freq'))
                    if g.verb
                        fprintf('applying method=%s to dim=%s\n',g.method{mm+1},g.method{mm});
                    end
                    [C peaks.freqs] = collapseDim(C,'dim',freqdim,...
                        'range',frangeidx,'method',g.method{mm+1},...
                        'dx',Conn.freqs(2)-Conn.freqs(1),'peakWidth',g.peakWidth, ...
                        'minpeakheight',g.connThresh);
                end

            end

        end
    end

    sz=size(C);
    if all(sz(3:end)==1)
        C = squeeze(C);
    end

    % remove diagonals
    if strcmpi(g.diags,'off')
        for q=1:size(C,3)
            C(:,:,q)=C(:,:,q).*~eye(size(C(:,:,q)));
        end
    end

    % apply connectivity threshold
    if g.connThresh
        C(C<g.connThresh) = 0;
    end

    % apply percentile threshold
    if ~isempty(g.prcThresh) && g.prcThresh<100
        % get specified percentile
        prc = prctile(C(:),100-g.prcThresh);
        C(C<prc)=0;
    end

    Conn.(connmethod) = C;

end

if ~isempty(frangeidx) && size(C,3)==1
    % frequency dimension has been collapsed
    % replace with median frequency within collapsed interval
    Conn.collapsedFreqs = Conn.freqs(frangeidx(1):frangeidx(end));
    Conn.freqs          = median(Conn.collapsedFreqs);
else
    Conn.freqs          = Conn.freqs(frangeidx(1):frangeidx(end));
end

if ~isempty(trangeidx) &&size(C,4)==1
    % time dimension has been collapsed
    % replace with median time point within collapsed interval
    Conn.collapsedTimes     = Conn.erWinCenterTimes(trangeidx(1):trangeidx(end));
    Conn.erWinCenterTimes   = median(Conn.collapsedTimes);
    Conn.winCenterTimes     = median(Conn.winCenterTimes(trangeidx(1):trangeidx(end)));
else
    Conn.erWinCenterTimes   = Conn.erWinCenterTimes(trangeidx(1):trangeidx(end));
    Conn.winCenterTimes     = Conn.winCenterTimes(trangeidx(1):trangeidx(end));
end


function SaveBinary(filename,data,varargin)

%SaveBinary - Save data in a multiplexed binary file.
%
%  USAGE
%
%    SaveBinary(filename,data,<options>)
%
%    filename       file to save to
%    data           data to save
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'precision'   sample precision (default = 'int16')
%     'mode'        either 'new' to create a new file (default) or 'append'
%                   to add to an existing file
%    =========================================================================

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

% Default values
% precision = 'int16'; % THIS SHOULD NEVER BE ASSUMED
precision = class(data);
mode = 'new';

if nargin < 2 | mod(length(varargin),2) ~= 0,
  error('Incorrect number of parameters (type ''help SaveBinary'' for details).');
end

% Parse options
for i = 1:2:length(varargin),
  if ~ischar(varargin{i}),
    error(['Parameter ' num2str(i+3) ' is not a property (type ''help SaveBinary'' for details).']);
  end
  switch(lower(varargin{i})),
    case 'precision',
      precision = varargin{i+1};
      if ~isstring_FMAT(precision),
        error('Incorrect value for property ''precision'' (type ''help SaveBinary'' for details).');
      end
    case 'mode',
      mode = lower(varargin{i+1});
      if ~isstring_FMAT(mode,'new','append'),
        error('Incorrect value for property ''mode'' (type ''help SaveBinary'' for details).');
      end
    otherwise,
      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help SaveBinary'' for details).']);
  end
end

sizeInBytes = 0;
switch precision,
	case {'uchar','unsigned char','schar','signed char','int8','integer*1','uint8','integer*1'},
		sizeInBytes = 1;
	case {'int16','integer*2','uint16','integer*2'},
		sizeInBytes = 2;
	case {'int32','integer*4','uint32','integer*4','single','real*4','float32','real*4'},
		sizeInBytes = 4;
	case {'int64','integer*8','uint64','integer*8','double','real*8','float64','real*8'},
		sizeInBytes = 8;
end

if strcmp(mode,'new'),
	f = fopen(filename,'w');
	status = fseek(f,0,'bof');
else
	f = fopen(filename,'a');
	status = fseek(f,0,'eof');
end
if status ~= 0,
	fclose(f);
	error('Could not start writing (possible reasons include insufficient access permissions).');
end

fwrite(f,data',precision);

fclose(f);


function rgb = magenta

% This returns a predefined color as [red green blue] values
%   red               = [255   0   0]/255;
%   green             = [  0 192   0]/255;
%   blue              = [  0   0 255]/255;
%   magenta           = [255 255   0]/255;
%   cyan              = [  0 255 255]/255;
%   yellow            = [255 255   0]/255;
%   white             = [255 255 255]/255;
%   black             = [  0   0   0]/255;
%
%   skull             = [140  85  85]/255
%   cortex            = [255 213 119]/255;
%   cortex_light      = [199 194 169]/255;
%   cortex_dark       = [100  97  85]/255;
%   skin              = [249 223 192]/255;
%   skin_light        = [249 223 192]/255;
%   skin_medium_light = [225 194 158]/255;
%   skin_medium       = [188 142 106]/255;
%   skin_medium_dark  = [155 102	65]/255;
%   skin_dark         = [ 91  71  61]/255;

rgb = [255 0 255]/255;


function y = cvx_isconcave( x, full )
error( nargchk( 1, 2, nargin ) );
if nargin == 2,
    y = ~imag( x );
elseif isreal( x ),
    y = true;
else
    y = nnz(imag(x)) == 0;
end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function [x] = parse(inStr)
% parse is a function which takes in a string vector of blank separated text
% and parses out the individual string items into a n item matrix, one row
% for each string.
%
% function [x] = parse(inStr)
% x     - the return matrix of strings
% inStr - the blank separated string vector

% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% 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 1, 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. A copy of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

sz=size(inStr);
strLen=sz(2);
x=blanks(strLen);
wordCount=1;
last=0;
for i=1:strLen,
  if inStr(i) == ' '
    wordCount = wordCount + 1;
    x(wordCount,:)=blanks(strLen);
    last=i;
  else
    x(wordCount,i-last)=inStr(i);
  end
end


p1 = [3 3 0]';
p2 = [3 3 -2]';
axis([-5 5 -5 5]);
plot


%MAPM Mapping to execute arbitray Matlab function on dataset
%
%    [B,OUT] = MAPM(A,COMMAND,PAR1,PAR2,....)
%    [B,OUT] = A*MAPM([],COMMAND,PAR1,PAR2,....)
%    [B,OUT] = A*MAPM(COMMAND,PAR1,PAR2,....)
%
% INPUT
%    A               Dataset or datafile or double
%    COMMAND         String with function name
%    {PAR1,...}      Cell array with optional parameters for COMMAND
%
% OUTPUT
%    B               Resulting dataset, datafile or double array
%    OUT             (only for datasets or doubles) possible additional
%                    outputs
%
% DESCRIPTION
% On the data in A, the double array A the following command is executed
%
%    [B,OUT] = COMMAND(DATA,PAR1,PAR2,....)
%
% If A is a dataset then B is converted to a similar dataset. If A is a
% cell array, then results are combined into a cell array as well.
%
% This command differs from the similar command FILTM which operates object
% by object (row by row). The COMMAND in MAPM operates on the entire data
% matrix.
%
% EXAMPLES
% argmin = mapm('min')*out2;
% % A*argmin returns for every column the row indices of the minimum
% % A'*argmin returns for every row the column indices of its minimum
%
% nexpm = mapm('uminus')*mapm('exp');
% % A*nexpm returns exp(-A), useful incombination with other commands
%
% SEE ALSO (PRTools Guide)
% DATASETS, DATAFILES, IM2OBJ, DATA2IM, FILTM, FILTIM, OUT2
% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function varargout = mapm(varargin)

  if nargin == 0
    error('No command found')
  end
  varargin = shiftargin(varargin,'char');
  if isempty(varargin{1})
    varargout{1} = prmapping(mfilename,'fixed_cell',varargin(2:end));
    varargout{1} = setname(varargout{1},'AnyMap');
    return
  end

  % now we have: mapm(data,command,pars)
  % data might be dataset, datafile, cell array, double, structure array
  pars = cell(1,nargin-2);     % input pars
  [a,command,pars{:}] = deal(varargin{:}); % use nice names
  if numel(pars) > 1 % allow argument list as cell array or not.
   pars = {pars}
  end
  varargout = cell(1,nargout);

  if isdatafile(a)               % for datafiles processing is stored

    if isempty(getpostproc(a)) & ~ismapping(command)
                                 % as preprocessing (if no postproc defined)
      b = addpreproc(a,command,pars);
    else                         % or as mapping as postprocessing
      v = prmapping(mfilename,'fixed',{command,pars});
      v = setname(v,mapname);
      b = addpostproc(a,v);      % store mapping
    end
    varargout{1} = b;
    return

  elseif isdataset(a) % are executed here

    try
      [varargout{:}] = my_feval(command,a,pars);
    catch me
      [varargout{:}] = my_feval(command,+a,pars);
      if nargout > 0
        if size(varargout{1},1) == size(a,1)
          varargout{1} = setdata(a,varargout{1});
        else
          varargout{1} = prdataset(varargout{1});
          varargout{1} = setuser(varargout{1},getuser(a));
        end
      end
    end

  elseif iscell(a)

    b = cell(size(a));
    varargout = cell(numel(a),numel(varargout));
    n = numel(b);
    s = sprintf('Processing %i objects: ',n);
    prwaitbar(n,s);
    for i=1:n
      prwaitbar(n,i,[s int2str(i)]);
      [varargout{i,:}] = my_feval(command,a{i},pars);
    end
    prwaitbar(0);

  else % doubles

    [varargout{:}] = my_feval(command,a,pars{:});

  end

return

function varargout = my_feval(command,a,pars)
  if nargin < 3, pars = []; end
  varargout = cell(1,nargout);
  if isempty(pars)
    [varargout{:}] = feval(command,a);
  elseif iscell(pars)
    [varargout{:}] = feval(command,a,pars{:});
  else
    [varargout{:}] = feval(command,a,pars);
  end
return


function [err,Loc] = FindChar (C, cfnd)
%
%   [err,Loc] = FindChar (C, cfnd)
%
%Purpose:
%   find certain characters in an array of characters, or a string
%
%
%Input Parameters:
%   C : an array of characters or a string
%   cfnd : the character you'r looking for like 'f'
%   	pass the following for special characters
%		'NewLine', 'Tab', 'Space', 'Comma'
%
%Output Parameters:
%   err : 0 No Problem
%       : 1 Mucho Problems
%   Loc : a vector of the location in C containing cfnd
%      ie any element Loc of C is cnfd. C(Loc) = cfnd
%
%
%More Info :
%
%   example :
%	ks2 = sprintf('d, v h\t\nc c , c d\n vf');
%	[err, Loc] = FindChar(ks2, ',')
% or in the previous case, you could use
%  [err, Loc] = FindChar(ks2, 'Comma')
% or
%  [err, Loc] = FindChar(ks2, 'Tab')
%
% ks2 could be a whole ascii file or a chunk of one, like
% fid = fopen('thisfile','r'); ks2 = fscanf(fid,'%c',100); fclose (fid);
% the previous line reads the 1st 100 characters
% carefull, if you use
% ks2 = fscanf(fid,'%s',100);
% you'll read the first 100 strings (space, tab and newline delimited)
%
% see also
%  SkipMatlabHelp
%  PurgeComments
%	NextString
%
%     Author : Ziad Saad
%     Date : Sat Mar 27 13:42:26 CST 1999

%Define the function name for easy referencing
FuncName = 'FindChar';

%Debug Flag
DBG = 1;

%initailize return variables
err = 1;
Loc = [];

switch cfnd,
	%to find the ascii number for new characters, try
	%	ks2 = sprintf('d, v h\t\n');
	%	ks2num = str2num(sprintf('%d\n',ks2))
	case 'NewLine',
		cfndInt = 10;
	case '\n',
		cfndInt = 10;
	case 'Tab',
		cfndInt = 9;
	case '\t',
		cfndInt = 9;
	case 'Space',
		cfndInt = 32;
	case 'Comma',
		cfndInt = 44;
	otherwise,
		if (length(cfnd) > 1),
			err = ErrEval(FuncName,'Err_Special Character not supported');
			return;
		else
			cfndInt = str2num(sprintf('%d\n',cfnd));
		end
end

%Now find such characters

	Loc = find (C == cfndInt(1));

%that's it, get back

err = 0;
return;


function B = get_reorder(A, idx, dim)
%GET_REORDER    Returns A with one of its dimensions indexed.
%
%   B = GET_REORDER(A, IDX, DIM)
%
%   Returns A(:, ..., :, IDX, :, ..., :), where DIM determines
%   in which dimension to place the IDX.
%
%   See also SET_REORDER.

%   MATPOWER
%   Copyright (c) 2009-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

ndim = ndims(A);
s.type = '()';
s.subs = cell(1, ndim);
for k = 1:ndim
    if k == dim
        s.subs{k} = idx;
    else
        s.subs{k} = ':';
    end
end
B = subsref(A, s);