function [ekg_RSlinB_am_ELF_CtO, ekg_RSlinB_bw_ELF_CtO, ekg_RSlinB_fm_ELF_CtO] = estimate_rr_is(ekg_RSlinB_am_ELF, ekg_RSlinB_bw_ELF, ekg_RSlinB_fm_ELF, up)
% Estimation of respiration rate using multiple methods

subj = 1;
loaded_this_subj_respSigs = 0;
%% Make window timings if necessary
[wins] = identify_subj_wins_is(ekg_RSlinB_am_ELF, ekg_RSlinB_bw_ELF, ekg_RSlinB_fm_ELF, up);
%% Cycle through each resp signal
for respSig_no = 1:3    % 3 input signals
    rel_name = ['ekg_RSlinB_' up.al.options.FMe{respSig_no} '_ELF'];
    for option_no = 1 : length(up.al.options.estimate_rr)
        % Skip if this processing has been done previously
        if strcmp(up.al.options.estimate_rr{option_no}, 'GCE')
            %save_name = [ respSigs{respSig_no}(1:3) '_' up.al.options.estimate_rr{option_no} ];
            save_name = [ rel_name '_' up.al.options.estimate_rr{option_no} ];
        else
            %save_name = [ respSigs{respSig_no} '_' up.al.options.estimate_rr{option_no} ];
            save_name = [ rel_name '_' up.al.options.estimate_rr{option_no} ];
        end
%         savepath = [up.paths.data_save_folder, num2str(subj), up.paths.filenames.rrEsts, '.mat'];
%         exist_log = check_exists(savepath, save_name);
%         if exist_log
%             continue
%         end

%         % load data if it hasn't yet been loaded
%         if ~loaded_this_subj_respSigs
%             % Signals
%             load([up.paths.data_save_folder, num2str(subj), up.paths.filenames.respSigs]);
%             % Window timings
%             load([up.paths.data_save_folder, num2str(subj), up.paths.filenames.win_timings, '.mat']);
%             loaded_this_subj_respSigs = 1;
%         end
        % Identify the relevant respSig data
        eval(['rel_data = ' rel_name ';']);
        % add current subject and resp sig for any methods that do not use a resp sig.
        rel_data.subj = subj;
        rel_data.respSig = rel_name;
        %eval(['rel_data.respSig = ' rel_name ';']); %respSigs{respSig_no};
        %% Calculate RR from this resp sig using each option for estimating RR
        if (length(rel_data.t) == 1 && isnan(rel_data.t)) || sum(isnan(rel_data.v))==length(rel_data.v)
            temp_rr.t = mean([wins.t_start(:)' ; wins.t_end(:)']); temp_rr.t = temp_rr.t(:);
            temp_rr.v = nan(length(temp_rr.t),1);
            [temp_rr.f, temp_rr.p] = deal(cell(length(temp_rr.t),1));
        else
            temp_rr = feval(up.al.options.estimate_rr{option_no}, rel_data, wins, up);
        end
        % store this series of rrs:
        eval([rel_name '_' up.al.options.estimate_rr{option_no} ' = temp_rr;']);

        clear temp_rr
%         %% Save RRs to file
%         save_or_append_data
    end
end

end


function [x,fval,exitflag,info] = opti_cbc(H,f,A,rl,ru,lb,ub,xtype,sos,x0,opts)
%OPTI_CBC Solve a MILP or MIQP using CBC
%
%   min f'*x      subject to:     rl <= A*x <= ru
%    x                            lb <= x <= ub
%                                 for i = 1..n: xi in Z
%                                 for j = 1..m: xj in {0,1}
%
%   x = opti_cbc([],f,A,rl,ru,lb,ub,xtype) solves a MILP where f is the
%   objective vector, A,rl,ru are the linear constraints, lb,ub are the
%   bounds and xtype is a string of integer variables ('C', 'I', 'B')
%
%   x = opti_cbc(H,f,A,rl,ru,lb,ub,xtype) solves a MIQP where H and f are
%   the objective matrix and vector respectively, A,rl,ru are the linear
%   constraints, lb,ub are the bounds and xtype is a string of integer
%   variables ('C', 'I', 'B') [NOT CURRENTLY SUPPORTED]
%
%   x = opti_cbc([H,...,xtype,sos) sos is a structure with fields type,
%   index, weight for SOS.
%
%   x = opti_cbc(H,...,sos,x0) uses x0 to warm start the solver.
%
%   x = opti_cbc(H,...,x0,opts) uses opts to pass cbcset options to the
%   solver.
%
%   [x,fval,exitflag,info] = opti_cbc(...) returns the objective value at
%   the solution, together with the solver exitflag, and an information
%   structure.
%
%   THIS IS A WRAPPER FOR CBC USING THE MEX INTERFACE
%   See supplied Eclipse Public License

%   Copyright (C) 2012 Jonathan Currie (IPL)

t = tic;

% Handle missing arguments
if nargin < 11, opts = optiset; end
if nargin < 10, x0 = []; end
if nargin < 9, sos = []; end
if nargin < 8, xtype = repmat('C',size(f)); end
if nargin < 7, ub = []; end
if nargin < 6, lb = []; end
if nargin < 5, error('You must supply at least 5 arguments to opti_cbc'); end

warn = strcmpi(opts.warnings,'all');

%Add in cbcset settings
if(isfield(opts,'solverOpts') && ~isempty(opts.solverOpts))
    popts = cbcset(opts.solverOpts);
else
    popts = cbcset;
end
%Add in options from optiset
popts.maxnodes = opts.maxnodes;
popts.maxtime = opts.maxtime;
popts.primalTol = opts.tolrfun;
popts.dualTol = opts.tolrfun;
popts.intTol = opts.tolint;
%Add objective bias
if(isfield(opts,'objbias')), popts.objbias = opts.objbias; end
%Setup display level
popts.display = dispLevel(opts.display,1,1);
popts.optiver = optiver;

%Check sparsity
if(~issparse(A))
    if(warn), optiwarn('OPTI:NotSparseA','The A matrix should be sparse, correcting: [sparse(A)]'); end
    A = sparse(A);
end
if(~issparse(H))
    if(~isempty(H) && warn), optiwarn('OPTI:NotSparseH','The H matrix should be sparse, correcting: [sparse(H)]'); end
    H = sparse(H);
end
%Check Sym Tril
if(any(any(triu(H,1) ~= 0)))
    if(warn), optiwarn('OPTI:NotTrilH','The H matrix should be Symmetric TRIL, correcting: [tril(H)]'); end
    H = tril(H);
end
%Check SOS
if(~isempty(sos))
    if(~isstruct(sos) || ~isfield(sos,'type') || ~isfield(sos,'index') || ~isfield(sos,'weight'))
        error('SOS constraints must be a structure with fields ''type'', ''index'' and ''weight''');
    end
    if(length(sos.type) == 1)
        sos.index = {sos.index};
        sos.weight = {sos.weight};
    end
end

%MEX contains error checking
[x,fval,status,iter,cobj] = cbc(H, f, A, rl, ru, lb, ub, xtype, sos, x0, popts);

%Assign Outputs
info.Nodes = iter;
info.AbsGap = abs(cobj-fval);
info.RelGap = abs(cobj-fval)/(1e-1 + abs(fval));
info.Time = toc(t);
info.Algorithm = 'CBC: Branch and Cut using CLP';

switch(status)
    case 0
        info.Status = 'Integer Optimal';
        exitflag = 1;
    case 1
        info.Status = 'Linear Relaxation Infeasible';
        exitflag = -1;
    case 2
        info.Status = 'Gap Reached';
        exitflag = 1;
    case 3
        info.Status = 'Maximum Nodes Reached';
        exitflag = 0;
    case 4
        info.Status = 'Maximum Time Reached';
        exitflag = 0;
    case 5
        info.Status = 'User Exited';
        exitflag = -5;
    case 6
        info.Status = 'Number of Solutions Reached';
        exitflag = 0;
    case 7
        info.Status = 'Linear Relaxation Unbounded';
        exitflag = -2;
	case 8
        info.Status = 'Proven Infeasible';
        exitflag = -1;
    otherwise
        info.Status = 'Unknown Termination';
        exitflag = -3;
end


function colorM = visualRefColormap(maxDose,refDose,numRows,baseStr,topStr)
%Returns the 'visualReference' colormap based on a 'base' colormap baseStr and
%a 'top' colormap topStr.  The base colormap is stretched from 0 to refDose.  Between
%refDose and maxDose (if there are such doses), the colormap follows the colormap
%defined by topStr.  See CERRColormap to see valid colormap strings.
%
%JOD, 16 Jan 03.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%We want to rescale the colormap to an arbitrary number of bins.
%Given the 'visual reference dose', and the fact that we always want a colormap
%with a length of n, then the number of bins up to the visual reference dose are:
%zero dose should map to an index of one.
%D_vr should map to the highest index in the colormap, cM.
%Let m be the number of rows in cM.

%Get base and top unrescaled colormaps
baseM = CERRColorMap(baseStr);
topM  = CERRColorMap(topStr);

doseV = linspace(0,maxDose,numRows);

s = size(baseM,1);
t = size(topM,1);

indexBase = (doseV/refDose) * (s - 1);   %Scale dose from 0 to (s-1)

highIndex = [(doseV/refDose) > 1];

%truncate
indexBase(highIndex) = [];

%now interpolate into the colormap:
baseRescaledM = zeros(length(indexBase),3);
baseRescaledM(:,1) = interp1([0:s-1],baseM(:,1),indexBase)';
baseRescaledM(:,2) = interp1([0:s-1],baseM(:,2),indexBase)';
baseRescaledM(:,3) = interp1([0:s-1],baseM(:,3),indexBase)';

colorM = baseRescaledM;

if any(highIndex)

  topRows = numRows - length(indexBase);
  topRescaledM = zeros(topRows,3);
  indexTop = ((doseV - refDose)/(max(doseV(:)) - refDose)) * (t - 1);  %Scale doses to (t-1)
  indexTop(~highIndex) = [];

  %and the corresponding colormap is
  topRescaledM(:,1) = interp1([0:t-1],topM(:,1),indexTop)';
  topRescaledM(:,2) = interp1([0:t-1],topM(:,2),indexTop)';
  topRescaledM(:,3) = interp1([0:t-1],topM(:,3),indexTop)';

  colorM = [baseRescaledM; topRescaledM];

end

%fini


% Based on https://se.mathworks.com/help/audio/ref/audiodevicereader-system-object.html
clear
clc
close all

% setup
samplingFreq = 8000; % Hz
recordingTime = 10; % s
segmentTime = 0.025; % s
segmentLength = round(segmentTime*samplingFreq);
deviceName = 'Default'; % use getAudioDevices(audioDeviceReader) to see available devices
micChannelNo = 1;

% initialise the recording object
% too see avai
AudioRecObj = audioDeviceReader(...
    'SampleRate', samplingFreq, ...
    'SamplesPerFrame', segmentLength, ...
    'NumChannels', length(micChannelNo), ...
    'Device', deviceName);

%
% AudioRecObj = audioDeviceReader(...
%     'SampleRate', samplingFreq, ...
%     'SamplesPerFrame', segmentLength, ...
%     'NumChannels', length(micChannelNo), ...
%     'Device', deviceName);
% Call setup to reduce the computational load of initialization in an
% audio stream loop.
AudioRecObj.setup();

% make a recording
nSegments = floor(recordingTime/segmentTime);
recordedData = nan(segmentLength, nSegments);
actFrameTimes = nan(1,nSegments);
for ii = 1:nSegments
%     tic
    [recordedSegment, numOverrun] = AudioRecObj();
%     toc
    % here we do some processing
    recordedData(:,ii) = recordedSegment(:);
    pause(0.01)
    % end of processing
    actFrameTimes(ii) = toc;
end
AudioRecObj.release();

%% plotting
figure(1)
plot((1:recordingTime*samplingFreq)'/samplingFreq, recordedData(:))
xlabel('time [s]')
ylabel('value [.]')
title('Recorded signal')

figure(2)
plot((1:nSegments)*segmentTime, cumsum(actFrameTimes),'.')
hold on
plot((1:nSegments)*segmentTime, (1:nSegments)*segmentTime, '--')
hold off
legend('Processed segment time', 'Real-time limit')
xlabel('sample recording time [s]')
ylabel('finished processing a segment [s]')
title('Processing time vs recorded time')


function im = RegdoCheckboard(Im1, Im2, rows, cols)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

    [m n p] = size(Im1);
    classname = class(Im1);
    %Im1 = cast(Im1, classname);
    %Im2 = cast(Im2, classname);

    m1 = fix(m/rows); n1 = fix(n/cols);
    black = zeros(m1, n1, classname);
    white = ones(m1, n1, classname);
    tile = [black white; white black];
    I = repmat(tile, [ceil(m/(2*m1)) ceil(n/(2*n1)) p]);
    c1 = I(1:m, 1:n, 1:p);
    c2 = (1-c1);

    CA_Image = c1.*(Im2) + c2.*(Im1);
    CA_Image(:,:,2) = CA_Image(:,:,1);
    CA_Image(:,:,3) = CA_Image(:,:,1);
    CA_Image = single(CA_Image);

    c1 = single(c1);
    CA_Image = (CA_Image - min(CA_Image(:))) / (max(CA_Image(:))-min(CA_Image(:)));
    CA_Image(:,:,2) = CA_Image(:,:,2) + c1*0.136;
    CA_Image(:,:,3) = CA_Image(:,:,3) + c1*0.136;
    CA_Image = min(CA_Image,1);

%     r = 0.05;
%     frac1 = (max(Im1(:))-min(Im1(:)))*r;
%     frac2 = (max(Im2(:))-min(Im2(:)))*r;
%     CA_Image = c1.*(Im2+frac2) + c2.*(Im1-frac1);

    im = CA_Image;

end


function model = gpsimMapTest

% GPSIMMAPTEST Tests the gradients of the GPSIMMAP model.
% FORMAT
% DESC tests the gradients and log likelihoods of the MAP
% approximation for the GPSIM model.
% RETURN model : the model that was used for testing.
%
% SEEALSO : gpsimMapCreate
%
% COPYRIGHT : Neil D. Lawrence, 2006

% SHEFFIELDML

colordef white
load demBarenco1;
B = model.comp{1}.B;
D = model.comp{1}.D;
S = model.comp{1}.S;
clear model

[y, yvar, gene, times, scale, rawExp, rawVar] = gpsimLoadBarencoData;

numGenes = size(gene, 1);
options = gpsimMapOptions(numGenes);
options.intPoints = 17;
options.B = B;
options.D = D;
options.S = S;

nonLinearities = {'linear', 'quadratic', 'negLogLogit', 'exp', 'sigmoid'};
nonLinearities = {'exp'};
for i = 1:length(nonLinearities)
  options.nonLinearity = nonLinearities{i};
  fprintf('Nonlinearity: %s\n', options.nonLinearity);
  model = gpsimMapCreate(numGenes, 1, times, y{1}, yvar{1}, options);
  params = gpsimMapExtractParam(model);

  model = gpsimMapExpandParam(model, params);

  % Give reasonable values to f.
  f = gsamp(zeros(1, size(model.f, 1)), model.K, 1);
  model = gpsimMapFunctionalExpandParam(model, f);

  gradientCheck(params, 'modelObjective', 'modelGradient', model);

  model.type = 'gpsimMapFunctional';
  f = gpsimMapFunctionalExtractParam(model);
  gradientCheck(f, 'modelObjective', 'modelGradient', model);
  hessianCheck(f, 'modelObjective', 'modelHessian', model);
end


function [x0] = ma_getX0ForEvent(event)
%ma_getX0ForEvent Summary of this function goes here
%   Detailed explanation goes here

    activeVars = event.vars(1,:) == 1;
    switch event.type
        case 'Coast'
            x0 = event.coastToValue(activeVars);
        case 'NBodyCoast'
            x0 = event.coastToValue(activeVars);
        case 'DV_Maneuver'
            dvOrig = event.maneuverValue(activeVars);
            x0 = dvOrig;
        case 'Set_State'
            if(strcmpi(event.subType,'setState'))
                epoch = event.epoch;
                rVect = event.rVect;
                vVect = event.vVect;
                gmu = event.centralBody.gm;

                [sma, ecc, inc, raan, arg, tru] = getKeplerFromState(rVect,vVect,gmu, true);

                x0 = [epoch, sma, ecc, inc, raan, arg, tru];
                x0 = x0(activeVars);
            elseif(strcmpi(event.subType,'estLaunch'))
                x0 = event.launch.launchValue(activeVars);
            end
        otherwise
            error('Unknown event type, could not determine x0 for optimization: %s', event.type);
    end
end


% Simulating Transducer Field Patterns Example
%
% This example demonstrates the use of k-Wave to compute the field pattern
% generated by a curved single element transducer in two dimensions. It
% builds on the Monopole Point Source In A Homogeneous Propagation Medium
% Example.
%
% author: Bradley Treeby
% date: 10th December 2009
% last update: 24th August 2014
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

% This file is part of k-Wave. k-Wave is free software: you can
% redistribute it and/or modify it under the terms of the GNU Lesser
% General Public License as published by the Free Software Foundation,
% either version 3 of the License, or (at your option) any later version.
%
% k-Wave 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 Lesser General Public License for
% more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.

clear all;

% =========================================================================
% SIMULATION
% =========================================================================

% create the computational grid
Nx = 216;           % number of grid points in the x (row) direction
Ny = 216;           % number of grid points in the y (column) direction
dx = 50e-3/Nx;    	% grid point spacing in the x direction [m]
dy = dx;            % grid point spacing in the y direction [m]
kgrid = makeGrid(Nx, dx, Ny, dy);

% define the properties of the propagation medium
medium.sound_speed = 1500;  % [m/s]
medium.alpha_power = 1.5;   % [dB/(MHz^y cm)]
medium.alpha_coeff = 0.75;  % [dB/(MHz^y cm)]

% create the time array
[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);

% define a curved transducer element
source.p_mask = makeCircle(Nx, Ny, 61, 61, 60, pi/2);

% define a time varying sinusoidal source
source_freq = 0.25e6;       % [Hz]
source_mag = 0.5;           % [Pa]
source.p = source_mag*sin(2*pi*source_freq*kgrid.t_array);

% filter the source to remove high frequencies not supported by the grid
source.p = filterTimeSeries(kgrid, medium, source.p);

% create a display mask to display the transducer
display_mask = source.p_mask;

% create a sensor mask covering the entire computational domain using the
% opposing corners of a rectangle
sensor.mask = [1, 1, Nx, Ny].';

% set the record mode capture the final wave-field and the statistics at
% each sensor point
sensor.record = {'p_final', 'p_max', 'p_rms'};

% assign the input options
input_args = {'DisplayMask', display_mask, 'PMLInside', false, 'PlotPML', false};

% run the simulation
sensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});

% =========================================================================
% VISUALISATION
% =========================================================================

% add the source mask onto the recorded wave-field
sensor_data.p_final(source.p_mask ~= 0) = 1;
sensor_data.p_max(source.p_mask ~= 0) = 1;
sensor_data.p_rms(source.p_mask ~= 0) = 1;

% plot the final wave-field
figure;
subplot(1, 3, 1), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_final, [-1 1]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
title('Final Wave Field');

% plot the maximum recorded pressure
subplot(1, 3, 2), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_max, [-1 1]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
title('Maximum Pressure');

% plot the rms recorded pressure
subplot(1, 3, 3), imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_rms, [-1 1]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
title('RMS Pressure');
scaleFig(2, 1);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Implemetation of the tracker described in paper
%	"MEEM: Robust Tracking via Multiple Experts using Entropy Minimization",
%   Jianming Zhang, Shugao Ma, Stan Sclaroff, ECCV, 2014
%
%	Copyright (C) 2014 Jianming Zhang
%
%	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/>.
%
%	If you have problems about this software, please contact: jmzhang@bu.edu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function resample(I_vf,step_size)
global sampler;
global svm_tracker;
global config;

if nargin < 2
    step_size = max(round(sampler.template_size(1:2)/5),1);
end

feature_map = imresize(I_vf,config.ratio,'nearest');
step_size = max(round(min(sampler.template_size(1:2))/4),1);
step_size = step_size([1 1]);
rect=svm_tracker.output;

upleft = round([rect(1)-sampler.roi(1)+1,rect(2)-sampler.roi(2)+1]);
if ~((upleft(1)<1) || (upleft(2)<1) || (round(upleft(1)+rect(3)-1)>size(I_vf,2)) || (round(upleft(2)+rect(4)-1)>size(I_vf,1)))
    sub_win=I_vf(round(upleft(2): (upleft(2)+rect(4)-1)),round(upleft(1): (upleft(1)+rect(3)-1)),:);
    output_feat = imresize(sub_win,config.template_sz);
    svm_tracker.output_feat = output_feat(:)';
else
    warning('tracking window outside of frame');
    keyboard
end

sampler.patterns_dt = [im2colstep(feature_map,sampler.template_size,[step_size, size(I_vf,3)])';...
    svm_tracker.output_feat];
temp = repmat(rect,[size(sampler.patterns_dt,1),1]);

[X Y] = meshgrid(1:step_size(2):size(feature_map,2)-sampler.template_size(2)+1,1:step_size(1):size(feature_map,1)-sampler.template_size(1)+1);
temp(1:end-1,1) = (X(:)-1)/config.ratio + sampler.roi(1);
temp(1:end-1,2) = (Y(:)-1)/config.ratio + sampler.roi(2);

%% compute cost table
left = max(round(temp(:,1)),round(rect(1)));
top = max(round(temp(:,2)),round(rect(2)));
right = min(round(temp(:,1)+temp(:,3)),round(rect(1)+rect(3)));
bottom = min(round(temp(:,2)+temp(:,4)),round(rect(2)+rect(4)));
ovlp = max(right - left,0).*max(bottom - top, 0);
sampler.costs = 1 - ovlp./(2*rect(3)*rect(4)-ovlp);

sampler.state_dt = temp;

end


function computeClinicalResults_RF(pathRF,nBoot,nSplit,testSplit,testCost,seeds,matlabPATH)

startpath = pwd;

cd(pathRF), load('training'), load('testing')
nameOutcomes = fieldnames(training.outcomes); nOutcomes = numel(nameOutcomes);
comb =  {{[1,2,3],...      % Loco        : Age, Subtype, T_Stage
        [1,2,4],...        % Loco        : Age, Subtype, N_Stage
        [1,2,5],...        % Loco        : Age, Subtype, TNM_Stage
        [1,2,3,4]},...     % Loco        : Age, Subtype, T_Stage, N_Stage
        {[1,2,3],...       % Distant     : Age, Subtype, T_Stage
        [1,2,4],...        % Distant     : Age, Subtype, N_Stage
        [1,2,5],...        % Distant     : Age, Subtype, TNM_Stage
        [1,2,3,4]},...     % Distant     : Age, Subtype, T_Stage, N_Stage
        {[1,2,3],...       % Death       : Age, Subtype, T_Stage
        [1,2,4],...        % Death       : Age, Subtype, N_Stage
        [1,2,5],...        % Death       : Age, Subtype, TNM_Stage
        [1,2,3,4]}};       % Death       : Age, Subtype, T_Stage, N_Stage
mkdir('batchLog_RFclinical'), cd('batchLog_RFclinical'), pathBatch = pwd;
time = 60; % Time in the wainting loop

% PRODUCE BATCH COMPUTATIONS TO FIND THE BEST CLINICAL VARIABLES
seed = seeds(1); batch = 0;
save('workspace','pathRF','nameOutcomes','comb','testCost','nSplit','testSplit','nBoot','seed'), pause(2);
for o = 1:nOutcomes
    batch = batch + 1;
    nameScript = ['batch',num2str(batch),'_script.m'];
    fid = fopen(nameScript,'w');
    fprintf(fid,'load(''workspace'')\n');
    fprintf(fid,['[indClinic,bestCost] = estimateClinicalRF(pathRF,nameOutcomes{',num2str(o),'},comb{',num2str(o),'},testCost,nSplit,testSplit,nBoot,seed);\n']);
    fprintf(fid,['save(''result_batch',num2str(batch),''',''indClinic'',''bestCost'')\n']);
    fprintf(fid,['system(''touch batch',num2str(batch),'_end'');\n']);
    fprintf(fid,'clear all');
    fclose(fid);
    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);
end

% WAITING LOOP
waitBatch(pathBatch,time,nOutcomes)
delete('workspace.mat')

% GROUP RESULTS
cd(pathBatch)
batch = 0; parameters = struct;
for o = 1:nOutcomes
    batch = batch + 1;
    load(['result_batch',num2str(batch)]) % Variables 'indClinic' and 'bestCost' gets out of there
    parameters.clinical.(nameOutcomes{o}) = indClinic;
    parameters.cost.(nameOutcomes{o}) = bestCost;
    delete(['result_batch',num2str(batch),'.mat'])
    clear indClinic bestCost
end
cd(pathRF), save('clinicalPARAM','parameters')

% COMPUTE THE RANDOM FORESTS
for o = 1:nOutcomes
    if strcmp(nameOutcomes{o},'DeathSign')
        outcome = training.outcomes.Death;
    else
        outcome = training.outcomes.(nameOutcomes{o});
    end
    indClinic = parameters.clinical.(nameOutcomes{o});
    cost = parameters.cost.(nameOutcomes{o});
    tableTrain = training.clinical.table(:,indClinic);
    cat = logical(training.clinical.categories(indClinic));
    rng(seeds(2)), [RF] = trainRF_table(tableTrain,outcome,cat,nBoot,cost);
    RF = compact(RF); % Compact version
    save(['RF_clinic_',nameOutcomes{o}],'RF')
end

% TEST THE RANDOM FORESTS
cd(pathRF), load('clinicalPARAM')
for o = 1:nOutcomes
    if strcmp(nameOutcomes{o},'DeathSign')
        outcome = testing.outcomes.Death;
        time = testing.timeToEvents.Death;
    else
        outcome = testing.outcomes.(nameOutcomes{o});
        time = testing.timeToEvents.(nameOutcomes{o});
    end
    censoring = 1 - outcome;
    results = struct;
    RF = load(['RF_clinic_',nameOutcomes{o}]); RF = struct2cell(RF); RF = RF{1};
    indClinic = parameters.clinical.(nameOutcomes{o});
    tableTest = testing.clinical.table(:,indClinic);
    [prob] = predictRF(tableTest,RF);
    results.probResponse = prob;
    [AUC,sensitivity,specificity,accuracy] = calcPerformMetrics(prob,outcome,0.5);
    CI = calcCI(prob,time,censoring);
    results.AUC = AUC; results.Sensitivity = sensitivity; results.Specificity = specificity; results.Accuracy = accuracy;
    results.CI = CI;
    save(['testResultsRF_clinic_',nameOutcomes{o}],'results'), clear results
end

cd(startpath)
end


slice = function mrThickOblVol(thick,obX,obY,volume,sagSize,numSlices,reflections,aTheta,cTheta,curSag);
% OBSOLETE
%
% mrThickOblVol(thick,obX,obY,volume,sagSize,numSlices,reflections
%                                    ,aTheta,cTheta,curSag);
%
% Places an averaged oblique image in the oblique window.
% POIRSON 08.09.96 Added reflection logic
% SPG 12.15.96 Replaced old oblique slice function calls. removed
%   reflection calls. they are covered by mrRotSagVol.

global obwin volslimin2 volslimax2

numextracts = 10;

if(obX(1) <= sagSize(2) & obY(1) <= sagSize(1) & obX(1) > 0 & obY(1) > 0 & ...
   obX(2) <= sagSize(2) & obY(2) <= sagSize(1) & obX(2) > 0 & obY(2) > 0 )

  d = sqrt((obY(2)-obY(1)).^2 + (obX(2)-obX(1)).^2);
  unitv = [(obX(2)-obX(1))/d, (obY(2)-obY(1))/d];
  perp = [-unitv(2), unitv(1)];
  obSize = mrFindObSize(obX,obY,sagSize,numSlices);

  newX = obX-perp(1)*(thick/2);
  newY = obY-perp(2)*(thick/2);

  for i = 1:numextracts
	newX = newX+perp(1)*(thick/numextracts);
	newY = newY+perp(2)*(thick/numextracts);
	[sagSlice,sagPts,temp,obPts] = mrRotSagVol(volume,newX,newY,obSize,sagSize,cTheta,aTheta,curSag,reflections,0);
        obSlices(i,:) = temp;
  end
	slice = mean(obSlices);

else

  error('Oblique points out of range. Re-Clip inplanes grid.');
end


function output = callqpas(interfacedata)

% Retrieve needed data
options = interfacedata.options;
model = yalmip2quadprog(interfacedata);

if size(model.Aeq,1)==0
    model.Aeq = [];
    model.beq = [];
end

if options.savedebug
    save debugfile model
end

if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
[x,flag,lm] = qpas(model.Q, model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, options.verbose);
solvertime = toc(solvertime);

% Internal format for duals
if ~isempty(lm)
    D_struc = [lm.equality;lm.inequality];
else
    D_struc = [];
end

if isempty(flag)
    problem = 9;
else
    % Check, currently not exhaustive...
    switch flag
        case 0
            problem = 0;
        case 2
            problem = 1;
        otherwise
            problem = 1;
    end
end

infostr = yalmiperror(problem,interfacedata.solver.tag);

% Save all data sent to solver?
if options.savesolverinput
    solverinput = model;
else
    solverinput = [];
end

% Save all data from the solver?
if options.savesolveroutput
    solveroutput.x = x;
    solveroutput.flag = flag;
    solveroutput.lm = lm;
else
    solveroutput = [];
end

% Standard interface
output = createOutputStructure(x(:),D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);


function k = taylororder
%TAYLORORDER  Order of Taylor evaluations
%
%   k = taylororder
%
%In the current initialization of the Taylor package, Taylor coefficients
%up to order k will be calculated. Result is -1 if Taylor package is not
%yet initialized.
%

% written  05/21/09     S.M. Rump
% modified 08/26/12     S.M. Rump  global variables removed
%

  INTLAB_TAYLOR_ORDER = getappdata(0,'INTLAB_TAYLOR_ORDER');
  if isempty(INTLAB_TAYLOR_ORDER)   % Taylor package not yet initialized
    k = -1;
  else
    k = INTLAB_TAYLOR_ORDER;
  end


% Convert the samples in the input file to a different format (ex: float complex to int16 complex)
%
% The input and output types need to be string names like 'single', 'int16', or 'int8'.
% To convert a file containing complex 32-bit floats to complex 16-bit ints for a radio with a 12-bit DAC:
%     convert_complex_file_type('/tmp/foo.fc32', 'single', '/tmp/foo.sc16', 'int16', 2^12);
%
% @param input_file_path Path to the input file containing complex samples of `input_type`
% @param input_type Sample type of each I and Q value in `input_file_path`
% @param output_file_path Path to the new file containing samples from the input file converted to `output_type`
% @param output_type New sample type of each I and Q value (converted from `input_type`)
% @param scalar Value to scale the input samples by before writing to disk
% @return sample_count Number of complex samples written to `output_file_path`
function [sample_count] = convert_complex_file_type(input_file_path, input_type, output_file_path, output_type, scalar)
    assert(isstring(input_file_path) || ischar(input_file_path) || iscellstr(input_file_path), ...
        'Input file path must be a string, char array, or cell string');
    assert(isstring(input_type) || ischar(input_type), 'Input type must be a string or char array');
    assert(isstring(output_file_path) || ischar(output_file_path) || iscellstr(output_file_path), ...
        'Output file path must be a string, char array, or cell string');
    assert(isstring(output_file_path) || ischar(output_file_path), 'Output type must be a string or char array');
    assert(isnumeric(scalar), 'Scalar must be a number');

    input_file_handle = fopen(input_file_path, 'r');
    assert(input_file_handle ~= -1, 'Could not open input file "%s"', input_file_path);

    output_file_handle = fopen(output_file_path, 'w');
    assert(output_file_handle ~= -1, 'Could not open output file "%s" for writing', output_file_path);

    input_file_sample_bytes = get_bytes_per_sample(input_type);

    % How many samples to work on at a time.  Keep this value as high as possible to reduce runtime.  But, don't go
    % crazy with it as it will plow through RAM
    chunk_size = 1e6;

    % Track the number of samples written
    sample_count = 0;

    % Read until there are no samples left in the input file
    while (~ feof(input_file_handle))
        % Read up to one chunk of samples (could be less if there aren't enough samples left in the file)
        input_samples = fread(input_file_handle, chunk_size * input_file_sample_bytes, input_type);

        % Scale and cast the input samples to the output
        output_samples = cast(input_samples * scalar, output_type);

        % Write the scaled samples to disk and update how many samples have been written
        sample_count = sample_count + fwrite(output_file_handle, output_samples, output_type);
    end

    % Convert to complex sample count
    sample_count = sample_count / 2;
end


function D = spm_diag_array(X)
% Extracts diagonal from 3-D arrays
% FORMAT D = spm_diag_array(X)
%
% X(:,i,i) -> D(:,i);
%__________________________________________________________________________
% Copyright (C) 2014 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_diag_array.m 5956 2014-04-16 14:34:25Z guillaume $

% extract diagnonals
%--------------------------------------------------------------------------
if iscell(X)
    D     = cell(size(X));
    for i = 1:numel(X)
        D{i} = spm_diag_array(X{i});
    end
    return
end
D     = zeros(size(X,1),size(X,2));
for i = 1:size(X,3)
    D(:,i) = X(:,i,i);
end


function mono = increasing_except_at(xL,xU,p)

if xU <= p || xL >= p
    mono = 'increasing';
else
    mono = 'none';
end


classdef VS_Stage < VS_AbstractStage
    %VS_Stage Basic stage with one tank and one engine (and no boosters)
    %   Detailed explanation goes here

    properties
        %direct inputs
        isp double = 300; %seconds
        dryMassFrac(1,1) double = 0.2;
        desiredT2W(1,1) double = 1.0;
        bodyInfo KSPTOT_BodyInfo = KSPTOT_BodyInfo.empty(1,0);

        %computed
        %payloadStage(1,:) VS_Stage = VS_Stage.empty(1,0);

        %optimized quantities
        dryMass(1,1) double = 1; %kg
        deltaV(1,1) double = 0; %m/s

        %flags
        isPayload(1,1) logical = false;
    end

    methods
        function obj = VS_Stage(phase)
            obj.phase = phase;
        end

        function deltaV = getStageDeltaV(obj)
            deltaV = obj.deltaV;
        end

        function dryMass = getTotalStageDryMass(obj)
            dryMass = obj.dryMass;
        end

        function expPropMass = computeExpendedPropMass(obj)
            expPropMass = obj.computeInitMass() - obj.computeFinalMass();
        end

        function tgtDryMass = computeTgtDryMass(obj)
            tgtDryMass = (obj.dryMassFrac/(1 - obj.dryMassFrac)) * obj.computeExpendedPropMass();
        end

        function stageTotalMass = computeStageTotalMass(obj)
            stageTotalMass = obj.dryMass + obj.computeExpendedPropMass();
        end

        function str = getStageOutputStr(obj)
            str = cell(0,1);
            str{end+1} = sprintf('\tStage: %s', obj.name);
            str{end+1} = sprintf('\t\tTotal Stage Dry Mass: %0.3f mT', obj.dryMass/1000);
            str{end+1} = sprintf('\t\tTotal Stage Prop Mass: %0.3f mT', obj.computeExpendedPropMass()/1000);
            str{end+1} = sprintf('\t\tTotal Stage Mass: %0.3f mT', obj.computeStageTotalMass()/1000);
            str{end+1} = sprintf('\t\tTotal Stage Delta-V: %0.3f km/s', obj.deltaV/1000);
            str{end+1} = sprintf('\t\tStage Req''d Thrust: %0.3f kN', obj.computeReqdThrust()/1000);
            str{end+1} = sprintf('\t\tStage Burn Time: %0.3f sec', obj.computeEngineBurnTime());
            str{end+1} = sprintf('\t\t----');
            str{end+1} = sprintf('\t\tStage Isp: %0.3f sec', obj.isp);
            str{end+1} = sprintf('\t\tStage Dry Mass Fraction: %0.3f', obj.dryMassFrac);
            str{end+1} = sprintf('\t\tStage Celestial Body: %s', obj.bodyInfo.name);
        end

        %%%%%%%% For Optimizer Use %%%%%%%%%
        function initStageForOpt(obj, phaseDvPerStage)
            obj.deltaV = phaseDvPerStage;

            if(not(obj.isPayloadOnlyStage()))
                diff = Inf;
                iterCnt = 1;
                while(diff >= 0.01 && iterCnt <=200)
                    obj.dryMass = obj.computeTgtDryMass();

                    diff = abs(obj.dryMass - obj.computeTgtDryMass());
                    iterCnt = iterCnt + 1;
                end
            else
                if(obj.dryMassFrac == 1)
                    obj.deltaV = 0;
                end
            end
        end

        function x = getStageOptimizerVars(obj)
            x = [];

            if(not(obj.isPayloadOnlyStage()))
                x = [obj.deltaV, obj.dryMass];
            else
                x = [obj.deltaV];
            end
        end

        function updateStageWithVars(obj, x)
            if(not(obj.isPayloadOnlyStage()))
                obj.deltaV = x(1);
                obj.dryMass = x(2);
            else
                obj.deltaV = x(1);
            end
        end

        function [lb,ub] = getStageOptVarBounds(obj)
            lb = [];
            ub = [];

            if(not(obj.isPayloadOnlyStage()))
                lb = [0, 0]; %dV and dry mass have lower bounds of 0
                ub = [Inf, Inf]; %no upper bounds on these variables
            else
                lb = 0;
                ub = Inf;
            end
        end

        function [c, ceq] = getStageNlConValues(obj)
            c = [];
            ceq = [];

%             if(not(obj.isPayloadOnlyStage()))
                ceq(1) = obj.getTotalStageDryMass() - obj.computeTgtDryMass();
%             end
        end
    end

    methods(Access=private)
        function finalMass = computeFinalMass(obj)
            finalMass = obj.computePayloadMass() + obj.dryMass;
        end

        function initMass = computeInitMass(obj)
            finalMass = obj.computeFinalMass();
            g0 = getG0();

            initMass = finalMass * exp(obj.deltaV/(g0*obj.isp));
        end

        function payloadMass = computePayloadMass(obj)
            if(isempty(obj.payloadStage))
                payloadMass = 0;
            else
                payloadMass = obj.payloadStage.computeInitMass();
            end
        end

        function reqdThrust = computeReqdThrust(obj)
            reqdThrust = obj.desiredT2W * (obj.computeStageTotalMass() + obj.computePayloadMass()) * obj.computeGforBody();
        end

        function engineBurnTime = computeEngineBurnTime(obj)
            engineBurnTime = obj.computeExpendedPropMass() / (obj.computeReqdThrust() / (getG0() * obj.isp));
        end

        function tf = isPayloadOnlyStage(obj)
            tf = obj.isPayload;
        end
    end
end


function frameloc = ufmf_write_frame(fp,stamp,x0,y0,w,h,val)

frameloc = ftell(fp);
% write the chunk id (points=1)
fwrite(fp,1,'uchar');
% write timestamp
fwrite(fp,stamp,'double');
% write number of points
npts = numel(x0);
fwrite(fp,npts,'uint32');

for i = 1:npts,
  % write x, y, width, height
  fwrite(fp,[x0(i),y0(i),w(i),h(i)],'ushort');
  % write region intensities
  fwrite(fp,val{i},'uint8');
end


function xcell = cellK(x,K)
% xcell = cellK(x,K)
%
% CELLK  Stores SeDuMi cone K-vector in cell-array format.
%
% On output xcell.f and xcell.l are the free and >=0 components,
% xcell.q{k}, xcell.r{k} and xcell.s{k} contain the Lorentz,
% Rotated Lorentz, and PSD-components, resp.
% xcell.s{k} is a K.s(k) x K.s(k) matrix.
%
% See also eigK, eyeK, sedumi.

% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%

% Remark: the cell-array scheme is inspired by SDPT3.
% Unlike in SDPT3 though, the cells are grouped in
% fields like xcell.q and xcell.s.
if nargin < 2
    error('cellK needs 2 input arguments')
end
if ~isstruct(K)
    error('K should be a structure')
end
i = 1;
if isfield(K,'f')
    xcell.f = x(i:i+K.f-1);
    i = i + K.f;
end
if isfield(K,'l')
    xcell.l = x(i:i+K.l-1);
    i = i + K.l;
end
% ------------------------------------------------------------
% Lorentz: this only works OUTSIDE sedumi, not for internal storage
% ------------------------------------------------------------
if isfield(K,'q')
    for k = 1: length(K.q)
        xcell.q{k} = x(i:i+K.q(k)-1);
        i = i + K.q(k);
    end
end
if isfield(K,'r')
    for k = 1: length(K.r)
        xcell.r{k} = x(i:i+K.r(k)-1);
        i = i + K.r(k);
    end
end
% ------------------------------------------------------------
% PSD-blocks:
% ------------------------------------------------------------
if isfield(K,'s')
    if ~isfield(K,'rsdpN')
        for k = 1: length(K.s)
            xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
            i = i + K.s(k)^2;
        end
    else
        % ------------------------------------------------------------
        % Only applicable for internal storage: complex-as-real-storage
        % ------------------------------------------------------------
        for k = 1: K.rsdpN
            xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
            i = i + K.s(k)^2;
        end
        j = sqrt(-1);
        for k = K.rsdpN+1:length(K.s)
            xcell.s{k} = mat(x(i:i+K.s(k)^2-1));
            i = i + K.s(k)^2;
            xcell.s{k} = xcell.s{k} + j * mat(x(i:i+K.s(k)^2-1));
            i = i + K.s(k)^2;
        end
    end
end


% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)
%
% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function qq = mrdivide(q1, q2)
%Quaternion.mrdivide Compute quaternion quotient.
%
% Q1/Q2   is a quaternion formed by Hamilton product of Q1 and inv(Q2)
% Q/S     is the element-wise division of quaternion elements by by the scalar S

    if isa(q2, 'Quaternion')
        % qq = q1 / q2
        %    = q1 * qinv(q2)

        qq = q1 * inv(q2);
    elseif isa(q2, 'double')
        qq = Quaternion( double(q1) / q2 );
    end
end


% This script reads word2vec bin file

addpath('./hglmm_fv_v1.6/utilities');
addpath('./hglmm_fv_v1.6/fv');
f_name = 'GoogleNews-vectors-negative300.bin';

% some settings
sqrt_flag = false;
norm_flag = false;

[w_names, w_features] = read_word2vec_binfile(f_name, sqrt_flag, norm_flag);

save('GoogleNews_words.mat','w_names');
save('GoogleNews_vectors.mat','w_features','-v7.3');


black=[0 0 0];white=[255 255 255];

Screen('FillRect', w, black, [wRect(3)/2-(s_width/2) wRect(1) wRect(3)/2+(s_width/2) wRect(1)+s_height]); % up
Screen('FillRect', w, black, [wRect(3)/2-(s_width/2) wRect(4)-s_height wRect(3)/2+(s_width/2) wRect(4)]); % down
Screen('FillRect', w, black, [wRect(1)  wRect(4)/2-(s_height/2)  wRect(1)+s_width   wRect(4)/2+(s_height/2)]); % left
Screen('FillRect',w,black,[wRect(3)-s_width wRect(4)/2-(s_height/2) wRect(3) wRect(4)/2+(s_height/2)]); % right
fixSize =80;
[X,Y] = RectCenter(wRect);
PixofFixationSize = 80;
FixCross = [X-1,Y-PixofFixationSize,X+1,Y+PixofFixationSize;X-PixofFixationSize,Y-1,X+PixofFixationSize,Y+1];
Screen('FillRect', w, black, FixCross');


function ops = convertOpenEphysToRawBInary(ops)

fname       = fullfile(ops.root, sprintf('%s.dat', ops.fbinary));
fidout      = fopen(fname, 'w');
%
clear fs
for j = 1:ops.Nchan
   fs{j} = dir(fullfile(ops.root, sprintf('*CH%d_*.continuous', j) ));
end
nblocks = cellfun(@(x) numel(x), fs);
if numel(unique(nblocks))>1
   error('different number of blocks for different channels!')
end
%
nBlocks     = unique(nblocks);
nSamples    = 1024;  % fixed to 1024 for now!

fid = cell(ops.Nchan, 1);

tic
for k = 1:nBlocks
    for j = 1:ops.Nchan
        fid{j}             = fopen(fullfile(ops.root, fs{j}(k).name));
        % discard header information
        fseek(fid{j}, 1024, 0);
    end
    %
    nsamps = 0;
    flag = 1;
    while 1
        samples = zeros(nSamples * 1000, ops.Nchan, 'int16');
        for j = 1:ops.Nchan
            collectSamps    = zeros(nSamples * 1000, 1, 'int16');

            rawData         = fread(fid{j}, 1000 * (nSamples + 6), '1030*int16', 10, 'b');

            nbatches        = ceil(numel(rawData)/(nSamples+6));
            for s = 1:nbatches
                rawSamps = rawData((s-1) * (nSamples + 6) +6+ [1:nSamples]);
                collectSamps((s-1)*nSamples + [1:nSamples]) = rawSamps;
            end
            samples(:,j)         = collectSamps;
        end

        if nbatches<1000
            flag = 0;
        end
        if flag==0
            samples = samples(1:s*nSamples, :);
        end

        samples         = samples';
        fwrite(fidout, samples, 'int16');

        nsamps = nsamps + size(samples,2);

        if flag==0
            break;
        end
    end
    ops.nSamplesBlocks(k) = nsamps;

    for j = 1:ops.Nchan
       fclose(fid{j});
    end

end

fclose(fidout);

toc


function p00_poly_write ( test, file_name )

%*****************************************************************************80
%
%% P00_POLY_WRITE collects data and writes it to a POLY file.
%
%  Discussion:
%
%    This routine collects information about the boundary for a given
%    problem, and writes that data to a POLY file that can be read by
%    TRIANGLE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer TEST, the index of the test problem
%
%    Input, string FILE_NAME, the name of the file to create.
%
  dim_num = 2;
%
%  Get a length scale.
%
  [ lo, hi ] = p00_box ( test, dim_num );

  scale = max ( abs ( hi(1:dim_num) - lo(1:dim_num) ) );
%
%  How many boundary segments are there?
%
  boundary_segment_num = p00_boundary_segment_num ( test );
%
%  Choose H so that we would expect to get about 100 boundary points if our
%  region were a square of any size.
%
  h = 0.04 * scale;

  node_num = 0;
  for segment_index = 1 : boundary_segment_num
    segment_length = p00_boundary_segment_length ( test, segment_index, h );
    node_num = node_num + segment_length;
  end
%
%  Now collect all the boundary nodes into one array.
%
  next = 1;

  for segment_index = 1 : boundary_segment_num

    segment_length = p00_boundary_segment_length ( test, segment_index, h );

    segment(1:dim_num,next:next+segment_length-1) = p00_boundary_segment ( ...
      test, segment_index, dim_num, segment_length );

    next = next + segment_length;

  end
%
%  How many edges are there?
%
  edge_num = 0;

  for segment_index = 1 : boundary_segment_num

    segment_length = p00_boundary_segment_length ( test, segment_index, h );

    edge_num = edge_num + segment_length - 1;

  end
%
%  Now collect the edges.
%
  e = 0;
  next = 1;

  for segment_index = 1 : boundary_segment_num

    segment_length = p00_boundary_segment_length ( test, segment_index, h );

    for j = 1 : segment_length - 1
      edge_nodes(1,e+j) = next + j - 1;
      edge_nodes(2,e+j) = next + j;
    end

    next = next + segment_length;
    e = e + segment_length - 1;

  end
%
%  Handle the holes.
%
  hole_num = p00_hole_num ( test );
  hole = zeros ( dim_num, hole_num );

  for hole_index = 1 : hole_num
    hole(1:dim_num,hole_index) = ( p00_hole_point ( test, hole_index, dim_num ) )';
  end
%
%  Write the POLY file.
%
  poly_write ( file_name, node_num, segment, edge_num, ...
    edge_nodes, hole_num, hole );

  return
end


function A = import_data(fname)
%IMPORT_DATA Import tensor-related data to a file.
%
%   A = IMPORT_DATA(FNAME) imports an object A from the file named FNAME.
%   The supported data types and formatting of the file are explained in
%   EXPORT_DATA.
%
%   See also TENSOR, EXPORT_DATA
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

%% Open file
fid = fopen(fname,'r');
if (fid == -1)
    error('Cannot open file %s',fname);
end

%% Get the type of object
line = fgets(fid);
type = sscanf(line, '%s');

%% Import the object

if strcmpi(type,'tensor')

    sz = import_size(fid);
    data = import_array(fid, prod(sz));
    A = tensor(data, sz);

elseif strcmpi(type,'matrix')

    sz = import_size(fid);
    data = import_array(fid, prod(sz));
    A = reshape(data, sz);

else

    error('Invalid data type for export');

end

%% Close file
fclose(fid);

function sz = import_size(fid)
% Import the size of something from a file
line = fgets(fid);
n = sscanf(line, '%d');
line = fgets(fid);
sz = sscanf(line, '%d');
sz = sz';
if (size(sz,2) ~= n)
    error('Imported dimensions are not of expected size');
end

function data = import_array(fid, n)
% Export dense data that supports numel and linear indexing
data = fscanf(fid, '%e', n);


function plot_cdfZ(vResults)

figure;i=1;cdfplot(reshape(vResults(i).mValueGrid,size(vResults(i).mValueGrid,1)*size(vResults(i).mValueGrid,2),1))
hold on;i=2;cdfplot(reshape(vResults(i).mValueGrid,size(vResults(i).mValueGrid,1)*size(vResults(i).mValueGrid,2),1))
hold on;i=3;cdfplot(reshape(vResults(i).mValueGrid,size(vResults(i).mValueGrid,1)*size(vResults(i).mValueGrid,2),1))

legend('a','b','c')
h=get(gca,'Children');

set(h(3),'Color',[0.8 0.8 0.8],'LineWidth',4)
set(h(2),'Color',[0 0 1],'LineWidth',2)
set(h(1),'Color',[1 0 0],'LineWidth',1)
set(gca,'YLim',[-0.05 1.05])


function [afresults, AfAnalysisWindows, AFfile] = PerformAFdetection(subjectID,trr,rr,sqi,HRVparams)
%   PerformAFdetection(subjectID,trr,rr,HRVparams)
%
%	OVERVIEW:
%       Perform Atrial Fibrillation (AF) detection
%
%   INPUT:
%       subjectID : string containing the identifier of the subject to be analyze
%       trr      : (seconds)a single row of time of the rr interval
%                   data
%       rr        : (seconds) a single row of peak to peak interval
%                   data
%       sqi       : Signal Quality Index; Requires a matrix with
%                   at least two columns. Column 1 should be timestamps
%                   should be timestamps of each sqi measure, and Column 2
%                   should be SQI on a scale from 0 to 1.
%       HRVparam  : struct of settings for hrv_toolbox analysis
%
%   OUTPUT:
%       afresults : a single row containing a flag (1) when AF is
%                   dettected in a window and 0 if no AF
%
%   DEPENDENCIES & LIBRARIES:
%       PhysioNet Cardiovascular Signal Toolbox
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%
%   REFERENCE:
%   Vest et al. "An Open Source Benchmarked HRV Toolbox for Cardiovascular
%   Waveform and Interval Analysis" Physiological Measurement (In Press), 2018.
%
%	REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:
%       Written by Giulia Da Poian (giulia.dap@gmail.com) on Sep 6, 2017.
%       Dependent scripts written by various authors
%       (see functions for details)
%	COPYRIGHT (C) 2018
%   LICENSE:
%       This software is offered freely and without warranty under
%       the GNU (v3 or later) public license. See license file for
%       more information
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Modified on 02.14.2018 to include SQI check before evaluating AF; if a
%   windows contains low SQI signal do not compute AF and mark the window
%   as NaN

if isempty(sqi)
     sqi(:,1) = trr;
     sqi(:,2) = ones(length(trr),1);
end

% 1. Calculate AF Features
AfAnalysisWindows = CreateWindowRRintervals(trr,rr,HRVparams,'af');
NNsamps = rr .* HRVparams.Fs;

AFtest = nan(length(AfAnalysisWindows),1);

for idx = 1:length(AfAnalysisWindows)
    tstart = AfAnalysisWindows(idx);

    if ~isnan(tstart)

        idxInWin = find(trr >= tstart & trr< tstart + HRVparams.af.windowlength);

        % Added by Giulia: exclude from the Analysis low quality
        % segments (SQI< SQI_threshold)
        sqiWin = sqi(sqi(:,1) >= tstart & sqi(:,1) < tstart + HRVparams.af.windowlength,2);
        LowQualityIdxs = find(sqiWin < HRVparams.sqi.LowQualityThreshold);

        % If enough data has an adequate SQI, perform the calculations
        cond1 = (numel(LowQualityIdxs)/length(sqiWin)) <  HRVparams.RejectionThreshold;
        % RR interval time series must be > 12 ans <60 to extract feautures
        cond2 = (length(NNsamps(idxInWin)) > 12 && length(NNsamps(idxInWin)) < 60);

        if (cond1 && cond2)
            features_af = AF_features(NNsamps(idxInWin),HRVparams.Fs);
            AFtest(idx) = SVM_AFdetection_withoutTrainingModel(features_af,1);
        end
    end
end

% 2. Export AF Data as CSV File

afresults = AFtest(:);
afcol_titles = {'AFtest'};

outputType = 'AF';
AFfile = SaveHRVoutput(subjectID,AfAnalysisWindows,afresults, ...
    afcol_titles, outputType, HRVparams, trr, rr);


function sizes = getVarSizes(obj, inputSizes)
%GETVARSIZES  Get the size of the variables
%   SIZES = GETVARSIZES(OBJ, INPUTSIZES) computes the SIZES of the
%   DagNN variables given the size of the inputs. `inputSizes` is
%   a cell array of the type `{'inputName', inputSize, ...}`
%   Returns a cell array with sizes of all network variables.
%
%   Example, compute the storage needed for a batch size of 256 for an
%   imagenet-like network:
%   ```
%   batch_size = 256; single_num_bytes = 4;
%   input_size = [net.meta.normalization.imageSize, batch_size];
%   var_sizes = net.getVarSizes({'data', input_size});
%   fprintf('Network activations will take %.2fMiB in single.\n', ...
%     sum(prod(cell2mat(var_sizes, 1))) * single_num_bytes ./ 1024^3);
%   ```

% Copyright (C) 2015 Andrea Vedaldi, Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

nv = numel(obj.vars) ;
sizes = num2cell(NaN(nv, 4),2)' ;

for i = 1:2:numel(inputSizes)
  v = obj.getVarIndex(inputSizes{i}) ;
  if isnan(v)
    error('Variable `%s` not found in the network.', inputSizes{i});
  end;
  if isempty(inputSizes{i+1})
    sizes{v} = [0 0 0 0] ;
  else
    sizes{v} = [inputSizes{i+1}(:)' ones(1, 4 - numel(inputSizes{i+1}))] ;
  end
end

for layer = obj.layers(obj.executionOrder)
  in = layer.inputIndexes ;
  out = layer.outputIndexes ;
  sizes(out) = layer.block.getOutputSizes(sizes(in)) ;
end


function Script_HOG_SVM_train()

% Change to your downloaded location
addpath('C:\liblinear\matlab')
addpath('../training_code/');
addpath('../utilities/');
addpath('../../data extraction/');

%% load shared definitions and AU data
shared_defs;

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

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

% Set the training function
svm_train = @svm_train_linear;

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

pca_loc = '../../pca_generation/generic_face_rigid.mat';

%%
for a=1:numel(aus)

    au = aus(a);

    rest_aus = setdiff(all_aus, au);

    % load the training and testing data for the current fold
    [train_samples, train_labels, valid_samples, valid_labels, ~, PC, means, scaling] = Prepare_HOG_AU_data_generic(train_recs, devel_recs, au, rest_aus, SEMAINE_dir, hog_data_dir);

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

    %% Cross-validate here
    [ best_params, ~ ] = validate_grid_search_no_par(svm_train, svm_test, false, train_samples, train_labels, valid_samples, valid_labels, hyperparams);

    model = svm_train(train_labels, train_samples, best_params);

    [prediction, a, actual_vals] = predict(valid_labels, valid_samples, model);

    % Go from raw data to the prediction
    w = model.w(1:end-1)';
    b = model.w(end);

    svs = bsxfun(@times, PC, 1./scaling') * w;

    name = sprintf('models/AU_%d_static.dat', au);

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

    write_lin_svm(name, means, svs, b, pos_lbl, neg_lbl);

    name = sprintf('results_SEMAINE_devel/AU_%d_static.mat', au);

    tp = sum(valid_labels == 1 & prediction == 1);
    fp = sum(valid_labels == 0 & prediction == 1);
    fn = sum(valid_labels == 1 & prediction == 0);
    tn = sum(valid_labels == 0 & prediction == 0);

    precision = tp/(tp+fp);
    recall = tp/(tp+fn);

    f1 = 2 * precision * recall / (precision + recall);

    save(name, 'model', 'f1', 'precision', 'recall', 'best_params', 'valid_labels', 'prediction');

end

end


function loadRaceline(filename_raceline, DDname)
%
% Author:
%   Leonhard Hermansdorfer      Date: 03.12.2020
%
% Description:
%   function used to load a raceline for trajectory planning emulation.
%
% Input:
%   filename_raceline:  name of file containing the raceline to be loaded
%                       data format:
%                       - delimiter: ';'
%                       - header char: '#'
%                       - max. number of s-coordinates: Variable "int_max_datapoints"
%                       - contained data:
%                       [s_m;x_m;y_m;psi_rad;kappa_radpm;vx_mps;ax_mps2(;banking_rad)]
%   DDname (optional):  name of data dictionary where to save raceline;
%                       default is "raceline.sldd"

%% user input

% fixed length of raceline data arrays
int_max_datapoints = 5000;

% number of vehicles (necessary for starting and parking position calculation)
int_count_vehicles = 10;

%% read csv-file which contains the raceline

    % name of data dictionary where to write raceline
    if ~exist("DDname", "var")
        DDname = "raceline.sldd";
    end

    % add .sldd to data dictionary name if not already included
    if ~contains(DDname, ".sldd")
        DDname = strcat(DDname,'.sldd');
    end

    % add .csv to filename if not already included
    if ~contains(filename_raceline, ".csv")
        filename_raceline = strcat(filename_raceline,'.csv');
    end

    % raise error when no raceline file with specified name is found
    if isempty(which(filename_raceline))
        error(strcat('No raceline file found with name: "', filename_raceline, '"!'))
    end

    % find first line without comment char '#' to determine where to start
    % reading the raceline file
    fid = fopen(filename_raceline);
    tline = fgetl(fid);

    int_row_start = 0;

    while contains(tline, '#')
        tline = fgetl(fid);
        int_row_start = int_row_start + 1;
    end

    % start reading raceline file at first row which contains relevant data
    raceline_data = dlmread(filename_raceline,';',int_row_start,0);

    % load corresponding racetrack file if available
    loadRacetrack(strcat('traj_ltpl_cl_', filename_raceline));

%% preprocess and reshape raceline data

    % get length of original raceline
    size_raceline_init = size(raceline_data);

    % get factor for reducing number of data points in output raceline array if it is above specified limit
    dist = ceil(size_raceline_init(1) / int_max_datapoints);

    % discard last row, if x,y-coordinates are the same (trajectory is closed)
    if abs(raceline_data(1, 2) - raceline_data(end, 2)) <= 0.1 && ...
        abs(raceline_data(1, 3) - raceline_data(end, 3)) <= 0.1

        int_count_validpoints = size_raceline_init(1) - 1;

    else
        int_count_validpoints = size_raceline_init(1);

    end

    % crop raceline data to fit maximum number of data points (rows)
    raceline_data_cropped = raceline_data(1:dist:int_count_validpoints, :);
    size_raceline_cropped = size(raceline_data_cropped,1);

    % get mean distance of cropped raceline for interpolation of
    % s-coordinate
    mean_sdistance = mean(diff(raceline_data_cropped(:, 1)));

    % fill raceline array with zeros to match max number of data points (rows)
    raceline_data_out = [raceline_data_cropped;
                zeros((int_max_datapoints - size_raceline_cropped), size_raceline_init(2))];

    % create Raceline struct which is then stored in raceline data dictionary
    Raceline.s_m = raceline_data_out(:,1);
    % extrapolate s-coordinate to end of raceline array
    Raceline.s_m(size_raceline_cropped+1:int_max_datapoints, 1) = ...
        (Raceline.s_m(size_raceline_cropped) + [1:(int_max_datapoints-size_raceline_cropped)] * mean_sdistance)';

    Raceline.x_m = raceline_data_out(:,2);
    Raceline.y_m = raceline_data_out(:,3);
    Raceline.psi_rad = raceline_data_out(:,4);
    Raceline.kappa_radpm = raceline_data_out(:,5);
    Raceline.vx_mps = raceline_data_out(:,6);
    Raceline.ax_mps2 = raceline_data_out(:,7);

    Raceline.ValidPointCnt = length(raceline_data(1:dist:int_count_validpoints,1));
    Raceline.s_m_end = Raceline.s_m(Raceline.ValidPointCnt);

    % if no banking information is available, write zeros
    try
        Raceline.banking_rad = raceline_data_out(:,8);
    catch
        Raceline.banking_rad = zeros(length(raceline_data_out(:,1)), 1);
    end

%% calculate default starting (activated vehicles) and parking position (deactivated vehicles)

    % TODO: add options as function arguments (e.g. "chain", "grid")

    % starting position
    s_distance_m = 15;

    x0_vehiclepose_start = [Raceline.x_m(1), Raceline.y_m(1), Raceline.psi_rad(1); ...
                            zeros((int_count_vehicles - 1), 3)];

    for i=2:int_count_vehicles

        s_target = Raceline.s_m(int_count_validpoints + 1) - s_distance_m * (i - 1);
        abs(Raceline.s_m - s_target);
        idx = find(abs(Raceline.s_m - s_target)==min(abs(Raceline.s_m - s_target)));

        x0_vehiclepose_start(i, :) = [Raceline.x_m(idx), Raceline.y_m(idx), Raceline.psi_rad(idx)];

    end

    % parking position
    s_distance_toraceline_m = 15;
    s_distance_betweenvehicles_m = 7;

    direction_raceline = [Raceline.x_m(2) - Raceline.x_m(1), ...
                          Raceline.y_m(2) - Raceline.y_m(1)];
    direction_raceline = direction_raceline ./ sqrt(sum(direction_raceline.^2));
    normalvec_direction_raceline = cross([direction_raceline, 0], [0,0,1]);
    normalvec_direction_raceline = normalvec_direction_raceline(1:2);
    x0_vehiclepose_park = zeros(int_count_vehicles, 3);

    for i=1:int_count_vehicles

        x0_vehiclepose_park(i, :) = ...
            [[Raceline.x_m(1), Raceline.y_m(1)] ...
             + normalvec_direction_raceline * s_distance_toraceline_m ...
             + -1 * s_distance_betweenvehicles_m * direction_raceline* (i - 1), ...
             Raceline.psi_rad(1) + pi/4];

    end

%% assign struct to data dictionary

    path2module = split(which(mfilename), "mod_control");
    path2racelines = strcat(path2module{1}, "mod_control/racelines/");
    filepath2racelineDD = strcat(path2racelines, DDname);

    try

        % open default data dictionary
        if DDname == "raceline.sldd"
            datadict = Simulink.data.dictionary.open(DDname);

        % create new data dictionary with custom name
        else

            % check if data dictionary with custom name already exists
            if exist(filepath2racelineDD, "file")
                i = 1;

                while exist(filepath2racelineDD, "file")
                    DDname_temp = split(DDname,'.sldd');
                    DDname_temp = DDname_temp(1);

                    filepath2racelineDD = strcat(path2racelines, DDname_temp, num2str(i),'.sldd');

                    i = i + 1;

                end

                warning(strcat('data dictionary already exists. New name is ', filepath2racelineDD));

            end

            datadict = Simulink.data.dictionary.create(filepath2racelineDD);

        end

        % delete old data dictionary content
        dDataSectObj = getSection(datadict,'Design Data');
        list_struct_entries = find(dDataSectObj, 'DataSource', DDname);

        % delete all data dict entries of type struct
        for i=1:length(list_struct_entries)
            deleteEntry(dDataSectObj, list_struct_entries(i).Name)
        end

        % write raceline, start position and raceline file info to data dictionary
        disp(strcat('Write raceline "', filename_raceline, '" to raceline data dictionary...'));

        addEntry(dDataSectObj, "Raceline", Raceline)

        % add starting and parking position to data dictionary

        % TODO: Replace
        addEntry(dDataSectObj,'x0_vehiclepose_stm',...
        [Raceline.x_m(1),Raceline.y_m(1),Raceline.psi_rad(1)]);

        addEntry(dDataSectObj,'x0_vehiclepose_dtm',...
        [Raceline.x_m(1), -1 * Raceline.y_m(1), 0, 0, 0, normalizeAngle((-pi/2) - Raceline.psi_rad(1))]);

        for i=1:int_count_vehicles
            addEntry(dDataSectObj, strcat("x0_vehiclepos_start_veh", num2str(i)), x0_vehiclepose_start(i, :))
         	addEntry(dDataSectObj, strcat("x0_vehiclepos_park_veh", num2str(i)), x0_vehiclepose_park(i, :))
        end

        % add name of current raceline
        addEntry(dDataSectObj, 'current_raceline', filename_raceline)

        % save and close data dictionary
        datadict.saveChanges()
        datadict.close();

        % activate raceline (if other mode was used before)DDObj = ...
        DDObj = Simulink.data.dictionary.open('TrajectoryPlanningEmulation.sldd');
        dataSectObj = getSection(DDObj, 'Design Data');
        switchObj = getEntry(dataSectObj, 'P_VDC_TrajEmulation_mode');
        setValue(switchObj, 0);
        % save & close
        saveChanges(DDObj);
        close(DDObj);

    catch e
        warning(['Something went wrong during configuration of ' ...
                'raceline data dictionary']);
        disp('******************************************');
        disp('Exception: ');
        disp(getReport(e))
        disp('******************************************');

    end

end


% VARGPLVMFEATURECLASSIFICATION Use vargplvm features to perform
% discriminative classification with log. regression.
%
%
% ARG: model   : The vargplvm model
% ARG: data    : A struct with:
%                 data.lbls      : Training labels in 1-of-K encoding
%                 data.lblsTs    : Test labels
%                 data.Xpred     : A test latent point (optional if data.Yts given)
%                 data.Xpred_var : A test latent variance (optional if data.Yts given)
%                 data.Yts       : Test output (optional if the 2 above given)
% ARG: options : A struct with options for the function: (Optional)
%                 options.samplesPerObserved: Populate tr. set with this amount of samples per q(x_i)
%                 options.samplesPerOutput  : When predicting FROM q(x*),
%                                             instead predict from many x*_j's sampled from q(x*) and
%                                             average predictions. samplesPerOutput says how many
%                                             x*_j's to sample.
%----
% RET: LogRegError      : Error when not populating training/predictions
% RET: LogRegErrorExt   : Error when populating training set
% RET: LogRegErrorExtOut: Error when populating trainign and predictions
%
% COPYRIGHT: Andreas C. Damianou, 2015
%
% SEEALSO: vargplvmPredictLatent.m
function [LogRegError, LogRegErrorExt, LogRegErrorExtOut, X_pred, varX_pred] = vargplvmFeatureClassification(model, data, options)

% Train classifiers from X to labels
labels = transformLabels(data.lbls)';
labelsTs = transformLabels(data.lblsTs)';

if ~isfield(data, 'X_pred')
    [X_pred, varX_pred] = ...
        vargplvmPredictLatent(model, data.Yts, [], false, model.globalOpt.reconstrIters,0,[],[],1);
else
    X_pred = data.X_pred;
    varX_pred = data.varX_pred;
end

if nargin < 3 || ~isfield(options, 'samplesPerObserved')
    samplesPerObserved = 5;
else
    samplesPerObserved = options.samplesPerObserved;
end
if nargin < 3 || ~isfield(options, 'samplesPerOutput')
    samplesPerOutput = 10;
else
    samplesPerOutput = options.samplesPerOutput;
end
% Use only SOME dimensions as features (e.g. the ones with best ARD weight)
if nargin < 3 || ~isfield(options, 'dims') || isempty(options.dims)
    dims = 1:model.q;
else
    dims = options.dims;
end

% Populate training set
%--- Take variance into account by sampling new data from the distribution
% Init sizes
Xnew = nan(size(model.vardist.means,1)*samplesPerObserved, size(model.vardist.means,2));
labelsNew = nan(size(Xnew,1), size(labels,2));
k=1;
% Take samples
for n=1:size(model.vardist.means,1)
    for kk = 1:samplesPerObserved
        Xnew(k,:) = model.vardist.means(n,:) + randn(size(model.vardist.means(n,:))).*sqrt(model.vardist.covars(n,:));
        labelsNew(k,:) = labels(n,:);
        k = k + 1;
    end
end
% Augment set with samples
Xext = [model.vardist.means; Xnew];
labelsExt = [labels; labelsNew];
clear 'Xnew' 'labelsNew';

% Training of logistic regression classifier. One for each label
% separately.
nClasses = length(unique(labels));
clear 'B' 'BExt'
for i=1:nClasses
    fprintf('\n # LogReg training for class # %d\n', i)
    lb = zeros(size(model.vardist.means(:,dims),1),1);
    lbExt = zeros(size(Xext(:,dims),1),1);
    lb(labels == i) = 1;
    lbExt(labelsExt == i) = 1;
    B{i} = glmfitWrapper(model.vardist.means(:,dims), lb,'binomial','logit',[],[],[],[],1000);
    BExt{i} = glmfitWrapper(Xext(:,dims), lbExt,'binomial','logit',[],[],[],[],1000);
end

svmmodel    = svmtrain(labels,                 model.vardist.means(:,dims),'-q');
%svmmodelExt = svmtrain(transformLabels(lbExt), model.layer{options.lOut}.vardist.means(:,dims),'-q');

[~, acc,~]    = svmpredict(labelsTs, X_pred(:,dims), svmmodel,'-q');
%[~, accExt] = svmpredict(labelsTs',X_pred, svmmodelExt);

% Prediction of each binary classifier
Ypred_logReg = zeros(size(data.lblsTs));
Ypred_logRegExtOut = zeros(size(data.lblsTs));
Ypred_logRegExt = zeros(size(data.lblsTs));
for i=1:nClasses
    for k=1:samplesPerOutput
        % Sample from the OUTPUT distribution, and then average predictions
        Xsamp = X_pred + randn(size(X_pred)).*sqrt(varX_pred);
        Ypred_logRegExtOut(:,i) = Ypred_logRegExtOut(:,i)+1/samplesPerOutput*glmval(BExt{i}, Xsamp(:,dims), 'logit');
    end
    Ypred_logReg(:,i) = glmval(B{i}, X_pred(:,dims), 'logit')';
    Ypred_logRegExt(:,i) = glmval(BExt{i}, X_pred(:,dims), 'logit')';
end
% Replace predictions with maximum probability (ie, make a decision)
[~,ind]=max(Ypred_logReg');
[~,indExt]=max(Ypred_logRegExt');
[~,indExtOut]=max(Ypred_logRegExtOut');
LogRegError = 0;
LogRegErrorExt = 0;
LogRegErrorExtOut = 0;
for i=1:size(X_pred,1)
    LogRegError = LogRegError + (ind(i) ~= labelsTs(i));
    LogRegErrorExt = LogRegErrorExt + (indExt(i) ~= labelsTs(i));
    LogRegErrorExtOut = LogRegErrorExtOut + (indExtOut(i) ~= labelsTs(i));
end

% fprintf('\n========================== REPORT ===========================\n')
% fprintf('# Error                                             : %d\n', LogRegError);
% fprintf('# Error with %d samp. PerObserved                    : %d\n', samplesPerObserved,LogRegErrorExt);
% fprintf('# Error with %d samp. PerObserved, %d samp.PerOutput : %d\n', samplesPerObserved, samplesPerOutput,LogRegErrorExtOut);
% fprintf('----------------------------------------------------------------\n\n');
%

N = size(X_pred,1);
fprintf('\n========================== REPORT ===========================\n')
fprintf('# Acc Reg:                                             : %.2f%%\n', (N-LogRegError)/N * 100);
fprintf('# Acc Reg: with %d samp. PerObserved                    : %.2f%%\n', samplesPerObserved,(N-LogRegErrorExt)/N*100);
fprintf('# Acc Reg: with %d samp. PerObserved, %d samp.PerOutput : %.2f%%\n', samplesPerObserved, samplesPerOutput,(N-LogRegErrorExtOut)/N*100);
fprintf('# Acc SVM:                                             : %.2f%%\n', acc(1));
%fprintf('# Acc SVM: with % samp. PerObserved                    : %.2f%%\n', samplesPerObserved,accExt(1));
fprintf('----------------------------------------------------------------\n\n');


%% SPHP-garden
% %{
imfolder = 'images\SPHP-garden';
im_n = 2;
imfile = cell(im_n,1);
imfile{1} = [imfolder '\' 'garden_01.jpg'];
imfile{2} = [imfolder '\' 'garden_02.jpg'];

im = cell(im_n,1);
for ii = 1:im_n
    im{ii} = imread(imfile{ii});
end

edge_list = [1,2];

imsize = zeros(im_n,3);

for ii = 1:im_n
    imsize(ii,:) = size(im{ii});
    if imsize(ii,1) > 720
        scale = 720/size(im{ii}, 1);
        im{ii} = imresize(im{ii}, scale);

        imsize(ii,:) = size(im{ii});
    end
end

mosaic = REW_mosaic( im, edge_list, 1, [], 0, imfolder );
%}


function [fathom] = ft2fathom(ft)
% Convert length from feet to fathoms.
% Chad A. Greene 2012
fathom = ft*0.1666666666667;


function test_CSIQ_SVR(testDatabase, testMethod, Trainingproportion)

    fprintf('Results on CSIQ:\n');
    if ~exist(fullfile('result', testDatabase, testMethod), 'dir')
        mkdir(fullfile('result', testDatabase, testMethod));
    end

    ref_list = dir(fullfile('databases', testDatabase,'src_imgs', '*.png'));

    mos = load(fullfile('databases', testDatabase, 'dmos.txt'));
    mos = mos';
    disClasses = dir(fullfile('databases', testDatabase,'dst_imgs'));
    disClasses = disClasses(3:end);
    count = 0;
    for type=1:length(disClasses)
        currentDisClassDirName = fullfile(testDatabase,'dst_imgs', disClasses(type,1).name);
        files = dir(fullfile('databases',currentDisClassDirName, '*.png'));
        for j=1:length(files)
            idx = strfind(files(j,1).name,'.');
            refImg = [files(j,1).name(1:idx(1)) 'png'];
            count = count + 1;
            disFilesList{count} = fullfile('databases',currentDisClassDirName, files(j,1).name);
            refFilesList{count} = fullfile('databases',testDatabase,'src_imgs', refImg);
            for p = 1:numel(ref_list)
                if strcmp(refImg,ref_list(p).name) == 1
                    classes(count) = p;
                    break;
                end
            end
        end
    end

    if ~exist(fullfile('result', testDatabase, testMethod, 'features.mat'), 'file')
        tic;
        for i = 1:numel(disFilesList)
            fprintf('processing image %d / %d \n',i,numel(disFilesList));
            features{i} = CallingTheSourceCodeForFeatureExtraction(disFilesList{i},testMethod);
        end
        features = cat(2,features{:});
        averageTime = toc/numel(disFilesList)
        save(fullfile('result', testDatabase, testMethod, 'features.mat'),'features','mos');
    else
        load(fullfile('result', testDatabase, testMethod, 'features.mat'),'features','mos');
    end

    idx = isnan(features);  features(idx) = 0; % for FRIQUEE

    tic;
    for seed = 1:10
        [trainingSet, testingSet] = generateTrainingSet(classes,seed,Trainingproportion);
        trainX = features(:,trainingSet)';
        testX = features(:,testingSet)';
        [trainX, testX] = featNormalize(trainX, testX);
        switch testMethod
            case 'BRISQUE'
                if Trainingproportion == 0.8
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 16 -g 0.05');
                elseif Trainingproportion == 0.5
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 16 -g 0.07');
                elseif Trainingproportion == 0.2
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 16 -g 0.09');
                end

            case 'CORNIA'
                svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 0');
            case 'HOSA'
                svm_model = train(mos(trainingSet)', sparse(trainX), '-s 11 -c 128');
            case 'DIIVINE'
                if Trainingproportion == 0.2
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 8 -g 0.03');
                elseif Trainingproportion == 0.5
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 8 -g 0.05');
                else
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 8 -g 0.08');
                end
            case 'FRIQUEE'
                if Trainingproportion == 0.8
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 128 -g 0.02');
                elseif Trainingproportion == 0.5
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 128 -g 0.002');
                else
                    svm_model = svmtrain(mos(trainingSet)', double(trainX), '-s 4 -t 2 -c 128 -g 0.08');
                end
            otherwise
                error('Unsupported Method!');
        end
        if strcmp(testMethod,'HOSA')
            [scores, ~,~] = predict(mos(testingSet)', sparse(testX), svm_model,'-q');
        else
            [scores, ~,~] = svmpredict(mos(testingSet)', double(testX), svm_model,'-q');
        end
        SRCC(seed) = corr(scores, mos(testingSet)', 'type', 'Spearman');
        PLCC(seed) = RegressionTID2013(scores, mos(testingSet)');
    end
    toc;
    fprintf('SRCC = %.4f, std = %.4f;  PLCC = %.4f, std = %.4f \n', abs(median(SRCC)), std(SRCC), abs(median((PLCC))), std((PLCC)));

end


function y = prod(varargin)
% Fixes special case prod([],1), prod([],1,...), prod('',1), prod('',1,...)
% Fixes special case prod(sym([])), prod(sym([]),...) (without specifying dimension)
if nargin>1 && isequal(size(varargin{1}), [0 0]) && isequal(varargin{2}, 1)
    y = ones(1,0);
elseif ( nargin==1 && isa(varargin{1}, 'sym') && isequal(size(varargin{1}), [0 0]) ) || ...
       ( nargin>1  && isa(varargin{1}, 'sym') && isequal(size(varargin{1}), [0 0]) && ~isnumeric(varargin{2}) )
    y = 1;
else
    if ~isa(varargin{1},'sym')
        y = builtin('prod', varargin{:});
    else
        y = builtin('@sym/prod', varargin{:});
    end
end
end


function N = uminus(N)
%UMINUS   Unitary minus for CHEBOP2 objects.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Negate all the variables coefficents:
A = N.coeffs;
if ( iscell(A) )
    for jj = 1:size(A, 1)
        for kk = 1:size(A, 2)
            A{jj,kk} = -A{jj,kk};
        end
    end
else
    A = -A;
end

% Do not negate the BCs:
if ( ~isempty(N.lbc) || ~isempty(N.rbc) || ~isempty(N.ubc) || ~isempty(N.dbc) )
    warning('CHEBFUN:CHEBOP2:unimus:BCs', ...
        'Operator has BCs. These were not negated.');
end

% Update the properties of the CHEBOP2:
N.coeffs = A;
op = N.op;
N.op = @(u) -op(u);

end


% TESTBED_PLOT_STATIONS - Plots the stations in the Testbed dataset.
%
% TESTBED_PLOT_STATIONS(COORDINATES, ...)
%
% COORDINATES is a matrix that has longitudes as the first row and latitudes
% as the second row. It can also be a struct which has COORDINATES as a
% field: COORDINATES.coordinates.

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

function testbed_plot_stations(coordinates, varargin)

% Default options
options = struct(...
    'Style', 'o', ...
    'MarkerSize', 4, ...
    'MarkerEdgeColor', 'k', ...
    'MarkerFillColor', [0.7 0 0.7]);
[options, errmsg, remopts] = argparse(options, varargin{:});
error(errmsg);

if nargin < 1
  % Default set of stations
  data = testbed_loaddata();
  data = testbed_preprocess(data);
  coordinates = data.coordinates;
end

if ~isnumeric(coordinates) && isstruct(coordinates)
  coordinates = coordinates.coordinates;
end

% Plot the stations
map_plot(coordinates', ...
         options.Style, ...
         'MarkerSize',      options.MarkerSize, ...
         'MarkerEdgeColor', options.MarkerEdgeColor, ...
         'MarkerFaceColor', options.MarkerFillColor, ...
         remopts{:});


function []=panel6irfdisp(N,n,Units,endo,irf_estimates,strshocks_estimates,IRFperiods,IRFt,stringdates1,T,decimaldates1,pref)

% IRFs
if pref.plot
% plot the figure
irf=figure('Tag','BEARresults');
set(irf,'Color',[0.9 0.9 0.9]);
   if IRFt==1
   set(irf,'name',['impulse response functions (no structural identifcation)']);
   elseif IRFt==2
   set(irf,'name',['impulse response functions (structural identification by Choleski ordering)']);
   elseif IRFt==3
   set(irf,'name',['impulse response functions (structural identification by triangular factorisation)']);
   end
% initiate the count
count=0;
% loop over units
for ii=1:N
   % loop over endogenous variables
   for jj=1:n
      % loop over units (for shocks)
      for kk=1:N
         % loop over shocks
         for ll=1:n
         % increment count
         count=count+1;
         % then plot
         subplot(N*n,N*n,count)
         temp=irf_estimates{(ii-1)*n+jj,(kk-1)*n+ll};
         hold on
         Xpatch=[(1:IRFperiods) (IRFperiods:-1:1)];
         Ypatch=[temp(1,:) fliplr(temp(3,:))];
         IRFpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
         set(IRFpatch,'facealpha',0.5);
         set(IRFpatch,'edgecolor','none');
         plot(temp(2,:),'Color',[0.4 0.4 1],'LineWidth',2);
         plot([1,IRFperiods],[0 0],'k--');
         hold off
         minband=min(temp(1,:));
         maxband=max(temp(3,:));
         space=maxband-minband;
         Ymin=minband-0.2*space;
         Ymax=maxband+0.2*space;
         set(gca,'XLim',[1 IRFperiods],'YLim',[Ymin Ymax],'FontName','Times New Roman');
            % top labels
            if jj==1
            title([Units{kk,1} '\_' endo{ll,1}],'FontWeight','normal');
            end
            % side labels
            if ll==1
            ylabel([Units{ii,1} '\_' endo{jj,1}],'FontWeight','normal');
            end
         end
      end
   end
end
% top supertitle
ax=axes('Units','Normal','Position',[.11 .075 .85 .88],'Visible','off');
set(get(ax,'Title'),'Visible','on')
title('Shock:','FontSize',11,'FontName','Times New Roman','FontWeight','normal');
% side supertitle
ylabel('Response of:','FontSize',12,'FontName','Times New Roman','FontWeight','normal');
set(get(ax,'Ylabel'),'Visible','on');
end
% save on Excel
% create the cell that will be saved on excel
irfcell={};
% build preliminary elements: space between the tables
vertspace=repmat({''},IRFperiods+3,1);
horzspace=repmat({''},2,5*N*n+N);
% loop over units
for ii=1:N
   % loop over endogenous variables
   for jj=1:n
   % initiate the cell of results
   rowcell={};
      % loop over units (for shocks)
      for kk=1:N
      endocell={};
         % loop over shocks
         for ll=1:n
         % create a header
         header=[{['response of ' Units{ii,1} '_' endo{jj,1} ' to ' Units{kk,1} '_' endo{ll,1} ' shocks']} {''} {''} {''};{''} {''} {''} {''};{''} {'lower bound'} {'median'} {'upper bound'}];
         % complete the cell
         tempcell=[[header;num2cell((1:IRFperiods)') num2cell((irf_estimates{(ii-1)*n+jj,(kk-1)*n+ll})')] vertspace];
         % concatenate to the previous parts of unitcell
         endocell=[endocell tempcell];
         end
      rowcell=[rowcell vertspace endocell];
      end
   % concatenate to the previous parts of irfcell
   irfcell=[irfcell;horzspace;rowcell];
   end
irfcell=[irfcell;horzspace];
end
% trim
irfcell=irfcell(3:end-2,2:end-1);
% write in excel
if pref.results==1
    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),irfcell,'IRF','B2');
end

% structural shocks

% generate plot, if there is any structural decomposition
if IRFt~=1
    if pref.plot
% plot
strshocks=figure('Tag','BEARresults');
set(strshocks,'Color',[0.9 0.9 0.9]);
set(strshocks,'name','structural shocks')
% initiate the count
count=0;
   % loop over units
   for ii=1:N
      % loop over endogenous variables
      for jj=1:n
      % increment count
      count=count+1;
      % then plot
      subplot(N,n,count)
      hold on
      Xpatch=[decimaldates1' fliplr(decimaldates1')];
      Ypatch=[strshocks_estimates{jj,1,ii}(1,:) fliplr(strshocks_estimates{jj,1,ii}(3,:))];
      Fpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
      set(Fpatch,'facealpha',0.6);
      set(Fpatch,'edgecolor','none');
      strs=plot(decimaldates1,strshocks_estimates{jj,1,ii}(2,:),'Color',[0.4 0.4 1],'LineWidth',2);
      plot([decimaldates1(1,1),decimaldates1(end,1)],[0 0],'k--');
      hold off
      minband=min(strshocks_estimates{jj,1,ii}(1,:));
      maxband=max(strshocks_estimates{jj,1,ii}(3,:));
      space=maxband-minband;
      Ymin=minband-0.2*space;
      Ymax=maxband+0.2*space;
      set(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'YLim',[Ymin,Ymax],'FontName','Times New Roman');
         % top labels
         if count<=n
         title(endo{count,1},'FontWeight','normal');
         end
         % side labels
         if jj==1
         ylabel(Units{ii,1},'FontWeight','normal');
         end
      end
   end
    end
% save on Excel
% create the cell that will be saved on excel
strshockcell={};
% build preliminary elements: space between the tables
vertspace=repmat({''},T+3,1);
horzspace=repmat({''},3,5*n);
   % loop over units
   for ii=1:N
   % initiate the cell of results
   unitcell={};
      % loop over endogenous variables (horizontal dimension)
      for jj=1:n
      % create a header
      header=[{[Units{ii,1} ': ' endo{jj,1}]} {''} {''} {''};{''} {''} {''} {''};{''} {'lower bound'} {'median'} {'upper bound'}];
      % complete the cell
      endocell=[[header;stringdates1 num2cell(strshocks_estimates{jj,:,ii}')] vertspace];
      % concatenate to the previous parts of unitcell
      unitcell=[unitcell endocell];
      end
   % concatenate to the previous parts of afcell
   strshockcell=[strshockcell;horzspace;unitcell];
   end
% trim
strshockcell=strshockcell(4:end,1:end-1);
% write in excel
if pref.results==1
    bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),strshockcell,'shocks','B2');
end
end


function xfinal = my_ola(xi, len, len1)
len2 = len - len1;

nFr = size(xi,2);
k=1;
xfinal=zeros(nFr*len2,1);
x_old = zeros(len1,1);
for j=1:nFr
%     plot(x_old); hold on;
%     plot(xi(1:len1),'r'); hold off;
%     legend('x_old', 'xi'); pause;
    xfinal(k:k+len1-1) = x_old + xi(1:len1,j);
%     xfinal(k:k+len1-1) = xi(1:len1,j);
    x_old = xi(1+len2:len,j);
    k = k + len2;

%     plot(xfinal(1:k)); pause;
end


function Z = ldivide(X,Y)
%LDIVIDE Left array divide for tensor.
%
%   LDIVIDE(A,B) is called for the syntax 'A .\ B' when A or B is a tensor.
%   A and B must have the same size, unless one is a scalar.
%
%   Examples
%   X = tenrand([4 3 2],5);
%   X .\ 3
%   X .\ X
%
%   See also TENSOR, TENSOR/RDIVIDE.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

Z = tenfun(@ldivide,X,Y);


function [ i, j, v ] = find( x )

%Disciplined convex/geometric programming information for FIND:
%   When used in CVX models, FIND cannot deduce the numeric value of a
%   CVX variable. So it returns the indices of elements that are
%   "structurally" nonzero; i.e., that are not *identically* zero.
%   This is similar to the concept of structural nonzeros in sparse
%   matrix factorizations. To illustrate the distinction, consider:
%      variable x(3);
%      x(2) == 0;
%      y = [x(1);0;x(3)];
%   In this case, FIND(x) returns [1;2;3] even though x(2) has been set
%   to zero in an equality constraint. (After all, the overall model may
%   be infeasible, in which case x(2) is arguably not zero.) However,
%   FIND(y) will return [1;3], because y(2) is identically zero.
%
%   When X is a CVX variable, the first two outputs of [I,J,V]=FIND(X)
%   are constant, and the third is a CVX variable containing the
%   structural nonzeros of X.
%
%   FIND(X) places no convexity restrictions on its argument.

ndxs = find( any( x.basis_, 1 ) );
ndxs = ndxs( : );

if nargout > 1,
    i = ndxs - 1;
    j = floor( i / x.size_(1) ) + 1;
    i = rem( i, x.size_(1) ) + 1;
else
	i = ndxs;
end

if nargout > 2,
    v = reshape( cvx_subsref( x, ndxs ), length( ndxs ) );
end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


classdef ElementSetEnum < matlab.mixin.SetGet
    %ElementSetEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        CartesianElements('Cartesian Elements', ...
                         {'Rx','Ry','Rz','Vx','Vy','Vz'}, ...
                         {'km','km','km','km/s','km/s','km/s'});
        KeplerianElements('Keplerian Orbit Elements', ...
                         {'SMA','Eccentricity','Inclination','RAAN','Arg Peri','True Aomaly'}, ...
                         {'km','','deg','deg','deg','deg'});
        GeographicElements('Geographical Elements', ...
                          {'Latitude','Longitude','Altitude','Velocity Az','Velocity El','Velocity Mag'}, ...
                          {'degN','degE','km','deg','deg','km/s'});
        UniversalElements('Universal Orbit Elements', ...
                         {'C3','Rp','Inclination','RAAN','Arg Peri','Time Past Peri.'}, ...
                         {'km^2/s^2','km','deg','deg','deg','sec'});
    end

    properties
        name(1,:) char
        elemNames(6,1) cell
        unitNames(6,1) cell
    end

    methods
        function obj = ElementSetEnum(name, elemNames, unitNames)
            obj.name = name;
            obj.elemNames = elemNames;
            obj.unitNames = unitNames;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('ElementSetEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('ElementSetEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('ElementSetEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function adj = tet_mesh_order10_adj_set ( node_num, tetra_num, tetra_node, ...
  adj_num, adj_row )

%*****************************************************************************80
%
%% TET_MESH_ORDER10_ADJ_SET sets the nodal adjacency matrix.
%
%  Discussion:
%
%    A compressed format is used for the nodal adjacency matrix.
%
%    It is assumed that we know ADJ_NUM, the number of adjacency entries
%    and the ADJ_ROW array, which keeps track of the list of slots
%    in ADJ where we can store adjacency information for each row.
%
%    We essentially repeat the work of TET_MESH_ORDER4_ADJ_COUNT, but
%    now we have a place to store the adjacency information.
%
%    A copy of the ADJ_ROW array is useful, as we can use it to keep track
%    of the next available entry in ADJ for adjacencies associated with
%    a given row.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, integer TETRA_NUM, the number of tetrahedrons.
%
%    Input, integer TETRA_NODE(10,TETRA_NUM), the nodes that make up the
%    tetrahedrons.
%
%    Input, integer ADJ_NUM, the total number of adjacency relationships,
%
%    Input, integer ADJ_ROW(NODE_NUM+1), the ADJ pointer array.
%
%    Output, integer ADJ(ADJ_NUM), the adjacency information.
%

%
%  Each order 10 tetrahedron defines 45 adjacency pairs.
%
  k = 0;
  for i = 1 : 9
    for j = i + 1 : 10
      pair(1,k*tet_num+1:(k+1)*tet_num) = tet_node(i,1:tet_num);
      pair(2,k*tet_num+1:(k+1)*tet_num) = tet_node(j,1:tet_num);
      k = k + 1;
    end
  end
%
%  Force the nodes of each pair to be listed in ascending order.
%
  pair_num = 45 * tetra_num;
  pair = i4col_sort2_a ( 2, pair_num, pair );
%
%  Rearrange the columns in ascending order.
%
  pair = i4col_sort_a ( 2, pair_num, pair );
%
%  Mark all entries of ADJ so we will know later if we missed one.
%
  adj(1:adj_num) = -1;
%
%  Copy the ADJ_ROW array and use it to keep track of the next
%  free entry for each row.
%
  adj_row_copy(1:node_num) = adj_row(1:node_num);
%
%  Now set up the ADJ_ROW counts.
%
  for k = 1 : pair_num

    if ( 1 < k )
      if ( pair(1,k-1) == pair(1,k) && pair(2,k-1) == pair(2,k) )
        continue
      end
    end

    i = pair(1,k);
    j = pair(2,k);

    adj(adj_row_copy(i)) = j;
    adj_row_copy(i) = adj_row_copy(i) + 1;
    adj(adj_row_copy(j)) = i;
    adj_row_copy(j) = adj_row_copy(j) + 1;

  end

  return
end


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
% ##2
%==============================================================================
%
% function varargout = viewIP(I,omega,m,varargin)
%
% visualizes the intensity projections of a 3D image
%
% Input:
%   I           discretized image
%   omega		describing the domain
%	m 			number of discretization points
%   varargin    optional parameters like {'axis','off'}
%
% Output:
%  ih			image handle
%  I			[I1,I2;I3',0]
%==============================================================================

function varargout = viewIP(I,omega,m,varargin)

if nargin==0
help(mfilename);
    runMinimalExample;
	return;
end

mode = 'max';
% reshape and form the average images
I  = reshape(I,m);
switch mode,
  case 'average',
    I1 = squeeze(sum(I,3))/m(3);
    I2 = squeeze(sum(I,2))/m(2);
    I3 = squeeze(sum(I,1))/m(1);
  case 'max',
    I1 = squeeze(max(I,[],3));
    I2 = squeeze(max(I,[],2));
    I3 = squeeze(max(I,[],1));
  case 'min',
    I1 = squeeze(min(I,[],3));
    I2 = squeeze(min(I,[],2));
    I3 = squeeze(min(I,[],1));
  otherwise, eror('nyi');
end;

I   = [I1,I2;I3',255+zeros(m(3),m(3))]; cla;
ih  = imagesc(I); axis image; hold on
ph1 = plot(0.5+m(2)*[1,1],0.5+[0,m(1)+m(3)],'b-','linewidth',2);
ph2 = plot(0.5+[0,m(2)+m(3)],0.5+m(1)*[1,1],'b-','linewidth',2);
ih  = [ih;ph1;ph2];

% the following lines add some nice stuff to the code.
% if varargin = {'title','FAIR','xlabel','x'}
% the code evaluates "title('FAIR');xlabel('x');"
for k=1:2:length(varargin),
  if not(isempty(varargin{k})),
    feval(varargin{k},varargin{k+1});
  end;
end;

if nargout == 1,
  varargout = {ih};
elseif nargout ==2,
  varargout = {ih,I};
end;

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

function runMinimalExample
load mice3D;
viewIP(dataT,omega,m);
%==============================================================================


% visualize_rbm - Visualize
% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
%
function [f] = visualize_rbm(f, R, v0, vf, h0, hf, W_grad, vbias_grad, hbias_grad);

    n_visible = floor(sqrt(size(R.W,1))).^2;

    set(0, 'CurrentFigure', f);

    subplot(3,3,1);
    visualize(R.W(1:n_visible,:), 1);
    title ('Weights');

    subplot(3,3,2);
    visualize(R.vbias(1:n_visible), 1);

    if R.adaptive_lrate.use == 1
        subplot(3,3,3);
        semilogy(R.signals.lrates);
        title('Learning rates');
    end

    subplot(3,3,4);
    visualize(v0(:,1:n_visible)', 1);
    title ('Data particles');

    subplot(3,3,5);
    visualize(vf(:,1:n_visible)', 1);
    title ('Fantasy particles');

    subplot(3,3,6);
    plot(R.signals.recon_errors);
    title ('Reconstruction errors');

    subplot(3,3,7);
    visualize(W_grad(1:n_visible,:), 1);
    title ('Gradient (Weights)');

    subplot(3,3,8);
    hist(mean(h0, 1));
    xlim([0 1]);
    title ('Average activation (data)');

    subplot(3,3,9);
    hist(mean(hf, 1));
    xlim([0 1]);
    title ('Average activation (model)');