function simulatedSamples = tapas_physio_simulate_pulse_samples(t, c, ...
    nSimulatedSamples, positionString, verbose)
% Simulates samples at start/end of physiological recording by estimating
% pulse template and average pulse rate, and continuing those
%
% simulatedSamples = tapas_physio_simulate_pulse_samples(t, c, ...
%     nSimulatedSamples, positionString, verbose)%
% IN
%
% OUT
%
% EXAMPLE
%   tapas_physio_simulate_pulse_samples
%
%   See also tapas_physio_get_cardiac_pulse_template tapas_physio_read_physlogfiles

% Author:   Lars Kasper
% Created:  2019-01-26
% Copyright (C) 2019 TNU, Institute for Biomedical Engineering,
%                    University of Zurich and ETH Zurich.
%
% This file is part of the TAPAS PhysIO Toolbox, which is released under
% the terms of the GNU General Public License (GPL), version 3. You can
% redistribute it and/or modify it under the terms of the GPL (either
% version 3 or, at your option, any later version). For further details,
% see the file COPYING or <http://www.gnu.org/licenses/>.

doDebug = verbose.level >=2;

% add artificial time series before
simulatedPulses = zeros(nSimulatedSamples, 1);
[pulseTemplate, idxPulses, meanPulseRateInSamples] = ...
    tapas_physio_get_cardiac_pulse_template(t, c, verbose, ...
    'doNormalizeTemplate', false, 'shortenTemplateFactor', .99);

doPrepend = false;
doAppend = false;
switch positionString
    case {'pre', 'before'}
        doPrepend = true;
        % Create last simulated pulse:
        % if first detected pulse in orig time series is further from start
        % than meanPulseRate, assume a regular heart beat also all the way
        % to the start, i.e. spacing by a multiple of meanPulseRateInSamples
        % to last simulated pulse
        if mod(idxPulses(1), meanPulseRateInSamples) == 0
            % if earliest pulse at multiple of pulse rate,
            % then next pulse would be just before start of orig time
            % series
            idxLastSimulatedPulse = nSimulatedSamples;
        else
            idxLastSimulatedPulse = nSimulatedSamples - meanPulseRateInSamples ...
                + mod(idxPulses(1), meanPulseRateInSamples);
        end
        % put 1 where pulses should occur before start of time series,
        % given earliest pulse and mean pulse rate, fill backwards...
        simulatedPulses(idxLastSimulatedPulse:-meanPulseRateInSamples:1) = 1;
    case {'post', 'after'}
        doAppend = true;
        % Create first simulated pulse:
        % if last detected pulse in orig time series is further from end
        % than meanPulseRate, assume a regular heart beat also all the way
        % to the end, i.e. spacing by a multiple of meanPulseRateInSamples
        % to first simulated pulse
        nSamplesOrig = numel(c);
        idxFirstSimulatedPulse = meanPulseRateInSamples ...
           - mod(nSamplesOrig - idxPulses(end), meanPulseRateInSamples);

        % put 1 where pulses should occur after end of time series
        % given last pulse event in orig time series and mean pulse rate...
        simulatedPulses(idxFirstSimulatedPulse:meanPulseRateInSamples:end) = 1;
    otherwise
        tapas_physio_log(...
            sprintf('Unknown positionString ''%s'' for simulating samples; Use ''pre'' or ''post''', positionString),...
            verbose, 2)
end

% ...and convolve with pulse template
% **TODO** tapas_physio_conv
simulatedSamples = conv(simulatedPulses, pulseTemplate, 'same');

if doDebug
    dt = t(2) - t(1);
    if doPrepend
        tNew = -flip(1:nSimulatedSamples)'*dt+t(1);
    elseif doAppend
        tNew = (1:nSimulatedSamples)'*dt+t(end);
    end
    verbose.fig_handles(end+1) = tapas_physio_get_default_fig_params();
    stringTitle = sprintf('Preproc: Added simulated samples %s time series', positionString);

    % plot orig time series and extension by simulated samples
    plot(t,c); hold all;
    plot(tNew, simulatedSamples);

    % plot time events of actual and simulated pulses as stems
    idxSimulatedPulses = find(simulatedPulses);
    stem(t(idxPulses), ones(numel(idxPulses)));
    stem(tNew(idxSimulatedPulses), ones(numel(idxSimulatedPulses)));

    % plot template pulse centered on one simulated pulse
    tStart = tNew(idxSimulatedPulses(1));
    nSamplesTemplate = numel(pulseTemplate);
    tTemplate = tStart+dt*(-ceil(pulseTemplate/2)+(0:(nSamplesTemplate-1)))';
    plot(tTemplate, pulseTemplate);
    title(stringTitle);
end


function m = max(G)
% return maximum value

m = max([G.points]);


% -------------------------------------------------------------------------
function live_paths = incremental_linking(frames,iouth,costtype,jumpgap,threhgap)
% -------------------------------------------------------------------------

num_frames = length(frames);

%% online path building

live_paths = struct(); %% Stores live paths
dead_paths = struct(); %% Store the paths that has been terminated
dp_count = 0;
for  t = 1:num_frames
    num_box = size(frames(t).boxes,1);
    if t==1
        for b = 1 : num_box
            live_paths(b).boxes = frames(t).boxes(b,:);
            live_paths(b).scores = frames(t).scores(b);
            live_paths(b).allScores(t,:) = frames(t).allScores(b,:);
            live_paths(b).pathScore = frames(t).scores(b);
            live_paths(b).foundAT(t) = 1;
            live_paths(b).count = 1;
            live_paths(b).lastfound = 0; %less than 5 mean yes
        end
    else
        lp_count = getPathCount(live_paths);

        %         fprintf(' %d ', t);
        edge_scores = zeros(lp_count,num_box);

        for lp = 1 : lp_count
            edge_scores(lp,:) = score_of_edge(live_paths(lp),frames(t),iouth,costtype);
        end

        dead_count = 0 ;
        coverd_boxes = zeros(1,num_box);
        path_order_score = zeros(1,lp_count);
        for lp = 1 : lp_count
            if live_paths(lp).lastfound < jumpgap %less than 5 mean yes
                box_to_lp_score = edge_scores(lp,:);
                if sum(box_to_lp_score)>0 %%checking if atleast there is one match
                    [m_score,maxInd] = max(box_to_lp_score);
                    live_paths(lp).count = live_paths(lp).count + 1;
                    lpc = live_paths(lp).count;
                    live_paths(lp).boxes(lpc,:) = frames(t).boxes(maxInd,:);
                    live_paths(lp).scores(lpc) = frames(t).scores(maxInd);
                    live_paths(lp).allScores(lpc,:) = frames(t).allScores(maxInd,:);
                    live_paths(lp).pathScore = live_paths(lp).pathScore + m_score;
                    live_paths(lp).foundAT(lpc) = t;
                    live_paths(lp).lastfound = 0;
                    edge_scores(:,maxInd) = 0;
                    coverd_boxes(maxInd) = 1;
                else
                    live_paths(lp).lastfound = live_paths(lp).lastfound +1;
                end

                scores = sort(live_paths(lp).scores,'ascend');
                num_sc = length(scores);
                path_order_score(lp) = mean(scores(max(1,num_sc-jumpgap):num_sc));

            else
                dead_count = dead_count + 1;
            end
        end

        % Sort the path based on scoe of the boxes and terminate dead path

        [live_paths,dead_paths,dp_count] = sort_live_paths(live_paths,....
            path_order_score,dead_paths,dp_count,jumpgap);
        lp_count = getPathCount(live_paths);
        % start new paths using boxes that are not assigned
        if sum(coverd_boxes)<num_box
            for b = 1 : num_box
                if ~coverd_boxes(b)
                    lp_count = lp_count + 1;
                    live_paths(lp_count).boxes = frames(t).boxes(b,:);
                    live_paths(lp_count).scores = frames(t).scores(b);
                    live_paths(lp_count).allScores = frames(t).allScores(b,:);
                    live_paths(lp_count).pathScore = frames(t).scores(b);
                    live_paths(lp_count).foundAT = t;
                    live_paths(lp_count).count = 1;
                    live_paths(lp_count).lastfound = 0;
                end
            end
        end
    end
end

live_paths = fill_gaps(live_paths,threhgap);
dead_paths = fill_gaps(dead_paths,threhgap);
lp_count = getPathCount(live_paths);
lp = lp_count+1;
if isfield(dead_paths,'boxes')
    for dp = 1 : length(dead_paths)
        live_paths(lp).start = dead_paths(dp).start;
        live_paths(lp).end = dead_paths(dp).end;
        live_paths(lp).boxes = dead_paths(dp).boxes;
        live_paths(lp).scores = dead_paths(dp).scores;
        live_paths(lp).allScores = dead_paths(dp).allScores;
        live_paths(lp).pathScore = dead_paths(dp).pathScore;
        live_paths(lp).foundAT = dead_paths(dp).foundAT;
        live_paths(lp).count = dead_paths(dp).count;
        live_paths(lp).lastfound = dead_paths(dp).lastfound;
        lp = lp + 1;
    end
end

live_paths = sort_paths(live_paths);

% -------------------------------------------------------------------------
function sorted_live_paths = sort_paths(live_paths)
% -------------------------------------------------------------------------
sorted_live_paths = struct();

lp_count = getPathCount(live_paths);
if lp_count>0
    path_order_score = zeros(1,lp_count);

    for lp = 1 : length(live_paths)
        scores = sort(live_paths(lp).scores,'descend');
        num_sc = length(scores);
        path_order_score(lp) = mean(scores(1:min(20,num_sc)));
    end

    [~,ind] = sort(path_order_score,'descend');
    for lpc = 1 : length(live_paths)
        olp = ind(lpc);
        sorted_live_paths(lpc).start = live_paths(olp).start;
        sorted_live_paths(lpc).end = live_paths(olp).end;
        sorted_live_paths(lpc).boxes = live_paths(olp).boxes;
        sorted_live_paths(lpc).scores = live_paths(olp).scores;
        sorted_live_paths(lpc).allScores = live_paths(olp).allScores;
        sorted_live_paths(lpc).pathScore = live_paths(olp).pathScore;
        sorted_live_paths(lpc).foundAT = live_paths(olp).foundAT;
        sorted_live_paths(lpc).count = live_paths(olp).count;
        sorted_live_paths(lpc).lastfound = live_paths(olp).lastfound;
    end
end

% -------------------------------------------------------------------------
function gap_filled_paths = fill_gaps(paths,gap)
% -------------------------------------------------------------------------
gap_filled_paths = struct();
if isfield(paths,'boxes')
    g_count = 1;

    for lp = 1 : getPathCount(paths)
        if length(paths(lp).foundAT)>gap
            gap_filled_paths(g_count).start = paths(lp).foundAT(1);
            gap_filled_paths(g_count).end = paths(lp).foundAT(end);
            gap_filled_paths(g_count).pathScore = paths(lp).pathScore;
            gap_filled_paths(g_count).foundAT = paths(lp).foundAT;
            gap_filled_paths(g_count).count = paths(lp).count;
            gap_filled_paths(g_count).lastfound = paths(lp).lastfound;
            count = 1;
            i = 1;
            while i <= length(paths(lp).scores)
                diff_found = paths(lp).foundAT(i)-paths(lp).foundAT(max(i-1,1));
                if count == 1 || diff_found == 1
                    gap_filled_paths(g_count).boxes(count,:) = paths(lp).boxes(i,:);
                    gap_filled_paths(g_count).scores(count) = paths(lp).scores(i);
                    gap_filled_paths(g_count).allScores(count,:) = paths(lp).allScores(i,:);
                    i = i + 1;
                    count = count + 1;
                else
                    for d = 1 : diff_found
                        gap_filled_paths(g_count).boxes(count,:) = paths(lp).boxes(i,:);
                        gap_filled_paths(g_count).scores(count) = paths(lp).scores(i);
                        gap_filled_paths(g_count).allScores(count,:) = paths(lp).allScores(i,:);
                        count = count + 1;
                    end
                    i = i + 1;
                end
            end
            g_count = g_count + 1;
        end
    end
end

% -------------------------------------------------------------------------
function [sorted_live_paths,dead_paths,dp_count] = sort_live_paths(live_paths,...
    path_order_score,dead_paths,dp_count,gap)
% -------------------------------------------------------------------------

sorted_live_paths = struct();
[~,ind] = sort(path_order_score,'descend');
lpc = 0;
for lp = 1 : getPathCount(live_paths)
    olp = ind(lp);
    if live_paths(ind(lp)).lastfound < gap
        lpc = lpc + 1;
        sorted_live_paths(lpc).boxes = live_paths(olp).boxes;
        sorted_live_paths(lpc).scores = live_paths(olp).scores;
        sorted_live_paths(lpc).allScores = live_paths(olp).allScores;
        sorted_live_paths(lpc).pathScore = live_paths(olp).pathScore;
        sorted_live_paths(lpc).foundAT = live_paths(olp).foundAT;
        sorted_live_paths(lpc).count = live_paths(olp).count;
        sorted_live_paths(lpc).lastfound = live_paths(olp).lastfound;
    else
        dp_count = dp_count + 1;
        dead_paths(dp_count).boxes = live_paths(olp).boxes;
        dead_paths(dp_count).scores = live_paths(olp).scores;
        dead_paths(dp_count).allScores = live_paths(olp).allScores;
        dead_paths(dp_count).pathScore = live_paths(olp).pathScore;
        dead_paths(dp_count).foundAT = live_paths(olp).foundAT;
        dead_paths(dp_count).count = live_paths(olp).count;
        dead_paths(dp_count).lastfound = live_paths(olp).lastfound;

    end
end

% -------------------------------------------------------------------------
function score = score_of_edge(v1,v2,iouth,costtype)
% -------------------------------------------------------------------------

N2 = size(v2.boxes,1);
score = zeros(1,N2);

% try
bounds1 = [v1.boxes(end,1:2) v1.boxes(end,3:4)-v1.boxes(end,1:2)+1];
% catch
%     fprintf('catch here')
% end
bounds2 = [v2.boxes(:,1:2) v2.boxes(:,3:4)-v2.boxes(:,1:2)+1];
iou = inters_union(bounds1,bounds2);

for i = 1 : N2

    if iou(i)>=iouth

        scores2 = v2.scores(i);
        scores1 = v1.scores(end);
        score_similarity = sqrt(sum((v1.allScores(end,:) - v2.allScores(i,:)).^2));
        if strcmp(costtype, 'score')
            score(i) =  scores2;
        elseif strcmp(costtype, 'scrSim')
            score(i) = 1-score_similarity;
        elseif strcmp(costtype, 'scrMinusSim')
            score(i) = scores2 + (1 - score_similarity);
        end

    end

end

% -------------------------------------------------------------------------
function lp_count = getPathCount(live_paths)
% -------------------------------------------------------------------------

if isfield(live_paths,'boxes')
    lp_count = length(live_paths);
else
    lp_count = 0;
end

% -------------------------------------------------------------------------
function iou = inters_union(bounds1,bounds2)
% -------------------------------------------------------------------------

inters = rectint(bounds1,bounds2);
ar1 = bounds1(:,3).*bounds1(:,4);
ar2 = bounds2(:,3).*bounds2(:,4);
union = bsxfun(@plus,ar1,ar2')-inters;

iou = inters./(union+eps);


 function y = proj_subset(ob, x, ia_start, ia_inc)
%function y = proj_subset(ob, x, ia_start, ia_inc)
%	y = G(:,ia, :,:) * x
%	caution: ia_start is from 1, not 0!

%if ob.is.empty, error empty, end
if ob.apower ~= 1, error 'power not done', end
if ob.is_transpose, error 'transpose not done', end

if ob.is_masked
	x = embed(x, ob.mask);
end

y = wtfmex('dsc,proj', ob.arg', single(x), ob.mask, ...
	int32(ia_start-1), int32(ia_inc), int32(ob.nthread), ob.chat);

y = y(:,ia_start:ia_inc:ob.na);

y = ob.scale * double(y(:));


% NEWTIMEFTRIALBASELN - Remove baseline power values for single trials in
%        newtimef. This only remove single trial baseline (not the average
%        baseline).
%
% Usage:
%   >>  tf = newtimefbaseln(tf, tvals, 'key', val);
%
% Inputs:
%   tf       - [3-D or 4-D array] single-trial spectral estimates
%           [freqs x times x trials] or [channels x freqs x times x trials)
%           The function may also process cell arrays of such inputs.
%   tvals    - [array] time values
%
% Optional inputs: 'baseline', 'basenorm' and 'trialbase'. Same definition
%  as for newtimef. If trialbase is 'off' this function does nothing.
%
% Outputs:
%   tf        - Baseline correct power (same size as input)
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, August 2016

% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2016, arno@sccn.ucsd.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function PP = newtimeftrialbaseln(PPori, timesout, varargin)

if nargin < 3
    help newtimefbaseln;
    return;
end

[g timefreqopts ] = finputcheck(varargin, ...
    {'basenorm'      'string'    {'on','off'} 'off';
    'baseline'      'real'      []          0;
    'trialbase'     'string'    {'on','off','full'} 'off';
    'verbose'       'string'    {'on','off'} 'on';
    }, 'newtimeftrialbaseln', 'ignore');
if ischar(g) error(g); return; end
PP = PPori; if ~iscell(PP), PP = { PP }; end

% ---------------
% baseline length
% ---------------
if size(g.baseline,2) == 2
    baseln = [];
    for index = 1:size(g.baseline,1)
        tmptime   = find(timesout >= g.baseline(index,1) & timesout <= g.baseline(index,2));
        baseln = union_bc(baseln, tmptime);
    end
    if length(baseln)==0
        error( [ 'There are no sample points found in the default baseline.' 10 ...
            'This may happen even though data time limits overlap with' 10 ...
            'the baseline period (because of the time-freq. window width).' 10 ...
            'Either disable the baseline, change the baseline limits.' ] );
    end
else
    if ~isempty(find(timesout < g.baseline))
         baseln = find(timesout < g.baseline); % subtract means of pre-0 (centered) windows
    else baseln = 1:length(timesout); % use all times as baseline
    end
end

for ind = 1:length(PP(:))

    P = PP{ind};

    % -----------------------------------------
    % remove baseline on a trial by trial basis
    % -----------------------------------------
    if strcmpi(g.trialbase, 'on'), tmpbase = baseln;
    else                           tmpbase = 1:size(P,2); % full baseline
    end
    if ~strcmpi(g.trialbase, 'off')
        if ndims(P) == 4
            mbase = mean(P(:,:,tmpbase,:),3);
            if strcmpi(g.basenorm, 'on')
                mstd = std(P(:,:,tmpbase,:),[],3);
                P = bsxfun(@rdivide, bsxfun(@minus, P, mbase), mstd);
            else P = bsxfun(@rdivide, P, mbase);
            end
        else
            mbase = mean(P(:,tmpbase,:),2);
            if strcmpi(g.basenorm, 'on')
                mstd = std(P(:,tmpbase,:),[],2);
                P = (P-repmat(mbase,[1 size(P,2) 1]))./repmat(mstd,[1 size(P,2) 1]); % convert to log then back to normal
            else
                P = P./repmat(mbase,[1 size(P,2) 1]);
                %P = 10 .^ (log10(P) - repmat(log10(mbase),[1 size(P,2) 1])); % same as above
            end
        end
    end

    PP{ind} = P;
end
if ~iscell(PPori) PP = PP{1}; end


function data = data2struct(data,T,options)

if length(options.embeddedlags)>1
    L = -min(options.embeddedlags) + max(options.embeddedlags);
else
    L = options.maxorder;
end

if ~isstruct(data), data = struct('X',data); end
if ~isfield(data,'C')
    if options.K>1, data.C = NaN(size(data.X,1)-L*length(T),options.K);
    else data.C = ones(size(data.X,1)-L*length(T),1);
    end
elseif size(data.C,1)==sum(T) && L>0 % we need to trim C
    ind = [];
    for j=1:length(T)
        t0 = sum(T(1:j-1)) - L*(j-1);
        if length(options.embeddedlags)>1
            ind = [ind (t0+1-min(options.embeddedlags)):(t0+T(j)-max(options.embeddedlags)) ];
        else
            ind = [ind (t0+options.maxorder+1:t0+T(j))];
        end
    end
    data.C = data.C(ind,:);
    %warning('C has more rows than it should; the first rows of each trial will be discarded\n')
end

end


%compute dcentralheadmag
function [data,units]=compute_dcentralheadmag(trx,n)

% inputfilename=[outputfolder,'centralheadmag.mat'];
% if ~exist(inputfilename,'file')
%     [trx]=compute_centralheadmag(trx,outputfolder);
% end
% load([outputfolder,'centralheadmag.mat'], 'data')
% centralheadmag=data;
%

larvae=trx.exp2flies{n};
numlarvae=numel(larvae);
dcentralheadmag=cell(1,numlarvae);
for i=1:numlarvae
    larva=larvae(i);
    dcentralheadmag{1,i}=(trx(larva).centralheadmag(2:end)-trx(larva).centralheadmag(1:end-1))./trx(larva).dt;
end

units=parseunits('mm/s');
data=dcentralheadmag;
% filename=[outputfolder, 'dcentralheadmag.mat'];
% save(filename, 'data', 'units')


function dispma3()
    % compare two rates, no fit
    % selects 4 times to define begining and end of two segments in
    % cumulative number curve and calls bvalnofit
    %
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals
    report_this_filefun();

    t1p = min(ZG.newt2.Date);
    t4p = max(ZG.newt2.Date);
    t2p = t4p - (t4p-t1p)/2;
    t3p = t2p;

    show_dialog()

    function show_dialog()
        % Input times t1p t2p t3p and t4p by editing or use cursor if desired
        %

        dlg=ZmapDialog();
        dlg.AddEdit('t1p','Time 1 (T1):', t1p,'enter begin segment 1');
        dlg.AddEdit('t2p','Time 2 (T2):', t2p,'enter end segment 1');
        dlg.AddEdit('t3p','Time 3 (T3):', t3p,'enter begin segment 2');
        dlg.AddEdit('t4p','Time 4 (T4):', t4p,'enter end segment 2');
        dlg.AddCheckbox('usecursor','Use Cursor', false,[],'select with mouse');

        par2 = 0.1 * ZG.newt2.Count;

        [myans, okpressed] =dlg.Create('Name', 'Select two time segments');
        if ~okpressed
            return
        end
        if myans.usecursor
            mouse_select()
        else
            bvanofit(ZG.newt2, [myans.t1p,myans.t2p] , [myans.t3p, myans.t4p]);
        end
    end

    function mouse_select()
        figure(findobj('Tag','cum','-and','Type','Figure'));

        seti = uicontrol('Units','normal','Position',[.4 .01 .2 .05],'String','Select T1  ');

        pause(0.5)

        par2 = 0.1 * ZG.newt2.Count;
        par3 = 0.12 * ZG.newt2.Count;
        t1 = ginput(1);
        t1p = [  t1 ; t1(1) t1(2)-par2; t1(1)   t1(2)+par2 ];
        plot(t1p(:,1),t1p(:,2),'r')
        text( t1(1),t1(2)+par3,['t1: ', num2str(t1p(1))] )
        seti.String = 'select T2';

        pause(0.5)

        t2 = [];
        t2 = ginput(1);
        t2p = [  t2 ; t2(1) t2(2)-par2; t2(1)   t2(2)+par2 ];
        plot(t2p(:,1),t2p(:,2),'r')
        text( t2(1),t2(2)+par3,['t2: ', num2str(t2p(1))] )
        seti.String = 'select T3';

        pause(0.5)

        t3 = [];
        t3 = ginput(1);
        t3p = [  t3 ; t3(1) t3(2)-par2; t3(1)   t3(2)+par2 ];
        plot(t3p(:,1),t3p(:,2),'r')
        text( t3(1),t3(2)+par3,['t3: ', num2str(t3p(1))] )
        seti.String = 'select T4';

        pause(0.5)

        t4 = [];
        t4 = ginput(1);
        t4p = [  t4 ; t4(1) t4(2)-par2; t4(1)   t4(2)+par2 ];
        plot(t4p(:,1),t4p(:,2),'r')
        text( t4(1),t4(2)+par3,['t4: ', num2str(t4p(1))] )

        delete(seti)

        show_dialog()
        pause(0.1)
    end
end


classdef BodyFixedOrbitVariable < AbstractOrbitModelVariable
    %BodyFixedOrbitVariable Summary of this class goes here
    %   Detailed explanation goes here

    properties
        varObj(1,1) BodyFixedOrbitStateModel = BodyFixedOrbitStateModel.getDefaultOrbitState();

        lb(1,6) double = 0;
        ub(1,6) double = 0;

        varLat(1,1) logical = false;
        varLong(1,1) logical = false;
        varAlt(1,1) logical = false;
        varBFAz(1,1) logical = false;
        varBFEl(1,1) logical = false;
        varBFMag(1,1) logical = false;
    end

    methods
        function obj = BodyFixedOrbitVariable(varObj)
            obj.varObj = varObj;
            obj.varObj.optVar = obj;

            obj.id = rand();
        end

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

            if(obj.varLat)
                x(end+1) = obj.varObj.lat;
            end

            if(obj.varLong)
                x(end+1) = obj.varObj.long;
            end

            if(obj.varAlt)
                x(end+1) = obj.varObj.alt;
            end

            if(obj.varBFAz)
                x(end+1) = obj.varObj.vVectNEZ_az;
            end

            if(obj.varBFEl)
                x(end+1) = obj.varObj.vVectNEZ_el;
            end

            if(obj.varBFMag)
                x(end+1) = obj.varObj.vVectNEZ_mag;
            end
        end

        function [lb, ub] = getBndsForVariable(obj)
            useTf = obj.getUseTfForVariable();

            lb = obj.lb(useTf);
            ub = obj.ub(useTf);
        end

        function [lb, ub] = getAllBndsForVariable(obj)
            lb = obj.lb;
            ub = obj.lb;
        end

        function setBndsForVariable(obj, lb, ub)
            if(length(lb) == 6 && length(ub) == 6)
                obj.lb = lb;
                obj.ub = ub;
            else
                useTf = obj.getUseTfForVariable();

                obj.lb(useTf) = lb;
                obj.ub(useTf) = ub;
            end
        end

        function useTf = getUseTfForVariable(obj)
            useTf = [obj.varLat        obj.varLong        obj.varAlt        obj.varBFAz        obj.varBFEl        obj.varBFMag];
        end

        function setUseTfForVariable(obj, useTf)
            obj.varLat  = useTf(1);
            obj.varLong = useTf(2);
            obj.varAlt  = useTf(3);
            obj.varBFAz = useTf(4);
            obj.varBFEl  = useTf(5);
            obj.varBFMag = useTf(6);
        end

        function updateObjWithVarValue(obj, x)
            xInd = 1;

            if(obj.varLat)
                obj.varObj.lat = x(xInd);
                xInd = xInd + 1;
            end

            if(obj.varLong)
                obj.varObj.long = x(xInd);
                xInd = xInd + 1;
            end

            if(obj.varAlt)
                obj.varObj.alt = x(xInd);
                xInd = xInd + 1;
            end

            if(obj.varBFAz)
                obj.varObj.vVectNEZ_az = x(xInd);
                xInd = xInd + 1;
            end

            if(obj.varBFEl)
                obj.varObj.vVectNEZ_el = x(xInd);
                xInd = xInd + 1;
            end

            if(obj.varBFMag)
                obj.varObj.vVectNEZ_mag = x(xInd);
                xInd = xInd + 1; %#ok<NASGU>
            end
        end

        function nameStrs = getStrNamesOfVars(obj, evtNum, varLocType)
            nameStrs = {sprintf('Event %i Latitude', evtNum), ...
                        sprintf('Event %i Longitude', evtNum), ...
                        sprintf('Event %i Altitude', evtNum), ...
                        sprintf('Event %i Body-Fixed Velocity Azimuth', evtNum), ...
                        sprintf('Event %i Body-Fixed Velocity Elevation', evtNum), ...
                        sprintf('Event %i Body-Fixed Velocity Magnitude', evtNum)};

            nameStrs = nameStrs(obj.getUseTfForVariable());
        end
    end
end


classdef nnmnist < nntest
  properties (TestParameter)
    networkType = {'dagnn', 'simplenn'}
  end

  methods (TestClassSetup)
    function init(test)
      addpath(fullfile(vl_rootnn, 'examples', 'mnist'));
    end
  end

  methods (Test)
    function valErrorRate(test, networkType)
      clear mex ; % will reset GPU, remove MCN to avoid crashing
                  % MATLAB on exit (BLAS issues?)
      if strcmp(test.dataType, 'double'), return ; end
      switch test.currentDevice
        case 'cpu'
          gpus = [];
        case 'gpu'
          gpus = 1;
      end
      trainOpts = struct('numEpochs', 1, 'continue', false, 'gpus', gpus, ...
        'plotStatistics', false);
      if strcmp(networkType, 'simplenn')
        trainOpts.errorLabels = {'error', 'top5err'} ;
      end
      [~, info] = cnn_mnist('train', trainOpts, 'networkType', networkType);
      test.verifyLessThan(info.train.error, 0.08);
      test.verifyLessThan(info.val.error, 0.025);
    end
  end
end


function nfgSetupMRDiffusion(phantomDir)
%Setup mrDiffusion files for BlueMatter NFG tests.
%
%   nfgSetupMRDiffusion(phantomDir)
%
%
% AUTHORS:
%   2009.08.05 : AJS wrote it
%
% NOTES:
%   * We are automatically dividing the NFG b-value by 1000, but there
%   should be a more appropriate dynamic way to do this.
%

% Directories
dtDir = nfgGetName('dtDir',phantomDir);
% Input Files
nfgGradFile = nfgGetName('nfgGradFile',phantomDir);
noisyImg = nfgGetName('noisyImg',phantomDir);
brainMaskFile = nfgGetName('brainMaskFile',phantomDir);
% Output Files
bvalsFile = nfgGetName('bvalsFile',phantomDir);
bvecsFile = nfgGetName('bvecsFile',phantomDir);

% XXX b-value factor to adjust into our units
bValFactor = 1000;

% Convert NFG grad file to ours
disp(' '); disp('Converting NFG gradient file to mrDiffusion format ...');
grad = load(nfgGradFile,'-ascii');
bvals = grad(:,4)/bValFactor;
bvecs = grad(:,1:3)';
fid = fopen(bvalsFile,'wt');
fprintf(fid, '%1.3f ', bvals);
fclose(fid);
fid = fopen(bvecsFile,'wt');
fprintf(fid, '%1.4f ', bvecs(1,:)); fprintf(fid, '\n');
fprintf(fid, '%1.4f ', bvecs(2,:)); fprintf(fid, '\n');
fprintf(fid, '%1.4f ', bvecs(3,:));
fclose(fid);

% Do tensor fitting
numBootstraps=300;
disp(' '); disp(['Tensor fitting with ' num2str(numBootstraps) ' bootstraps ...']);
dtiRawFitTensorMex(noisyImg, bvecsFile, bvalsFile, dtDir, numBootstraps);

% Fix automatically generated brain mask
disp(' '); disp('Fixing automatically generated brain mask ...');
ni = niftiRead(brainMaskFile);
ni.data(:) = 1;
writeFileNifti(ni);

% Need to produce pdf image now
disp(' '); disp('Creating ConTrack PDF file ...');
mtrCreateConTrackOptionsFromROIs(0,1,dtDir);

return;


function dlY = spatialDropout(dlX,dropoutFactor,fmt,doTraining)

if doTraining
    maskSize = size(dlX);
    maskSize(fmt=='S') = 1;

    dropoutScaleFactor = single(1 - dropoutFactor);
    dropoutMask = (rand(maskSize,'like',dlX) > dropoutFactor) / dropoutScaleFactor;

    dlY = dlX .* dropoutMask;
else
    dlY = dlX;
end

end


function runTracker_VOT(hp_name, hp_value)
%RUN_TRACKER_VOT executes the tracker within the evaluation of the VOT toolkit

    %% Read params.txt
	if nargin>0
		% hyperparams mode
	    params = readParams('params.txt', hp_name, hp_value);
	else
		% normal mode
		params = readParams('params.txt');
	end

    %% Read files
    fid = fopen('images.txt','r');
    inter = textscan(fid,'%[^\n]');
    params.img_files = inter{1,1};
    im = imread(params.img_files{1});
    fclose(fid);

    % check if sequence is grayscale
    if(size(im,3)==1)
        params.grayscale_sequence = true;
    end

    params.bb_VOT = csvread('region.txt');
    region = params.bb_VOT(1,:);
    params.img_path = '';
    % save sequence name
    C = strsplit(params.img_files{1},'/');
    if ~isempty(C)
        params.sequence = C{end-1};
    else
        params.sequence = 'error_sequence_not_detected';
    end
    %% Convert to axis-aligned bbox
    if(numel(region)==8)
        % polygon format
        [cx, cy, w, h] = getAxisAlignedBB(region);
    else
        x = region(1);
        y = region(2);
        w = region(3);
        h = region(4);
        cx = x+w/2;
        cy = y+h/2;
    end

    % init_pos is the centre of the initial bounding box
    params.init_pos = [cy cx];
    params.target_sz = round([h w]);

    [params, bg_area, fg_area, area_resize_factor] = initializeAllAreas(im, params);

    params.fout = fopen('output.txt','w');

    % start actual tracking
    trackerMain(params,im, bg_area, fg_area, area_resize_factor);
    fclose('all');
    % within VOT benchmark the tracker has to terminate at the end of each sequence
    exit
end


function aviname = MakeJAABAResultsMovie_PositiveClips(expdir,scorefn,varargin)

%%

textcolor = [0,0,0];
fontsize = 14;
trx_linewidth = 1;
target_linewidth = 2;
trxcolor = [0,0,0];
labelcolor = [.7,0,0];
trx_rad = 25;
compression = 'None';
allowedcompressions = {'Indeo3', 'Indeo5', 'Cinepak', 'MSVC', 'RLE', 'None','Uncompressed AVI','Motion JPEG AVI'};
useVideoWriter = exist('VideoWriter','file');
aviname = '';
fps = 10;
usemencoder = true;

[nzoomr,nzoomc,...
  figpos,...
  moviefilestr,trxfilestr,...
  hfig,...
  nframesout,...
  weight_id,weight_tmid,...
  weight_length,weight_sumscore,...
  weight_meanscore,...
  min_sumscore,...
  min_length,...
  pxwidthradius,...
  pxheightradius,...
  awidthradius,...
  aheightradius,...
  pxborder,...
  aborder,...
  nframesborder,...
  labelcolor,...
  useVideoWriter,...
  avifileTempDataFile,aviname,fps,...
  usemencoder,...
  behavior,...
  debug] ...
  = myparse(varargin,...
  'nzoomr',4,'nzoomc',5,...
  'figpos',[50,50,1500,1000],...
  'moviefilestr','movie.ufmf',...
  'trxfilestr','registered_trx.mat',...
  'hfig',1001,...
  'nframesout',500,...
  'weight_id',100,...
  'weight_tmid',1,...
  'weight_length',1,...
  'weight_sumscore',1,...
  'weight_meanscore',.01,...
  'min_sumscore',0,...
  'min_length',0,...
  'pxwidthradius',[],...
  'pxheightradius',[],...
  'awidthradius',3,...
  'aheightradius',3,...
  'pxborder',5,...
  'aborder',1,...
  'nframesborder',5,...
  'labelcolor',labelcolor,...
  'useVideoWriter',useVideoWriter,...
  'avifileTempDataFile','',...
  'aviname',aviname,...
  'fps',fps,...
  'usemencoder',usemencoder,...
  'behavior','',...
  'debug',false);

TMID = 1;
LENGTH = 2;
SUMSCORE = 3;
MEANSCORE = 4;

w = nan(4,1);
w(TMID) = weight_tmid;
w(LENGTH) = weight_length;
w(SUMSCORE) = weight_sumscore;
w(MEANSCORE) = weight_meanscore;

if ~ischar(compression),
  compression = '';
end
if ~ispc && ~useVideoWriter,
  compression = 'None';
end
if ~isempty(compression) && ~any(strcmpi(compression,allowedcompressions)),
  fprintf('Unknown compressor %s\n',compression);
  compression = '';
end

if isempty(aviname),
  [~,experiment_name] = fileparts(expdir);
  if isempty(behavior),
    tmp = regexprep(scorefn,'\.mat$','');
    tmp = regexprep(tmp,'[sS]cores_?','');
    behavior = regexprep(tmp,'[sS]core_?','');
  end
  aviname = fullfile(expdir,sprintf('JAABA%sExamples_%s.avi',behavior,experiment_name));
end

%% open files
moviename = fullfile(expdir,moviefilestr);
[readframe,nframes,fid] = get_readframe_fcn(moviename);
im = readframe(1);
[nr,nc,ncolors] = size(im);

trxname = fullfile(expdir,trxfilestr);
[trx,trxname,loadsucceeded,timestamps] = load_tracks(trxname);
if ~loadsucceeded,
  error('Could not load trx from file %s',trxname);
end
nids = length(trx);
trxendframes = [trx.endframe];
trxfirstframes = [trx.firstframe];
T0 = min(trxfirstframes);
T1 = max(trxendframes);

scorefilename = fullfile(expdir,scorefn);
tmp = load(scorefilename);
scores = cell(1,nids);
labels = cell(1,nids);
for j = 1:nids,
  scores{j} = tmp.allScores.scores{j}(trxfirstframes(j):trxendframes(j));
  labels{j} = tmp.allScores.postprocessed{j}(trxfirstframes(j):trxendframes(j))>0;
 end

%% compute statistics of bouts

X = [];
ids = [];
allt0s = [];
allt1s = [];
alllengths = [];

for i = 1:nids,
  idx = scores{i} > 0;
  [t0s,t1s] = get_interval_ends(idx);
  t1s = t1s - 1;
  sumscores = [0,cumsum(scores{i})];
  allt0s = [allt0s,t0s]; %#ok<AGROW>
  allt1s = [allt1s,t1s]; %#ok<AGROW>
  ids = [ids,i+zeros(size(t0s))]; %#ok<AGROW>
  xcurr = nan(4,numel(t0s));
  xcurr(TMID,:) = (t0s+t1s)/2;
  xcurr(LENGTH,:) = t1s-t0s+1;
  alllengths = [alllengths,xcurr(LENGTH,:)]; %#ok<AGROW>
  xcurr(SUMSCORE,:) = sumscores(t1s+1)-sumscores(t0s);
  xcurr(MEANSCORE,:) = xcurr(SUMSCORE,:) ./ xcurr(LENGTH,:);
  X = [X,xcurr]; %#ok<AGROW>
end
badidx = X(SUMSCORE,:) < min_sumscore | X(LENGTH,:) < min_length;
X(:,badidx) = [];
allt0s(badidx) = [];
allt1s(badidx) = [];
ids(badidx) = [];
nbouts = size(X,2);

% get the rank for each of these stats
for i = 1:size(X,1),
  [~,order] = sort(X(i,:));
  [~,order] = sort(order);
  X(i,:) = order / nbouts; %#ok<AGROW>
end

ischosen = false(1,nbouts);
did = ones(1,nbouts);
dx = ones(size(X));
nframesfilled = zeros([nzoomr,nzoomc]);
boutis = cell(nzoomr,nzoomc);
while true,

  % choose the most different example
  d = weight_id*did + sum(bsxfun(@times,w,dx),1);
  d(ischosen) = -1;
  maxd = max(d);
  idxcurr = find(d == maxd);
  if numel(idxcurr) > 1,
    i = randsample(idxcurr,1);
  else
    i = idxcurr;
  end

  if ischosen(i),
    break;
  end

  % update distances
  did(ids == ids(i)) = 0;
  dx = min(dx,abs(bsxfun(@minus,X,X(:,i))));

  % try to put this somewhere
  [nfilledcurr,j] = min(nframesfilled(:));

  if nfilledcurr >= nframesout,
    break;
  end

  t0 = max(1,allt0s(i)-nframesborder);
  t1 = min(trx(ids(i)).nframes,allt1s(i)+nframesborder);
  n = t1-t0+1;

  [r,c] = ind2sub([nzoomr,nzoomc],j);
  boutis{r,c}(end+1) = i;
  nframesfilled(j) = nframesfilled(j) + n;
  ischosen(i) = true;

end

nframesout = min(nframesout,max(nframesfilled(:)));

tsout = nan(nzoomr,nzoomc,nframesout);
idsout = nan(nzoomr,nzoomc,nframesout);
t1sout = nan(nzoomr,nzoomc,nframesout);

for r = 1:nzoomr,
  for c = 1:nzoomc,
    off = 0;
    for i = 1:numel(boutis{r,c}),
      j = boutis{r,c}(i);
      t0 = max(1,allt0s(j)-nframesborder) + trx(ids(j)).firstframe - 1;
      t1 = min(trx(ids(j)).nframes,allt1s(j)+nframesborder) + trx(ids(j)).firstframe - 1;
      n = t1-t0+1;
      idsout(r,c,off+1:off+n) = ids(j);
      tsout(r,c,off+1:off+n) = t0:t1;
      t1sout(r,c,off+1:off+n) = t1;
      off = off + n;
    end
  end
end

%% output window sizes

a = [trx.a];
meana = nanmedian(a)*4;
if isempty(pxwidthradius),
  pxwidthradius = awidthradius*meana;
end
if isempty(pxheightradius),
  pxheightradius = aheightradius*meana;
end
if isempty(pxborder),
  pxborder = aborder*meana;
end

axh = figpos(4)/nzoomr;
axw = figpos(3)/nzoomc;
pxheightradius1 = min((pxwidthradius)*axh / axw,(nr-1)/2);
pxwidthradius1 = min((pxheightradius)*axw / axh,(nc-1)/2);
pxheightradius = max(pxheightradius1,pxheightradius);
pxwidthradius = max(pxwidthradius1,pxwidthradius);
ax = MakeJAABAResultsMovie_ResetAxis(nc/2,nr/2,1,nr,nc,pxwidthradius,pxheightradius,pxborder);
axround = max(1,[min(nc,[floor(ax(1)),ceil(ax(2))]),...
  min(nr,[floor(ax(3)),ceil(ax(4))])]);
ax = repmat(ax(:),[1,nzoomr,nzoomc]);
axround = repmat(axround(:),[1,nzoomr,nzoomc]);

%% create the figure

figure(hfig);
clf;
set(hfig,'Position',figpos);

hax = createsubplots(nzoomr,nzoomc,0);
hax = reshape(hax,[nzoomr,nzoomc]);
hinfo = nan(nzoomr,nzoomc);
him = nan(nzoomr,nzoomc);
htrx = nan(nzoomr,nzoomc);
htarget = nan(nzoomr,nzoomc);
hlabel = nan(nzoomr,nzoomc);
for i = 1:nzoomr*nzoomc,
  him(i) = imagesc(0,'Parent',hax(i),[0,255]);
  axis(hax(i),'image');
  axis(hax(i),ax(:,i)');
  hold(hax(i),'on');
  htrx(i) = plot(hax(i),nan,nan,'.-','LineWidth',trx_linewidth,'color',trxcolor);
  hlabel(i) = plot(hax(i),nan,nan,'.','LineWidth',trx_linewidth,'color',labelcolor);
  htarget(i) = plot(hax(i),nan,nan,'-','LineWidth',target_linewidth,'color','k');
  hinfo(i) = text(ax(1,i),ax(4,i),'','Parent',hax(i),'Color',textcolor,...
    'FontUnits','pixels','FontSize',fontsize,...
    'HorizontalAlignment','left',...
    'VerticalAlignment','bottom');

  set(hax(i),'XTickLabel',{},'YTickLabel',{});
end
colormap gray;

if ~debug,
  set(hfig,'Visible','off');
end

%%

isfirstframe = true;

for j = 1:nframesout,

  if mod(j,10) == 0,
    fprintf('Frame %d / %d\n',j,nframesout);
  end
  for r = 1:nzoomr,
    for c = 1:nzoomc,
      t = tsout(r,c,j);
      if isnan(t),
        set(him(r,c),'CData',0);
        set(htrx(r,c),'XData',nan,'YData',nan);
        set(hlabel(r,c),'XData',nan,'YData',nan);
        set(htarget(r,c),'XData',nan,'YData',nan);
        set(hinfo(r,c),'String','');
        continue;
      end
      fly = idsout(r,c,j);
      i = t+trx(fly).off;
      im = readframe(t);

      i0 = max(1,min(trx(fly).nframes,i-trx_rad));
      i1 = max(1,min(trx(fly).nframes,i+trx_rad));
      tmpx = trx(fly).x(i0:i1);
      tmpy = trx(fly).y(i0:i1);

      set(htrx(r,c),'XData',tmpx,...
        'YData',tmpy);
      set(hlabel(r,c),'XData',tmpx(labels{fly}(i0:i1)),...
        'YData',tmpy(labels{fly}(i0:i1)));

      updatefly(htarget(r,c),trx(fly).x(i),trx(fly).y(i),...
        trx(fly).theta(i),trx(fly).a(i),trx(fly).b(i));
      if labels{fly}(i),
        set(htarget(r,c),'Color',labelcolor);
      else
        set(htarget(r,c),'Color',trxcolor);
      end

      outofbounds = trx(fly).x(i)-pxborder < ax(1,r,c) || ...
        trx(fly).x(i)+pxborder > ax(2,r,c) || ...
        trx(fly).y(i)-pxborder < ax(3,r,c) || ...
        trx(fly).y(i)+pxborder > ax(4,r,c);

      if j == 1 || tsout(r,c,j)-1 ~= tsout(r,c,j-1) || outofbounds,
        j1 = t1sout(r,c,j)+trx(fly).off;
        ax(:,r,c) = MakeJAABAResultsMovie_ResetAxis(trx(fly).x(i:j1),trx(fly).y(i:j1),1,nr,nc,pxwidthradius,pxheightradius,pxborder);
        axis(hax(r,c),ax(:,r,c)');
        set(hinfo(r,c),'Position',ax([1,4]));
        axround(:,r,c) = max(1,[min(nc,[floor(ax(1,r,c)),ceil(ax(2,r,c))]),...
          min(nr,[floor(ax(3,r,c)),ceil(ax(4,r,c))])]);
        set(hinfo(r,c),'Position',ax([1,4],r,c));
      end
      set(him(r,c),'CData',im(axround(3,r,c):axround(4,r,c),axround(1,r,c):axround(2,r,c)),...
        'XData',axround([1,2],r,c),'YData',axround([3,4],r,c));
      set(hinfo(r,c),'String',sprintf('Target %d, t = %fs',fly,timestamps(t)));
    end
  end

  if isfirstframe,
    if ~debug,

      if useVideoWriter,
        if strcmpi(compression,'None') || strcmpi(compression,'Uncompressed AVI'),
          profile = 'Uncompressed AVI';
        else
          profile = 'Motion JPEG AVI';
        end
        aviobj = VideoWriter(aviname,profile); %#ok<TNMLP>
        set(aviobj,'FrameRate',fps);
        if ~strcmpi(profile,'Uncompressed AVI'),
          set(aviobj,'Quality',100);
        end
        open(aviobj);
      else
        if isempty(avifileTempDataFile),
          aviobj = avifile(aviname,'fps',fps,'quality',100,'compression',compression);  %#ok<REMFF1>
        else
          aviobj = myavifile(aviname,'fps',fps,'quality',100,'compression',compression,...
            'TempDataFile',avifileTempDataFile);
          fprintf('Temporary data file for avi writing: %s\n',aviobj.TempDataFile);
        end
      end
    end

  end

  if ~debug,

    if isfirstframe,
      fr = getframe_invisible(hfig);
      [height,width,~] = size(fr);
      gfdata = getframe_initialize(hfig);
      [fr,height,width] = getframe_invisible_nocheck(gfdata,[height,width],false,false);
    else
      fr = getframe_invisible_nocheck(gfdata,[height,width],false);
    end

    if useVideoWriter,
%       fr = getframe(hfig);
%       height = size(fr.cdata,1);
%       width = size(fr.cdata,2);
      writeVideo(aviobj,fr);
    else
      aviobj = addframe(aviobj,hfig);
    end
    %set(hfig,'Visible','off');
  end

  pos = get(hfig,'Position');
  if any(pos(3:4)~=figpos(3:4)),
    pos(3:4) = figpos(3:4);
    set(hfig,'Position',pos);
  end

  if debug,
    drawnow;
  end

  isfirstframe = false;

end

%% clean up

if ~debug,
  if useVideoWriter,
    close(aviobj);
  else
    aviobj = close(aviobj); %#ok<NASGU>
  end
end

fclose(fid);

%% compress using mencoder

if ~debug && isunix && usemencoder,
  if ~useVideoWriter,
    width = aviobj.Width;
    height = aviobj.Height;
  end
  [path,base,ext] = fileparts(aviname);
  tmpfile = fullfile(path,[base,'_tmp',ext]);
  newheight = 4*ceil(height/4);
  newwidth = 4*ceil(width/4);
  % subtitles are upside down, so encode with subtitles and flip, then flip
  % again
  cmd = sprintf('mencoder %s -o %s -ovc xvid -xvidencopts fixed_quant=4 -vf scale=%d:%d',...
    aviname,tmpfile,newwidth,newheight);
  status = system(cmd);
  if status ~= 0,
    error('Failed to compress avi to %s',tmpfile);
  end
  unix(sprintf('mv %s %s',tmpfile,aviname));
end


%-----------------------------------------------------------------------
% Job saved on 04-Sep-2015 11:55:24 by cfg_util (rev $Rev: 7703 $)
% spm SPM - SPM12 (12.1)
% cfg_basicio BasicIO - Unknown
%-----------------------------------------------------------------------#
matlabbatch{1}.spm.tools.beamforming.data.val = 1;
matlabbatch{1}.spm.tools.beamforming.data.gradsource = 'inv';
matlabbatch{1}.spm.tools.beamforming.data.space = 'MNI-aligned';
matlabbatch{1}.spm.tools.beamforming.data.overwrite = 0;
matlabbatch{2}.spm.tools.beamforming.sources.BF(1) = cfg_dep('Prepare data: BF.mat file', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));
matlabbatch{2}.spm.tools.beamforming.sources.reduce_rank = [2 3];
matlabbatch{2}.spm.tools.beamforming.sources.keep3d = 1;
matlabbatch{2}.spm.tools.beamforming.sources.plugin.mesh.orient = 'unoriented';
matlabbatch{2}.spm.tools.beamforming.sources.plugin.mesh.fdownsample = 1;
matlabbatch{2}.spm.tools.beamforming.sources.plugin.mesh.symmetric = 'no';
matlabbatch{2}.spm.tools.beamforming.sources.plugin.mesh.flip = false;
matlabbatch{2}.spm.tools.beamforming.sources.visualise = 1;
matlabbatch{3}.spm.tools.beamforming.features.BF(1) = cfg_dep('Define sources: BF.mat file', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));
matlabbatch{3}.spm.tools.beamforming.features.whatconditions.all = 1;
matlabbatch{3}.spm.tools.beamforming.features.woi = [-100 0
                                                     100 200];
matlabbatch{3}.spm.tools.beamforming.features.modality = {'MEG'};
matlabbatch{3}.spm.tools.beamforming.features.fuse = 'no';
matlabbatch{3}.spm.tools.beamforming.features.plugin.vbfa.nl = 5;
matlabbatch{3}.spm.tools.beamforming.features.plugin.vbfa.nem = 50;
matlabbatch{3}.spm.tools.beamforming.features.regularisation.manual.lambda = 0;
matlabbatch{3}.spm.tools.beamforming.features.bootstrap = false;
matlabbatch{4}.spm.tools.beamforming.inverse.BF(1) = cfg_dep('Covariance features: BF.mat file', substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));
matlabbatch{4}.spm.tools.beamforming.inverse.plugin.champagne.nem = 100;
matlabbatch{4}.spm.tools.beamforming.inverse.plugin.champagne.vcs = 0;
matlabbatch{4}.spm.tools.beamforming.inverse.plugin.champagne.nupd = 0;
matlabbatch{5}.spm.tools.beamforming.output.BF(1) = cfg_dep('Inverse solution: BF.mat file', substruct('.','val', '{}',{4}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.whatconditions.all = 1;
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.sametrials = false;
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.woi = [100 200];
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.foi = [0 Inf];
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.contrast = 1;
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.result = 'bycondition';
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.scale = 0;
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.powermethod = 'trace';
matlabbatch{5}.spm.tools.beamforming.output.plugin.image_power.modality = 'MEG';
matlabbatch{6}.spm.tools.beamforming.write.BF(1) = cfg_dep('Output: BF.mat file', substruct('.','val', '{}',{5}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));
matlabbatch{6}.spm.tools.beamforming.write.plugin.gifti.normalise = 'all';
matlabbatch{6}.spm.tools.beamforming.write.plugin.gifti.space = 'mni';
matlabbatch{6}.spm.tools.beamforming.write.plugin.gifti.visualise = 2;


function failed_old_halfspace_bug243

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY

% this tests for bug 243

% create vol conductor for halfspace (in mm)
geom.pnt = [[0 2 0];[0 0 0];[1 2 0]];
vol_hs = ft_headmodel_halfspace(geom,[-1 -1 -1],'conductivity',1);

% FIXME: this solution takes into account only dipole projected on surface
%   choose adequate electrodes set

  % create vol conductor for sphere (radius = 100 m)
  r = 1e5; % in mm
  pnt = r*mesh_sphere(162);
  pnt(:,3) = pnt(:,3) - r;
  % figure,ft_plot_mesh(pnt),axis on
  vol_sph = ft_headmodel_singlesphere(pnt,'conductivity',1);

% FIXME: test infinite vs halfspace when both electrodes and dipoles are
% very far away from plane

% FIXME: test halfpsace versus BEM when the surface is very big

% create infinite volume conductor
vol = [];
vol.type = 'infinite';

% create electrodes positions
elec.pnt = [[0 0 -0.2];[0 0 -0.4];[0 0 -0.6];[0 0 -0.8];[0 0 -1];[0 0 -1.2];[0 0 -1.4];[0 0 -1.6]];
for i=1:8
  elec.label{i} = sprintf('ch%0.2d',i);
end

% apply the necessary sensors/volume transformations
[vol_hs1, sens1]  = ft_prepare_vol_sens(vol_hs, elec);
% [vol_sph1, sens2] = ft_prepare_vol_sens(vol_sph, elec);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% 1 first try, calculate lf for certain dipoles positions
pos = [[0 -1 -1];[0 -1 -2];[-1 -2.5 -1]];Ndip = size(pos,1);
ori = [[0 0 1];[0 0 1];[0 0 1]]; ori = ori'; mori = ori(:);
[lf]  = ft_compute_leadfield(pos, sens1, vol);
lf  = lf *mori;
[lf1] = ft_compute_leadfield(pos, sens1, vol_hs1);
lf1 = lf1 *mori;

figure,plot(lf)
figure,plot(lf1)

% 2 near to surface
pos = [[0 -1 -0.1];[0 -1 -0.2];[-1 -2.5 -0.5]];Ndip = size(pos,1);
[lf]  = ft_compute_leadfield(pos, sens1, vol);
[lf1] = ft_compute_leadfield(pos, sens1, vol_hs1);
figure,plot(lf)
figure,plot(lf1)

% 3 far away from surface
pos = [[0 -1 -10];[0 -1 -2];[-1 -2.5 -5]];Ndip = size(pos,1);
[lf]  = ft_compute_leadfield(pos, sens1, vol); lf = lf *mori;
[lf1] = ft_compute_leadfield(pos, sens1, vol_hs1);lf1 = lf1 *mori;
figure,plot(lf)
figure,plot(lf1)

% 4 far away and electrode-dipoles are near
elec.pnt = 1e6*[[0 0.1 -0.2];[0 0 -0.3];[0 0.2 -0.2];[0 0.3 -0.3];[0 0.7 -.2];[0 1 -.3];[0 1.1 -.2];[0 1.4 -.3]];
pos = 1e7*[[0 -1 -1];[0 -1 -2];[0 -2.5 -2]];Ndip = size(pos,1);
[lf]  = ft_compute_leadfield(pos, elec, vol); %lf = lf *mori;
[lf1] = ft_compute_leadfield(pos, elec, vol_hs1); %lf1 = lf1 *mori;
figure,plot(lf)
figure,plot(lf1)


function gmt_scale(hAxes, sOutput, sPrefix)

% Get the figure-handle
hFigure = get(hAxes, 'Parent');

% Is there a colorbar?
vKids = get(hFigure, 'Children');
for nCnt = length(vKids):-1:1
  sType = get(vKids(nCnt), 'Type');
  sTag = get(vKids(nCnt), 'Tag');
  if (strcmp(sType, 'axes') & strcmp(sTag, 'Colorbar'))
    vUserData = get(vKids(nCnt), 'UserData');
    if vUserData.PlotHandle == hAxes

    % Extract the colormap
     vCLim = get(hAxes, 'CLim');
     mColormap = colormap(hAxes);
     [nRow, nCol] = size(mColormap);
     fRange = vCLim(2)-vCLim(1);
     fStep = fRange/(nRow-1);

     % Create the cpt-file and save it
     mMap = [];
     for nRowCnt = 1:nRow-1
       mMap = [mMap; (vCLim(1)+((nRowCnt-1)*fStep)) mColormap(nRowCnt,:).*255 (vCLim(1)+(nRowCnt*fStep)) mColormap(nRowCnt+1,:).*255];
     end
     save([sPrefix 'colormap.cpt'], 'mMap', '-ascii');

    % Get properties of colorbar
    vXTick = get(vKids(nCnt), 'XTick');
    vYTick = get(vKids(nCnt), 'YTick');
    if isempty(vXTick)
      % Colorbar is vertical
      sD = '';
  vYDiff = diff(vYTick);
 vSel = ~(vYDiff == 0);
 vYDiff = vYDiff(:,vSel);
 fYDiff = min(abs(vYDiff));
     sB = num2str(fYDiff);
    else
      % Colorbar is horizontal
      sD = 'h';
     vXDiff = diff(vXTick);
    vSel = ~(vXDiff == 0);
    vXDiff = vXDiff(:,vSel);
    fXDiff = min(abs(vXDiff));
     sB = num2str(fXDiff);
    end
%

    %get(vKids(nCnt))

    % Plot the colorbar
hFile = fopen(sOutput, 'a');
    fprintf(hFile, 'psscale -D6.3i/1.35i/3i/0.3i%s -C%s -B%s -O -K >> $output\n', sD, [sPrefix 'colormap.cpt'], sB);

fclose(hFile);

end
  end
end


% PRTBRVDISCRETEHIERARCHY - PRT BRV Discrete hierarchical model structure
%   Has parameters that specify a dirichlet density

classdef prtBrvDiscreteHierarchy

    properties
        lambda
    end
    methods
        function self = prtBrvDiscreteHierarchy(varargin)
            if nargin < 1
                return
            end

            self = defaultParameters(self,varargin{1});
        end

        function self = defaultParameters(self, nDimensions)
            self.lambda = ones(1,nDimensions)/nDimensions;
            %self.lambda = ones(1,nDimensions)*nDimensions;
        end

        function tf = isValid(self)
            tf = ~isempty(self.lambda);
        end
    end
end


function []=ps_load_initial_gamma(endian)
%PS_LOAD_INITIAL_GAMMA Initial load of files into matlab workspace
%
%   Andy Hooper, Dec 2012
%
%   =======================================================================
%   01/2016 DB: Replace save with stamps_save which checks for var size when
%               saving
%   01/2016 AH: Save sensor
%   12/2016 AH: Set xy from lonlat
%   08/2017 AH: Allow for missing null ifg
%   =======================================================================

if nargin<1
   endian='b';
end

%NB IFGS assumed in ascending date order
logit;
logit('Loading data into matlab...')

phname=['./pscands.1.ph']; % for each PS candidate, a float complex value for each ifg
ijname=['./pscands.1.ij']; % ID# Azimuth# Range# 1 line per PS candidate
llname=['./pscands.1.ll']; % output from pt2geo
xyname=['./pscands.1.xy']; % output from pt2geo
hgtname=['./pscands.1.hgt']; %
daname=['./pscands.1.da']; %
rscname = ['../rsc.txt'];
pscname=['../pscphase.in'];

psver=1;
fid=fopen(rscname);
if fid<0
    error([rscname,' does not exist'])
end
rslcpar=textscan(fid,'%s');
rslcpar=rslcpar{1}{1};
fclose(fid);

fid=fopen(pscname);
if fid<0
    error([pscname,' does not exist'])
end
ifgs=textscan(fid,'%s');
fclose(fid);
ifgs=ifgs{1}(2:end);
nb=length(ifgs{1});
master_day=str2num(ifgs{1}(nb-21:nb-14));
n_ifg=length(ifgs);
n_image=n_ifg;
day=zeros(n_ifg,1);
for i=1:n_ifg
    day(i)=str2num(ifgs{i}(nb-12:nb-5));
end

year=floor(day/10000);
month=floor((day-year*10000)/100);
monthday=day-year*10000-month*100;
day=datenum(year,month,monthday);

master_day_yyyymmdd=master_day;
year=floor(master_day/10000);
month=floor((master_day-year*10000)/100);
monthday=master_day-year*10000-month*100;
master_day=datenum(year,month,monthday);

master_ix=sum(day<master_day)+1;
if day(master_ix)~=master_day
    master_master_flag='0' % no null master-master ifg provided
    day=[day(1:master_ix-1);master_day;day(master_ix:end)];
else
    master_master_flag='1' % yes, null master-master ifg provided
end

heading=readparm(rslcpar,'heading:');
setparm('heading',heading,1);

freq=readparm(rslcpar,'radar_frequency:');
lambda=299792458/freq;
setparm('lambda',lambda,1);

sensor=readparm(rslcpar,'sensor:');
if ~isempty(strfind('sensor','ASAR'))
    platform='ENVISAT';
else
    platform=sensor; % S1A for Sentinel-1A
end
setparm('platform',platform,1);

ij=load(ijname);
n_ps=size(ij,1);

rps=readparm(rslcpar,'range_pixel_spacing');
rgn=readparm(rslcpar,'near_range_slc');
se=readparm(rslcpar,'sar_to_earth_center');
re=readparm(rslcpar,'earth_radius_below_sensor');
rgc=readparm(rslcpar,'center_range_slc');
naz=readparm(rslcpar,'azimuth_lines');
prf=readparm(rslcpar,'prf');

mean_az=naz/2-0.5; % mean azimuth line

rg=rgn+ij(:,3)*rps;
look=acos((se^2+rg.^2-re^2)./(2*se*rg)); % Satellite look angles

bperp_mat=zeros(n_ps,n_image,'single');
for i=1:n_ifg
    basename=[ifgs{i}(1:nb-4),'base'];
    B_TCN=readparm(basename,'initial_baseline(TCN):',3);
    BR_TCN=readparm(basename,'initial_baseline_rate:',3);
    bc=B_TCN{2}+BR_TCN{2}*(ij(:,2)-mean_az)/prf;
    bn=B_TCN{3}+BR_TCN{3}*(ij(:,2)-mean_az)/prf;
    bperp_mat(:,i)=bc.*cos(look)-bn.*sin(look); % Convert baselines from (T)CN to perp-para coordinates
    %bpara=bc*sin(look)+bn*cos(look)
end

bperp=mean(bperp_mat)';
if master_master_flag==1
    bperp_mat=bperp_mat(:,[1:master_ix-1,master_ix+1:end]);
else
    bperp=[bperp(1:master_ix-1);0;bperp(master_ix:end)];
end
%bperp=[bperp(1:master_ix-1);0;bperp(master_ix:end)]; % insert master-master bperp (zero)
%bperp_mat=repmat(single(bperp([1:master_ix-1,master_ix+1:end]))',n_ps,1);

inci=acos((se^2-re^2-rg.^2)./(2*re*rg));
mean_incidence=mean(inci);
mean_range=rgc;

fid=fopen(phname,'r',endian);
ph=zeros(n_ps,n_ifg,'single');
byte_count=n_ps*2;
for i=1:n_ifg
    [ph_bit,byte_count]=fread(fid,[(n_ps)*2,1],'float=>single');
    ph(:,i)=complex(ph_bit(1:2:end),ph_bit(2:2:end));
end

zero_ph=sum(ph==0,2);
nonzero_ix=zero_ph<=1;       % if more than 1 phase is zero, drop node
if master_master_flag==1
    ph(:,master_ix)=1;
else
    ph=[ph(:,1:master_ix-1),ones(n_ps,1),ph(:,master_ix:end)];
    n_ifg=n_ifg+1;
    n_image=n_image+1;
end

if exist(llname,'file')
    fid=fopen(llname,'r');
    lonlat=fread(fid,[2,inf],'float',endian);
    lonlat=lonlat';
    fclose(fid);
else
    error([llname,' does not exist']);
end

ll0=(max(lonlat)+min(lonlat))/2;

xy=llh2local(lonlat',ll0)'*1000;

sort_x=sortrows(xy,1);
sort_y=sortrows(xy,2);
n_pc=round(n_ps*0.001);
bl=mean(sort_x(1:n_pc,:)); % bottom left corner
tr=mean(sort_x(end-n_pc:end,:)); % top right corner
br=mean(sort_y(1:n_pc,:)); % bottom right  corner
tl=mean(sort_y(end-n_pc:end,:)); % top left corner

theta=(180-heading)*pi/180;
if theta>pi
    theta=theta-2*pi;
end

rotm=[cos(theta),sin(theta); -sin(theta),cos(theta)];
xy=xy';
xynew=rotm*xy; % rotate so that scene axes approx align with x=0 and y=0
if max(xynew(1,:))-min(xynew(1,:))<max(xy(1,:))-min(xy(1,:)) &...
   max(xynew(2,:))-min(xynew(2,:))<max(xy(2,:))-min(xy(2,:))
    xy=xynew; % check that rotation is an improvement
    disp(['Rotating by ',num2str(theta*180/pi),' degrees']);
end

xy=single(xy');
[dummy,sort_ix]=sortrows(xy,[2,1]); % sort in ascending y order
xy=xy(sort_ix,:);
xy=[[1:n_ps]',xy];
xy(:,2:3)=round(xy(:,2:3)*1000)/1000; % round to mm

ph=ph(sort_ix,:);
ij=ij(sort_ix,:);
ij(:,1)=1:n_ps;
lonlat=lonlat(sort_ix,:);
bperp_mat=bperp_mat(sort_ix,:);

% removing Nan values if pressent in lonlat, phase
ix_nan = (sum(isnan(lonlat),2)>=1 | sum(isnan(ph),2)>=1);
lonlat(ix_nan,:)=[];
ij(ix_nan,:)=[];
xy(ix_nan,:)=[];
n_ps = size(lonlat,1);
% update the first column
ij(:,1)=[1:n_ps]';
xy(:,1)=[1:n_ps]';

savename=['ps',num2str(psver)];
stamps_save(savename,ij,lonlat,xy,bperp,day,master_day,master_ix,n_ifg,n_image,n_ps,sort_ix,ll0,master_ix,mean_incidence,mean_range);

save psver psver

phsavename=['ph',num2str(psver)];
ph(ix_nan,:)=[];
stamps_save(phsavename,ph);

bpsavename=['bp',num2str(psver)];
bperp_mat(ix_nan,:)=[];
stamps_save(bpsavename,bperp_mat);

lasavename=['la',num2str(psver)];
la=inci(sort_ix); % store incidence not look angle for gamma
la(ix_nan,:)=[];
stamps_save(lasavename,la);

if exist(daname,'file')
  D_A=load(daname);
  D_A=D_A(sort_ix);
  D_A(ix_nan,:)=[];
  dasavename=['da',num2str(psver)];
  stamps_save(dasavename,D_A);
end

if exist(hgtname,'file')
    fid=fopen(hgtname,'r');
    hgt=fread(fid,[1,inf],'float',endian);
    hgt=hgt';
    hgt=hgt(sort_ix);
    fclose(fid);
    hgt(ix_nan,:)=[];
    hgtsavename=['hgt',num2str(psver)];
    stamps_save(hgtsavename,hgt);
end

logit(1);


function [vertex,face] = read_vtk(filename, verbose)

% read_vtk - read data from VTK file.
%
%   [vertex,face] = read_vtk(filename, verbose);
%
%   'vertex' is a 'nb.vert x 3' array specifying the position of the vertices.
%   'face' is a 'nb.face x 3' array specifying the connectivity of the mesh.
%
%   Copyright (c) Mario Richtsfeld

if nargin<2
    verbose = 1;
end

fid = fopen(filename,'r');
if( fid==-1 )
    error('Can''t open the file.');
    return;
end

str = fgets(fid);   % -1 if eof
if ~strcmp(str(3:5), 'vtk')
    error('The file is not a valid VTK one.');
end

%%% read header %%%
str = fgets(fid);
str = fgets(fid);
str = fgets(fid);
str = fgets(fid);
nvert = sscanf(str,'%*s %d %*s', 1);

% read vertices
[A,cnt] = fscanf(fid,'%f %f %f', 3*nvert);
if cnt~=3*nvert
    warning('Problem in reading vertices.');
end
A = reshape(A, 3, cnt/3);
vertex = A;

% read polygons
str = fgets(fid);
str = fgets(fid);

info = sscanf(str,'%c %*s %*s', 1);

if((info ~= 'P') && (info ~= 'V'))
    str = fgets(fid);
    info = sscanf(str,'%c %*s %*s', 1);
end

if(info == 'P')

    nface = sscanf(str,'%*s %d %*s', 1);

    [A,cnt] = fscanf(fid,'%d %d %d %d\n', 4*nface);
    if cnt~=4*nface
        warning('Problem in reading faces.');
    end

    A = reshape(A, 4, cnt/4);
    face = A(2:4,:)+1;
end

if(info ~= 'P')
    face = 0;
end

% read vertex ids
if(info == 'V')

    nv = sscanf(str,'%*s %d %*s', 1);

    [A,cnt] = fscanf(fid,'%d %d \n', 2*nv);
    if cnt~=2*nv
        warning('Problem in reading faces.');
    end

    A = reshape(A, 2, cnt/2);
    face = repmat(A(2,:)+1, 3, 1);
end

if((info ~= 'P') && (info ~= 'V'))
    face = 0;
end

fclose(fid);

return


%% Default template
%% Plot some Pole Figures

plotPDF(odf,[Miller(1,0,0),Miller(1,1,0)],'antipodal')


function resFileClean = preprocessResult(resFile, seqName, dataDir, force, minvis)
% reads submitted (raw) MOT16 result from .txt
% and removes all boxes that are associated with ambiguous annotations
% such as sitting people, cyclists or mannequins.
% Also removes partially occluded boxes if minvis>0

% resFile='/home/amilan/research/projects/bmtt-dev/code/bae/res/0001/ADL-Rundle-6.txt';
% seqName = 'MOT16-09';
assert(cleanRequired(seqName),'preproccessing should only be done for MOT16/17')

if nargin<4, force=1; end
if nargin<5, minvis=0; end

fprintf('Preprocessing (cleaning) %s...\n',seqName);

% if file does not exist, do nothing
if ~exist(resFile,'file')
    fprintf('Results file does not exist\n');
    resFileClean = [];
    return;
end

[p,f,e]=fileparts(resFile);
cleanDir = [p,filesep,'clean'];
if ~exist(cleanDir, 'dir'), mkdir(cleanDir); end
resFileClean = [cleanDir,filesep,f,e];

% if clean file already exists and no need to redo, skip
if ~force && exist(resFileClean, 'file')
    fprintf('skipping...\n');
    return;
end

% if file empty, just copy it
tf = dir(resFile);
if tf.bytes == 0
    fprintf('Results file empty\n');
    copyfile(resFile,resFileClean);
    return;
end

if nargin<3, dataDir = getDataDir; end

% [seqName, seqFolder, imgFolder, imgExt, F, dirImages] ...
%     = getSeqInfo(seq, dataDir);

[seqName, seqFolder, imgFolder, frameRate, F, imWidth, imHeight, imgExt] ...
    = getSeqInfoFromFile(seqName, dataDir);

% read in result
resRaw = dlmread(resFile);

%%

% read ground truth
gtFolder = [dataDir,seqName,filesep,'gt',filesep];
gtFile = [gtFolder,'gt.txt'];
gtRaw = dlmread(gtFile);

% make sure we have MOT16 ground truth (= 9 columns)
assert(size(gtRaw,2)==9, 'unknown GT format')

% define which classes should be ignored
distractors = {'person_on_vhcl','static_person','distractor','reflection'};

keepBoxes = true(size(resRaw,1),1);

showVis = 0;

td=0.5; % overlap threshold
for t=1:F
    if ~mod(t,100), fprintf('.'); end

    % find all result boxes in this frame
    resInFrame = find(resRaw(:,1)==t); N = length(resInFrame);
    resInFrame = reshape(resInFrame,1,N);

    % find all GT boxes in frame
    GTInFrame = find(gtRaw(:,1)==t); Ngt = length(GTInFrame);
    GTInFrame = reshape(GTInFrame,1,Ngt);

    % compute all overlaps for current frame
    allisects=zeros(Ngt,N);
    g=0;
    for gg=GTInFrame
        g=g+1; r=0;
        bxgt=gtRaw(gg,3); bygt=gtRaw(gg,4); bwgt=gtRaw(gg,5); bhgt=gtRaw(gg,6);
        for rr=resInFrame
            r=r+1;
            bxres=resRaw(rr,3); byres=resRaw(rr,4); bwres=resRaw(rr,5); bhres=resRaw(rr,6);

            if bxgt+bwgt<bxres, continue; end % ignore if no horizontal overlap
            if bxgt>bxres+bwres, continue; end

            if bygt+bhgt<byres, continue; end % ignore if no vertical overlap
            if bygt>byres+bhres, continue; end

            allisects(g,r)=boxiou(bxgt,bygt,bwgt,bhgt,bxres,byres,bwres,bhres);
        end
    end
%     t

    tmpai=allisects;
    tmpai=1-tmpai;
    tmpai(tmpai>td)=Inf;
    [Mtch,Cst]=Hungarian(tmpai);
    [mGT,mRes]=find(Mtch);
%     pause
    nMtch = length(mGT);
    % go through all matches
    for m=1:nMtch
        g=GTInFrame(mGT(m)); % gt box
        gtClassID = gtRaw(g,8);
        gtClassString = classIDToString(gtClassID);

        % if we encounter a distractor, mark to remove box
        if ismember(gtClassString, distractors)
            r = resInFrame(mRes(m)); % result box
            keepBoxes(r) = false;

            if showVis
                bxgt=gtRaw(g,3); bygt=gtRaw(g,4); bwgt=gtRaw(g,5); bhgt=gtRaw(g,6); idgt=gtRaw(g,2);
                bxres=resRaw(r,3); byres=resRaw(r,4); bwres=resRaw(r,5); bhres=resRaw(r,6); idres=resRaw(r,2);

                clf
                im = imread(fullfile(dataDir,seqName,'img1',sprintf('%06d.jpg',t)));
                imshow(im); hold on
                text(50,50,sprintf('%d',t),'color','w')

                % show GT box
%                 text(bxgt,bygt-20,sprintf('%d',idgt),'color','w')
                classString = insertEscapeChars(classIDToString(gtClassID));
                text(bxgt+50,bygt-20,sprintf('%s',classString),'color','w')
                rectangle('Position',[bxgt,bygt,bwgt,bhgt],'EdgeColor','w');

                % show Res box
%                 text(bxres,byres-20,sprintf('%d',idres),'color','y')
                rectangle('Position',[bxres,byres,bwres,bhres],'EdgeColor','y');

                pause(.01)
            end
        end

        % if we encounter a partially occluded box, mark to remove
        if gtRaw(g,9)<minvis
            r = resInFrame(mRes(m)); % result box
            keepBoxes(r) = false;

            if showVis
                bxgt=gtRaw(g,3); bygt=gtRaw(g,4); bwgt=gtRaw(g,5); bhgt=gtRaw(g,6); idgt=gtRaw(g,2);
                bxres=resRaw(r,3); byres=resRaw(r,4); bwres=resRaw(r,5); bhres=resRaw(r,6); idres=resRaw(r,2);

                clf
                im = imread(fullfile(dataDir,seqName,'img1',sprintf('%06d.jpg',t)));
                imshow(im); hold on
                text(50,50,sprintf('%d',t),'color','w')

                % show GT box
                text(bxgt+50,bygt-20,sprintf('vis %.1f',gtRaw(g,9)*100),'color','w')
                rectangle('Position',[bxgt,bygt,bwgt,bhgt],'EdgeColor','w');

                % show Res box
%                 text(bxres,byres-20,sprintf('%d',idres),'color','y')
                rectangle('Position',[bxres,byres,bwres,bhres],'EdgeColor','y');

                pause(.01)
                pause
            end
        end

    end
end

%%
fprintf('\nRemoving %d boxes from solution...\n',numel(find(~keepBoxes)));
resNew = resRaw;
resNew=resNew(keepBoxes,:);

%% write new file into new dir (clean)
dlmwrite(resFileClean, resNew);

% end


% The COBRAToolbox: testCheckObjective.m
%
% Purpose:
%     - Tests the changeObjective function
%

global CBTDIR

currentDir = pwd; % save the current path

% initialize the test
fileDir = fileparts(which('testCheckObjective'));
cd(fileDir);

% load the ecoli core model
model = getDistributedModel('ecoli_core_model.mat');

abbr = checkObjective(model);

assert(strcmp(abbr{1}, 'Biomass_Ecoli_core_w_GAM'));

% test if there are more than 1 objective
model.c(1) = 1;
abbr = checkObjective(model);
assert(strcmp(abbr{1}, 'ACALD'));
assert(strcmp(abbr{2}, 'Biomass_Ecoli_core_w_GAM'));

% test if there is no objective - will throw a warning message
w = warning ('off','all');
model.c(1) = 0;
model.c(13) = 0;
try
    abbr = checkObjective(model);
catch ME
    assert(length(ME.message) > 0)
end
w = warning ('on','all');

% change the directory
cd(currentDir)


function value = mean(sF1)
% mean value of a spherical function
%

value = mean(sF1.values(:));

end


function [w] = mne_read_w_file(filename)
%
% [w] = mne_read_w_file(filename)
%
% Reads a binary w file into the structure w with the following fields
%
% vertices - vector of vertex indices (0-based)
% data     - vector of data values
%

%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
%
%     $Id$
%
%     Revision 1.6  2006/04/23 15:29:41  msh
%     Added MGH to the copyright
%
%     Revision 1.5  2006/04/10 23:26:54  msh
%     Added fiff reading routines
%
%     Revision 1.4  2005/12/05 20:23:21  msh
%     Added fiff_save_evoked. Improved error handling.
%
%     Revision 1.3  2005/11/21 03:19:12  msh
%     Improved error handling
%
%     Revision 1.2  2005/11/21 02:15:51  msh
%     Added more routines
%
%     Revision 1.1  2005/11/21 01:41:57  msh
%     Introduced structures and start all function names with mne_
%
%
me='MNE:mne_read_w_file';
if(nargin ~= 1)
   error(me,'usage: [w] = mne_read_w_file(filename)');
end

% open it as a big-endian file
[fid,message] = fopen(filename, 'rb', 'b') ;
if (fid < 0)
   error(me,message);
end

fread(fid, 1, 'int16') ;
vnum       = mne_fread3(fid) ;
w.data     = zeros(vnum,1) ;
w.vertices = zeros(vnum,1) ;
for i=1:vnum
  w.vertices(i) = mne_fread3(fid) ; % vertex number (0-based)
  w.data(i)     = fread(fid, 1, 'float') ; % vertex value
end
w.vertices = uint32(w.vertices);

fclose(fid) ;
return;


classdef C10MOP6 < EvoXBenchProblem
% <multi> <real> <large/none> <expensive/none>

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

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


function bnet = mk_alarm_bnet()

% Written by Qian Diao <qian.diao@intel.com> on 11 Dec 01

N = 37;
dag = zeros(N,N);
dag(21,23) = 1 ;
dag(21,24) = 1 ;
dag(1,24) = 1 ;
dag(1,23) = 1 ;
dag(2,26) = 1 ;
dag(2,25) = 1 ;
dag(2,24) = 1 ;
dag(2,13) = 1 ;
dag(2,23) = 1 ;
dag(13,30) = 1 ;
dag(30,31) = 1 ;
dag(3,14) = 1 ;
dag(3,19) = 1 ;
dag(4,36) = 1 ;
dag(14,35) = 1 ;
dag(32,33) = 1 ;
dag(32,35) = 1 ;
dag(32,34) = 1 ;
dag(32,36) = 1 ;
dag(15,21) = 1 ;
dag(5,31) = 1 ;
dag(27,30) = 1 ;
dag(28,31) = 1 ;
dag(28,29) = 1 ;
dag(26,28) = 1 ;
dag(26,27) = 1 ;
dag(16,31) = 1 ;
dag(16,37) = 1 ;
dag(23,26) = 1 ;
dag(23,29) = 1 ;
dag(23,25) = 1 ;
dag(6,15) = 1 ;
dag(7,27) = 1 ;
dag(8,21) = 1 ;
dag(19,20) = 1 ;
dag(19,22) = 1 ;
dag(31,32) = 1 ;
dag(9,14) = 1 ;
dag(9,17) = 1 ;
dag(9,19) = 1 ;
dag(10,33) = 1 ;
dag(10,34) = 1 ;
dag(11,16) = 1 ;
dag(12,13) = 1 ;
dag(12,18) = 1 ;
dag(35,37) = 1 ;

node_sizes = 2*ones(1,N);
node_sizes(2) = 3;
node_sizes(6) = 3;
node_sizes(14) = 3;
node_sizes(15) = 4;
node_sizes(16) = 3;
node_sizes(18) = 3;
node_sizes(19) = 3;
node_sizes(20) = 3;
node_sizes(21) = 4;
node_sizes(22) = 3;
node_sizes(23) = 4;
node_sizes(24) = 4;
node_sizes(25) = 4;
node_sizes(26) = 4;
node_sizes(27) = 3;
node_sizes(28) = 3;
node_sizes(29) = 4;
node_sizes(30) = 3;
node_sizes(32) = 3;
node_sizes(33) = 3;
node_sizes(34) = 3;
node_sizes(35) = 3;
node_sizes(36) = 3;
node_sizes(37) = 3;

bnet = mk_bnet(dag, node_sizes);

bnet.CPD{1} = tabular_CPD(bnet, 1,[0.96 0.04 ]);
bnet.CPD{2} = tabular_CPD(bnet, 2,[0.92 0.03 0.05 ]);
bnet.CPD{3} = tabular_CPD(bnet, 3,[0.8 0.2 ]);
bnet.CPD{4} = tabular_CPD(bnet, 4,[0.95 0.05 ]);
bnet.CPD{5} = tabular_CPD(bnet, 5,[0.8 0.2 ]);
bnet.CPD{6} = tabular_CPD(bnet, 6,[0.01 0.98 0.01 ]);
bnet.CPD{7} = tabular_CPD(bnet, 7,[0.01 0.99 ]);
bnet.CPD{8} = tabular_CPD(bnet, 8,[0.95 0.05 ]);
bnet.CPD{9} = tabular_CPD(bnet, 9,[0.95 0.05 ]);
bnet.CPD{10} = tabular_CPD(bnet, 10,[0.9 0.1 ]);
bnet.CPD{11} = tabular_CPD(bnet, 11,[0.99 0.01 ]);
bnet.CPD{12} = tabular_CPD(bnet, 12,[0.99 0.01 ]);
bnet.CPD{13} = tabular_CPD(bnet, 13,[0.95 0.95 0.05 0.1 0.1 0.01 0.05 0.05 0.95 0.9 0.9 0.99 ]);
bnet.CPD{14} = tabular_CPD(bnet, 14,[0.05 0.95 0.5 0.98 0.9 0.04 0.49 0.01 0.05 0.01 0.01 0.01 ]);
bnet.CPD{15} = tabular_CPD(bnet, 15,[0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.97 ]);
bnet.CPD{16} = tabular_CPD(bnet, 16,[0.3 0.98 0.4 0.01 0.3 0.01 ]);
bnet.CPD{17} = tabular_CPD(bnet, 17,[0.99 0.1 0.01 0.9 ]);
bnet.CPD{18} = tabular_CPD(bnet, 18,[0.05 0.01 0.9 0.19 0.05 0.8 ]);
bnet.CPD{19} = tabular_CPD(bnet, 19,[0.05 0.98 0.01 0.95 0.9 0.01 0.09 0.04 0.05 0.01 0.9 0.01 ]);
bnet.CPD{20} = tabular_CPD(bnet, 20,[0.95 0.04 0.01 0.04 0.95 0.29 0.01 0.01 0.7 ]);
bnet.CPD{21} = tabular_CPD(bnet, 21,[0.97 0.97 0.01 0.97 0.01 0.97 0.01 0.97 0.01 0.01 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 ]);
bnet.CPD{22} = tabular_CPD(bnet, 22,[0.95 0.04 0.01 0.04 0.95 0.04 0.01 0.01 0.95 ]);
bnet.CPD{23} = tabular_CPD(bnet, 23,[0.97 0.97 0.97 0.97 0.97 0.97 0.01 0.95 0.97 0.97 0.01 0.95 0.01 0.4 0.97 0.97 0.01 0.5 0.01 0.3 0.97 0.97 0.01 0.3 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.03 0.01 0.01 0.97 0.03 0.01 0.58 0.01 0.01 0.01 0.48 0.01 0.68 0.01 0.01 0.01 0.68 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.97 0.01 ]);
bnet.CPD{24} = tabular_CPD(bnet, 24,[0.97 0.97 0.97 0.97 0.97 0.97 0.01 0.01 0.4 0.1 0.01 0.01 0.01 0.01 0.2 0.05 0.01 0.01 0.01 0.01 0.2 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.49 0.58 0.84 0.9 0.29 0.01 0.01 0.75 0.25 0.01 0.01 0.01 0.01 0.7 0.15 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.3 0.01 0.05 0.08 0.3 0.97 0.08 0.04 0.25 0.38 0.08 0.01 0.01 0.09 0.25 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.2 0.01 0.01 0.01 0.4 0.01 0.9 0.01 0.45 0.6 0.9 0.97 0.97 0.01 0.59 0.97 0.97 ]);
bnet.CPD{25} = tabular_CPD(bnet, 25,[0.97 0.97 0.97 0.01 0.6 0.01 0.01 0.5 0.01 0.01 0.5 0.01 0.01 0.01 0.01 0.97 0.38 0.97 0.01 0.48 0.01 0.01 0.48 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.01 0.97 ]);
bnet.CPD{26} = tabular_CPD(bnet, 26,[0.97 0.97 0.97 0.01 0.01 0.03 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.01 0.01 0.97 0.97 0.95 0.01 0.01 0.94 0.01 0.01 0.88 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.97 0.04 0.01 0.01 0.1 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.97 0.01 ]);
bnet.CPD{27} = tabular_CPD(bnet, 27,[0.98 0.98 0.98 0.98 0.95 0.01 0.95 0.01 0.01 0.01 0.01 0.01 0.04 0.95 0.04 0.01 0.01 0.01 0.01 0.01 0.01 0.04 0.01 0.98 ]);
bnet.CPD{28} = tabular_CPD(bnet, 28,[0.01 0.01 0.04 0.9 0.01 0.01 0.92 0.09 0.98 0.98 0.04 0.01 ]);
bnet.CPD{29} = tabular_CPD(bnet, 29,[0.97 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.97 0.01 0.01 0.01 0.01 0.97 0.97 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.97 0.97 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.97 0.97 0.43 ]);
bnet.CPD{30} = tabular_CPD(bnet, 30,[0.98 0.98 0.01 0.98 0.01 0.69 0.01 0.01 0.98 0.01 0.01 0.3 0.01 0.01 0.01 0.01 0.98 0.01 ]);
bnet.CPD{31} = tabular_CPD(bnet, 31,[0.05 0.01 0.05 0.01 0.05 0.01 0.05 0.01 0.05 0.01 0.05 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.1 0.01 0.95 0.01 0.95 0.05 0.1 0.01 0.95 0.01 0.95 0.05 0.1 0.01 0.3 0.01 0.3 0.01 0.95 0.01 0.99 0.05 0.95 0.05 0.95 0.01 0.99 0.05 0.99 0.05 0.3 0.01 0.99 0.01 0.3 0.01 0.95 0.99 0.95 0.99 0.95 0.99 0.95 0.99 0.95 0.99 0.95 0.99 0.99 0.99 0.99 0.99 0.99 0.99 0.9 0.99 0.05 0.99 0.05 0.95 0.9 0.99 0.05 0.99 0.05 0.95 0.9 0.99 0.7 0.99 0.7 0.99 0.05 0.99 0.00999999 0.95 0.05 0.95 0.05 0.99 0.01 0.95 0.01 0.95 0.7 0.99 0.01 0.99 0.7 0.99 ]);
bnet.CPD{32} = tabular_CPD(bnet, 32,[0.1 0.01 0.89 0.09 0.01 0.9 ]);
bnet.CPD{33} = tabular_CPD(bnet, 33,[0.98 0.33333334 0.01 0.33333334 0.01 0.33333334 0.01 0.33333334 0.98 0.33333334 0.01 0.33333334 0.01 0.33333334 0.01 0.33333334 0.98 0.33333334 ]);
bnet.CPD{34} = tabular_CPD(bnet, 34,[0.98 0.33333334 0.01 0.33333334 0.01 0.33333334 0.01 0.33333334 0.98 0.33333334 0.01 0.33333334 0.01 0.33333334 0.01 0.33333334 0.98 0.33333334 ]);
bnet.CPD{35} = tabular_CPD(bnet, 35,[0.98 0.95 0.3 0.95 0.04 0.01 0.8 0.01 0.01 0.01 0.04 0.69 0.04 0.95 0.3 0.19 0.04 0.01 0.01 0.01 0.01 0.01 0.01 0.69 0.01 0.95 0.98 ]);
bnet.CPD{36} = tabular_CPD(bnet, 36,[0.98 0.98 0.01 0.4 0.01 0.3 0.01 0.01 0.98 0.59 0.01 0.4 0.01 0.01 0.01 0.01 0.98 0.3 ]);
bnet.CPD{37} = tabular_CPD(bnet, 37,[0.98 0.98 0.3 0.98 0.1 0.05 0.9 0.05 0.01 0.01 0.01 0.6 0.01 0.85 0.4 0.09 0.2 0.09 0.01 0.01 0.1 0.01 0.05 0.55 0.01 0.75 0.9 ]);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 the National Renewable Energy Laboratory and Sandia Corporation
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Run the WEC-Sim RM3 Test Case for 1DOF w/PTO
% This script will run the RM3 in WEC-Sim for irregular waves with Hs=2.5[m]
% and Tp=8[s]. The RM3 WEC models has 2 bodies, restricted to heave motion
% only, and has PTO damping=1200[kN-s/m].

global plotNO
locdir=pwd;
%% Run Simulation
wecSim;                     % Run Simulation

%% Post-Process Data
% Body 1
B1.WEC_Sim_new.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_new.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_new.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_new.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_new.time=B1.WEC_Sim_new.time;
Rel.WEC_Sim_new.heave=B1.WEC_Sim_new.heave-B2.WEC_Sim_new.heave;
% Spectrum
Sp.WEC_Sim_new.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_new.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

%% Load Data
irrSSoutput_new=output;        % Keeps new run in workspace
load('irregularSS_org.mat')    % Load Previous WEC-Sim Data

%% Post-Process Data
% Body 1
B1.WEC_Sim_org.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_org.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_org.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_org.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_org.time=B1.WEC_Sim_org.time;
Rel.WEC_Sim_org.heave=B1.WEC_Sim_org.heave-B2.WEC_Sim_org.heave;
% Spectrum
Sp.WEC_Sim_org.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_org.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

clear Hshift1 Hshift2

%% Quantify Maximum Difference Between Saved and Current WEC-Sim Runs
[irregularSS.B1_H_max ,irregularSS.B1_H_I]=max(abs(B1.WEC_Sim_org.heave-B1.WEC_Sim_new.heave));
[irregularSS.B2_H_max ,irregularSS.B2_H_I]=max(abs(B2.WEC_Sim_org.heave-B2.WEC_Sim_new.heave));
[irregularSS.Rel_H_max,irregularSS.Rel_H_I]=max(abs(Rel.WEC_Sim_org.heave-Rel.WEC_Sim_new.heave));

irregularSS.B1  = B1;
irregularSS.B2  = B2;
irregularSS.Rel = Rel;
irregularSS.Sp  = Sp;

save('irregularSS','irregularSS')

%% Plot Old vs. New Comparison
if plotNO==1 % global variable
    cd ../..
    plotOldNew(B1,B2,Rel,[irregularSS.B1_H_max ,irregularSS.B1_H_I],...
        [irregularSS.B2_H_max ,irregularSS.B2_H_I],...
        [irregularSS.Rel_H_max,irregularSS.Rel_H_I],'IrregularSS');
    cd(locdir)
end
%% Clear output and .slx directory

try
	rmdir('output','s')
	rmdir('slprj','s')
	delete('RM3.slx.autosave', 'RM3_sfun.mexmaci64')
catch
end


function channels = smoothAngleChannels(channels, skel);

% SMOOTHANGLECHANNELS Try and remove artificial discontinuities associated with angles.

% MOCAP

for i=1:length(skel.tree)
  for j=1:length(skel.tree(i).rotInd)
    col = skel.tree(i).rotInd(j);
    if col
      for k=2:size(channels, 1)
        diff=channels(k, col)-channels(k-1, col);
        if abs(diff+360)<abs(diff)
          channels(k:end, col)=channels(k:end, col)+360;
        elseif abs(diff-360)<abs(diff)
          channels(k:end, col)=channels(k:end, col)-360;
        end
      end
    end
  end
end


%INITUNDISTORTRECTIFYMAP  Computes the undistortion and rectification transformation map
%
%     [map1, map2] = cv.initUndistortRectifyMap(cameraMatrix, distCoeffs, siz)
%     [...] = cv.initUndistortRectifyMap(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __cameraMatrix__ Input camera matrix `A = [f_x 0 c_x; 0 f_y c_y; 0 0 1]`
% * __distCoeffs__ Input vector of distortion coefficients
%   `[k1,k2,p1,p2,k3,k4,k5,k6,s1,s2,s3,s4,taux,tauy]` of 4, 5, 8, 12 or 14
%   elements. If the vector is empty, the zero distortion coefficients are
%   assumed.
% * __siz__ Undistorted image size `[w,h]`.
%
% ## Output
% * __map1__ The first output map. See `M1Type`.
% * __map2__ The second output map. See `M1Type`.
%
% ## Options
% * __R__ Optional rectification transformation in the object space (3x3
%   matrix). `R1` or `R2`, computed by cv.stereoRectify can be passed here. If
%   the matrix is empty, the identity transformation is assumed. default empty
% * __NewCameraMatrix__, __P__ New camera matrix (3x3)
%   `Ap = [fp_x 0 cp_x; 0 fp_y cp_y; 0 0 1]` or new projection matrix `P`
%   (3x4). If empty, uses the default new camera matrix from
%   cv.getDefaultNewCameraMatrix (with `CenterPrincipalPoint=true`).
%   default empty
% * __M1Type__ Type of the first output map, default -1 (equivalent to
%   `int16`). See cv.convertMaps. Accepted types are:
%   * __int16__ first output map is a MxNx2 `int16` array, second output map
%     MxNx1 `uint16` (fixed-point representation).
%   * __single1__ first output map is a MxNx1 `single` matrix, second output
%     map is MxNx1 `single` (separate floating-point representation).
%   * __single2__ first output map is a MxNx2 `single` matrix, second output
%     map is empty (combined floating-point representation).
%
% The function computes the joint undistortion and rectification
% transformation and represents the result in the form of maps for
% cv.remap. The undistorted image looks like original, as if it is captured
% with a camera using the camera matrix `NewCameraMatrix` and zero distortion.
% In case of a monocular camera, `NewCameraMatrix` is usually equal to
% `cameraMatrix`, or it can be computed by cv.getOptimalNewCameraMatrix for a
% better control over scaling. In case of a stereo camera, `NewCameraMatrix`
% is normally set to `P1` or `P2` computed by cv.stereoRectify.
%
% Also, this new camera is oriented differently in the coordinate space,
% according to `R`. That, for example, helps to align two heads of a stereo
% camera so that the epipolar lines on both images become horizontal and
% have the same y-coordinate (in case of a horizontally aligned stereo
% camera).
%
% The function actually builds the maps for the inverse mapping algorithm
% that is used by cv.remap. That is, for each pixel `(u,v)` in the
% destination (corrected and rectified) image, the function computes the
% corresponding coordinates in the source image (that is, in the original
% image from camera). The following process is applied:
%
%     x = (u - cp_x) / fp_x
%     y = (v - cp_y) / fp_y
%     [X Y Z]' = inv(R) * [x y 1]'
%     xp = X / W
%     yp = Y / W
%     r^2 = xp^2 + yp^2
%     xpp = xp*(1 + k1*r^2 + k2*r^4 + k3*r^6)/(1 + k4*r^2 + k5*r^4 + k6*r^6) +
%           2*p1*xp*yp + p2*(r^2 + 2*xp^2) + s1*r^2 + s2*r^4
%     ypp = yp*(1 + k1*r^2 + k2*r^4 + k3*r^6)/(1 + k4*r^2 + k5*r^4 + k6*r^6) +
%           p1*(r^2 + 2*yp^2) + 2*p2*xp*yp + s3*r^2 + s4*r^4
%       [xppp]   [R33(taux,tauy)              0 -R13(taux,tauy)]                  [xpp]
%     s*[yppp] = [             0 R33(taux,tauy) -R23(taux,tauy)] * R(taux,tauy) * [ypp]
%       [   1]   [             0              0               1]                  [  1]
%     map_x(u,v) = xppp * f_x + c_x
%     map_y(u,v) = yppp * f_y + c_y
%
% where `k1`, `k2`, `p1`, `p2`, `k3`, `k4`, `k5`, `k6`, `s1`, `s2`, `s3`,
% `s4`, `taux`, `tauy` are the distortion coefficients.
%
% In case of a stereo camera, this function is called twice: once for each
% camera head, after cv.stereoRectify, which in its turn is called after
% cv.stereoCalibrate. But if the stereo camera was not calibrated, it is still
% possible to compute the rectification transformations directly from the
% fundamental matrix using cv.stereoRectifyUncalibrated. For each camera, the
% function computes homography `H` as the rectification transformation in a
% pixel domain, not a rotation matrix `R` in 3D space. `R` can be computed
% from `H` as:
%
%     R = inv(cameraMatrix) * H * cameraMatrix
%
% where `cameraMatrix` can be chosen arbitrarily.
%
% See also: cv.remap, cv.convertMaps, cv.getOptimalNewCameraMatrix,
%  cv.stereoRectify, cv.stereoCalibrate, cv.stereoRectifyUncalibrated
%


%Example of a script that can be used to set up different thermodynamic models depending on the pH temp etc

% [modelT,directions]=setupThermoModel(model,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,temp,cpHa,ppHa,epHa,isCyto,isExt,biomassRxnAbbr,Ecoli_symphID_rxnAbbr,Legendre,useKeqData,nStdDevGroupCont,figures)

mkdir one
cd one
metBoundsFile=[];
rxnBoundsFile=[];
Legendre=1;
useKeqData=1;
nStdDevGroupCont=0;
cumNormProbCutoff=0.2;
figures=0;
printToFile=1;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,310.15,7.7,7.7,7.7,0.25,0.25,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);

cd ../
mkdir two
cd two
Legendre=1;
useKeqData=1;
nStdDevGroupCont=1;
figures=1;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,310.15,7.7,7.7,7.7,0.25,0.25,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);

cd ../
mkdir three
cd three
Legendre=1;
useKeqData=1;
nStdDevGroupCont=0;
figures=0;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,298.15,7,7,7,0,0,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);

cd ../
mkdir four
cd four
Legendre=1;
useKeqData=0;
nStdDevGroupCont=0;
figures=0;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,310.15,7.7,7.7,7.7,0.25,0.25,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);

cd ../
mkdir five
cd five
Legendre=1;
useKeqData=0;
nStdDevGroupCont=1;
figures=0;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,310.15,7.7,7.7,7.7,0.25,0.25,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);

cd ../
mkdir six
cd six
Legendre=1;
useKeqData=0;
nStdDevGroupCont=0;
figures=0;
[modelT,directions]=setupThermoModel(iAF1,metAbbrAlbertyAbbr,metGroupCont,Alberty2006,298.15,7,7,7,0,0,'Ec_biomass_iAF1260_core_59p81M',Ecoli_symphID_rxnAbbr,metBoundsFile,rxnBoundsFile,Legendre,useKeqData,nStdDevGroupCont,cumNormProbCutoff,figures,printToFile);


function saved=loadEEG(dd, order, band, ival, channel_layout)

[cnt,mrk,mnt]=eegfile_loadMatlab(dd);
cnt = proc_filtButter(cnt,order,band);
cnt = proc_selectChannels(cnt,channel_layout);
% cnt to eo
epo=cntToEpo(cnt,mrk,ival);
%% variables can b changed by the data
classes=size(epo.className,2);
trial=size(epo.x,3)/2/(classes-1);

%% extract the rest class
for ii =1:classes
    if strcmp(epo.className{ii},'Rest')
        epoRest=proc_selectClasses(epo,{epo.className{ii}});
        epoRest.x=datasample(epoRest.x,trial,3,'Replace',false);
        epoRest.y=datasample(epoRest.y,trial,2,'Replace',false);
    else
        epo_check(ii)=proc_selectClasses(epo,{epo.className{ii}});
        % random sampling
        epo_check(ii).x=datasample(epo_check(ii).x,trial,3,'Replace',false);
        epo_check(ii).y=datasample(epo_check(ii).y,trial,2,'Replace',false);
    end
end
if classes<7
    epo_check(size(epo_check,2)+1)=epoRest;
end

%% concatenate the classes
for ii=1:size(epo_check,2)
    if ii==1
        concatEpo=epo_check(ii);
    else
        concatEpo=proc_appendEpochs(concatEpo,epo_check(ii));
    end
end
saved=concatEpo;


% SBPLOT - create axes in arbitrary subplot grid positions and sizes
%
% Usage:  >> axis_handle = sbplot(v,h,index)
%         >> axis_handle = sbplot(v,h,[index1 index2])
%         >> axis_handle = sbplot(v,h,[index1 index2],axprop,..)
%         >> axis_handle = sbplot(v,h,[index1 index2],'ax',handle,axprop,..)
%
% Inputs:
%   v,h    - Integers giving the vertical and horizontal ranks of the tiling.
%   index  - Either a single subplot index, in which case the command
%            is equivalent to subplot, or a two-element vector giving
%            the indices of two corners of the SBPLOT area according
%            to SUBPLOT convention (e.g., left-to-right, top-to-bottom).
%   axprop - Any axes property(s), e.g., >> sbplot(3,3,3,'color','w')
%   handle - Following keyword 'ax', sbplot tiles the given axes handle
%            instead of the whole figure
%
% Output:
%  axis_handle - matlab axis handle
%
% Note:
%   sbplot is essentially the same as the subplot command except that
%   sbplot axes may span multiple tiles. Also, SBPLOT will not erase
%   underlying axes.
%
%  Examples: >> sbplot(3,3,6);plot(rand(1,10),'g');
%            >> sbplot(3,3,[7 2]);plot(rand(1,10),'r');
%            >> sbplot(8,7,47);plot(rand(1,10),'b');
%
% Authors: Colin Humphries, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, La Jolla, June, 1998

% Copyright (C) June 1998, Colin Humphries & Scott Makeig, SCCN/INC/UCSD,
% scott@sccn.ucsd.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% reformatted by Scott Makeig, 6/10/98
% 12/22/00 test nargin<3 -sm
% 01/21/01 added (recursive) axes option 'ax' -sm
% 01-25-02 reformated help & licence -ad

function [out] = sbplot(m,n,gridpos,varargin) % varargin is std. matlab arg list

if nargin<3
   error('            requires >=3 arguments');
end

if nargin>3 && strcmp(varargin{1},'ax')
   pos = get(varargin{2},'Position'); %  sbplot(3,1,[2 3]) -> 0.4111 0.1100 0.4939 0.815
   varargin = {varargin{3:end}};
else
   pos = get(gcf,'DefaultAxesPosition'); %  [0.1300    0.1100    0.7750    0.815]
end

Xpad = pos(1);      % lower-left distance from left side of figure
Ypad = pos(2);      % lower-left distance from bottom of figure

Xlen = pos(3);      % axes width
Ylen = pos(4);      % axes height

if n == 2
  xspace = Xlen*0.27/(n-0.27);      % xspace between axes as per subplot
else
  xspace = (0.9*Xlen)*0.27/(n-0.9*0.27);
end

if m == 2
  yspace = Ylen*0.27/(m-0.27);      % yspace between axes as per subplot
else                                % WHY Xlen (.775) instead of Ylen (.815) ??
  yspace = (0.9*Ylen)*0.27/(m-0.9*0.27);
end

xlength = (Xlen-xspace*(n-1))/n;  % axes width
ylength = (Ylen-yspace*(m-1))/m;  % axes height

% Convert tile indices to grid positions
if length(gridpos) == 1
  xgridpos(1) = mod(gridpos,n);   % grid position
  if xgridpos(1) == 0
    xgridpos(1) = n;
  end
  xgridpos(2) = 1;                   % grid length
  ygridpos(1) = m-ceil(gridpos/n)+1; % grid position
  ygridpos(2) = 1;                   % grid length
else
  xgridpos(1) = mod(gridpos(1),n);
  if xgridpos(1) == 0
    xgridpos(1) = n;
  end
  tmp = mod(gridpos(2),n);
  if tmp == 0
    tmp = n;
  end
  if tmp > xgridpos(1)
    xgridpos(2) = tmp-xgridpos(1)+1;
  else
    xgridpos(2) = xgridpos(1)-tmp+1;
    xgridpos(1) = tmp;
  end

  ygridpos(1) = m-ceil(gridpos(1)/n)+1;
  tmp = m-ceil(gridpos(2)/n)+1;
  if tmp > ygridpos(1)
    ygridpos(2) = tmp-ygridpos(1)+1;
  else
    ygridpos(2) = ygridpos(1)-tmp+1;
    ygridpos(1) = tmp;
  end
end

% Calculate axes coordinates
position(1) = Xpad+xspace*(xgridpos(1)-1)+xlength*(xgridpos(1)-1);
position(2) = Ypad+yspace*(ygridpos(1)-1)+ylength*(ygridpos(1)-1)-0.03;
position(3) = xspace*(xgridpos(2)-1)+xlength*xgridpos(2);
position(4) = yspace*(ygridpos(2)-1)+ylength*ygridpos(2);

% Create new axes
ax = axes('Position',position,varargin{:});

% Output axes handle
if nargout > 0
  out = ax;
end


% gigascience -> EMG signal figure

clear all; clc; close all;

dd='C:\Users\Doyeunlee\Desktop\Analysis\01_Raw data\';
% filelist={'sub01','sub02','sub03','sub04','sub05','sub06','sub07','sub08','sub09','sub10'};
filelist={'session1_sub4_multigrasp_MI_EMG'};
ival=[0 4500];

% selected_class = [11 12 13 15 16 17 18 20 21 22 23 43 44 45 47 48 49 51 52 53];
% selected_class = {'F3','F1','Fz','F2','F4','FC3','FC1','FCz','FC2','FC4','C3','C1', 'Cz', 'C2', 'C4','CP3','CP1','CPz','CP2','CP4','P3','P1','Pz','P2','P4'};
% selected_class = {'C3','C1', 'Cz', 'C2', 'C4'};
% selected_class = {'Cz'};
selected_class ={'EMG_1','EMG_2','EMG_3','EMG_4','EMG_5','EMG_6','EMG_ref'};
% selected_class = [1 2 3 4 5 6 7];

fold = 5;

for sub = 1:length(filelist)
    [cnt,mrk,mnt]=eegfile_loadMatlab([dd '\' filelist{sub}]);

    cnt=proc_selectChannels(cnt,selected_class);
    cnt=proc_filtButter(cnt,5,[10 500]);
    epo=cntToEpo(cnt,mrk,ival);

    classes=size(epo.className,2);
    trial=size(epo.x,3)/2/(classes-1);

    eachClassFold_no=trial/fold;

end

fs = 250;
% plot(psd(spectrum.periodogram, cntReach.x, 'Fs', fs));
% psdest = psd(spectrum.periodogram, cntReach.x, 'Fs',fs);
% plot(psdest.Frequencies,psdest.Data);
% xlabel('Hz'); grid on;
% ylim([0 60]);
% xlim([0 60]);
% hold on;
%
% fs = 250;
% figure();
% plot(psd(spectrum.periodogram, cntReach_ME.x, 'Fs', fs));
% psdest = psd(spectrum.periodogram, cntReach_ME.x, 'Fs',fs);
% plot(psdest.Frequencies,psdest.Data);
% xlabel('Hz'); grid on;
% ylim([0 60]);
% xlim([0 60]);
%
% xdft = fft(cntReach_ME.x);
% xdft = xdft(1:length(cntReach_ME.x)/2+1);
% freq = 0:fs/length(cntReach_ME.x):fs/2;
% figure();
% plot(freq,abs(xdft));
% xlabel('Hz');

% T = 1/fs;
% tx = [0:length(cnt.x)-1]/fs;
% figure();
% subplot(211);
% plot(tx,cnt.x); xlabel('Time(s)'); ylabel('Amplitude(uV)');

% mean_EEGsig = mean(cnt.x);
% max_value = max(cnt.x);
% mean_value = mean(cnt.x);
% threshold=(max_value - mean_value)/2;
% subplot(212), plot(tx, mean_value);
% xlabel('Time (s)'); ylabel('Amplitude(uV)');

% T = 1/fs;
% tx = [0:length(cntReach.x)-1]/fs;
% figure();
% % subplot(211);
% plot(tx,cntReach.x); xlabel('Time(s)'); ylabel('Amplitude(uV)');

epo_1 = cntToEpo(cnt, mrk, ival);
fv_1 = proc_rectifyChannels(epo_1);
fv_1 = proc_movingAverage(fv_1, 100, 'centered');
fv_1 = proc_baseline(fv_1, [0 500]);

result = mean(fv_1.x,3);
a = result;

X = abs(a);
X_1 = movmean(X, 30);

plot(X_1);
% plot(X_1,'LineWidth',1.5);
% ylim([0 200]);
xticks([0 1250 3750 6250 8750 11250]);
xlim([0 11251]);
% ylim([0 35]); % reaching
ylim([0 35]); % grasp
% ylim([0 10]); % twist