function evaluation(norm_pred_list,gt_dir,setting_name,setting_class,legend_name)
load(gt_dir);
if ~exist(sprintf('./plot/baselines/Val/%s/%s',setting_class,legend_name),'dir')
    mkdir(sprintf('./plot/baselines/Val/%s/%s',setting_class,legend_name));
end
IoU_thresh = 0.5;
event_num = 61;
thresh_num = 1000;
org_pr_cruve = zeros(thresh_num,2);
count_face = 0;

for i = 1:event_num
    img_list = file_list{i};
    gt_bbx_list = face_bbx_list{i};
    pred_list = norm_pred_list{i};
    sub_gt_list = gt_list{i};
    img_pr_info_list = cell(length(img_list),1);

    fprintf('%s, current event %d\n',setting_name,i);
    for j = 1:length(img_list)
        gt_bbx = gt_bbx_list{j};
        pred_info = pred_list{j};
        keep_index = sub_gt_list{j};
        count_face = count_face + length(keep_index);

        if isempty(gt_bbx) || isempty(pred_info)
            continue;
        end
        ignore = zeros(size(gt_bbx,1),1);
        if ~isempty(keep_index)
            ignore(keep_index) = 1;
        end

        [pred_recall, proposal_list] = image_evaluation(pred_info, gt_bbx, ignore, IoU_thresh);

        img_pr_info = image_pr_info(thresh_num, pred_info, proposal_list, pred_recall);
        img_pr_info_list{j} = img_pr_info;
    end
    for j = 1:length(img_list)
        img_pr_info = img_pr_info_list{j};
        if ~isempty(img_pr_info)
            org_pr_cruve(:,1) = org_pr_cruve(:,1) + img_pr_info(:,1);
            org_pr_cruve(:,2) = org_pr_cruve(:,2) + img_pr_info(:,2);
        end
    end
end
pr_cruve = dataset_pr_info(thresh_num, org_pr_cruve, count_face);
save(sprintf('./plot/baselines/Val/%s/%s/wider_pr_info_%s_%s.mat',setting_class,legend_name,legend_name,setting_name),'pr_cruve','legend_name','-v7.3');
end

function [pred_recall,proposal_list] = image_evaluation(pred_info, gt_bbx, ignore, IoU_thresh)
    pred_recall = zeros(size(pred_info,1),1);
    recall_list = zeros(size(gt_bbx,1),1);
    proposal_list = zeros(size(pred_info,1),1);
    proposal_list = proposal_list + 1;
    pred_info(:,3) = pred_info(:,1) + pred_info(:,3);
    pred_info(:,4) = pred_info(:,2) + pred_info(:,4);
    gt_bbx(:,3) = gt_bbx(:,1) + gt_bbx(:,3);
    gt_bbx(:,4) = gt_bbx(:,2) + gt_bbx(:,4);
    for h = 1:size(pred_info,1)
        overlap_list = boxoverlap(gt_bbx, pred_info(h,1:4));
        [max_overlap, idx] = max(overlap_list);
        if max_overlap >= IoU_thresh
            if (ignore(idx) == 0)
                recall_list(idx) = -1;
                proposal_list(h) = -1;
            elseif (recall_list(idx)==0)
                recall_list(idx) = 1;
            end
        end
        r_keep_index = find(recall_list == 1);
        pred_recall(h) = length(r_keep_index);
    end
end

function img_pr_info = image_pr_info(thresh_num, pred_info, proposal_list, pred_recall)
    img_pr_info = zeros(thresh_num,2);
    for t = 1:thresh_num
        thresh = 1-t/thresh_num;
        r_index = find(pred_info(:,5)>=thresh,1,'last');
        if (isempty(r_index))
            img_pr_info(t,2) = 0;
            img_pr_info(t,1) = 0;
        else
            p_index = find(proposal_list(1:r_index) == 1);
            img_pr_info(t,1) = length(p_index);
            img_pr_info(t,2) = pred_recall(r_index);
        end
    end
end

function pr_cruve = dataset_pr_info(thresh_num, org_pr_cruve, count_face)
    pr_cruve = zeros(thresh_num,2);
    for i = 1:thresh_num
        pr_cruve(i,1) = org_pr_cruve(i,2)/org_pr_cruve(i,1);
        pr_cruve(i,2) = org_pr_cruve(i,2)/count_face;
    end
end


%%
dt = 0.2;
b = Bicycle('L', 2.6, 'speedmax', 30, 'steermax', 0.6, 'dt', dt, 'x0', [0 0 0])

b.add_driver( RandomPath(10) );

p = b.run(1000);

%%

clf
[car.image,~,car.alpha] = imread('car2.png');
car.rotation = 180;
car.centre = [81,110];
car.centre = [648; 173];
car.length = 4.2;

plotvol(10)

a = gca

x = [0 0 0]';
h=plot_vehicle(p, 'model', car, 'trail', 'r:')
a.XLimMode = 'manual';
a.YLimMode = 'manual';
set(gcf, 'Color', 'w')
grid on
a = gca;
xyzlabel


function [uOutput] = scecimp(nFunction, sFilename)
% import SCEC (Caltech) Data Center format
% Filter function switchyard
%%%%     CHANGE THESE LINES %%%%%%%%%%%
if nFunction == FilterOp.getDescription
  uOutput = 'SCEC (Caltech) Data Center format';
elseif nFunction == FilterOp.getWebpage
  uOutput = 'SCEC.htm'; %%%%    DO NOT CHANGE %%%%%%%%%%%
elseif nFunction == FilterOp.importCatalog
    % Read formated data
    mData = textread(sFilename, '%s', 'delimiter', '\n', 'whitespace', '');
    % Create empty catalog
    uOutput = zeros(length(mData), 9);
    % Loop through all lines of catalog and convert them
    mData = char(mData);
    l = find( mData == ' ' );
    mData(l) = '0';
    errc = 1;

    try % this is the fast method ....
        i = 1:length(mData(:,1));
        [uOutput] = readvalues(mData,i,i);

    catch  % this is the line by line method ..
        for i = 1:length(mData(:,1))
            if rem(i,100) == 0 ; disp([ num2str(i) ' of ' num2str(length(mData)) ' events processed ']); end
            try
                uOutput(i,:) = readvalues(mData,i,1);
            catch
                errc = errc + 1;
                if errc == 100
                    if stoploop
                        return
                    end
                end
                msg.dbfprintf('Import: Problem in line %d of %s. Line ignored.\n',i, sFilename);
                uOutput(i,:)=nan;
            end
        end

    end
    l = isnan(uOutput(:,1));
    uOutput(l,:) = [];

end

%%%%%%%%%%%%%%%%%%%%%%
%%%%     CHANGE THESE LINES %%%%%%%%%%%

function [uOutput] = readvalues(mData,i,k)

  uOutput(k,1) = str2num(mData(i,34:37)) - str2num(mData(i,39:43))/60 ;  % Longitude
uOutput(k,2) = str2num(mData(i,26:27)) + str2num(mData(i,29:33))/60 ;  % Latitude
uOutput(k,3) = str2num(mData(i,1:4));    % Year
uOutput(k,4) = str2num(mData(i,6:7));    % Month
uOutput(k,5) = str2num(mData(i,9:10));   % Day
uOutput(k,6) = str2num(mData(i,47:49));  % Magnitude
uOutput(k,7) = str2num(mData(i,55:59));  % Depth
uOutput(k,8) = str2num(mData(i,13:14));  % Hour
uOutput(k,9) = str2num(mData(i,16:17));  % Minute
% convert to decimal years
uOutput(k,3) = decyear([uOutput(k,3) uOutput(k,4) uOutput(k,5) uOutput(k,8) uOutput(k,9)]);

% convert to decimal years
uOutput(k,3) = decyear([uOutput(k,3) uOutput(k,4) uOutput(k,5) uOutput(k,8) uOutput(k,9)]);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%    DO NOT CHANGE %%%%%%%%%%%

function [mystop] = stoploop()

ButtonName=questdlg('More than 100 lines could not be read. Continue?', ...
    'Interrupt?', ...
    'Yes','No','Nope');

switch ButtonName
case 'Yes'
    disp('going on');
    mystop = 0;
case 'No'
    mystop = 1;
end % switch


function spm_MDP_plot(MDP)
% creates a movie of hierarchical expectations and outcomes
% FORMAT spm_MDP_plot(MDP))
%
% MDP - nested MDP (and DEM) structures
%     - (requires fields to specify the labels of states and outcomes)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_MDP_plot.m 6977 2016-12-24 17:48:44Z karl $

% Preliminaries
%--------------------------------------------------------------------------
cla,axis([1 20 0 8]); axis image, hold on, box on
set(gca,'Fontsize',16,'XColor','r','TickLength',[0 0],'XTick',[],'YTick',[])
title('Narrative construction','FontSize',16)

% switch off basis functions for visual stimuli
%--------------------------------------------------------------------------
try
global STIM
B = STIM.B;
STIM.B = 1;
end

% hidden factors to display (one per level)
%--------------------------------------------------------------------------
scale  = 1 - 1/16;                             % background level for text
try k1 = MDP.label.k;     catch, k1 = 1; end
try k2 = MDP.MDP.label.k; catch, k2 = 1; end

% cycle over highest level
%--------------------------------------------------------------------------
T1     = size(MDP.xn{k1},4);
F1     = fix(1024/(T1*numel(MDP.label.name{k1}{1})));
F1     = min(max(F1,8),32);
for t1 = 1:T1

    % draw stuff
    %----------------------------------------------------------------------
    p     = 1 - squeeze(MDP.xn{k1}(end,:,:,t1));
    p     = p*scale;
    str   = MDP.label.name{k1};
    ns    = size(p,1);
    nt    = size(p,2);
    for i = 1:nt
        for j = 1:ns
            try
                set(h1(i,j),'Color',[1 1 1]*p(j,i));
            catch
                h1(i,j) = text(16*i/nt,j/ns + 6,str(j),...
                    'HorizontalAlignment','center',...
                    'Color',[1 1 1]*p(j,i),'FontSize',F1);
            end
        end
    end

    % next level down
    %----------------------------------------------------------------------
    if isfield(MDP,'mdp')
        T2     = size(MDP.mdp(t1).xn{k2},4);
        F2     = fix(1024/(T2*numel(MDP.MDP.label.name{k1}{1})));
        F2     = min(max(F2,8),32);
        for t2 = 1:T2

            % draw stuff
            %--------------------------------------------------------------
            p     = 1 - squeeze(MDP.mdp(t1).xn{k2}(end,:,:,t2));
            p     = p*scale;
            str   = MDP.MDP.label.name{k2};
            ns    = size(p,1);
            nt    = size(p,2);
            for i = 1:nt
                for j = 1:ns
                    try
                        set(h2(i,j),'Color',[1 1 1]*p(j,i));
                    catch
                        h2(i,j) = text(16*i/nt,j/ns + 4,str(j),...
                            'HorizontalAlignment','center',...
                            'Color',[1 1 1]*p(j,i),'FontSize',F2);
                    end
                end
            end

            % check for extra time points
            %--------------------------------------------------------------
            try
                delete(h2((nt + 1):end,:))
            end

            % next level down
            %--------------------------------------------------------------
            if isfield(MDP.mdp(t1),'dem')

                % accumulated expectations from Bayesian filtering
                %----------------------------------------------------------
                o  = MDP.mdp(t1).dem(t2).X;
                no = numel(o);
                T  = size(o{1},2);

            else

                % observed outcomes
                %----------------------------------------------------------
                o  = MDP.mdp(t1).o;
                no = size(o,1);
                T  = 16;
            end

            % outcome modalities
            %--------------------------------------------------------------
            set(gca,'XTickLabel',MDP.MDP.label.modality)
            set(gca,'XTick',16*(1:no)/no)

            F3     = fix(1024/(no*numel(MDP.MDP.label.outcome{1}{1})));
            F3     = min(max(F3,8),32);
            for t3 = 1:T

                % draw stuff
                %----------------------------------------------------------
                for i = 1:no

                    if iscell(o)

                        % probabilistic outcomes (expectations)
                        %--------------------------------------------------
                        x     = 16*i/no;
                        p     = spm_softmax(log(o{i}(:,t3))/4);
                        str   = MDP.MDP.label.outcome{i};
                        [p,j] = sort(p,'descend');
                        col   = [1 1 1] - [0 1 1]*(p(1) - 1/numel(p));
                        try
                            set(h3(i),'String',str(j(1)),...
                                'Color',col);
                        catch
                            h3(i) = text(x,3,str(j(1)),...
                                'HorizontalAlignment','center',...
                                'Color',col,'FontSize',F3);
                        end

                        % observations in image format
                        %--------------------------------------------------
                        x     = [-1 1] + x;
                        y     = [-1 1] + 1;
                        try
                            px = MDP.mdp(t1).dem(t2).pU.x{1}(:,t3);
                            pv = MDP.mdp(t1).dem(t2).pU.v{2}(:,t3);
                            px = spm_unvec(px,MDP.MDP.DEM.G(1).x);
                            pv = spm_unvec(pv,MDP.MDP.DEM.G(2).v);
                            Y  = MDP.MDP.DEM.label{i}(px,pv);
                            try
                                delete(h4(i))
                            end
                            h4(i) = image(x,y,flipud(Y)*64);

                        end

                    else

                        % deterministic outcomes
                        %--------------------------------------------------
                        str = MDP.MDP.label.outcome{i}{o(i,t2)};
                        try
                            set(h3(i),'String',str);
                        catch
                            h3(i) = text(16*i/no,2,str,'Color','r',...
                                'HorizontalAlignment','center','FontSize',F3);
                        end
                    end
                end

                % plot timelines
                %----------------------------------------------------------
                x  = [1 1]*(t3 + (t2 - 1)*T + (t1 - 1)*T*MDP.MDP.T);
                x  = 1 + 16*x/(MDP.MDP.T*MDP.T*T);
                y  = [7.2 8];
                try
                    set(l1,'XData',x);
                catch
                    l1 = line(x,y,'Color','r','LineWidth',8);
                end

                x  = [1 1]*(t3 + (t2 - 1)*T);
                x  = 1 + 16*x/(T*T2);
                y  = [5.2 6];
                try
                    set(l2,'XData',x);
                catch
                    l2 = line(x,y,'Color','r','LineWidth',8);
                end

                x  = [1 1]*t3;
                x  = 1 + 16*x/T;
                y  = [3.2 4];
                try
                    set(l3,'XData',x);
                catch
                    l3 = line(x,y,'Color','r','LineWidth',8);
                end

                % and save graphics
                %----------------------------------------------------------
                try
                    M(end + 1) = getframe(gca);
                catch
                    M = getframe(gca);
                end

            end
        end

    else

        % observed outcomes
        %------------------------------------------------------------------
        o      = MDP.o;
        no     = size(o,1);
        T      = 16;
        F3     = fix(1024/(no*numel(MDP.label.outcome{1}{1})));
        F3     = min(max(F3,8),48);

        % outcome modalities
        %------------------------------------------------------------------
        set(gca,'XTickLabel',MDP.label.modality)
        set(gca,'XTick',16*(1:no)/no)

        for t3 = 1:T

            % draw stuff
            %--------------------------------------------------------------
            for i = 1:no
                str = MDP.label.outcome{i}{o(i,t1)};
                try
                    set(h3(i,j),'String',str);
                catch
                    h3(i,j) = text(16*i/no,2,str,'Color','r',...
                        'HorizontalAlignment','center','FontSize',F3);
                end
            end

            % plot timelines
            %--------------------------------------------------------------
            x  = [1 1]*(t3 + (t1 - 1)*T);
            x  = 1 + 16*x/(T*T1);
            y  = [7.2 8];
            try
                set(l2,'XData',x);
            catch
                l2 = line(x,y,'Color','r','LineWidth',8);
            end

            x  = [1 1]*t3;
            x  = 1 + 16*x/T;
            y  = [5.2 6];
            try
                set(l3,'XData',x);
            catch
                l3 = line(x,y,'Color','r','LineWidth',8);
            end

            % and save graphics
            %--------------------------------------------------------------
            try
                M(end + 1) = getframe(gca);
            catch
                M = getframe(gca);
            end

        end
    end
end

% save movie
%--------------------------------------------------------------------------
try, STIM.B = B; end
set(gca,'Userdata',{M,16})
set(gca,'ButtonDownFcn','spm_DEM_ButtonDownFcn')


function d = fmris_read_analyze(file,Z,T);
%
% Read in 1 4D or >1 3D Analyze format Image Volumes
%
% Usage
%
% d=Read_Analyze(file);
% Reads in all image data and attributes into the structure d.
%
% d=Read_Analyze(file,Z,T);
% Reads in chosen planes and frames and attributes into the structure d.
% Z and T are vectors e.g. Z=1:31;T=1:12; or Z=[24 26];T=[1 3 5];
%
% (c) Roger Gunn & John Aston
%
% HISTORY:
% 2004.02.15 Bob Dougherty (RFD): fixed minor bug- d.file_name gets
% clobbered, so we use 'file' instead.
% Get machine format on which the file was written:
machineformat = getmachineformat(file);
if ~isempty(machineformat)
   % Read Header Information
   d = Read_Analyze_Hdr(file,machineformat);

   % try to get file precision if it is unknown:
   if strcmp(d.precision,'Unknown')
      d.precision=getprecision(deblank(file),machineformat,d.dim,d.global);
   end
   % Read Image Data
   if ~isempty(d) & ~strcmp(d.precision,'Unknown')

      if nargin==1 | strcmp(d.precision,'uint1')

         % Read in Whole Analyze Volume
         fid = fopen(file,'r',machineformat);
         if fid > -1
            d.data=d.scale*reshape(fread(fid,prod(d.dim),d.precision),d.dim(1),d.dim(2),d.dim(3),d.dim(4));
            fclose(fid);
         else
            errordlg('Check Image File: Existence, Permissions ?','Read Error');
         end;

         if nargin==3
            if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))
               d.data=d.data(:,:,Z,T);
               d.Z=Z;
               d.T=T;
            else
               errordlg('Incompatible Matrix Identifiers !','Read Error');
            end
         end

      elseif nargin==3
         % Read in Chosen Planes and Frames
         if (T(1)~=0)|(Z(1)~=0)

            if all(Z>0)&all(Z<=d.dim(3))&all(T>0)&all(T<=d.dim(4))

               fid = fopen(d.file_name,'r',machineformat);
               if fid > -1
                  d.data=zeros(d.dim(1),d.dim(2),length(Z),length(T));
                  for t=1:length(T)
                     for z=1:length(Z)
                        status=fseek(fid,d.hdr.byte*((T(t)-1)*prod(d.dim(1:3))+(Z(z)-1)*prod(d.dim(1:2))),'bof');
                        d.data(:,:,z,t)=d.scale*fread(fid,[d.dim(1) d.dim(2)],d.precision);
                     end
                  end
                  d.Z=Z;
                  d.T=T;
                  fclose(fid);
               else
                  errordlg('Check Image File: Existence, Permissions ?','Read Error');
               end;

            else
               errordlg('Incompatible Matrix Identifiers !','Read Error');
            end;

         end;
      else
         errordlg('Unusual Number of Arguments','Read Error');
      end;
   else
      if strcmp(d.precision,'Unknown');
         errordlg('Unknown Data Type (Precision?)','Read Error');
      end
   end;
else
   errordlg('Unknown Machine Format','Read Error');
end
% if there is no slice thickness, set it to 6mm:
if d.vox(3)==0
   d.vox(3)=6;
end
d.file_name = file;
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function machineformat=getmachineformat(file);
% Get machine format by reading the d.hdr.dim(1) attribute and
% making sure it is 1, 2, 3 or 4.
machineformat=[];
for mf='nlbdgcas'
   fid = fopen([file(1:(length(file)-3)) 'hdr'],'r',mf);
   if fid > -1
      fseek(fid,40,'bof');
      if any(fread(fid,1,'int16')==1:4)
         machineformat=mf;
         fclose(fid);
         break
      else
         fclose(fid);
      end
   else
      errordlg('Check Header File: Existence, Permissions ?','Read Error');
      break
   end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function precision=getprecision(file,machineformat,dim,range);
% Get precision by reading a value from the middle of the .img file and
% making sure it is within the global attribute
precisions=['int8   '
        'int16  '
        'int32  '
        'int64  '
        'uint8  '
        'uint16 '
        'uint32 '
        'uint64 '
        'single '
        'float32'
        'double '
        'float64' ];
nbytes=[1 2 4 8 1 2 4 8 4 4 8 8];
middle_vol=dim(1)*dim(2)*floor(dim(3)/2)+dim(1)*round(dim(2)/2)+round(dim(1)/2);
h=dir(file);
n=ceil(h.bytes/prod(dim));
fid = fopen(file,'r',machineformat);
if fid > -1
   for i=1:size(precisions,1)
      if nbytes(i)==n
         status=fseek(fid,middle_vol*n,'bof');
         if status==0
            precision=deblank(precisions(i,:));
            x=fread(fid,10,precision);
            if all(range(1)<=x) & all(x<=range(2))
               return
            end
         end
      end
   end
end
errordlg('Check Header File: Existence, Permissions ?','Read Error');
precision='Unknown';
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d=Read_Analyze_Hdr(file,machineformat);
% Read Analyze Header information into the structure d
% Adapted from John Ashburners spm_hread.m
fid  = fopen([file(1:(length(file)-3)) 'hdr'],'r',machineformat);
if fid > -1

   % read (struct) header_key
   %---------------------------------------------------------------------------
   fseek(fid,0,'bof');

   d.hdr.sizeof_hdr 		= fread(fid,1,'int32');
   d.hdr.data_type  		= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.db_name    		= deblank(setstr(fread(fid,18,'char'))');
   d.hdr.extents    		= fread(fid,1,'int32');
   d.hdr.session_error   	= fread(fid,1,'int16');
   d.hdr.regular    		= deblank(setstr(fread(fid,1,'char'))');
   d.hdr.hkey_un0    		= deblank(setstr(fread(fid,1,'char'))');

   % read (struct) image_dimension
   %---------------------------------------------------------------------------
   fseek(fid,40,'bof');

   d.hdr.dim    			= fread(fid,8,'int16');
   d.hdr.vox_units    		= deblank(setstr(fread(fid,4,'char'))');
   d.hdr.cal_units    		= deblank(setstr(fread(fid,8,'char'))');
   d.hdr.unused1			= fread(fid,1,'int16');
   d.hdr.datatype			= fread(fid,1,'int16');
   d.hdr.bitpix				= fread(fid,1,'int16');
   d.hdr.dim_un0			= fread(fid,1,'int16');
   d.hdr.pixdim				= fread(fid,8,'float');
   d.hdr.vox_offset			= fread(fid,1,'float');
   d.hdr.funused1			= fread(fid,1,'float');
   d.hdr.funused2			= fread(fid,1,'float');
   d.hdr.funused3			= fread(fid,1,'float');
   d.hdr.cal_max			= fread(fid,1,'float');
   d.hdr.cal_min			= fread(fid,1,'float');
   d.hdr.compressed			= fread(fid,1,'int32');
   d.hdr.verified			= fread(fid,1,'int32');
   d.hdr.glmax				= fread(fid,1,'int32');
   d.hdr.glmin				= fread(fid,1,'int32');

   % read (struct) data_history
   %---------------------------------------------------------------------------
   fseek(fid,148,'bof');

   d.hdr.descrip			= deblank(setstr(fread(fid,80,'char'))');
   d.hdr.aux_file			= deblank(setstr(fread(fid,24,'char'))');
   d.hdr.orient				= fread(fid,1,'char');
   d.hdr.origin				= fread(fid,5,'uint16');
   d.hdr.generated			= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.scannum			= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.patient_id			= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.exp_date			= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.exp_time			= deblank(setstr(fread(fid,10,'char'))');
   d.hdr.hist_un0			= deblank(setstr(fread(fid,3,'char'))');
   d.hdr.views				= fread(fid,1,'int32');
   d.hdr.vols_added			= fread(fid,1,'int32');
   d.hdr.start_field		= fread(fid,1,'int32');
   d.hdr.field_skip			= fread(fid,1,'int32');
   d.hdr.omax				= fread(fid,1,'int32');
   d.hdr.omin				= fread(fid,1,'int32');
   d.hdr.smax				= fread(fid,1,'int32');
   d.hdr.smin				= fread(fid,1,'int32');

   fclose(fid);

   % Put important information in main structure
   %---------------------------------------------------------------------------

   d.dim    	  			= d.hdr.dim(2:5)';
   vox 						= d.hdr.pixdim(2:5)';
   if 	vox(4)==0
      vox(4)=[];
   end
   d.vox       				= vox;
   d.vox_units       		= d.hdr.vox_units;
   d.vox_offset	    		= d.hdr.vox_offset;
   scale     				= d.hdr.funused1;
   d.scale     			  	= ~scale + scale;
   d.global					= [d.hdr.glmin d.hdr.glmax];
   d.calib					= [d.hdr.cal_min d.hdr.cal_max];
   d.calib_units			= d.hdr.cal_units;
   d.origin    				= d.hdr.origin(1:3)';
   d.descrip   				= d.hdr.descrip(1:max(find(d.hdr.descrip)));

   switch d.hdr.datatype
   case 1
      d.precision 	= 'uint1';
      d.hdr.byte 	= 0;
   case 2
      d.precision 	= 'uint8';
      d.hdr.byte 	= 1;
   case 4
      d.precision 	= 'int16';
      d.hdr.byte 	= 2;
   case 8
      d.precision 	= 'int32';
      d.hdr.byte 	= 4;
   case 16
      d.precision 	= 'float';
      d.hdr.byte 	= 4;
   case 64
      d.precision 	= 'double';
      d.hdr.byte 	= 8;
   otherwise
      d.precision 	= 'Unknown';
      d.hdr.byte 	= 0;
   end

else
   d=[];
   errordlg('Check Header File: Existence, Permissions ?','Read Error');
end
return


function G = egrad(X)
  global P;
  global PA;
  % Same comment here about Xmat.
  Xmat = X.U*X.S*X.V';
  G = P.*Xmat - PA;
end


function mrk= mrk_sortChronologically(mrk, varargin)
%MRK_SORTCHRONOLOGICALLY - Sort Markers Chronologically
%
%Synopsis:
%  MRK_OUT= mrk_sortChronologically(MRK_IN, <OPT>)
%
%Arguments:
%  MRK_IN: Marker structure as received by file_loadBV
%  OPT: struct or property/value list of optional properties:
%    'RemoveVoidClasses': Void classes are removed from the list of classes.
%    'Classwise': Each class is sorted chronologically, default 0.
%
%Returns:
% MRK_OUT: Marker structure with events sorted chronologically

% Benjamin Blankertz

props= {'Sort',              0  'BOOL';
        'RemoveVoidClasses'  1  'BOOL';
        'Classwise'          0  '!BOOL';
        };
props_selectEvents= mrk_selectEvents;

if nargin==0,
  mrk= opt_catProps(props, props_selectEvents);
  return
end

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

misc_checkType(mrk, 'STRUCT(time)');

if opt.Classwise,
  nClasses= size(mrk.y,1);
  si= zeros(nClasses, length(mrk.time));
  for ci= 1:nClasses,
    idx= find(mrk.y(ci,:));
    [so,sidx]= sort(mrk.time(idx));
    si(ci, 1:length(idx))= idx(sidx);
  end
  si= si(find(si));
else
  [so,si]= sort(mrk.time);
end

opt_selectEvents= opt_substruct(opt, props_selectEvents(:,1));
mrk= mrk_selectEvents(mrk, si, opt_selectEvents, 'Sort',0);


function  matRad_plotAxisLabels(axesHandle,ct,plane,slice,defaultFontSize,tickdist)
% matRad function to plot x and y labels denoting the ct dimensions
% according to the selected plane
%
% call
%   matRad_plotAxisLabels(axesHandle,ct,plane,slice,defaultFontSize)
%   matRad_plotAxisLabels(axesHandle,ct,plane,slice,defaultFontSize,
%   tickdist)
%
% input
%   axesHandle         handle to axes the slice should be displayed in
%   ct                 matRad ct structure
%   plane              plane view (coronal=1,sagittal=2,axial=3)
%   slice              slice in the selected plane of the 3D cube
%   defaultFontSize    default font size as double value
%
% output
%   -
%
% References
%   -
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright 2017 the matRad development team.
%
% This file is part of the matRad project. It is subject to the license
% terms in the LICENSE file found in the top-level directory of this
% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part
% of the matRad project, including this file, may be copied, modified,
% propagated, or distributed except according to the terms contained in the
% LICENSE file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ~exist('defaultFontSize','var') || isempty(defaultFontSize)
    defaultFontSize = 12;
end

if ~exist('tickdist','var') || isempty(tickdist)
    tickdist = 50;
end
%% Set axis labels and plot iso center
if  plane == 3% Axial plane
    if ~isempty(ct.resolution.x) && ~isempty(ct.resolution.y)
        set(axesHandle,'XTick',0:tickdist/ct.resolution.x:1000);
        set(axesHandle,'YTick',0:tickdist/ct.resolution.y:1000);
        set(axesHandle,'XTickLabel',0:tickdist:1000*ct.resolution.x);
        set(axesHandle,'YTickLabel',0:tickdist:1000*ct.resolution.y);
        xlabel(axesHandle,'x [mm]','FontSize',defaultFontSize)
        ylabel(axesHandle,'y [mm]','FontSize',defaultFontSize)
        title(axesHandle,['axial plane z = ' num2str(ct.resolution.z*slice) ' [mm]'],'FontSize',defaultFontSize)
    else
        xlabel(axesHandle,'x [voxels]','FontSize',defaultFontSize)
        ylabel(axesHandle,'y [voxels]','FontSize',defaultFontSize)
        title(axesHandle,'axial plane','FontSize',defaultFontSize)
    end
elseif plane == 2 % Sagittal plane
    if ~isempty(ct.resolution.y) && ~isempty(ct.resolution.z)
        set(axesHandle,'XTick',0:tickdist/ct.resolution.z:1000)
        set(axesHandle,'YTick',0:tickdist/ct.resolution.y:1000)
        set(axesHandle,'XTickLabel',0:tickdist:1000*ct.resolution.z)
        set(axesHandle,'YTickLabel',0:tickdist:1000*ct.resolution.y)
        xlabel(axesHandle,'z [mm]','FontSize',defaultFontSize);
        ylabel(axesHandle,'y [mm]','FontSize',defaultFontSize);
        title(axesHandle,['sagittal plane x = ' num2str(ct.resolution.y*slice) ' [mm]'],'FontSize',defaultFontSize)
    else
        xlabel(axesHandle,'z [voxels]','FontSize',defaultFontSize)
        ylabel(axesHandle,'y [voxels]','FontSize',defaultFontSize)
        title(axesHandle,'sagittal plane','FontSize',defaultFontSize);
    end
elseif plane == 1 % Coronal plane
    if ~isempty(ct.resolution.x) && ~isempty(ct.resolution.z)
        set(axesHandle,'XTick',0:tickdist/ct.resolution.z:1000)
        set(axesHandle,'YTick',0:tickdist/ct.resolution.x:1000)
        set(axesHandle,'XTickLabel',0:tickdist:1000*ct.resolution.z)
        set(axesHandle,'YTickLabel',0:tickdist:1000*ct.resolution.x)
        xlabel(axesHandle,'z [mm]','FontSize',defaultFontSize)
        ylabel(axesHandle,'x [mm]','FontSize',defaultFontSize)
        title(axesHandle,['coronal plane y = ' num2str(ct.resolution.x*slice) ' [mm]'],'FontSize',defaultFontSize)
    else
        xlabel(axesHandle,'z [voxels]','FontSize',defaultFontSize)
        ylabel(axesHandle,'x [voxels]','FontSize',defaultFontSize)
        title(axesHandle,'coronal plane','FontSize',defaultFontSize)
    end
end

end


% msTrain

LOAD = 1;

nsegments = [5 7 10 15 20 25 35 50 60 70 80 90 100 Inf]; % number of segments per segmentation
ncv = 1; % number of cross-validation sets
labeltol = 0.9; % required percentage of single-label pixels for segment to be good
nclasses = 23;

datadir = '~/data/eccv08/msrc21/';
imdir = '~/data/msrc/MSRC_ObjCategImageDatabase_v2/Images/';
outdir = '~/data/eccv08/msrc21/';

if LOAD
    load(fullfile(datadir, 'msrc_imsegs.mat'));
    load(fullfile(datadir, 'trainLabels.mat'));
    load(fullfile(datadir, 'trainTestFn_tu.mat'));
    load(fullfile(outdir, 'msSuperpixelLabels.mat'));
    load(fullfile(outdir, 'msSuperpixelData.mat'));
    load(fullfile(outdir, 'msEdgeData.mat'));
    load(fullfile(outdir, 'msEdgeClassifier_tu.mat'));
end

allind = union(train, test);
trainind1 = train(1:50);
trainind = train;
trainind2 = setdiff(trainind, trainind1);
testind = test;

nimages = numel(imsegs);

disp('Converting labels to superpixels')
if ~exist('splabels', 'var')
    splabels = msLabelMap2Sp(labels, {imsegs.segimage});
    save(fullfile(outdir, 'msSuperpixelLabels.mat'), 'splabels');
end

disp('Getting superpixel features')
if ~exist('spfeatures', 'var')
    spfeatures = mcmcGetAllSuperpixelData(imdir, imsegs);
    save(fullfile(outdir, 'msSuperpixelData.mat'), 'spfeatures');
end

disp('Getting edge features')
if ~exist('efeatures', 'var')
    [efeatures, adjlist] = mcmcGetAllEdgeData(spfeatures, imsegs);
    save(fullfile(outdir, 'msEdgeData.mat'), 'efeatures', 'adjlist');
end

disp('Training edge classifier')
if ~exist('eclassifier', 'var')
    eclassifier = msTrainEdgeClassifier(efeatures(trainind1), ...
        adjlist(trainind1), imsegs(trainind1), splabels(trainind1));
    ecal = msCalibrateEdgeClassifier(efeatures(trainind2), adjlist(trainind2), ...
        imsegs(trainind2), eclassifier, splabels(trainind2), ncv);
    ecal = ecal{1};
    save(fullfile(outdir, 'msEdgeClassifier_tu.mat'), 'eclassifier', 'ecal');
end

disp('Getting multiple segmentations')
if ~exist('smaps', 'var')
    for f = allind
        pE{f} = test_boosted_dt_mc(eclassifier, efeatures{f});
        pE{f} = 1 ./ (1+exp(ecal(1)*pE{f}+ecal(2)));
        smaps{f} = msCreateMultipleSegmentations(pE{f}, adjlist{f}, ...
            imsegs(f).nseg, nsegments);
    end
    save(fullfile(outdir, 'msMultipleSegmentations_tu_tmp.mat'), 'pE', 'smaps');
end

disp('Getting segment features')
if ~exist('segfeatures', 'var')
    for f = allind
        if mod(f, 50)==0, disp(num2str(f)), end
        im = im2double(imread([imdir '/' imsegs(f).imname]));
        imdata = mcmcComputeImageData(im, imsegs(f));

        for k = 1:numel(nsegments)
            segfeatures{f, k} = mcmcGetSegmentFeatures(imsegs(f), ...
                spfeatures{f}, imdata, smaps{f}(:, k), (1:max(smaps{f}(:, k))));
            [mclab{f, k}, mcprc{f, k}, allprc{f, k}, trainw{f, k}] = ...
                msSegs2labels(imsegs(f), smaps{f}(:, k), splabels{f}, nclasses);
            seglabel{f, k} = mclab{f, k}.*(mcprc{f, k}>labeltol);
            seggood{f,k} =  1*(mcprc{f, k}>labeltol) + (-1)*(mcprc{f, k}<labeltol);
        end
    end
    save(fullfile(outdir, 'msSegmentFeatures_tu_tmp.mat'), 'segfeatures', 'seglabel', 'seggood', 'trainw');
end

disp('Training segmentation classifier')
if ~exist('segclassifier', 'var')
    traindata = segfeatures(trainind, :);
    trainlabels = seggood(trainind, :);
    trainweights = trainw(trainind, :);
    segclassifier = mcmcTrainSegmentationClassifier2(traindata, trainlabels, trainweights);
    save(fullfile(outdir, 'msSegmentationClassifier_tu_tmp.mat'), 'segclassifier');
end

disp('Training label classifier')
if ~exist('labelclassifier', 'var')
    traindata = segfeatures(trainind, :);
    trainlabels = seglabel(trainind, :);
    trainweights = trainw(trainind, :);
    labelclassifier = msTrainLabelClassifier(traindata, trainlabels, trainweights, classnames, Inf);
    %labelclassifier = mcmcTrainSegmentClassifier2(traindata, trainlabels, trainweights);
    save(fullfile(outdir, 'msLabelClassifier_tu_tmp.mat'), 'labelclassifier');
end

save(fullfile(outdir, 'msClassifiers_tu_tmp.mat'), 'eclassifier', 'segclassifier', 'labelclassifier', 'ecal');


function ROI = motionCompSaveROI(view,ROI,ROIname,resample)
%
%    gb 05/14/05
%
%    ROI = motionCompSaveROI(view,ROI,ROIname,resample)
%
% Stores the ROI into the directory HOMEDIR/Inplane/ROI with the name
% ROIname.
%
% Inputs:
%   - view: current Inplane view
%   - ROIname: string name of the ROI.
%   - resample: The ROI is stored in the anatomy format which is twice
%   bigger than the functional data format. Set resample to 1 if you are
%   saving a ROI having the size of the functional data.

% Initializes arguments and variables
global dataTYPES
curDataType = viewGet(view,'currentDataType');
curScan = viewGet(view,'currentScan');

if ieNotDefined('ROIname')
    ROIname = 'ROInoname';
end

if ieNotDefined('resample')
    resample = 1;
end

scan = viewGet(view,'curScan');

% Resamples the ROI if needed
if resample
    size1 = sliceDims(view,scan);
    size2 = size(view.anat);
    T = maketform('affine',[size2(2)/size1(2) 0 0; 0 size2(1)/size1(1) 0; 0 0 1]);

    ROI = imtransform(ROI,T,'nearest');
    ROI = [zeros(1,size(ROI,2) + 1,size(ROI,3));zeros(size(ROI,1),1,size(ROI,3)),ROI];

    nVoxels = size2(1:2);
else
    nVoxels = sliceDims(view,scan);
end

% Transforms it to the storage format which is a set of 3-coordinate
% vectors belonging to the ROI.
roiIndex = find(ROI)' - 1;
ROIz = floor(roiIndex/prod(nVoxels));
roiIndex = rem(roiIndex,prod(nVoxels));
ROIy = floor(roiIndex/nVoxels(1));
ROIx = rem(roiIndex,nVoxels(1));

ROIx = ROIx + 1;
ROIy = ROIy + 1;
ROIz = ROIz + 1;
ROI = [ROIx;ROIy;ROIz];

% Saves the ROI
pathStr = roiDir(view);
pathStr = fullfile(pathStr,[ROIname '.mat']);
ROI = struct('color','b','coords',ROI,'name',ROIname,'viewType','Inplane');
save(pathStr,'ROI');


function curr_layer = F_weight2activation(curr_layer)

curr_layer.a = curr_layer.W;

end


%%test network
cam1_size=size(label_test_cam1);
cam2_size=size(label_test_cam2);
cam3_size=size(label_test_cam3);
cam1_feature1=[];
cam1_feature2=[];
cam1_feature3=[];
cam1_score=[];
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=0:floor(cam1_size(1)/param.test_batch_size)-1
    fprintf('process cam1:%d/%d\n',m,floor(cam1_size(1)/param.test_batch_size)-1);
    for n=1:param.test_batch_size
        im_data=imread(test_image_name_cam1{m*param.test_batch_size+n});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,n)=im_data;
        test_batch_data(:,:,1,n)=test_batch_data(:,:,1,n)-104;
        test_batch_data(:,:,2,n)=test_batch_data(:,:,2,n)-117;
        test_batch_data(:,:,3,n)=test_batch_data(:,:,3,n)-123;
    end
    net.blobs('data').set_data(test_batch_data);
    net.forward_prefilled;
    cam1_feature1=[cam1_feature1;(squeeze(net.blobs('data1_p_1').get_data))'];
    cam1_feature2=[cam1_feature2;(squeeze(net.blobs('data1_p_2').get_data))'];
    cam1_feature3=[cam1_feature3;(squeeze(net.blobs('data1_p_3').get_data))'];
    cam1_score=[cam1_score;(squeeze(net.blobs('sig').get_data))'];
end
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size+1:cam1_size(1)
    fprintf('process cam1:%d/%d\n',m,cam1_size(1));
        count=m-(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size;
        im_data=imread(test_image_name_cam1{m});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,count)=im_data;
        test_batch_data(:,:,1,count)=test_batch_data(:,:,1,count)-104;
        test_batch_data(:,:,2,count)=test_batch_data(:,:,2,count)-117;
        test_batch_data(:,:,3,count)=test_batch_data(:,:,3,count)-123;
end
net.blobs('data').set_data(test_batch_data);
net.forward_prefilled;
index=cam1_size(1)-(floor(cam1_size(1)/param.test_batch_size))*param.test_batch_size;
result1=(squeeze(net.blobs('data1_p_1').get_data))';
result2=(squeeze(net.blobs('data1_p_2').get_data))';
result3=(squeeze(net.blobs('data1_p_3').get_data))';
score=(squeeze(net.blobs('sig').get_data))';
cam1_feature1=[cam1_feature1;result1(1:index,:)];
cam1_feature2=[cam1_feature2;result2(1:index,:)];
cam1_feature3=[cam1_feature3;result3(1:index,:)];
cam1_score=[cam1_score;score(1:index,:)];
gallery_feature=[];
gallery_label=[];
for m=1:param.test_person_num
    test_label_index=find(label_test_cam1==(m));
    if isempty(test_label_index)
        continue;
    end
    a=bsxfun(@times,cam1_feature1(test_label_index,:),cam1_score(test_label_index,1));
    b=bsxfun(@times,cam1_feature2(test_label_index,:),cam1_score(test_label_index,2));
    c=bsxfun(@times,cam1_feature3(test_label_index,:),cam1_score(test_label_index,3));
    gallery_feature=[gallery_feature;sum(a/sum(cam1_score(test_label_index,1))),sum(b/sum(cam1_score(test_label_index,2))),sum(c/sum(cam1_score(test_label_index,3)))];
%     gallery_feature=[gallery_feature;sum(a/sum(cam1_score(test_label_index,1)))];
%     gallery_feature=[gallery_feature;sum(b/sum(cam1_score(test_label_index,2)))];
%     gallery_feature=[gallery_feature;sum(c/sum(cam1_score(test_label_index,3)))];
    gallery_label=[gallery_label;m];
end
%extract feature cam3
cam3_feature1=[];
cam3_feature2=[];
cam3_feature3=[];
cam3_score=[];
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=0:floor(cam3_size(1)/param.test_batch_size)-1
        fprintf('process cam3:%d/%d\n',m,floor(cam3_size(1)/param.test_batch_size)-1);
    for n=1:param.test_batch_size
        im_data=imread(test_image_name_cam3{m*param.test_batch_size+n});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,n)=im_data;
        test_batch_data(:,:,1,n)=test_batch_data(:,:,1,n)-104;
        test_batch_data(:,:,2,n)=test_batch_data(:,:,2,n)-117;
        test_batch_data(:,:,3,n)=test_batch_data(:,:,3,n)-123;
    end
    net.blobs('data').set_data(test_batch_data);
    net.forward_prefilled;
    cam3_feature1=[cam3_feature1;(squeeze(net.blobs('data1_p_1').get_data))'];
    cam3_feature2=[cam3_feature2;(squeeze(net.blobs('data1_p_2').get_data))'];
    cam3_feature3=[cam3_feature3;(squeeze(net.blobs('data1_p_3').get_data))'];
    cam3_score=[cam3_score;(squeeze(net.blobs('sig').get_data))'];
end
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=(floor(cam3_size(1)/param.test_batch_size))*param.test_batch_size+1:cam3_size(1)
        fprintf('process cam3:%d/%d\n',m,cam3_size(1));
        count=m-(floor(cam3_size(1)/param.test_batch_size))*param.test_batch_size;
        im_data=imread(test_image_name_cam3{m});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,count)=im_data;
        test_batch_data(:,:,1,count)=test_batch_data(:,:,1,count)-104;
        test_batch_data(:,:,2,count)=test_batch_data(:,:,2,count)-117;
        test_batch_data(:,:,3,count)=test_batch_data(:,:,3,count)-123;
end
net.blobs('data').set_data(test_batch_data);
net.forward_prefilled;
index=cam3_size(1)-(floor(cam3_size(1)/param.test_batch_size))*param.test_batch_size;
result1=(squeeze(net.blobs('data1_p_1').get_data))';
result2=(squeeze(net.blobs('data1_p_2').get_data))';
result3=(squeeze(net.blobs('data1_p_3').get_data))';
score=(squeeze(net.blobs('sig').get_data))';
cam3_feature1=[cam3_feature1;result1(1:index,:)];
cam3_feature2=[cam3_feature2;result2(1:index,:)];
cam3_feature3=[cam3_feature3;result3(1:index,:)];
cam3_score=[cam3_score;score(1:index,:)];
for m=1:param.test_person_num
    test_label_index=find(label_test_cam3==(m));
    if isempty(test_label_index)
        continue;
    end
    a=bsxfun(@times,cam3_feature1(test_label_index,:),cam3_score(test_label_index,1));
    b=bsxfun(@times,cam3_feature2(test_label_index,:),cam3_score(test_label_index,2));
    c=bsxfun(@times,cam3_feature3(test_label_index,:),cam3_score(test_label_index,3));
    gallery_feature=[gallery_feature;sum(a/sum(cam3_score(test_label_index,1))),sum(b/sum(cam3_score(test_label_index,2))),sum(c/sum(cam3_score(test_label_index,3)))];
%     gallery_feature=[gallery_feature;sum(a/sum(cam3_score(test_label_index,1)))];
%     gallery_feature=[gallery_feature;sum(b/sum(cam3_score(test_label_index,2)))];
%     gallery_feature=[gallery_feature;sum(c/sum(cam3_score(test_label_index,3)))];
    gallery_label=[gallery_label;m];
end
%extract feature cam2
cam2_feature1=[];
cam2_feature2=[];
cam2_feature3=[];
cam2_score=[];
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=0:floor(cam2_size(1)/param.test_batch_size)-1
        fprintf('process cam2:%d/%d\n',m,floor(cam2_size(1)/param.test_batch_size)-1);
    for n=1:param.test_batch_size
        im_data=imread(test_image_name_cam2{m*param.test_batch_size+n});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,n)=im_data;
        test_batch_data(:,:,1,n)=test_batch_data(:,:,1,n)-104;
        test_batch_data(:,:,2,n)=test_batch_data(:,:,2,n)-117;
        test_batch_data(:,:,3,n)=test_batch_data(:,:,3,n)-123;
    end
    net.blobs('data').set_data(test_batch_data);
    net.forward_prefilled;
    cam2_feature1=[cam2_feature1;(squeeze(net.blobs('data1_p_1').get_data))'];
    cam2_feature2=[cam2_feature2;(squeeze(net.blobs('data1_p_2').get_data))'];
    cam2_feature3=[cam2_feature3;(squeeze(net.blobs('data1_p_3').get_data))'];
    cam2_score=[cam2_score;(squeeze(net.blobs('sig').get_data))'];
end
test_batch_data=zeros(224,224,3,param.test_batch_size,'single');
for m=(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size+1:cam2_size(1)
        fprintf('process cam2:%d/%d\n',m,cam2_size(1));
        count=m-(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size;
        im_data=imread(test_image_name_cam2{m});
        im_data=imresize(single(im_data),[224 224]);
        im_data=im_data(:,:,[3,2,1]);
        im_data=permute(im_data,[2,1,3]);
        test_batch_data(:,:,:,count)=im_data;
        test_batch_data(:,:,1,count)=test_batch_data(:,:,1,count)-104;
        test_batch_data(:,:,2,count)=test_batch_data(:,:,2,count)-117;
        test_batch_data(:,:,3,count)=test_batch_data(:,:,3,count)-123;
end
net.blobs('data').set_data(test_batch_data);
net.forward_prefilled;
index=cam2_size(1)-(floor(cam2_size(1)/param.test_batch_size))*param.test_batch_size;
result1=(squeeze(net.blobs('data1_p_1').get_data))';
result2=(squeeze(net.blobs('data1_p_2').get_data))';
result3=(squeeze(net.blobs('data1_p_3').get_data))';
score=(squeeze(net.blobs('sig').get_data))';
cam2_feature1=[cam2_feature1;result1(1:index,:)];
cam2_feature2=[cam2_feature2;result2(1:index,:)];
cam2_feature3=[cam2_feature3;result3(1:index,:)];
cam2_score=[cam2_score;score(1:index,:)];
prob_feature=[];
prob_label=[];
for m=1:param.test_person_num
    test_label_index=find(label_test_cam2==(m));
    if isempty(test_label_index)
        continue;
    end
    a=bsxfun(@times,cam2_feature1(test_label_index,:),cam2_score(test_label_index,1));
    b=bsxfun(@times,cam2_feature2(test_label_index,:),cam2_score(test_label_index,2));
    c=bsxfun(@times,cam2_feature3(test_label_index,:),cam2_score(test_label_index,3));
    prob_feature=[prob_feature;sum(a/sum(cam2_score(test_label_index,1))),sum(b/sum(cam2_score(test_label_index,2))),sum(c/sum(cam2_score(test_label_index,3)))];

%     prob_feature=[prob_feature;sum(a/sum(cam2_score(test_label_index,1)))];
%     prob_feature=[prob_feature;sum(b/sum(cam2_score(test_label_index,2)))];
%     prob_feature=[prob_feature;sum(c/sum(cam2_score(test_label_index,3)))];

    prob_label=[prob_label;m];
end
% cal cmc
prob_norm=bsxfun(@rdivide,prob_feature,sum(abs(prob_feature).^2,2).^(1/2));
gallery_norm=bsxfun(@rdivide,gallery_feature,sum(abs(gallery_feature).^2,2).^(1/2));
score_matrix=prob_norm*gallery_norm';
rank1_hit=0;
rank5_hit=0;
rank10_hit=0;
rank20_hit=0;
problen=size(prob_feature,1);
for m=1:problen
    [~,location_temp]=sort(score_matrix(m,:),2,'descend');
    location=gallery_label(location_temp);
    if find(location(1)==prob_label(m))
        rank1_hit=rank1_hit+1;
    end
    if find(location(1:5)==prob_label(m))
        rank5_hit=rank5_hit+1;
    end
    if find(location(1:10)==prob_label(m))
        rank10_hit=rank10_hit+1;
    end
    if find(location(1:20)==prob_label(m))
        rank20_hit=rank20_hit+1;
    end
end
rank_acc=[rank1_hit/problen,rank5_hit/problen,rank10_hit/problen,rank20_hit/problen];
fin=fopen(param.result_save_file,'a');
fprintf(fin,'up split_index:%d,iter:%d, rank1:%f,rank5:%f,rank10:%f,rank20:%f\n',split_index,iter,rank_acc(1),rank_acc(2),rank_acc(3),rank_acc(4));
fprintf('split_index:%d,iter:%d, rank1:%f,rank5:%f,rank10:%f,rank20:%f\n',split_index,iter,rank_acc(1),rank_acc(2),rank_acc(3),rank_acc(4));
fclose(fin);


% This function can read in all the information from the HTK model file
% with specifications of AURORA2 baseline system.

% AUTHOR: XIAO XIONG
% CREATED: 7 Jul, 2006
% LAST MODIFIED: 7 Jul, 2006
function model = readHTKmodel(file_name,digits_file)

% digits = {'sil','one','two','three','four','five','six','seven','eight','nine','zero','oh'};
if nargin < 2
    digits_file = 'E:\Research\Workspace\Projects\Normalization\AURORA2\LIB\words4';
end
if nargin < 1
    file_name = 'E:\Research\Workspace\Projects\Normalization\AURORA2\MODEL\MFCC_0DA\hmm20\models';
end
silence = {'sil','sp','silst'};
FID = fopen(file_name,'r');
digits = my_cat(digits_file);
digits2 = {};
for i=1:length(digits)
    if length(digits{i})>0
        digits2{end+1} = digits{i};
    end
end
digits = digits2;

% Read in the global parameters
fsearch('~o',FID);
tmp = textscan(FID,'%s %d %d',1);
tmp = fgetl(FID); tmp = fgetl(FID);
idx = regexp(tmp,'<');
Dimension = str2num(tmp(idx(1)+10:idx(2)-1));        % Dimension of the feature vector
idx = regexp(tmp,'<');
feature_type = tmp(idx(3)+1:idx(4)-2);         % type of the feature vector
cov_type = tmp(idx(4)+1:end-1);;             % type of the covariance matrix

% Read in the silst model
endOfFile = fsearch('~s "silst"',FID);
if endOfFile==0
    model.silst.NUMSTATES = 1;
    tmp = textscan(FID,'%s %d',1);
    if strcmp(tmp{1},'<MEAN>')
        model.silst.NUMMIXES = 1;
        fseek(FID,-7,'cof');
    else
        model.silst.NUMMIXES = tmp{2};
    end
    % model.('silst').NUMMIXES = tmp{2};
    for i=1:model.silst.NUMMIXES
        if model.silst.NUMMIXES>1
            tmp = textscan(FID,'%s %d',1);
            tmp = textscan(FID,'%f ',1);
            model.silst.weight(i) = tmp{1};
        else
            model.silst.weight(i) = 1;
        end

        tmp = textscan(FID,'%s %d',1);
        tmp = textscan(FID,'%f ',Dimension);
        model.silst.mean(:,i) = tmp{1};

        tmp = textscan(FID,'%s %d',1);
        tmp = textscan(FID,'%f ',Dimension);
        model.silst.var(:,i) = tmp{1};

        tmp = textscan(FID,'%s %f',1);
        model.silst.GCONST(:,i) = tmp{2};
    end
    model.silst.weight = model.silst.weight(:);
end

% Read in the sp model
frewind(FID);
endOfFile = fsearch(sprintf('~h "sp"'),FID);
if endOfFile==0
    fsearch(sprintf('<TRANSP> 3'),FID);
    model.sp = model.silst;
    model.sp.NUMSTATES = 1;
    for j=1:model.sp.NUMSTATES+2
        tmp = textscan(FID,'%f ',3);
        model.sp.TRANSP(j,:) = tmp{1};
    end
end

% Read in the digit models
for i=1:length(digits)
    frewind(FID);
    fsearch(sprintf('~h "%s"',digits{i}),FID);
    tmp = textscan(FID,'%s',1);
    tmp = textscan(FID,'%s %d',1);

    if strcmp(digits{i},'@')
        currDigit = 'AA';
    else
        currDigit = digits{i};
    end
    model.(currDigit).NUMSTATES = tmp{2}-2;

    for j=1:model.(currDigit).NUMSTATES
        tmp = textscan(FID,'%s %d',1);
        tmp = textscan(FID,'%s',1);
        if strcmp(tmp{1},'~s')  % this is a silst state
            tmp = textscan(FID,'%s',1);
            model.(currDigit).NUMMIXES(j) = model.silst.NUMMIXES;
            if model.silst.NUMMIXES == 1
                model.(currDigit).mean(:,1,j) = model.silst.mean;
                model.(currDigit).var(:,1,j) = model.silst.var;
                model.(currDigit).weight(1,j) = model.silst.weight;
            else
                model.(currDigit).mean(:,:,j) = model.silst.mean;
                model.(currDigit).var(:,:,j) = model.silst.var;
                model.(currDigit).weight(:,j) = model.silst.weight;
            end
            continue;
        elseif strcmp(tmp{1},'<MEAN>')
            model.(currDigit).NUMMIXES(j) = 1;
            fseek(FID,-7,'cof');
        else
            tmp = textscan(FID,'%d',1);
            model.(currDigit).NUMMIXES(j) = tmp{1};
        end
        for k=1:model.(currDigit).NUMMIXES(j)
            if model.(currDigit).NUMMIXES(j)>1
                tmp = textscan(FID,'%s %d',1);
                tmp = textscan(FID,'%f ',1);
                model.(currDigit).weight(k,j) = tmp{1};
            else
                model.(currDigit).weight(k,j) = 1;
            end
            tmp = textscan(FID,'%s %d',1);
            tmp = textscan(FID,'%f ',Dimension);
            model.(currDigit).mean(:,k,j) = tmp{1};

            tmp = textscan(FID,'%s %d',1);
            tmp = textscan(FID,'%f ',Dimension);
            model.(currDigit).var(:,k,j) = tmp{1};

            tmp = textscan(FID,'%s %f',1);
            model.(currDigit).GCONST(k,j) = tmp{2};
        end
    end
    % Read in the trainsit matrix
    tmp = textscan(FID,'%s %d',1);
    for j=1:model.(currDigit).NUMSTATES+2
        tmp = textscan(FID,'%f ',model.(currDigit).NUMSTATES+2);
        model.(currDigit).TRANSP(j,:) = tmp{1};
    end
end
fclose(FID);


%% Visualize Unsupervised Network Results
clear all; close all; clc

addpath(genpath('./'))
addpath(genpath('./../Tools/'))

mesh_0 = load('./artist_models/model_0_remesh'); mesh_0 = mesh_0.part;
mesh_1 = load('./artist_models/model_1_remesh'); mesh_1 = mesh_1.model;

% X = load('./Unsupervised Network Results/test_list_0_1.mat');
% [~, unsupervised_matches] = max(squeeze(X.softCorr),[],1);
load('./Unsupervised Network Results/matches_unsupervised.mat');

colors = create_colormap(mesh_1,mesh_1);
figure;
subplot(1,2,1); colormap(colors);
plot_scalar_map(mesh_1,[1: size(mesh_1.VERT,1)]');freeze_colors;title('Target');

subplot(1,2,2); colormap(colors(unsupervised_matches,:));
plot_scalar_map(mesh_0,[1: size(mesh_0.VERT,1)]');freeze_colors;title('Source');

%save('matches_unsupervised.mat','unsupervised_matches');


classdef nme_shunt_dc < mp.nme_shunt & mp.form_dc

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

%     properties
%     end     %% properties

    methods
        function obj = build_params(obj, nm, dm)
            build_params@mp.nme_shunt(obj, nm, dm); %% call parent

            dme = obj.data_model_element(dm);
            obj.p = dme.gs;                         %% shunt conductances
        end
    end     %% methods
end         %% classdef


function planC = createUniformlySlicedPlanC(planC)
%
% function planC = createUniformlySlicedPlanC(planC)
%
% This function creates uniformly sliced planC
%
% APA, 08/19/2011

global planC

indexS = planC{end};

% Get scan grid
zValuesV = [planC{indexS.scan}.scanInfo(:).zValue];
zDiffV = diff(zValuesV);
if ~all(zDiffV == min(zDiffV))
   % Create new z-vector
   minSpac = min(zDiffV);
   zValNewV = zValuesV(1):minSpac:zValuesV(end);

else
    % Already uniform plan
    return

end

% Loop over new z-values and create new scanArray
numSlices = length(zValNewV);

scanInfoS = planC{indexS.scan}.scanInfo(1);
scanInfoS.sliceThickness = minSpac;
scanInfoS.voxelThickness = minSpac;

for i = 1:numSlices

    % Find the nearest non-uniform slice
    nearestZindexV(i) = findnearest(zValuesV,zValNewV(i));

    scanArrayNewM(:,:,i) = planC{indexS.scan}.scanArray(:,:,nearestZindexV(i));

    scanInfoS.zValue = zValNewV(i);

    newScanInfoS(i) = scanInfoS;

end

planC{indexS.scan}.scanArray = scanArrayNewM;

clear scanArrayNewM;

planC{indexS.scan}.scanInfo = newScanInfoS;

% Change structure z-cords
numStructures = planC{indexS.structures};
for strNum = 1:length(numStructures)

    newStructureS = planC{indexS.structures}(strNum);

    newStructureS.numberOfScans = numSlices;

    newStructureS.contour(:) = [];
    newStructureS.contour
    newStructureS.contour(1:numSlices) = planC{indexS.structures}(strNum).contour(nearestZindexV);

    for slcNum = 1:length(newStructureS.contour)

        for segNum = 1:length(newStructureS.contour(slcNum).segments)

            if ~isempty(newStructureS.contour(slcNum).segments(segNum).points)

                newStructureS.contour(slcNum).segments(segNum).points(:,3) = zValNewV(slcNum);

            end

        end

    end

    planC{indexS.structures}(strNum) = newStructureS;

end

% ReRaster and Uniformize

reRasterAndUniformize;


%% REW_lawn
% %{
imfolder = 'images\REW_lawn';
im_n = 2;
imfile = cell(im_n,1);
imfile{1} = [imfolder '\' 'lawn_01.jpg'];
imfile{2} = [imfolder '\' 'lawn_02.jpg'];

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

edge_list = [1,2];

imsize = zeros(im_n,3);

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

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

mosaic = REW_mosaic( im, edge_list, 1, 'persp', 0, imfolder );
%}


function bool = is_dim_custom(varargin)
%IS_DIM_CUSTOM true for a custom grid
%
%   Usage: bool = is_grid_custom(x1,x2,...)
%
%   Input parameters:
%       x1,x2,... - axis / m; single value or [xmin,xmax] or nD-array
%
%   Output parameters:
%       bool      - array of logical indicating whether each input is an
%                   nD-array
%
%   IS_DIM_CUSTOM(x1,x2,..) checks if we have a custom grid by checking if any
%   of the given x,y,z values is a nD-array.
%
%   See also: xyz_grid, xyz_axes_selection, plot_sound_field

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking input parameters =======================================
isargnumeric(varargin{:});

%% ===== Computation =====================================================
bool = cellfun(@(x) numel(x)>2, varargin);


function [faces,vertices] = mesh_emse2mat3d(vertex,patch)

% mesh_emse2mat3d - Convert emse vertex/patches to matlab vertices/faces
%
% Useage: [faces,vertices] = mesh_emse2mat3d(vertex,patch)
%
%           vertex & patch are generated from emse files with
%           mesh_emse2matlab (see this file for more help).
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $

% Licence:  GNU GPL, no implied or express warranties
% History:  12/98 Abbas Kouzani
%           09/01 Darren.Weber_at_radiology.ucsf.edu
%                 - converted to function, rather than script
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%S=sprintf('load %s',file);eval(S);

vertices = zeros(length(vertex),3);
for i=1:length(vertex),
    vertices(i,1) = vertex(i).location1;
    vertices(i,2) = vertex(i).location2;
    vertices(i,3) = vertex(i).location3;
end

faces = zeros(length(patch),3);
for i=1:length(patch),

    v = patch(i).vertex1;   flag = 0;
    for j=1:length(vertex),
        if isequal(v, vertex(j).address)
            faces(i,1) = j; flag = 1; break;
        end
    end
    if (flag==0) fprintf('...error in patch(%d).vertex1!\n',i); break;end

    v = patch(i).vertex2;   flag = 0;
    for j=1:length(vertex),
        if isequal(v, vertex(j).address)
            faces(i,2) = j; flag = 1; break;
        end
    end
    if (flag==0) fprintf('...error in patch(%d).vertex2!\n',i); break;end

    v = patch(i).vertex3;   flag = 0;
    for j=1:length(vertex),
        if isequal(v, vertex(j).address)
            faces(i,3) = j; flag = 1; break;
        end
    end
    if (flag==0) fprintf('...error in patch(%d).vertex3!\n',i); break;end
end

%disp('...Saving');
%GET1=input(' Enter output filename: ','s');
%S=sprintf('save %s faces vertices',GET1);
%eval(S);


function [TWARes] = TWA_MMA(Param, freq, ecg, q,r,s, stlen)
%OVERVIEW, This function checks for arrhythmia in the current analysis window across all
% leads. If no arrhythmia is detected it then calls sub functions which first align the beats in the analysis
% window and find correlations of each beat with a template, to determine if the ecg data is clean enough for analysis.
% If alignment is successful, TWAs are evaluated using the MMA method
% coupled with a surrogate non parametric reshuffling method used for
% reducing false positive TWA detections.
%
% INPUTS        MANDATORY           DESCRIPTION
%               Param               Structure contains parameters used for
%                                   computing TWAs.
%
%               freq                Sampling frequency of the ecg data,
%                                   needs to be 1000 Hz.
%
%               ecg                 N by M array of ecg data. Contains M
%                                   channels of ECG with N datapoints each.
%
%               q                   array of q point locations
%
%               r                   array of r point locations
%
%               s                   array of s point locations
%
%               stlen               scalar, estimate of s-t segment length
%
% OUTPUT
%
%               TWARes              Structure contains the result for TWA
%                                   computation. Contains the following fields,
%
%               .VAlt               TWA amplitude estimates for the analysis
%                                   window.
%
%               .VAlt_Sig           TWA amplitude estimates which are statistically
%                                   significant compared to the noise threshold
%                                   estimate.
%
%               .noise_median       median of the gamma distribution used to model the noise.
%
%               .noise_95           95th percentile of the gamma distribution
%                                   used to model the noise.
%
%               .VAltPt             The location of the point with maximum
%                                   difference between the average even and odd beats.
%
%   REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   ORIGINAL SOURCE AND AUTHORS:
%       Written by Shamim Nemati,
%       editted by Ismail Sadiq on 10/26/2019.
%	COPYRIGHT (C) 2019
%   LICENSE:
%       This software is offered freely and without warranty under
%       the GNU (v3 or later) public license. See license file for
%       more information. The license may be found in
%       the Documents folder of the Physionet-Cardiovascular-Signal-Toolbox.

TWARes.successfull = false;

WIN_SIZE = Param.Interval; %e.g., 60beats
OVERLAP_SIZE = floor(WIN_SIZE/2);
TWARes=[];
Num_Ch = size(ecg, 2);

Align.fidBase = []; Align.fid = []; Align.valid = [];

if (length(r) < WIN_SIZE) % need at least one window of beats
    disp('TWAbyMMAOnAFile: Not enough beats...')
    TWARes.HR=NaN;
    TWARes.VAlt=NaN*ones(1,Num_Ch);TWARes.VAlt_Sig=NaN*ones(1,Num_Ch);
    TWARes.VAltPt=NaN*ones(1,Num_Ch);
    TWARes.Noise_Median= NaN*ones(1,Num_Ch);TWARes.Noise_95 = NaN*ones(1,Num_Ch);
    return;
end

i = 0;
for j = 1:(WIN_SIZE-OVERLAP_SIZE):length(r)-WIN_SIZE+1
    i=i+1;
    disp(['Analysis window index = ' num2str(i)])
    beats = j:j+WIN_SIZE-1;

    % Check for arrhythmia

    cur_r = r(beats); % Check current window of beats for arrhythmia
    features = AF_features(diff(cur_r),freq);
    Index_test = SVM_AFdetection_withoutTrainingModel(features,1);
    if (Index_test)
        disp('Arrhythmia detected...')
        TWARes.HR(i)=NaN;
        TWARes.VAlt(i, :)=NaN*ones(1,Num_Ch);TWARes.VAlt_Sig(i, :)=NaN*ones(1,Num_Ch);
        TWARes.VAltPt(i,:)=NaN*ones(1,Num_Ch);
        TWARes.Noise_Median(i, :) = NaN*ones(1,Num_Ch);TWARes.Noise_95(i, :) = NaN*ones(1,Num_Ch);
        % If arrhythmia detected continue to next window
        continue;
    end

    try
        % Align beats and check validity for analysis before computing TWAs
        [Align hrt_rate] = Align_Beats(beats, q(beats), r(beats), s(beats), stlen, ecg, 1000, Param);
    catch
        % If failed to align due to catch continue to next window.
        disp('TWAbyMMAOnAFile: Catch says alignment failed...')
        TWARes.HR(i)=NaN;
        TWARes.VAlt(i, :)=NaN*ones(1,Num_Ch);TWARes.VAlt_Sig(i, :)=NaN*ones(1,Num_Ch);
        TWARes.VAltPt(i,:)=NaN*ones(1,Num_Ch);
        TWARes.Noise_Median(i, :) = NaN*ones(1,Num_Ch);TWARes.Noise_95(i, :) = NaN*ones(1,Num_Ch);
        continue;
    end
    if (isempty(Align.fid))
        disp('TWAbyMMAOnAFile: alignment failed ...');
        TWARes.HR(i)=NaN;
        TWARes.VAlt(i, :)=NaN*ones(1,Num_Ch); TWARes.VAlt_Sig(i, :)=NaN*ones(1,Num_Ch);
        TWARes.VAltPt(i,:)=NaN*ones(1,Num_Ch);
        TWARes.Noise_Median(i, :)=NaN*ones(1,Num_Ch);TWARes.Noise_95(i, :) = NaN*ones(1,Num_Ch);
        continue;
    else
        disp('TWAbyMMAOnAFile: alignment succeeded ...');
    end

    disp('TWAbyMMAOnAFile: looking for alternans ...');
    TWARes.HR(i) = hrt_rate;
    try
        [TWARes.VAlt(i, :), TWARes.VAlt_Sig(i, :), TWARes.Noise_Median(i,:),TWARes.Noise_95(i,:),...
            TWARes.VAltPt(i,:)]= TWA_by_MMA(Param, TWARes, ecg, Align); % *********************** Estimates T-wave alternans from the beat Matrix
    catch
        disp('TWAbyMMAOnAFile: search for alternans failed ')
        TWARes.VAlt(i, :)=NaN*ones(1,Num_Ch); TWARes.VAlt_Sig(i, :)=NaN*ones(1,Num_Ch);
        TWARes.VAltPt(i,:)=NaN*ones(1,Num_Ch);
        TWARes.Noise_Median(i, :)=NaN*ones(1,Num_Ch);TWARes.Noise_95(i, :) = NaN*ones(1,Num_Ch);
        continue;
    end
end

TWARes.successfull = true;

return;


function roi = dtiReadRoi(fileName, xformParams)
%
%  roi = dtiReadRoi([fileName], [xformParams])
%
% HISTORY:
%  2005.02.24 RFD: pulled code from other places to modularize.
%  2008.04.01 RFD: now forces ROI coords to 'double' type.

if(~exist('fileName','var') || isempty(fileName))
    [f, p] = uigetfile({'*.mat';'*.*'}, 'Load ROI file...');
    if(isnumeric(f)), disp('Read ROI canceled.'); roi=[]; return; end
    fileName = fullfile(p,f);
end
if(~exist('xformParams','var')) xformParams = []; end
load(fileName);

% We now save version and coordinate space fields. But for backwards compatability....
if(~exist('versionNum')) versionNum = 0.1; end
if(~exist('coordinateSpace')) coordinateSpace = 'acpc'; end
if ~exist('roi','var'), error('No ROI variable found.'); end

% New field in ROI struct for the DTI query ID. We alway reset it to -1
% when loading to indicate no associated dtiQuery ROI.
roi.query_id = -1;

roi.coords = double(roi.coords(~any(isnan(roi.coords')),:));
roi.visible = 1;
if(~strcmp(coordinateSpace,'acpc'))
    % try to find a matching coordinate space xform
    if(~isfield(xformParams,'name'))
        if(strcmp(coordinateSpace,'MNI'))
            csInd = 1;
        else
            error('t1NormParams has an old format (no coord space name).');
        end
    else
        csInd = strmatch(coordinateSpace, {xformParams.name}, 'exact');
        if(isempty(csInd))
            warning(['No coord spaces matching ROI coord space "' coordinateSpace '".']);
        end
    end
    if(~isempty(xformParams) && ~isempty(xformParams(csInd)))
        if(~isfield(xformParams(csInd),'sn') || isempty(xformParams(csInd).sn))
            disp(['Subject data appear to be in the same space as the ROI (' coordinateSpace ')- not warping ROI...']);
        else
            disp(['Warping ROI coords from ' coordinateSpace ' space to this subject''s space...']);
            % *** TO DO: we assume that the xform is an SPM-style sn struct. We
            % should figure out how to support other xforms.
            roi.coords = mrAnatXformCoords(xformParams(csInd).sn, roi.coords);
        end
    else
        disp(['NOTE: ROI coordinate space is ' coordinateSpace ', but there are no spatial norm params- ROI loaded WITHOUT coordinate transform.']);
    end
end

return;


function test_bug1599(datainfo, version)

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_sourceanalysis ft_inverse_lcmv

% fixedori is set correctly in ft_inverse_lcmv, the only problem is
% that ft_sourceanalysis seems to not bother about this when using a
% predefined filter

if nargin<1
  datainfo = ref_datasets;
end
if nargin<2
  version = 'latest';
end

%% Try to reproduce
% load your very favourite data
k = 10; % ctf data
inputfile = fullfile(datainfo(k).origdir,version,'timelock',datainfo(k).type,['timelock_trl_' datainfo(k).datatype '.mat']);
load(inputfile);

% make grid'n'vol
vol = [];
vol.o = [0 0 4];
vol.r = 12;
vol.unit = 'cm';
vol.type = 'singlesphere';

sourcemodel = [];
sourcemodel.resolution = 2.5;

% compute filter
cfg                 = [];
cfg.headmodel       = vol;
cfg.sourcemodel     = sourcemodel;
cfg.method          = 'lcmv';
cfg.lcmv.keepfilter = 'yes';
cfg.lcmv.fixedori   = 'no';
filter              = ft_sourceanalysis(cfg, timelock);

cfg               = [];
cfg.headmodel     = vol;
cfg.method        = 'lcmv';
% cfg.rawtrial    = 'yes';
cfg.sourcemodel   = keepfields(filter, {'pos', 'filter', 'filterdimord', 'label'});
cfg.lcmv.fixedori = 'yes';
oriyes            = ft_sourceanalysis(cfg, timelock);
cfg.lcmv.fixedori = 'no';
orino             = ft_sourceanalysis(cfg, timelock);

% cfg is of course different, see above, so remove it
orino             = rmfield(orino, 'cfg');
oriyes            = rmfield(oriyes, 'cfg');

if ~isfield(oriyes.avg, 'ori')
  error('ori not added when it should be');
end

if isfield(orino.avg, 'ori')
  error('ori added when it should not be');
end

fprintf('test_bug1599 is all fine\n');


function [money, accum_bet, acc, central_money, bk_money, nTrans] = calc_money_bks_H_A_opCls(aux, bet_type, money, ...
    bet, increase_bet, bookies_home_code_yrs, bookies_away_code_yrs, bk_money, accumulator)

% Game by game, place bets on each bookie
% Check if there is enough money in a bookie and place a bet.
% Keep the history of the central money to see the zeros

% lim =  money + bet * 12;

loss = 0.03; %loss on every transaction

central_money = money;

z = 1;
c = 1;
nTrans = 0;

bet_type = bet_type(~isnan(bet_type));
aux = aux(~isnan(bet_type), :);
bookies_home_code_yrs = bookies_home_code_yrs(~isnan(bet_type));
bookies_away_code_yrs = bookies_away_code_yrs(~isnan(bet_type));

for gm = 1 : size(aux, 1)

    if bet > 3000
        bet = 3000;
    end

    accum_bet(z) = bet; %#ok

    if bet_type(gm) == 1

        id_bk = bookies_home_code_yrs(gm);
        % Add money to the bookie if we are below the limit
        if bk_money(id_bk) < bet
            bk_money(id_bk) = bk_money(id_bk) + bet;
            central_money(c+1) = central_money(c) - bet;
            % Transfer money from another bookie if we ran out of central
            % money
            if central_money(c+1) <= bet
               [~, id_max] = max(bk_money);
               bk_money(id_max) = bk_money(id_max) - (bet + (bet * loss)); % we are losing a margin with the movement
               central_money(c+1) = central_money(c+1) + bet;
               nTrans = nTrans + 1;
            end
            c = c + 1;
        end

        if aux(gm,1) == 1
            mony = (aux(gm,5) - 1) * bet; % bet won
            bk_money(id_bk) = bk_money(id_bk) + mony;
            acc(z) = 1;
        else
            mony = -1 * bet; % bet lost
            bk_money(id_bk) = bk_money(id_bk) + mony;
            acc(z) = 0;
        end

    elseif bet_type(gm) == 2

        id_bk = bookies_away_code_yrs(gm);
        % Add money to the bookie if we are below the limit
        if bk_money(id_bk) < bet
            bk_money(id_bk) = bk_money(id_bk) + bet;
            central_money(c+1) = central_money(c) - bet;

            % Transfer money from another bookie if we ran out of central
            % money
            if central_money(c+1) <= bet
               [~, id_max] = max(bk_money);
               bk_money(id_max) = bk_money(id_max) - (bet + (bet * loss)); % we are losing a margin with the movement
               central_money(c+1) = central_money(c+1) + bet;
               nTrans = nTrans + 1;
            end

            c = c + 1;
        end

        if aux(gm,1) == 2
            mony = (aux(gm,7) - 1) * bet; % bet won
            bk_money(id_bk) = bk_money(id_bk) + mony;
            acc(z) = 1;
        else
            mony = -1 * bet; % bet lost
            bk_money(id_bk) = bk_money(id_bk) + mony;
            acc(z) = 0;
        end

    elseif bet_type(gm) == 3

        if aux(gm,1) == 0
            mony = (aux(gm,6) - 1) * bet; % bet won
            acc(z) = 1;
        else
            mony = -1 * bet; % bet lost
            acc(z) = 0;
        end

    else
        continue; % not a game to bet, go to next game

    end

    money(z+1) = money(z) + mony;

    bet = money(z+1) * accumulator;
%     if money(z+1) > lim && increase_bet == 1
%
%         bet = bet * 2;
%
%         lim = lim * 2;
%
%     end
    z = z + 1;

%     if z == 4000
%         disp('here')
%     end
end


function y = At_Subset(x,n,Omega);

y = zeros(n,1);
y(Omega) =x;


function [X,Y] = ToyCarPairsToLabels(pairs, instance_matrix)
        imgs1 = [pairs.img1];
        imgs2 = [pairs.img2];

        keymat = [[imgs1.classId] [imgs2.classId]; [imgs1.id] [imgs2.id]];
        ids = unique(keymat','rows');

        X = instance_matrix(:,ids(:,2));
        Y = ids(:,1)';
end


classdef MeshCreatorFromInputFile < handle

    properties (Access = public)
        backgroundMesh
        boundaryMesh
    end

    properties (Access = private)
        inputFile
    end

    methods (Access = public)

        function obj = MeshCreatorFromInputFile(cParams)
            obj.init(cParams);
            obj.createBackgroundMesh();
            obj.createBoundaryMesh();
        end

    end

    methods (Access = private)

        function init(obj,cParams)
           obj.inputFile = cParams.inputFile;
        end

        function createBackgroundMesh(obj)
            coord = [];
            connec = [];
            eval(obj.inputFile);
            s.coord  = coord(:,2:3);
            s.connec = connec(:,2:end);
            obj.backgroundMesh = Mesh(s);
        end

        function createBoundaryMesh(obj)
            eval(obj.inputFile);
            if exist('External_border_nodes','var')
                s.borderNodes    = External_border_nodes;
                s.borderElements = External_border_elements;
                s.backgroundMesh = obj.backgroundMesh;
                b = BoundaryMeshCreatorFromData(s);
                obj.boundaryMesh = b.create();
            else
            s.backgroundMesh = obj.backgroundMesh;
            s.dimension = 1:obj.backgroundMesh.ndim;
            bC = BoundaryMeshCreatorFromRectangularBox(s);
            obj.boundaryMesh = bC.create();
            end
        end

    end

end


% visualizeHKS
clear all; close all; clc;

gptoolbox_path = ''; % complete
addpath(genpath(gptoolbox_path));

data_folder = '..\data\';
meshes = dir([data_folder,'*.o*']); % a list of all the meshes in the data folder
meshes = {meshes.name}; % access each mesh name by meshes{i}

cam_folder = [data_folder, 'cams\'];
cams = dir([cam_folder,'*.mat']); % a list of all the cam in the cams folder
cams = {cams.name};

addpath(data_folder); addpath(cam_folder);

%% Compute the HKS using gptoolbox

%% Display the HKS on a few meshes for a small fixed time t.


% --------------------------------------------------------
% MDP Tracking
% Copyright (c) 2015 CVGL Stanford
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
%
% show LK tracking results
function LK_show(im1, im2, xFI, BB1, xFJ, BB2)

% Create a new image showing the two images side by side.
im3 = appendimages(im1,im2);

% Show a figure with lines joining the accepted matches.
h = figure(2);
set(h, 'Position', [100 100 2*size(im3,2) 2*size(im3,1)]);
axis equal;
colormap('gray');
imagesc(im3);
hold on;
cols1 = size(im1,2);
loc1 = xFI(1:2,:)';
loc2 = xFJ(1:2,:)';
plot(loc1(:,1), loc1(:,2), 'ro', 'LineWidth', 2);
plot(loc2(:,1)+cols1, loc2(:,2), 'yo', 'LineWidth', 2);
for i = 1: size(loc1,1)
    if isnan(loc2(i,1)) == 0
        line([loc1(i,1) loc2(i,1)+cols1], [loc1(i,2) loc2(i,2)], 'Color', 'c', 'LineWidth', 2);
    end
end

rectangle('Position', [BB1(1) BB1(2) BB1(3)-BB1(1) BB1(4)-BB1(2)], 'EdgeColor', 'g', 'LineWidth', 4);
rectangle('Position', [BB2(1)+cols1 BB2(2) BB2(3)-BB2(1) BB2(4)-BB2(2)], 'EdgeColor', 'y', 'LineWidth', 4);
axis off;
hold off;

% Return a new image that appends the two images side-by-side.

function im = appendimages(image1, image2)

% Select the image with the fewest rows and fill in enough empty rows
%   to make it the same height as the other image.
rows1 = size(image1,1);
rows2 = size(image2,1);

if (rows1 < rows2)
     image1(rows2,1) = 0;
else
     image2(rows1,1) = 0;
end

% Now append both images side-by-side.
im = [image1 image2];


% VL_DEMO  Run all demos

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

root = vl_root ;
demo_path = fullfile(root,'toolbox','demo') ;
test_path = fullfile(root,'toolbox','test') ;

addpath(demo_path) ;
addpath(test_path) ;

vl_demo_sift_basic ;
vl_demo_sift_peak ;
vl_demo_sift_edge ;
vl_demo_sift_cmd ;
vl_demo_sift_or ;
vl_demo_sift_match ;
vl_demo_sift_vs_ubc ;

vl_demo_dsift ;

vl_demo_mser_basic ;
vl_demo_mser_delta ;
vl_demo_mser_cmd ;

vl_test_hikmeans ;
vl_test_ikmeans ;
vl_test_imintegral ;

vl_demo_aib ;

vl_demo_quickshift ;
vl_demo_slic ;

vl_demo_kdtree ;
vl_demo_kdtree_sift ;
vl_demo_kdtree_self ;
vl_demo_kdtree_forest ;
vl_demo_kdtree_ann ;

vl_demo_imdisttf ;

rmpath(demo_path);
rmpath(test_path);