function []=ps_calc_tca
%PS_CALC_TCA calculate topo-correlated atmosphere
%   execute in according INSAR (for PS) or SMALL_BASELINES (for SB) ifg
%   correction after running stamps(1,7)
%
%   The script will load already existing correction
%   Keep in mind that it is better to apply no
%   correction if the correlation is low !
%
%   Hannes Bathke, November 2012
%
%   ================================================================
%   11/2012 HB added more precise pixel selection, bugfixes
%   11/2012 HB drop ifg index included
%   01/2013 AH converted to function and name changed
%   08/2014 DB Append the correction in case the tca variable esits
%   08/2014 DB Change such can be ran without having ran step 7
%   ================================================================

clear all
close all

plot_flag = 1;    % 0 --> no plot/ 1 -> plot uph, correction, corrected ifg after each correction
%% load standard ps indata check if sbas or ps folder
% load interferograms

load psver
psname=['./ps',num2str(psver)];
sclaname=['./scla',num2str(psver) '.mat'];
sclasbname=['./scla_sb',num2str(psver) '.mat'];
phuwname=['./phuw',num2str(psver) '.mat'];
phuwsbname=['./phuw_sb',num2str(psver) '.mat'];

ps=load(psname);

num_ifg = ps.n_ifg;
num_pix = ps.n_ps;

small_baseline_flag = getparm('small_baseline_flag');
if ~strcmpi(small_baseline_flag,'y')
    disp('working on the PS interferograms');
    if exist([phuwname],'file')
        stratname=['./tca',num2str(psver)];
        u_ph = load(phuwname');

    end
    if exist(sclasbname,'file')==2
        scla=load(sclaname);
        % subtract dem error
        ph_all=u_ph.ph_uw - scla.ph_scla;

        fprintf('DEM error removed \n')
    else
        ph_all=u_ph.ph_uw  ;
    end
else
    disp('working on the SB interferograms');
    if exist([phuwsbname],'file')
        stratname=['./tca_sb',num2str(psver)];
        u_ph = load(phuwsbname);
     end
    if exist(sclasbname,'file')==2
        scla=load(sclasbname);
        % subtract dem error
        ph_all=u_ph.ph_uw - scla.ph_scla;
        fprintf('DEM error removed \n')

    else
        ph_all=u_ph.ph_uw;
    end
end

% if existent load strat correction
strat_corr = zeros(num_pix,num_ifg);

% load dem data
if exist('hgt2.mat','file')
    dem = load('hgt2.mat');
else
    disp('dem height not existing yet, please run StaMPS(1,7) once')
    exit
end

% select interferograms for correction
drop_ifg_index = getparm('drop_ifg_index');
disp(['dropped ifgs: ',num2str(drop_ifg_index)]);
disp(['Loop through ',num2str(num_ifg),' ifgs:']);
ifg = input('Start with which ifg? ');
end_ifg = input('End with which ifg? ');

for k = ifg : end_ifg
    disp(['interferogram number ',num2str(k)])
    % check if ifg is on drop index
    if k == drop_ifg_index;
        disp('ifg dropped, nothing done, next');
    else
        figure;
        plot(dem.hgt,ph_all(:,k),'.k')
        hold on
        xlabel('DEM Elevation [m]');
        ylabel('unwrapped phase')
        do_corr = input('correlation existent? (yes - 1; no(next ifg) - 0 ) ');
        if do_corr == 1
            disp('Click 2 edges of a rectangle within the linear function\n should be fitted to the pixels ');
            bounds = ginput(2);
            low_hgt = min(bounds(:,1));
            high_hgt = max(bounds(:,1));
            low_uph = min(bounds(:,2));
            high_uph = max(bounds(:,2));
            %find pixels within bounds
            did = find(low_hgt < dem.hgt & dem.hgt < high_hgt);
            phid = find(low_uph < ph_all(:,k) & ph_all(:,k) < high_uph);
            pix_int = intersect(did,phid);
            plot(dem.hgt(pix_int),ph_all(pix_int,k),'.b')

            % build design matrix
            dem_range = low_hgt:1:high_hgt;
            A = [dem.hgt(pix_int) ones(length(pix_int),1)];
            Afull = [dem_range' ones(length(dem_range),1)];

            % do the inversion
            coef = (A'*A)\A'*ph_all(pix_int,k);
            strat_fun = Afull * coef;

            % display fitted function
            plot(dem_range,strat_fun,'-r')
            hold off
            strat_corr(:,k) = coef(1)*dem.hgt;

            if (plot_flag)
                % plot results
                figure; scatter(ps.lonlat(:,1),ps.lonlat(:,2),5,strat_corr(:,k),'filled');
                title('estimated stratified atm comp'); colorbar
                caxis([min(ph_all(:,k)) max(ph_all(:,k))])

                figure; scatter(ps.lonlat(:,1),ps.lonlat(:,2),5,ph_all(:,k),'filled');
                title(['unwrapped phase of ifg ',num2str(k)]); colorbar
                caxis([min(ph_all(:,k)) max(ph_all(:,k))])

                figure; scatter(ps.lonlat(:,1),ps.lonlat(:,2),5,...
                    (ph_all(:,k)-strat_corr(:,k)),'filled');
                title(['corrected ifg ',num2str(k)]); colorbar
                caxis([min(ph_all(:,k)) max(ph_all(:,k))])

                next = input('next ifg? (1 --> yes) (0 --> EXIT) ');
                if next == 1
                    close all
                else
                    break
                end
            end
            close all
        else
            disp(['no correlation in interferogram ',num2str(k),' no correction applied--> 0']);
            close all
        end
    end
end

% save matrix
if exist([stratname,'.mat'],'file')~=2
    save([stratname,'.mat'],'strat_corr')
else
    save([stratname,'.mat'],'-append','strat_corr')
end


bn = '/biac3/wandell4/data/reading_longitude/dti_y4/zs070717/raw/dti_g13_b800';
bn = '/biac3/wandell4/data/reading_longitude/dti_y4/zs070717/raw/dti_g87_b800';

dwRaw = niftiRead([bn '.nii.gz']);
sz = size(dwRaw.data);
d = single(dwRaw.data);
clear dwRaw;
bvecs = dlmread([bn '.bvecs']);
bvals = dlmread([bn '.bvals']);

% Apply eddy/motion correction
load([bn '_ecXform.mat']);

[X,Y,Z] = ndgrid([1:sz(1)],[1:sz(2)],[1:sz(3)]);
x = [X(:)'; Y(:)'; Z(:)']; clear X Y Z;
% Run the first one separate to cache the voxel list (x).
d(:,:,:,1) = reshape(mrAnatFastInterp3(d(:,:,:,1), x, [xform(1).ecParams xform(1).phaseDir]),sz(1:3));
for(ii=2:sz(4))
    if(mod(ii,30)==0), fprintf('Processing vol %d of %d...\n',ii,sz(4)); end
    % Save a few cycles by not resending the voxel list (x) on each iteration.
    d(:,:,:,1) = reshape(mrAnatFastInterp3(d(:,:,:,ii), [], [xform(ii).ecParams xform(ii).phaseDir]),sz(1:3));
end
d = double(d);

bv = dtiRawReorientBvecs(bvecs,xform,false);
tau = 40;
q = [bv.*sqrt(repmat(bvals./tau,3,1))]';
X = [ones(size(q,1),1) -tau.*q(:,1).^2 -tau.*q(:,2).^2 -tau.*q(:,3).^2 -2*tau.*q(:,1).*q(:,2) -2*tau.*q(:,1).*q(:,3) -2*tau.*q(:,2).*q(:,3)];

[x,y,z]=meshgrid([5:10],[5:10],[30:40]);
noiseRegion = sub2ind(sz(1:3),x,y,z);
for(ii=1:sz(4))
   tmp = d(:,:,:,ii);
   n(ii,:) = double(tmp(noiseRegion(:)));
end
sd = std(n(:));
signalSigma = 1.5267*sd;

tic;[dt,pdd] = dtiFitTensor(d,X); toc
makeMontage3(abs(pdd));

[fa,md] = dtiComputeFA(dt(:,:,:,2:7));
md(md>5)=5; md(md<0)=0;
showMontage(md);
fa(fa<0)=0; fa(fa>1)=1;
showMontage(fa);

sl = squeeze(md(6,:,:));
figure;imagesc(sl);axis image; colormap gray; colorbar
roi = roipoly;
t = 25;
fprintf('Self-diffusion @ %0.1f C = %0.2f, measured diffusivity = %0.2f.\n',t,dtiSelfDiffusionOfWater(t),mean(sl(roi(:))));


% This subroutine assigns creates a grid with
% spacing dx,dy (in degreees). The size will
% be selected interactiVELY. The bvalue in each
% volume around a grid point containing ni earthquakes
% will be calculated as well as the magnitude
% of completness
%   Stefan Wiemer 1/95

disp ('This is /src/stressdepth_ratio.m');
%% disp  ('PLEASE SET my_dir TO YOUR WORKING DIRECTORY!!!!!');

global no1 bo1 inb1 inb2

if sel == 'in'
    % get the grid parameter
    % initial values
    %
    dx = 0.1;
    dy = 0.1 ;
    ni = 1000;
    Nmin = 50;
    stan2 = nan;
    stan = nan;
    prf = nan;
    av = nan;
    mid_point = 5;
    top_zonet = 0;
    top_zoneb = 5;
    bot_zonet = 7;
    bot_zoneb = 15;
    topstan2 = nan;
    botstan2 = nan;
    topstan = nan;
    botstan = nan;
    topav = nan;
    botav = nan;
    use_old_win = 1;
    lab1 = 'b-value-depth-ratio:';

    % make the interface
    %
    figure_w_normalized_uicontrolunits(...
        'Name','Depth Ratio Grid Input Parameter',...
        'NumberTitle','off', ...
        'MenuBar','none', ...
        'NextPlot','new', ...
        'units','points',...
        'Visible','off', ...
        'Position',[ wex+200 wey-200 650 300]);
    axis off
    labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature)'];

    labelPos = [0.2 0.60 0.6  0.08];
    hndl2=uicontrol(...
        'Style','popup',...
        'Position',labelPos,...
        'Units','normalized',...
        'String',labelList2,...
        'Callback','inb2 =get(hndl2,''Value''); ');

    % set(hndl2,'value',5);

    % creates a dialog box to input grid parameters
    %
    %

    % mid_point_field=uicontrol('Style','edit',...
    %     'Position',[.47 .80 .12 .08],...
    %     'Units','normalized','String',num2str(mid_point),...
    %     'Callback','mid_point=str2double(get(mid_point_field,''String'')); set(mid_point_field,''String'',num2str(mid_point));');

    top_zonet_field=uicontrol('Style','edit',...
        'Position',[.36 .80 .06 .06],...
        'Units','normalized','String',num2str(top_zonet),...
        'Callback','top_zonet=str2double(get(top_zonet_field,''String'')); set(top_zonet_field,''String'',num2str(top_zonet));');
    top_zoneb_field=uicontrol('Style','edit',...
        'Position',[.36 .74 .06 .06],...
        'Units','normalized','String',num2str(top_zoneb),...
        'Callback','top_zoneb=str2double(get(top_zoneb_field,''String'')); set(top_zoneb_field,''String'',num2str(top_zoneb));');

    bot_zonet_field=uicontrol('Style','edit',...
        'Position',[.78 .80 .06 .06],...
        'Units','normalized','String',num2str(bot_zonet),...
        'Callback','bot_zonet=str2double(get(bot_zonet_field,''String'')); set(bot_zonet_field,''String'',num2str(bot_zonet));');
    bot_zoneb_field=uicontrol('Style','edit',...
        'Position',[.78 .74 .06 .06],...
        'Units','normalized','String',num2str(bot_zoneb),...
        'Callback','bot_zoneb=str2double(get(bot_zoneb_field,''String'')); set(bot_zoneb_field,''String'',num2str(bot_zoneb));');

    freq_field=uicontrol('Style','edit',...
        'Position',[.30 .50 .12 .08],...
        'Units','normalized','String',num2str(ni),...
        'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');

    freq_field0=uicontrol('Style','edit',...
        'Position',[.70 .50 .12 .08],...
        'Units','normalized','String',num2str(ra),...
        'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');

    freq_field2=uicontrol('Style','edit',...
        'Position',[.30 .40 .12 .08],...
        'Units','normalized','String',num2str(dx),...
        'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');

    freq_field3=uicontrol('Style','edit',...
        'Position',[.30 .30 .12 .08],...
        'Units','normalized','String',num2str(dy),...
        'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');

    tgl1 = uicontrol('Style','checkbox',...
        'string','Number of Events:',...
        'Position',[.09 .50 .2 .08], 'Callback','set(tgl2,''value'',0)',...
        'Units','normalized');

    set(tgl1,'value',1);

    tgl2 =  uicontrol('Style','checkbox',...
        'string','OR: Constant Radius',...
        'Position',[.47 .50 .2 .08], 'Callback','set(tgl1,''value'',0)',...
        'Units','normalized');

    freq_field4=uicontrol('Style','edit',...
        'Position',[.30 .20 .12 .08],...
        'Units','normalized','String',num2str(Nmin),...
        'Callback','Nmin=str2double(get(freq_field4,''String'')); % set(freq_field4,''String'',num2str(Nmin));');

    close_button=uicontrol('Style','Pushbutton',...
        'Position',[.60 .05 .15 .12 ],...
        'Units','normalized','Callback','close;done','String','Cancel');

    go_button1=uicontrol('Style','Pushbutton',...
        'Position',[.20 .05 .15 .12 ],...
        'Units','normalized',...
        'Callback',' inb1 =get(hndl2,''Value'');tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');close,sel =''ca'', stressdepth_ratio',...
        'String','Go');
    Nmin;
    text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.20 .75 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Please choose an Mc estimation option   ');

    mid_txt=text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.24 1.0 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Depth limits for depth ratio calculation  ');

    top_txt=text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.10 .85 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Top and bottom for TOP zone(km):');

    bot_txt=text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.40 .85 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Top and bottom for BOTTOM zone(km):');

    txt3 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.30 0.64 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String',' Grid Parameter');
    txt5 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.06 0.40 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing in x (dx) in deg:');

    txt6 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.06 0.29 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing in y (dy) in deg:');

    txt7 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.06 0.17 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Min. No. of events > Mc:');

    set(gcf,'visible','on');
    watchoff

end   % if nargin ==0

% for plotting number of events used (ni) in view_bdepth
ni_plot = ni;

% get the grid-size interactively and
% calculate the b-value in the grid by sorting
% thge seimicity and selectiong the ni neighbors
% to each grid point

if sel == 'ca'

    [file1,path1] = uiputfile([my_dir fs '*.mat'], 'Grid Datafile Name?') ;

    selgp
    itotal = length(newgri(:,1));
    if length(gx) < 4  ||  length(gy) < 4
        errordlg('Selection too small! (Dx and Dy are in degreees! ');
        return
    end

    zmap_message_center.set_info(' ','Running bdepth_ratio... ');think
    %  make grid, calculate start- endtime etc.  ...
    %
    t0b = min(a.Date)  ;
    n = a.Count;
    teb = a(n,3) ;
    tdiff = round((teb - t0b)*365/par1);
    loc = zeros(3, length(gx)*length(gy));

    % loop over  all points
    %
    i2 = 0.;
    i1 = 0.;
    bvg = [];
    allcount = 0.;
    nobv = 0;
    wai = waitbar(0,' Please Wait ...  ');
    set(wai,'NumberTitle','off','Name','b-value grid - percent done');;
    drawnow

    % sort by depth

    % [s,is] = sort(a.Depth);
    % adepth = a(is(:,1),:);

    % find row index of ratio midpoint
    l = a.Depth >= top_zonet & a.Depth <  top_zoneb;
    top_zone = a.subset(l);

    l = a.Depth >= bot_zonet & a.Depth <  bot_zoneb;
    bot_zone = a.subset(l);

    %
    % overall b-value
    [bv magco stan av me mer me2,  pr] =  bvalca3(top_zone,inb1,inb2);
    tbo1 = bv; tno1 = length(top_zone(:,1));

    [bv magco stan av me mer me2,  pr] =  bvalca3(bot_zone,inb1,inb2);
    bbo1 = bv; bno1 = length(bot_zone(:,1));

    depth_ratio = tbo1/bbo1;

    disp(depth_ratio);
    hodis = [hodi '/stinvers'];
    do = ['cd  ' hodis ]; eval(do)

    % loop over all points
    for i= 1:length(newgri(:,1))
        x = newgri(i,1);y = newgri(i,2);
        allcount = allcount + 1.;
        i2 = i2+1;

        % calculate distance from center point and sort wrt distance
        l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;
        [s,is] = sort(l);
        b = a(is(:,1),:) ;       % re-orders matrix to agree row-wise

        if tgl1 == 0   % take point within r
            l3 = l <= ra;
            b = a.subset(l3);      % new data per grid point (b) is sorted in distanc  (from center point)
            rd = ra;
        else
            % take first ni points
            b = b(1:ni,:);      % new data per grid point (b) is sorted in distance
            l2 = sort(l); rd = l2(ni);

        end

        %estimate the completeness and b-value
        newt2 = b;

        % sort by depth

        l = b(:,7) >= top_zonet & b(:,7) <  top_zoneb;
        topb = b(l,:);
        per_in_top = (length(topb)/length(b))*100.0;
        l = b(:,7) >= bot_zonet & b(:,7) <  bot_zoneb;
        botb = b(l,:);
        per_in_bot = (length(botb)/length(b))*100.0;

        if length(topb) >= Nmin & length(botb) >= Nmin

            tmpi = [topb(:,10:12)];
            fid = fopen('data2','w');
            str = ['Inversion data'];str = str';

            fprintf(fid,'%s  \n',str');
            fprintf(fid,'%7.3f  %7.3f  %7.3f\n',tmpi');

            fclose(fid);
            delete data2.slboot Xtemp.slboot

            unix(' slfast data2 ');
            load data2.slboot
            dtop = data2;

            tmpi = [botb(:,10:12)];
            fid = fopen('data2','w');
            str = ['Inversion data'];str = str';

            fprintf(fid,'%s  \n',str');
            fprintf(fid,'%7.3f  %7.3f  %7.3f\n',tmpi');

            fclose(fid);
            delete data2.slboot Xtemp.slboot

            unix(' slfast data2 ');
            load data2.slboot
            dbot = data2;

            ltopb = length(topb);
            lbotb = length(botb);
            bvg = [bvg ; dtop(2,2:7) dtop(1,1) dbot(2,2:7) dbot(1,1) ltopb lbotb ];

            waitbar(allcount/itotal)
        end

    end

    % plot the results
    % old and re3 (initially ) is the b-value matrix
    %
    normlap2=ones(length(tmpgri(:,1)),1)*nan;
    normlap2(ll)= bvg(:,1);
    re3=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,5);
    r=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,6);
    meg=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,2);
    old1=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,7);
    avm=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,8);
    Prmap=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,9);
    top_b=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,10);
    bottom_b=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,11);
    per_top=reshape(normlap2,length(yvect),length(xvect));

    normlap2(ll)= bvg(:,12);
    per_bot=reshape(normlap2,length(yvect),length(xvect));

    %  normlap2(ll)= bvg(:,13);
    %  ltopb=reshape(normlap2,length(yvect),length(xvect));

    % normlap2(ll)= bvg(:,14);
    % lbotb=reshape(normlap2,length(yvect),length(xvect));

    old = re3;

    % View the b-value map
    view_bdepth

end   % if sel = na

% Load exist b-grid
if sel == 'lo'
    [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');
    if length(path1) > 1
        think
        load([path1 file1])
        normlap2=ones(length(tmpgri(:,1)),1)*nan;

        normlap2(ll)= bvg(:,1);
        re3=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,5);
        r=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,6);
        meg=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,2);
        old1=reshape(normlap2,length(yvect),length(xvect));

        %  normlap2(ll)= bvg(:,7);
        %  pro=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,7);
        avm=reshape(normlap2,length(yvect),length(xvect));

        %  normlap2(ll)= bvg(:,9);
        % stanm=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,8);
        Prmap=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,9);
        top_b=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,10);
        bottom_b=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,11);
        per_top=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,12);
        per_bot=reshape(normlap2,length(yvect),length(xvect));

        %    normlap2(ll)= bvg(:,13);
        %    ltopb=reshape(normlap2,length(yvect),length(xvect));

        %   normlap2(ll)= bvg(:,14);
        %  lbotb=reshape(normlap2,length(yvect),length(xvect));

        old = re3;

        view_bdepth
    else
        return
    end
end


name='bimodal.png'
raw=double(imread(name));
rawgray=raw(:,:,1);
smoothgray=imgaussfilt(rawgray,70);
figure()
surf(rawgray,'edgecolor','none')
figure()
surf(smoothgray,'edgecolor','none')
imwrite(uint16(smoothgray*255),['green' name '.tiff']);
testIN=imread(['green' name]);
figure()
surf(testIN,'edgecolor','none')


%BagOfWords Bag of words class
%
% The BagOfWords class holds sets of features for a number of images and
% supports image retrieval by comparing new images with those in the 'bag'.
%
% Methods::
% isword        Return all features assigned to word
% occurrences   Return number of occurrences of word
% remove_stop   Remove stop words
% wordvector    Return word frequency vector
% wordfreq      Return words and their frequencies
% similarity    Compare two word bags
% contains      List the images that contain a word
% exemplars     Display examples of word support regions
% display       Display the parameters of the bag of words
% char          Convert the parameters of the bag of words to a string
%
% Properties::
% K         The number of clusters specified
% nstop     The number of stop words specified
% nimages   The number of images in the bag
%
% Reference::
%
% J.Sivic and A.Zisserman,
% "Video Google: a text retrieval approach to object matching in videos",
% in Proc. Ninth IEEE Int. Conf. on Computer Vision, pp.1470-1477, Oct. 2003.
%
% See also PointFeature.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

classdef BagOfWords < handle
    properties
        features    % vector of all features in the bag (PointFeature class)

        K       % number of clusters
        C       % cluster centres (NDxNW)
        words   % vector of word indices (NW)

        nstop     % number of stop words
        stopwords  % list of stop words
        map        % maps word index with stop words to word index without stop words

        nimages       % number of images (NI)

        wv          % cached word vectors
    end

    methods
        function bag = BagOfWords(sf, a1)
        %BagOfWords.BagOfWords Create a BagOfWords object
        %
        % B = BagOfWords(F, K) is a new bag of words created from the feature
        % vector F and with K words.  F can also be a cell array, as produced
        % by ISURF() for an image sequence.
        %
        % The features are sorted into K clusters and each cluster is termed
        % a visual word.
        %
        % B = BagOfWords(F, B2) is a new bag of words created from the feature
        % vector F but clustered to the words (and stop words) from the existing
        % bag B2.
        %
        % Notes::
        % - Uses the MEX function vl_kmeans to perform clustering (vlfeat.org).
        %
        % See also PointFeature, ISURF.

            % save the feature vector
            if iscell(sf)
                bag.features = [sf{:}];
            else
                bag.features = sf;
            end
            bag.nimages = max([bag.features.image_id]);

            if isnumeric(a1)
                K = a1;
                % do the clustering
                [bag.C,L] = vl_kmeans([bag.features.descriptor], K, ...
                    'verbose', 'algorithm', 'elkan');

                bag.K = K;
                bag.words = double(L);

            elseif isa(a1, 'BagOfWords')
                oldbag = a1;

                % cluster using number of words from old bag
                bag.words = closest([bag.features.descriptor], oldbag.C);

                if oldbag.stopwords > 0
                    % remove stopwords as per the original bag file
                    bag.K = oldbag.K;
                    bag.stopwords = oldbag.stopwords;
                    k = find(ismember(bag.words, oldbag.stopwords));

                    fprintf('Removing %d features associated with stop words\n', length(k));

                    bag.words(k) = [];
                    bag.words = oldbag.map(bag.words);
                    bag.features(k) = [];
                end

                bag.compute_wv(oldbag);

            end
        end

        function f = isword(bag, words)
        %BagOfWords.isword Features from words
        %
        % F = B.isword(W) is a vector of feature objects that are assigned to any of
        % the word W.  If W is a vector of words the result is a vector of features
        % assigned to all the words in W.
            k = ismember(bag.words, words);
            f = bag.features(k);
        end

        function n = occurrence(bag, word)
        %BagOfWords.occurrence Word occurrence
        %
        % N = B.occurrence(W) is the number of occurrences of the word W across
        % all features in the bag.
            n = sum(bag.words == word);
        end

        function [all2, S] = remove_stop(bag, nstop)
        %BagOfWords.remove_stop Remove stop words
        %
        % B.remove_stop(N) removes the N most frequent words (the stop words)
        % from the bag.  All remaining words are renumbered so that the word
        % labels are consecutive.

            [w,f] = count_unique(bag.words);
            [f,i] = sort(f, 'descend');
            bag.stopwords = w(i(1:nstop));

            % remove all features that are stop words from L and all
            k = find(ismember(bag.words, bag.stopwords));

            fprintf('Removing %d features associated with %d most frequent words\n', ...
                length(k), nstop);

            % fix the labels
            b = zeros(1,length(bag.words));
            b(bag.stopwords) = 1;
            bag.map = [1:length(bag.words)] - cumsum(b);

            bag.words(k) = [];
            bag.words = bag.map(bag.words);
            bag.features(k) = [];

        end

        function wv = wordvector(bag, k)
        %BagOfWords.wordvector  Word frequency vector
        %
        % WF = B.wordvector(J) is the word frequency vector for the J'th image
        % in the bag.  The vector is Kx1 and the angle between any two WFVs is
        % an indication of image similarity.
        %
        % Notes::
        % - The word vector is expensive to compute so a lazy evaluation is
        %   performed on the first call to this function
            if isempty(bag.wv)
                bag.compute_wv();
            end
            if nargin > 1
                wv = bag.wv(:,k);
            else
                wv = bag.wv;
            end
        end

        % compute  image-word frequency
        function W = iwf(bag)

            N = bag.nimages;  % number of images

            % Create the word frequency matrix W
            %  column correspond to images
            %  row correspond to words
            %  each element is the number of occurences of that word in that iamge
            W = [];
            id = [bag.features.image_id];

            nl = bag.K - length(bag.stopwords);

            for i=1:bag.nimages
                % get the words associated with image i
                words = bag.words(id == i);

                % create columns of the W
                [w,f] = count_unique(words);
                v = zeros(nl,1);
                v(w) = f;
                W = [W v];
            end
        end

        function W = compute_wv(bag, bag2)

            if nargin == 2
                Wv = bag2.iwf();
                N = bag2.nimages;
                W = bag.iwf();
            else
                Wv = bag.iwf();
                N = bag.nimages;
                W = Wv;
            end

            Ni = sum( Wv'>0 );

            m = [];
            for i=1:bag.nimages
                % number of words in this image
                nd = sum( W(:,i) );

                % word occurrence frequency
                nid = W(:,i)';

                v = nid/nd .* log(N./Ni);
                v(~isfinite(v)) = 0;
                m = [m v'];
            end

            if nargout == 1
                W = m;
            else
                bag.wv = m;
            end
        end

        function [w,f] = wordfreq(bag)
        %BagOfWords.wordfreq Word frequency statistics
        %
        % [W,N] = B.wordfreq() is a vector of word labels W and the corresponding
        % elements of N are the number of occurrences of that word.
            [w,f] = count_unique(bag.words);
        end

        % compute similarity matrix
        function sim = similarity(bag1, bag2)
            wv1 = bag1.wordvector;
            wv2 = bag2.wordvector;
            for i=1:bag1.nimages
                for j=1:bag2.nimages
                    v1 = wv1(:,i); v2 = wv2(:,j);
                    sim(i,j) = dot(v1,v2) / (norm(v1) * norm(v2));
                end
            end
        end

        function display(bag)
        %BagOfWords.display Display value
        %
        % B.display() displays the parameters of the bag in a compact human
        % readable form.
        %
        % Notes::
        % - This method is invoked implicitly at the command line when the result
        %   of an expression is a BagOfWords object and the command has no trailing
        %   semicolon.
        %
        % See also BagOfWords.char.

            loose = strcmp( get(0, 'FormatSpacing'), 'loose');
            if loose
                disp(' ');
            end
            disp([inputname(1), ' = '])
            if loose
                disp(' ');
            end
            disp(char(bag))
            if loose
                disp(' ');
            end
        end

        function s = char(bag)
        %BagOfWords.char Convert to string
        %
        % S = B.char() is a compact string representation of a bag of words.
            s = sprintf(...
            'BagOfWords: %d features from %d images\n           %d words, %d stop words\n', ...
                length(bag.features), bag.nimages, ...
                bag.K-length(bag.stopwords), length(bag.stopwords));
        end

        function v = contains(bag, word)
        %BagOfWords.contains Find images containing word
        %
        % K = B.contains(W) is a vector of the indices of images in the sequence that
        % contain one or more instances of the word W.
            v = unique([bag.isword(word).image_id]);
        end

        function out = exemplars(bag, words, images, varargin)
        %BagOfWords.exemplars Display exemplars of words
        %
        % B.exemplars(W, IMAGES, OPTIONS) displays examples of the support regions of
        % the words specified by the vector W.  The examples are displayed as a table
        % of thumbnail images.  The original sequence of images from which the features
        % were extracted must be provided as IMAGES.
        %
        % IM = B.exemplars(W, IMAGES, OPTIONS) as above but returns the thumbnails
        % as a composite image.
        %
        % Options::
        % 'columns',N       Number of columns to display (default 10)
        % 'maxperimage',M   Maximum number of exemplars to display from any
        %                   one image (default 2)
        % 'width',W         Width of each thumbnail [pixels] (default 50)
        % 'label'           Display word labels on the thumbnails.

            opt.gap = 2;
            opt.columns = 10;
            opt.maxperimage = 2;
            opt.width = 50;
            opt.label = false;
            opt.rows = [];

            opt = tb_optparse(opt, varargin);

            % figure the number of exemplars to show, no more than opt.maxperimage
            % from any one image
            nexemplars = 0;
            exemplars = {};
            for w=words
                image_prev = [];
                count = 0;
                for f=bag.isword(w)
                    if f.image_id == image_prev
                        count = count + 1;
                        if count > opt.maxperimage
                            continue;
                        end
                    end

                    exemplars = [exemplars {{w, f}}];
                end
            end

            if isempty(opt.rows)
                nr = ceil( length(exemplars) / opt.columns);
            else
                nr = opt.rows;
            end
            nc = min(length(exemplars), opt.columns);

            n = min(length(exemplars), nr*nc);
            exemplars = exemplars(1:n);

            Ng = opt.width+opt.gap;
            composite = ones(nr*Ng, nc*Ng);

            % render the support regions into composite image
            row = 0; col = 0;
            for ex=exemplars
                ex = ex{1};
                word = ex{1}; f = ex{2};

                % extract it from the containing image
                support = f.support(images, opt.width);

                % paste it into the panel
                composite = ipaste(composite, support, [col row]*Ng, 'zero');

                % update row/column indices
                col = col + 1;
                if col >= opt.columns
                    row = row + 1;
                    col = 0;
                end
            end

            if nargout == 1
                % output specified, return the image
                out = composite;
            else
                if opt.label
                    % no output specified, optionally label the cells

                    if nargout == 0
                        idisp(composite, 'plain');
                    end

                    row = 0; col = 0;
                    for ex=exemplars
                        ex = ex{1};
                        word = ex{1}; f = ex{2};

                        text(col*Ng+opt.gap*2, row*Ng+3*opt.gap, ...
                            sprintf('%d #%d', word, f.image_id), 'Color', 'g')

                        % update row/column indices
                        col = col + 1;
                        if col >= opt.columns
                            row = row + 1;
                            col = 0;
                        end
                    end
                else
                    idisp(composite, 'plain');
                end
            end
        end
    end
end


function p=classprob(t,j)
%CLASSPROB Class probabilities for tree nodes.
%   P=CLASSPROB(T) returns an N-by-M array P of class probabilities for the
%   nodes in the classification tree T, where N is the number of nodes
%   and M is the number of classes.  For any node number K, the class
%   probabilities P(K,:) are the estimated probabilities for each class
%   for a point satisfying the conditions for node K.
%
%   P=CLASSPROB(T,J) takes an array J of node numbers and returns the
%   class probabilities for the specified nodes.
%
%   See also CLASSREGTREE, CLASSREGTREE/NUMNODES.

%   Copyright 2006-2007 The MathWorks, Inc.
%   $Revision: 1.1.6.3 $  $Date: 2007/02/15 21:48:02 $

if isequal(t.method,'regression')
    error('stats:classregtree:classprob:NotClassification',...
          'The CLASSPROB method is not available for regression trees.');
end
if nargin>=2 && ~validatenodes(t,j)
    error('stats:classregtree:classprob:InvalidNode',...
          'J must be an array of node numbers or a logical array of the proper size.');
end

if nargin<2
    p = t.classprob;
else
    p = t.classprob(j,:);
end


function [xdot] = secondOrderDynamics(obj, t, x, controller, params, logger)
    % calculate the dynamical equation of the second order dynamical system
    %
    % Parameters:
    % t: the time instant @type double
    % x: the states @type colvec
    % controller: the controller @type Controller
    % params: the parameter structure @type struct
    % logger: the data logger object @type SimLogger
    %
    % Return values:
    % xdot: the derivative of the system states @type colvec

    % extract the state variables into x and dx
    nx = obj.numState;
    q = x(1:nx);
    dq = x(nx+1:end);

    % store time and states into object private data for future use
    obj.t_ = t;
    obj.states_.x = q;
    obj.states_.dx = dq;

    % compute the mass matrix and drift vector (internal dynamics)
    M = calcMassMatrix(obj, q);
    Fv = calcDriftVector(obj, q, dq);

    %% get the external input
    % initialize the Gv_ext vector
    Gv_ext = zeros(nx,1);
    f_ext_name = fieldnames(obj.Inputs.External);
    if ~isempty(f_ext_name)              % if external inputs are defined
        n_ext = length(f_ext_name);

        for i=1:n_ext
            f_name = f_ext_name{i};
            % get the Gvec function object
            % g_fun = obj.Gvec.External.(f_name);
            % call the callback function to get the external input
            f_ext = obj.ExternalInputFun(obj, f_name, t, q, dq, params, logger);
            % compute the Gvec, and add it up
            Gv_ext = Gv_ext + feval(obj.GvecName_.External.(f_name),q,f_ext);

            % store the external inputs into the object private data
            obj.inputs_.External.(f_name) = f_ext;
        end
    end

    %% holonomic constraints
    h_cstr_name = fieldnames(obj.HolonomicConstraints);
    if ~isempty(h_cstr_name)           % if holonomic constraints are defined
        h_cstr = struct2array(obj.HolonomicConstraints);
        n_cstr = length(h_cstr);
        % determine the total dimension of the holonomic constraints
        cdim = sum([h_cstr.Dimension]);
        % initialize the Jacobian matrix
        Je = zeros(cdim,nx);
        Jedot = zeros(cdim,nx);

        idx = 1;
        for i=1:n_cstr
            cstr = h_cstr(i);

            % calculate the Jacobian
            [Jh,dJh] = calcJacobian(cstr,q,dq);
            cstr_indices = idx:idx+cstr.Dimension-1;
            tol = 1e-2;
            if norm(Jh*dq) > tol
                warning('The holonomic constraint %s violated.', h_cstr_name{i});
            end
            Je(cstr_indices,:) = Jh;
            Jedot(cstr_indices,:) = dJh;
            idx = idx + cstr.Dimension;
        end
    else
        Je = [];
        Jedot = [];
    end

    %% calculate the constrained vector fields and control inputs
    control_name = fieldnames(obj.Inputs.Control);
    Gv_u = zeros(nx,1);
    if ~isempty(control_name)
        Be = feval(obj.GmapName_.Control.(control_name{1}),q);
        Ie    = eye(nx);

        if isempty(Je)
            vfc = [
                dq;
                M \ (Fv)];
            gfc = [
                zeros(size(Be));
                M \ Be];
        else
            XiInv = Je * (M \ transpose(Je));
            % compute vector fields
            % f(x)
            vfc = [
                dq;
                M \ ((Ie-transpose(Je) * (XiInv \ (Je / M))) * (Fv) - transpose(Je) * (XiInv \ Jedot * dq))];

            % g(x)
            gfc = [
                zeros(size(Be));
                M \ (Ie - transpose(Je)* (XiInv \ (Je / M))) * Be];
        end
        % compute control inputs
        if ~isempty(controller)
            u = calcControl(controller, t, x, vfc, gfc, obj, params, logger);
        else
            u = zeros(size(Be,2),1);
        end
        Gv_u = Be*u;
        obj.inputs_.Control.(control_name{1}) = u;
    end
    %% calculate constraint wrench of holonomic constraints
    Gv = Gv_ext + Gv_u;
    % Calculate constrained forces
    Gv_c = zeros(nx,1);
    if ~isempty(h_cstr_name)
        lambda = -XiInv \ (Jedot * dq + Je * (M \ (Fv + Gv)));
        % the constrained wrench inputs
        Gv_c = transpose(Je)*lambda;

        % extract and store
        idx = 1;
        for i=1:n_cstr
            cstr = h_cstr(i);
            hval.(h_cstr_name{i}) = calcConstraint(cstr,q);
            cstr_indices = idx:idx+cstr.Dimension-1;
            input_name = cstr.InputName;
            obj.inputs_.ConstraintWrench.(input_name) = lambda(cstr_indices);
            idx = idx + cstr.Dimension;
        end
    else
        hval = [];
    end

    Gv = Gv + Gv_c;

    % the system dynamics
    xdot = [dq;
        M \ (Fv + Gv)];
    obj.states_.ddx = xdot(nx+1:end);

    if ~isempty(logger)
        calc = logger.calc;

        calc.t       = t;
        calc.states  = obj.states_;
        calc.inputs  = obj.inputs_;
        calc.hval     = hval;

        logger.calc  = calc;
    end
end


% Mostly bottom-up method for generating a set
% of good candidate parses to optimize further.
%
% Input
%  I: [n x n bool] binary image
%  lib: library
%  ninit: number of parses to choose
%  verbose: true/false
%
% Output
%  bestMP: [ninit x 1 cell] list of best candidate motor programs
%  score_sorted: [n x 1] score of all parses considered in sorted order
%
function [bestMP,score_sorted] = generate_random_parses(I,lib,ninit,verbose)
    if ~exist('verbose','var')
       verbose = false;
    end

    % Check that image is in the right format
    assert(UtilImage.check_black_is_true(I));

    % If we have a blank image
    if sum(sum(I))==0
       bestMP = [];
       return
    end

    % Get character skeleton from the fast bottom-up method
    G = extract_skeleton(I,verbose);

    % Create a set of random parses through random walks
    ps = defaultps_bottomup;
    if verbose, fprintf(1,'\ngenerating random walks...\n'); end
    RW = RandomWalker(G);
    PP = ProcessParses(I,lib,verbose);

    % Add deterministic minimum angle walks
    for i=1:ps.nwalk_det
        PP.add(RW.det_walk);
    end

    % Sample random walks until we reach capacity.
    walk_count = PP.nwalks;
    while (PP.nl < ps.max_nstroke) && (walk_count < ps.max_nwalk)
        list_walks = RW.sample(1);
        PP.add(list_walks{1});
        walk_count = walk_count + 1;
        if verbose && mod(walk_count,5)==0
            fprintf(1,'%d,',walk_count);
            if mod(walk_count,20)==0
               fprintf(1,'\n');
            end
        end
    end
    if verbose, fprintf(1,'done.\n'); end

    % Turn parses into motor programs with additional search
    % and processing
    [bestMP,score_sorted] = parses_to_MPs(I,PP,ninit,lib,verbose);

end


function value = function_3d_name ( ifunc )

%*****************************************************************************80
%
%% FUNCTION_3D_NAME returns the name of the current 3D function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 April 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer IFUNC, the index of the function.
%
%    Output, character FNAME(7), the name of the function.
%
  if ( ifunc == 1 )
    value = '      1';

  elseif ( ifunc == 2 )
    value = '      X';
  elseif ( ifunc == 3 )
    value = '      Y';
  elseif ( ifunc == 4 )
    value = '      Z';

  elseif ( ifunc == 5 )
    value = '    X*X';
  elseif ( ifunc == 6 )
    value = '    X*Y';
  elseif ( ifunc == 7 )
    value = '    X*Z';
  elseif ( ifunc == 8 )
    value = '    Y*Y';
  elseif ( ifunc == 9 )
    value = '    Y*Z';
  elseif ( ifunc == 10 )
    value = '    Z*Z';

  elseif ( ifunc == 11 )
    value = '    X^3';
  elseif ( ifunc == 12 )
    value = '  X*Y*Z';
  elseif ( ifunc == 13 )
    value = '  Z*Z*Z';

  elseif ( ifunc == 14 )
    value = '    X^4';
  elseif ( ifunc == 15 )
    value = 'X^2 Z^2';
  elseif ( ifunc == 16 )
    value = '    Z^4';

  elseif ( ifunc == 17 )
    value = '    X^5';
  elseif ( ifunc == 18 )
    value = '    X^6';
  elseif ( ifunc == 19 )
    value = '      R';
  elseif ( ifunc == 20 )
    value = ' SIN(X)';
  elseif ( ifunc == 21 )
    value = ' EXP(X)';
  elseif ( ifunc == 22 )
    value = '1/(1+R)';
  elseif ( ifunc == 23 )
    value = 'SQRT(R)';
  else
    value = '???????';
  end

  return
end


function blobs_size = caffe_get_blobs_size(net, blob_names)
%
% This file is part of the code that implements the following ICCV2015 accepted paper:
% title: "Object detection via a multi-region & semantic segmentation-aware CNN model"
% authors: Spyros Gidaris, Nikos Komodakis
% institution: Universite Paris Est, Ecole des Ponts ParisTech
% Technical report: http://arxiv.org/abs/1505.01749
% code: https://github.com/gidariss/mrcnn-object-detection
%
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2015 Spyros Gidaris
%
% "Object detection via a multi-region & semantic segmentation-aware CNN model"
% Technical report: http://arxiv.org/abs/1505.01749
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------

num_blobs  = length(blob_names);
blobs_size = cell(num_blobs,1);
for i = 1:num_blobs
    size_this     = net.blobs(blob_names{i}).shape;
    blobs_size{i} = ones(1,4);
    blobs_size{i}((end-length(size_this)+1):end) = size_this;
end
end


% DEMCMU35VARGPLVMANIMATE Load results for the dyn. GPLVM on CMU35 data and
% produce animation and plots. The plots (and errors) are in the data
% space. For plots / errors  in the scaled space (for comparison with FGPLVM)
% see demCmu35VargplvmPlotsScaled.m
% DESC Load results for the dyn. GPLVM on CMU35 data and produce animation
% and plots.
% COPYRIGHT :  Andreas C. Damianou, Michalis K. Titsias, 2011
%
% SEEALSO : demCmu35VargplvmLoadChannels, demCmu35gplvmVargplvm3.m,
% demCmu35VargplvmPlotsScaled.m
% VARGPLVM

randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'cmu35gplvm';
if ~exist('experimentNo') experimentNo = 33; end
% Options for the following: 'Legs', 'Body'
if ~exist('predictPart') predictPart = 'Legs'; end
% Sampling:
if ~exist('doSampling') doSampling = 0; end
if ~exist('showSkel') showSkel = 1; end
if ~exist('displayPlots')  displayPlots = 1; end
% -1 is a flag meaning that plotRange == missingInd
if ~exist('plotRange') plotRange = -1; end

% load data
[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);
dataSetName = 'cmu35gplvm';

capName = dataSetName;
capName(1) = upper(capName(1));
fileName=['dem' capName 'Vargplvm' num2str(experimentNo)];

% load data
[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);
origBias = mean(Y);
origScale = 1./sqrt(var(Y));

legInd = [8:14];
bodyInd = [21:50];

startInd = 63;
dt=0.05;
timeStampsTest = ([0:size(Ytest,1)-1].*dt)';

load(fileName)
model.dynamics.t_star = timeStampsTest;

% Choose one of the following lines as appropriate to obtain the results for the leg or body reconstruction
% respectively.
if strcmp(predictPart,'Legs')
    load(['demCmu35Vargplvm' num2str(experimentNo) 'PredLegs.mat']); missingInd = legInd;
elseif strcmp(predictPart, 'Body')
    load(['demCmu35Vargplvm' num2str(experimentNo) 'PredBody.mat']) ;missingInd = bodyInd;
end

YtestOrig = Ytest;
YtestGplvm = Ytest;
YtestGplvm(startInd:end, missingInd) = NaN;
indexMissingData = startInd:size(YtestGplvm);
% In case only barmu and lambda are loaded from the results then the next step is necessary to find
% the predictive dencity Ypred.
[x, varx, modelUpdated] = vargplvmDynamicsUpdateModelTestVar(model, barmu, lambda, YtestGplvm);
Testmeans = x(indexMissingData, :);
Testcovars = varx(indexMissingData, :);
[mu, sigma] = vargplvmPosteriorMeanVar(modelUpdated, Testmeans, Testcovars);
Ypred = mu;

%%
origYtest = Ytest;
err = origYtest(startInd:end, missingInd) - Ypred(:, missingInd);
err = err*180/pi;
angleErrorGplvm = sqrt(mean(mean((err.*err))))
load cmu35TaylorScaleBias
err = err.*repmat(scale(1, missingInd+9), size(origYtest, 1)-startInd+1, 1);
taylorErrorGplvm = sum(sum(err.*err))/length(missingInd)

%%
% NN
temp = ones(1, size(Ytest, 2));
temp(missingInd) = 0;
presentInd = find(temp);
YtrainNn = Y(:, presentInd);
YtestNn = origYtest(startInd:end, presentInd);
dists = dist2(YtrainNn, YtestNn);
[void, bestIndNn] = min(dists);

%%

if displayPlots
    colordef white
    if plotRange == -1 % flag
        plotRange = missingInd;
    end
    for plotNo = plotRange
        figNo = plotNo - min(plotRange) + 1;
        figure(figNo)
        clf
        lin = plot(1:size(origYtest, 1), origYtest(:, plotNo), '-')
        hold on
        lin = [lin; plot(1:size(origYtest, 1), [origYtest(1:startInd-1, plotNo); Y(bestIndNn, plotNo)], ':')];
        lin = [lin; plot(1:size(origYtest, 1), [origYtest(1:startInd-1, plotNo); Ypred(:, plotNo)], '--')];
        ax = gca;
        xlabel('Frame')
        ylabel('Normalized joint angle')
        set(ax, 'fontname', 'arial');
        set(ax, 'fontsize', 20);
        set(lin, 'lineWidth', 2);
        pos = get(gcf, 'paperposition')
        origpos = pos;
        pos(3) = pos(3)/2;
        pos(4) = pos(4)/2;
        set(gcf, 'paperposition', pos);
        fontsize = get(gca, 'fontsize');
        set(gca, 'fontsize', fontsize/2);
        lineWidth = get(gca, 'lineWidth');
        set(gca, 'lineWidth', lineWidth*2);
        set(gcf, 'paperposition', origpos);
    end
end

%%

if showSkel
    skel = acclaimReadSkel('35.asf');
    [tmpchan, skel] = acclaimLoadChannels('35_01.amc', skel);
    channels1 = demCmu35VargplvmLoadChannels(Ytest,skel);
    channels2 = demCmu35VargplvmLoadChannels(Ypred,skel);
    channels3 = demCmu35VargplvmLoadChannels(Y(bestIndNn, :),skel);
    %skelPlayData(skel, channels, 1/25);

    startInd = 63;
    skelPlayData2(skel, 1/15, channels1(startInd:end,:), channels2, channels3,{'Ytest','YpredGPLVM','YpredNN'});
end

%%

if doSampling
 %   timeStampsTestOrig = timeStampsTest;
 %   timeStampsTest = (timeStampsTest(end):dt:(timeStampsTest(end)+100*dt))';
    model.dynamics.t_star = timeStampsTest;
    seqTest = 1; % WALK
    %seqTest = 17; % RUN

    if seqTest ~= 1
        datFrom = model.dynamics.seq(seqTest-1)+1;
    else
        datFrom = 1;
    end
    datEnd=model.dynamics.seq(seqTest);

    model.dynamics.t_star = model.dynamics.t_star(1:(datEnd+1-datFrom));%%%
    %     clear model
    %     load demCmu35VargplvmOne
    %     %load demCmu35VargplvmOneRun
    %     ySamp, xSamp] = vargpTimeDynamicsSample(model,1);
    %     channels4 = demCmu35VargplvmLoadChannels(ySamp,skel);
    %     skelPlayData(skel, channels4, 1/25);

    [ySamp, xSamp] = vargpTimeDynamicsSampleSeq(model,1,seqTest);
    channels4 = demCmu35VargplvmLoadChannels(ySamp,skel);
    skelPlayData(skel, channels4, 1/10);

    %     [Testmeans2 Testcovars2] = vargplvmPredictSeq(model.dynamics, timeStampsTest,1);
    %     Varmu2 = vargplvmPosteriorMeanVar(model, Testmeans2, Testcovars2);
    %     channels5 = demCmu35VargplvmLoadChannels(Varmu2,skel);
    %     skelPlayData(skel, channels5, 1/25);

end
%%
%lvmVisualise(model, [], 'skelVisualise', 'skelModify', channels, skel);
%lvmVisualise(model, [], 'TEMPskelVisualise', 'skelModify', channels1,
%skel);


function [y, t] = Raw_to_DeltaConc_Example(filename, hbType, channels)
%
%    Example 1:   Plot channel 1 delta HbO concentration, derived from
%                 acquisition file test.snirf
%
%       cd '<root folder>\Homer3\UnitTests\Example_RunFuncOffline'
%       Raw_to_DeltaConc_Example('./test.snirf');
%
%    Example 2:   Plot channels 1 and 2 delta HbR concentration, derived
%                 from acquisition file test.snirf
%
%       cd '<root folder>\Homer3\UnitTests\Example_RunFuncOffline'
%       Raw_to_DeltaConc_Example('./test.snirf', 2, [1,2]);
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parse args
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Arg 1
[pname, fname] = fileparts(filename);

% Arg 2:  Hb type - {1 -> HbO,  2 -> HbR,  3 -> HbT}
if ~exist('hbType','var') || isempty(hbType)
    hbType   = 1;
end

% Arg 3:
if ~exist('channels','var') || isempty(channels)
    channels = 1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load acquisition file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
acquired = SnirfClass([pname, '/', fname, '.snirf']);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Call sequence of user functions to get from acquired data
% to delta concentration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dod = hmrR_Intensity2OD(acquired.data);
dod = hmrR_BandpassFilt(dod, 0.01, 0.50);
dc  = hmrR_OD2Conc_new(dod, acquired.probe, [1,1]);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extract plot data from output of last function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
t = dc.time;
y = dc.GetDataTimeSeries('reshape');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PlotData(t, y, hbType, channels);


function [acc_t,predictions_hard,predictions_soft,genplot] = standard_classifier_test(model,X,Y,T,options,binsize)
% Fit an already trained classifier given by the structure model to the
% test data given in X with labels Y.
%
% INPUT
% model: a classification model outputted from the function
%           standard_classifier_train
% X: Brain data, (total time by regions) or (time by trials by regions)
% Y: Stimulus, (total time by q). This variable can either be entered as a
%       single vector of class assignments (ie q=1 and y takes values
%       1,2,...N=total number of classes); or can be entered as a matrix of
%       labels where each column contains 1 or 0 denoting whether that
%       class is active.
% T: Length of series
%       options             structure with the following subfields:
%           classifier      String indicating calssifer type;
%                   logistic    Logistic Regression classifier (default)
%                   SVM         Linear support vector machine classifier
%                   LDA         Linear Discriminant Analysis classifier
%           regularisation  String indicating type of regularisation;
%                   L1          Lasso regularisation
%                   L2          Ridge regularisation (default)
%                   ARD         Automatic relevance determination
%           lambda          Vector of regularisation penalty values to be
%                           tested
% binsize: NOT YET IMPLMENTED
%           how many consecutive time points will be used for each estiamtion.
%           By default, this is 1, such that one decoding model
%               is estimated using 1 time point
%
% OUTPUT
%
%
% Author: Cam Higgins, OHBA, University of Oxford (2019)

if nargin < 5 || isempty(options), options = struct(); end
if nargin < 6, binsize = 1; end

if ~all(T==T(1)), error('All elements of T must be equal for time-aligned classification'); end
N = length(T); ttrial = T(1);

if size(Y,1) < size(Y,2); Y = Y'; end
q = size(Y,2);
if size(Y,1) == length(T) % one value per trial
    responses = Y;
elseif length(Y(:)) ~= (ttrial*N*q)
    error('Incorrect dimensions in Y')
else
    responses = reshape(Y,[ttrial N q]);
    Ystar = reshape(repmat(responses(1,:,:),[ttrial,1,1]),[ttrial*N q]);
    responses = permute(responses(1,:,:),[2 3 1]); % N x q
    if ~all(Y(:)==Ystar(:))
        error('For time-aligned classification, the same stimulus must be presented for the entire trial');
    end
end

Ycopy = Y;
if size(Ycopy,1) == N
    Ycopy = repmat(reshape(Ycopy,[1 N q]),[ttrial 1 1]);
else
    Ycopy = reshape(Ycopy,[ttrial N q]);
end
% no demeaning by default if this is a classification problem
if ~isfield(options,'demeanstim'), options.demeanstim = 0; end

options.Nfeatures = 0;
options.K = 1;
%[X,Y,T] = preproc4hmm(X,Y,T,options); % this demeans Y
p = size(X,2);

%reshape to 3d vectors:
X = reshape(X,[ttrial N p]);
Y = reshape(Y,[ttrial N q]);

if (binsize/2)==0
    warning(['binsize must be an odd number, setting to ' num2str(binsize+1)])
    binsize = binsize + 1;
end

if any(T~=ttrial), error('All trials must have the same length'); end
if nargin<5, binsize = 1; end

if ~isfield(model,'classifier')
    error('Model inputted does not conform to requirements; it should be trained using the function standard_classifier_train.m');
else
    classifier = model.classifier;
    if ~(strcmp(classifier,'logistic') || strcmp(classifier,'SVM') ||...
            strcmp(classifier,'LDA') || strcmp(classifier,'KNN') || ...
            strcmp(classifier,'decisiontree') || strcmp(classifier,'SVM_rbf'));
        error('model.classifier can only take values "logistic", "SVM" or "LDA"');
    end
end
if strcmp(classifier,'logistic')
    Q_star = size(model.betas,3); %check if multinomial regression
else
    Q_star=q;
end
if ~isfield(options,'generalisationplot'),options.generalisationplot=false;end
if isfield(model,'lambda')
    L=length(model.lambda);
else
    L=1;
end

halfbin = floor(binsize/2);
%nwin = round(ttrial / binsize);
%binsize = floor(ttrial / nwin);
%RidgePen = lambda * eye(p);

if strcmp(classifier,'logistic')
    Y(Y==-1)=0;
    Y_pred = zeros(ttrial,N,Q_star,L);
    Y_pred_genplot=zeros(ttrial,ttrial,N,Q_star,L);
    for iLambda=1:L
        for t=1:ttrial
            if p>1
                Y_pred(t,:,:,iLambda)=squeeze(X(t,:,:))*permute(model.betas(t,:,:,iLambda),[2,3,1,4]) + repmat(model.intercepts(t,:,iLambda),N,1);
            else
                Y_pred(t,:,:,iLambda)=X(t,:)'*permute(model.betas(t,:,:,iLambda),[2,3,1,4]) + repmat(model.intercepts(t,:,iLambda),N,1);
            end
            if options.generalisationplot
                for t2=1:ttrial
                    Y_pred_genplot(t,t2,:,:,iLambda)= ...
                        squeeze(X(t2,:,:))*permute(model.betas(t,:,:,iLambda),[2,3,1,4]) + repmat(model.intercepts(t,:,iLambda),N,1);
                end
            end
        end
    end

    for iL=1:L
        if Q_star~=q
            pred_temp=multinomLogRegPred(Y_pred(:,:,:,iL));
            predictions_soft(:,:,iL)=reshape(pred_temp,[ttrial*N,q]);
            predictions_hard(:,:,iL)=hardmax(predictions_soft(:,:,iL));
        else
            Y_pred = reshape(Y_pred,[ttrial*N,q,L]);
            predictions_soft(:,:,iL)=log_sigmoid(Y_pred(:,:,iL));
            if Q_star>1
                predictions_hard(:,:,iL)=hardmax(Y_pred(:,:,iL));
            else
                predictions_hard(:,:,iL) = Y_pred(:,:,iL)>0;
            end
        end
    end
    if options.generalisationplot
        if Q_star==q
            Y_pred_genplot = reshape(Y_pred_genplot,[ttrial, ttrial*N,Q_star,L]);
            for iL=1:iL
                for t=1:ttrial
                    Y_pred_genplot(t,:,:,iL) = hardmax(squeeze(Y_pred_genplot(t,:,:,iL)));
                end
            end
        else %multinomial:
            Y_pred_genplot_q = zeros([ttrial, ttrial,N,q,L]);
            for iL=1:iL;
                for t=1:ttrial
                    pred_temp = multinomLogRegPred(squeeze(Y_pred_genplot(t,:,:,:,iL)));
                    pred_temp = reshape(pred_temp,[ttrial*N,q]);
                    Y_pred_genplot_q(t,:,:,:,iL) = reshape(hardmax(pred_temp),[ttrial,N,q]);
                end
            end
            Y_pred_genplot=Y_pred_genplot_q;
        end
    end
elseif strcmp(classifier,'SVM') || strcmp(classifier,'SVM_rbf')
     % note this uses distance from hyperplane as soft score to allow
     % multiclass categorisation
     Y_pred = zeros(ttrial,N,q);
     Y_pred_genplot=zeros(ttrial,ttrial,N,q);
     for t=1:ttrial
        for iStim=1:q
            %[~,sc] = predict(model.SVM{t,iStim},squeeze(X(t,:,:)));
            [~,sc] = model.SVM{t,iStim}.predict(squeeze(X(t,:,:)));
            Y_pred(t,:,iStim)=sc(:,2);
            if options.generalisationplot
                for t2=1:ttrial
                    %[~,sc] = predict(model.SVM{t,iStim},squeeze(X(t2,:,:)));
                    [~,sc] = model.SVM{t,iStim}.predict(squeeze(X(t2,:,:)));
                    Y_pred_genplot(t,t2,:,iStim)= sc(:,2);
                end
            end
        end
     end
     Y_pred = reshape(Y_pred,[ttrial*N,q,L]);
     predictions_soft=Y_pred;
     predictions_hard=hardmax(Y_pred);
     if options.generalisationplot
        Y_pred_genplot = reshape(Y_pred_genplot,[ttrial, ttrial*N,q]);
        for t=1:ttrial
            if q>1
                Y_pred_genplot(t,:,:) = hardmax(squeeze(Y_pred_genplot(t,:,:)));
            else
                Y_pred_genplot(t,:,:) = squeeze(Y_pred_genplot(t,:,:))>0;
            end
        end
    end
elseif strcmp(classifier,'LDA')
    X = reshape(X,[ttrial*N,p]);
    [predictions_hard, predictions_soft] = LDApredict(model,repmat(eye(ttrial),N,1),X);
    if q>1
        predictions_soft = exp(predictions_soft - repmat(max(predictions_soft,[],2),1,q));
        predictions_soft = rdiv(predictions_soft,sum(predictions_soft,2));
    end
elseif strcmp(classifier,'KNN')
    if ~isfield(model,'K');model.K=1;end
    predictions_hard = zeros(ttrial,N,q);
    for t=1:ttrial
        candidates = squeeze(model.X_train(t,:,:));
        D=dist(squeeze(X(t,:,:)),candidates');
        for n=1:N
            [dists,inds]=sort(D(n,:));
            if options.K==1
                M=model.Y_train(t,inds(1:options.K),:);
                ind_winner = find(squeeze(M));
                predictions_hard(t,n,ind_winner) = 1;
            else
                Y_pred=squeeze(model.Y_train(t,inds(1:options.K),:));
                M = sum(Y_pred,1);
                [M,inds2] = sort(M,'descend');
                if M(1)>M(2)
                    predictions_hard(t,n,inds2(1)) = 1;
                else %tie break - just take closest point
                    ind_winner = find(squeeze(model.Y_train(t,inds(1),:)));
                    predictions_hard(t,n,inds(1)) = 1;
                end
            end
        end
    end
    predictions_hard = reshape(predictions_hard,[ttrial*N,q]);
    predictions_soft = predictions_hard;
elseif strcmp(classifier,'decisiontree');
    predictions_hard = zeros(ttrial,N,q);
    for t=1:ttrial
        temp = model.decisiontree{t}.predict(squeeze(X(t,:,:)));
        for n=1:N
            predictions_hard(t,n,temp(n))=1;
        end
    end
    predictions_hard = reshape(predictions_hard,[ttrial*N,q]);
    predictions_soft = predictions_hard;
end

%and compute accuracy metrics using hard classification output:
Y = reshape(logical(Y==1),[ttrial*N q]);
predictions_hard=logical(predictions_hard);
true_preds = all(~xor(predictions_hard,Y),2);
acc = mean(true_preds);
acc_t = mean(reshape(true_preds,[ttrial,N]),2);
if options.generalisationplot
    Y_true_genplot = repmat(permute(Ycopy,[4,1,2,3]),[ttrial,1,1,1]);
    Y_pred_genplot = reshape(Y_pred_genplot,[ttrial, ttrial,N,q]);
    if q>1
        accplot = sum(logical(Y_true_genplot) & logical(Y_pred_genplot),4);
    else
        accplot = ~xor(logical(Y_true_genplot),logical(Y_pred_genplot));
    end
    genplot = squeeze(mean(accplot,3));
else
    genplot=[];
end
end

function preds_hard = hardmax(Y_pred)
% assuming multiple binomial only; Y_pred of dimension [NT x q]
if ndims(Y_pred)>2
    error('Wrong dimensions entered for computing predictions');
end
if size(Y_pred,2)>1
    [~,a] = max(Y_pred,[],2);
else
    a = Y_pred>0;
end
preds_hard = zeros(size(Y_pred));
for i=1:length(preds_hard)
    preds_hard(i,a(i))=1;
end

end


function [ T1temp MP2RAGEcorrected] = T1B1correctpackageTFL( B1img,MP2RAGEimg,T1,MP2RAGE,brain,varargin)
% usage
%
% [  T1corr MP2RAGEcorr] = T1B1correctpackage(B1,MP2RAGEimg,T1,MP2RAGE,brain,varargin)
%
% B1 and MP2RAGEimg (and T1) are the nii structures resulting from loading
% the MP2RAGE (MP2RAGEimg, T1) and the result of some B1 mapping technique
%  with load_nii or load_untouch_nii
%
% the variable B1 is compulsory
%
% Only MP2RAGEimg or the T1 have to be loaded (I usually use the MP2RAGEimg)
%
% the variables that are not loaded can be simply left empty []
%
% MP2RAGE  variable contains all the relevant sequence
% information as delailed below
%
% B1 will be given in relative units => 1 if it was correct; values can varie
% from 0-2
%
%     MP2RAGE.B0=7;           % in Tesla
%     MP2RAGE.TR=6;           % MP2RAGE TR in seconds
%     MP2RAGE.TRFLASH=6.7e-3; % TR of the GRE readout
%     MP2RAGE.TIs=[800e-3 2700e-3];% inversion times - time between middle of refocusing pulse and excitatoin of the k-space center encoding
%     MP2RAGE.NZslices=[40 80];% Slices Per Slab * [PartialFourierInSlice-0.5  0.5]
%     MP2RAGE.FlipDegrees=[4 5];% Flip angle of the two readouts in degrees
%
% brain can be an image in the same space as the MP2RAGE and the
% Sa2RAGE that has zeros where there is no need to do any T1/B1 calculation
% (can be a binary mask or not). if left empty the calculation is done
% everywhere
%
% additionally the inversion efficiency of the adiabatic inversion can be
% set as a last optional variable. Ideally it should be 1.
% In the first implementation of the MP2RAGE the inversino efficiency was
% measured to be ~0.96
%
% outputs are:
%  T1corr - T1map corrected for B1 bias
%  MP2RAGEcorr - MP2RAGE image corrected for B1 bias
%
%
% please cite:
% Marques, J.P., Gruetter, R., 2013. New Developments and Applications of the MP2RAGE Sequence - Focusing the Contrast and High Spatial Resolution R1 Mapping. PLoS ONE 8. doi:10.1371/journal.pone.0069294
% Marques, J.P., Kober, T., Krueger, G., van der Zwaag, W., Van de Moortele, P.-F., Gruetter, R., 2010a. MP2RAGE, a self bias-field corrected sequence for improved segmentation and T1-mapping at high field. NeuroImage 49, 1271�1281. doi:10.1016/j.neuroimage.2009.10.002
%

% Check B1 range
b1med = median(prctile(B1img(:),90));

if b1med > 5

     warning(sprintf(['=============== mp2rage::b1correction ==========='...
        '\n B1 data is not in [0-2] range. B1map magnitude will be scaled down.'  ...
        '\n ===========================================================' ...
        ]));

    if b1med > 10 &&  b1med < 500

        B1img = double(B1img)./100;

    elseif b1med>500 && b1med<1500

        B1img = double(B1img)./1000;
    end
end

b1med = median(prctile(B1img(:),90));

if ~(b1med > 0.5) && ~(b1med < 1.5)

    warning(sprintf(['=============== mp2rage::b1correction ==========='...
        '\n B1 data may not be in the required [0-2] range'  ...
        '\n ===========================================================' ...
        ]));

end

if nargin==6

    invEFF=varargin{1};

else

    invEFF=0.96;

end

if isempty(brain)

    if isempty(MP2RAGEimg)

        brain=T1;

        brain.img=ones(size(brain.img));

    else

        brain=MP2RAGEimg;

        brain.img=ones(size(brain.img));

    end;

end;

B1_vector=0.005:0.05:1.9;

T1_vector=0.5:0.05:5.2;

[MP2RAGE.Intensity MP2RAGE.T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);

if isempty(MP2RAGEimg)

    T1.img=double(T1.img)/1000;

    MP2RAGEimg.img=reshape(interp1(MP2RAGE.T1vector,MP2RAGE.Intensity,T1.img(:)),size(B1img));

    MP2RAGEimg.img(isnan(MP2RAGEimg.img))=-0.5;

else

    MP2RAGEimg.img=double(MP2RAGEimg.img)/4095-0.5;

end;

%% now the fun starts

% creates a lookup table of MP2RAGE intensities as a function of B1 and T1

k=0;

for b1val=B1_vector

    k=k+1;

    [Intensity T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,b1val*MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);

    MP2RAGEmatrix(k,:)=interp1(T1vector,Intensity,T1_vector);

end;

k=0;

%% make the matrix  MP2RAGEMatrix into T1_matrix(B1,ratio)

npoints=40;

MP2RAGE_vector=linspace(-0.5,0.5,npoints);

k=0;

for b1val=B1_vector

    k=k+1;

    try

        T1matrix(k,:)=interp1(MP2RAGEmatrix(k,:),T1_vector,MP2RAGE_vector,'pchirp');

    catch

        temp=MP2RAGEmatrix(k,:);

        temp(isnan(temp))=linspace(-0.5-eps,-1,length(find(isnan(temp)==1)));

        temp=interp1(temp,T1_vector,MP2RAGE_vector);

        T1matrix(k,:)=temp;

    end;

end;

%% correcting the estimates of T1 and B1 iteratively

T1temp=MP2RAGEimg;

brain.img(B1img==0)=0;

brain.img(MP2RAGEimg.img==0)=0;

T1temp.img(brain.img==0)=0;

T1temp.img(brain.img==1)=0;

B1img(brain.img==0)=0;

temp=squeeze(T1temp.img(:,end/2,:));

T1temp.img(brain.img~=0)=interp2(MP2RAGE_vector,B1_vector,T1matrix,MP2RAGEimg.img(brain.img~=0),B1img(brain.img~=0));

T1temp.img(isnan(T1temp.img))=4;

temp2=squeeze(T1temp.img(:,end/2,:));

%% creates an MP2RAGEcorrected image and puts both the B1 and T1 in the ms scale

[MP2RAGE.Intensity MP2RAGE.T1vector ]=MP2RAGE_lookuptable(2,MP2RAGE.TR,MP2RAGE.TIs,MP2RAGE.FlipDegrees,MP2RAGE.NZslices,MP2RAGE.TRFLASH,'normal',invEFF);

MP2RAGEcorrected=MP2RAGEimg;

MP2RAGEcorrected.img=reshape(interp1(MP2RAGE.T1vector,MP2RAGE.Intensity,T1temp.img(:)),size(T1temp.img));

MP2RAGEcorrected.img(isnan(MP2RAGEcorrected.img))=-0.5;

MP2RAGEcorrected.img=round(4095*(MP2RAGEcorrected.img+0.5));

%T1temp.img=(T1temp.img)*1000;

end


function a = permute(a,order)
%PERMUTE      Permute array dimensions
%
%Implements the Matlab function "permute", similar syntax and semantics
%

% written  09/17/08     S.M. Rump
%

  if isa(a,'intval')
    if a.complex
      a.mid = permute(a.mid,order);
      if ~isequal(a.rad,0)
        a.rad = permute(a.rad,order);
      end
    else
      a.inf = permute(a.inf,order);
      a.sup = permute(a.sup,order);
    end
  else
    error('invalid call of permute for intervals')
  end


function ct3(im,w)
%function ct3(im,w)
%
%Allows simple browsing of a CT scan using the mousewheel.  Assumes a grid
%spacing ratio of 3:1 axial thickness:radial thickness for display purposes
%
%Usage: ct3(im) will open Figures 1,2, and 3 and use imshow() to display the
%       CT dataset contained in "im" in all 3 orthogonal planes (sagittal,
%       coronal, axial).  Scrolling the mousewheel will move to the
%       next/previous slice in the active figure window.  Clicking the mouse
%       will print the current slice number of all 3 figure windows in
%       the console.
%
%input:
%   -im: 3D array of grayscale values.  This function assumes that the
%        1st and 2nd dimensions of the array contain the radial (or
%        sagittal/coronal) data, and the 3rd dimension of "im" contains
%        axial data.  This function also assumes a voxel size ratio of
%        1:1:3.
%
%   -w : (optional) window to use for display.  Default=[-140 160]
%        1x2 numerical array that contains the range of values of interest
%        to be displayed using ct3
%        note - use Matlab built-in function "imcontrast" (Image Proc Toolbox)
%        or plot the image data using hist() to easily determine the proper
%        window for your dataset
%
%output:
%        none
%
%ex:
%     ct3(im)
%     ct3(im, [-140 160])

%reverse the z direction
im=im(:,:,end:-1:1);

f1=figure(1);
f2=figure(2);
f3=figure(3);

slice1=floor(size(im,1)/2);
slice2=floor(size(im,2)/2);
slice3=floor(size(im,3)/2);

mn=1;

mx1=size(im,1);
mx2=size(im,2);
mx3=size(im,3);

if nargin < 2
    w=[-140 160];
    %w=[766 961];
end

%% INITALIZE THE FIGURE WINDOWS

figure(3)
i3=imshow(im(:,:,slice3),w, 'parent',gca);
set(gca,'position',[0 0 1 1])
hold on
p311=plot([0 mx2/10],[slice1 slice1],'g', 'linewidth',2);
p312=plot([mx2*9/10 mx2],[slice1 slice1],'g', 'linewidth',2);
p321=plot([slice2 slice2],[0 mx1/10],'g', 'linewidth',2);
p322=plot([slice2 slice2],[mx1*9/10 mx1],'g', 'linewidth',2);
hold off

figure(1)
i1=imshow(permute(im(slice1,:,:),[3 2 1]),w,'parent',gca);
set(gca,'position',[0 0 1 1])
set(gca,'DataAspectRatio',[3 1 1])
%set(gcf, 'position',(get(f3,'position')))
hold on
p131=plot([0 mx2/10],[slice3 slice3],'g', 'linewidth',2);
p132=plot([mx2*9/10 mx2],[slice3 slice3],'g', 'linewidth',2);
p121=plot([slice2 slice2],[0 mx3/10],'g', 'linewidth',2);
p122=plot([slice2 slice2],[mx3*9/10 mx3],'g', 'linewidth',2);
hold off

figure(2)
i2=imshow(permute(im(:,slice2,:),[3 1 2]),w,'parent',gca);
set(gca,'position',[0 0 1 1])
hold on
p231=plot([0 mx1/10],[slice3 slice3],'g', 'linewidth',2);
p232=plot([mx1*9/10 mx1],[slice3 slice3],'g', 'linewidth',2);
p211=plot([slice1 slice1],[0 mx3/10],'g', 'linewidth',2);
p212=plot([slice1 slice1],[mx3*9/10 mx3],'g', 'linewidth',2);
set(gca,'DataAspectRatio',[3 1 1])
%set(gcf, 'position',(get(f3,'position')))
hold off

set(f1, 'WindowScrollWheelFcn', @wheel)
set(f1, 'WindowButtonDownFcn', @click)
set(f2, 'WindowScrollWheelFcn', @wheel)
set(f2, 'WindowButtonDownFcn', @click)
set(f3, 'WindowScrollWheelFcn', @wheel)
set(f3, 'WindowButtonDownFcn', @click)

%% CAPTURE MOUSEWHEEL EVENTS
    function wheel(src, evnt)
        cur=gcf;
        switch cur
            case 1
                if evnt.VerticalScrollCount > 0
                    slice1=slice1+1;
                else
                    slice1=slice1-1;
                end
                slice1=re_eval1(slice1);
            case 2
                if evnt.VerticalScrollCount > 0
                    slice2=slice2-1;
                else
                    slice2=slice2+1;
                end
                slice2=re_eval2(slice2);
            case 3
                if evnt.VerticalScrollCount > 0
                    slice3=slice3+1;
                else
                    slice3=slice3-1;
                end
                slice3=re_eval3(slice3);
            otherwise
                %do nothing
        end
    end

%% REDRAW FIGURES
    function slice1=re_eval1(slice1)
        if slice1>mx1
            slice1=mx1;
        elseif slice1<mn
            slice1=mn;
        else
            %imshow(flipud(imresize(squeeze(im(slice1,:,:)), size(squeeze(im(slice1,:,:))).*[1 3])'),w,'parent',gca)
            set(i1,'CData',permute(im(slice1,:,:),[3 2 1]))
        end
        do_lines
    end
    function slice2=re_eval2(slice2)
        if slice2>mx2
            slice2=mx2;
        elseif slice2<mn
            slice2=mn;
        else
            %imshow(flipud(imresize(squeeze(im(:,slice2,:)), size(squeeze(im(:,slice2,:))).*[1 3])'),w,'parent',gca)
            set(i2,'CData',permute(im(:,slice2,:),[3 1 2]))
        end
        do_lines
    end
    function slice3=re_eval3(slice3)
        if slice3>mx3
            slice3=mx3;
        elseif slice3<mn
            slice3=mn;
        else
            %imshow(im(:,:,slice3),w, 'parent',gca)
            set(i3,'CData',im(:,:,slice3))
        end
        do_lines
    end
%% CAPTURE MOUSE CLICKS
    function click(src,evnt)
        %account for reversal of z dimension
        disp(num2str([slice1 slice2 (mx3+1-slice3)]))

    end

%% REDRAW MARKER LINES
    function do_lines
        set(p131,'YData',[slice3 slice3]);
        set(p121,'XData',[slice2 slice2]);
        set(p132,'YData',[slice3 slice3]);
        set(p122,'XData',[slice2 slice2]);

        set(p231,'YData',[slice3 slice3]);
        set(p211,'XData',[slice1 slice1]);
        set(p232,'YData',[slice3 slice3]);
        set(p212,'XData',[slice1 slice1]);

        set(p311,'YData',[slice1 slice1]);
        set(p321,'XData',[slice2 slice2]);
        set(p312,'YData',[slice1 slice1]);
        set(p322,'XData',[slice2 slice2]);
    end

end


% The COBRAToolbox: testSampleCbModelRHMC.m
%
% Purpose:
%     - tests the sampleCbModel function using RHMC using the E. coli Core Model
%

% initialize the test
fileDir = fileparts(which('testSampleCbModelRHMC'));
models = {};
models{1} = getDistributedModel('ecoli_core_model.mat');
models{2} = getDistributedModel('Acidaminococcus_sp_D21.mat');
load('Recon1.0model.mat', 'Recon1')
models{3} = Recon1;
try
   S = load('iDopaNeuro1.mat');
   names = fieldnames(S);
   models{4} = S.(names{1});
end

fprintf('   Testing sampleCbModel with RHMC ... \n' );

for i = 1:length(models)
   model = models{i};
   n = length(model.lb);
   model.vMean = randn(n,1);
   model.vCov = rand(n,1);
   options.nPointsReturned = 1000;

   for j = 1:3
      [modelSampling, samples, volume] = sampleCbModel(model, '', 'RHMC', options);
      modelSampling.samples = samples;
      ESS = min(effective_sample_size(samples));
      pVal = distribution_test(modelSampling);
      okay = (ESS > 100 && pVal > 0.01 && pVal < 0.99);
      if okay, break; end
   end
   assert(okay);
end

fprintf('Done.\n');


function [inflMap, colXCoord, rowYCoord, colDividerXCoord, rowDividerYCoord, rowLeafPositions] = getLSInfluenceMapFactorEx(LS,leak,beamIndex)
%"getLSInfluenceMap"
%   Gets an image of the influence generated by the beam described in LS.
%   Use getDICOMLeafPositions to generate LS.
%
%JRA&KZ 02/8/05
%
%Usage:
%   function inflMap = getLSInfluenceMap(LS);
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Maximum precision of leaf position, in mm.
precision = .1;

%Get x max, min and round to precision value.
% xMax = ceil(max(vertcat(LS.xLimits{1}),[],1) / precision) * precision;
% xMin = floor(min(vertcat(LS.xLimits{1}),[],1) / precision) * precision;
% fieldSize.x = max(xMax) - min(xMin);
% fieldLim.x  = [max(xMax) min(xMin)];

%Siemens no X jaws exist
if ~isfield(LS,'xLimits')
    xMax = ceil(max(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;
    xMin = floor(min(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;
    LS.xLimits{1}(1) = xMin;
    LS.xLimits{1}(2) = xMax;
end

xMax = ceil(max(vertcat(LS.xLimits{:}),[],1) / precision) * precision;
xMin = floor(min(vertcat(LS.xLimits{:}),[],1) / precision) * precision;
fieldSize.x = max(xMax) - min(xMin);
fieldLim.x  = [max(xMax) min(xMin)];

yMax = ceil(max(vertcat(LS.yLimits{:}),[],1) / precision) * precision;
yMin = floor(min(vertcat(LS.yLimits{:}),[],1) / precision) * precision;
fieldSize.y = max(yMax) - min(yMin);
fieldLim.y  = [max(yMax) min(yMin)];

yRes = precision;
nyElements = ceil(fieldSize.y/yRes);
xRes = precision;
nxElements = ceil(fieldSize.x/xRes);

inflMap=zeros(nyElements, nxElements);
colDividerXCoord = linspace(fieldLim.x(2), fieldLim.x(1), nxElements+1);
rowDividerYCoord = linspace(fieldLim.y(2), fieldLim.y(1), nyElements+1);

if isfield(LS, 'yLeafPositions')
    rowLeafPositions = round(interp1(rowDividerYCoord, 1:nyElements+1, LS.yLeafPositions,'linear', 'extrap'));
    rowLeafPositions = clip(rowLeafPositions, 1, nyElements+1, 'limits');
    leafBoundariesToKeep = [diff(rowLeafPositions)>0;logical(1)];
    rowLeafPositions = rowLeafPositions(leafBoundariesToKeep);
    leavesToKeep = leafBoundariesToKeep(1:end-1);
else
    %LS.xLeafPositions{1} = [xMin xMax-precision];
    LS.xLeafPositions{1} = [xMin xMax];
    LS.meterSetWeight = {1};
    rowLeafPositions = [1 nyElements+1];
    leavesToKeep = 1;
end

if length(LS.meterSetWeight) == 1
    doses = LS.meterSetWeight{:};
else
    doses = [0 diff([LS.meterSetWeight{:}])];
end

h = waitbar(0,['Generating Fluence Map For Beam ',num2str(beamIndex)]);

for i=1:length(LS.xLeafPositions)

    nLeaves = length(LS.xLeafPositions{i})/2;

    if length(LS.xLimits) > 1
        jpL = LS.xLimits{i}(1);
        jpR = LS.xLimits{i}(2);
    else
        jpL = LS.xLimits{1}(1);
        jpR = LS.xLimits{1}(2);
    end

    lpL = LS.xLeafPositions{i}(1:nLeaves);
    lpR = LS.xLeafPositions{i}(nLeaves+1:end);
    lpLK = lpL(leavesToKeep);
    lpRK = lpR(leavesToKeep);
    lpLCols = interp1(colDividerXCoord, 1:nxElements+1, lpLK, 'linear', 'extrap');
    lpRCols = interp1(colDividerXCoord, 1:nxElements+1, lpRK, 'linear', 'extrap');

    %Column divider positions of jaws.
    jpLCol = interp1(colDividerXCoord, 1:nxElements+1, jpL, 'linear', 'extrap');
    jpRCol = interp1(colDividerXCoord, 1:nxElements+1, jpR, 'linear', 'extrap');

    lpLCols = clip(lpLCols, jpLCol, jpRCol, 'limits');
    lpRCols = clip(lpRCols, jpLCol, jpRCol, 'limits');

    lpLCols = round(lpLCols);
    lpRCols = round(lpRCols);

    %head scatter radiation parametrs for varian
    a2 = 0.078;
    beta = 1.79;
    lambda = 7.69;

    for j=1:length(lpLCols)
        %HCF from output ratio for MLC fields Zhu, MedPhys
        YMLC = rowDividerYCoord(rowLeafPositions(j)) + abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))))/2;
        YMLC = YMLC/10;
        sizeLeaf = abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))));
        sizeLeaf = sizeLeaf/10;
        HCF_UP = 1 + a2*(erf(2*lpLK(j)*beta/(10*lambda)) +  erf(2*lpRK(j)*beta/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;
        HCF_Down = 1 + a2*(erf(2*jpL/(10*lambda)) +  erf(2*jpR/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;
        HCF = HCF_UP/HCF_Down;
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) + HCF*doses(i);
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) + leak*doses(i);
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) + leak*doses(i);
    end

    waitbar(i/length(LS.xLeafPositions));
end
close(h);
colXCoord = colDividerXCoord(1:end-1) + precision/2;
rowYCoord = rowDividerYCoord(1:end-1) + precision/2;


function labeled_output = PTKWatershedMeyerFromStartingPointsMatlab(image, starting_labels)
    % PTKWatershedMeyerFromStartingPointsMatlab. Implementation of Meyer flooding algorithm.
    %
    %     This is a Matlab-only implementation of the mex function
    %     PTKWatershedMeyerFromStartingPoints. Use the mex function is possible
    %     as this is faster.
    %
    %     Inputs
    %     ------
    %
    %     image = 16-bit ingeter image (int16). The watershed regions grow according to the minima of these points
    %
    %     starting_labels - 8-bit integer (int8). Labels of starting points for the watershed
    %
    %     labeled_output - 8-bit integer (int8). Labels of the image assigned to
    %                       watershed regions. Watershed points are given the label -2
    %
    %     The watershed starts from the positive-valued labels in
    %     starting_labels and grows out into the zero-valued points, with the
    %     result returned in labeled_output. Regions starting from points with
    %     the same label can merge together. Negative labels are treated as
    %     fixed barriers. The do not grow and other regions cannot grow into
    %     them.
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    disp('PTKWatershedMeyerFromStartingPointsMatlab');
    warning('PTKWatershedMeyerFromStartingPointsMatlab:MatlabVersion', 'This is a slow Matlab implementation of the mex function PTKWatershedMeyerFromStartingPoints. For improved performance, use PTKWatershedMeyerFromStartingPoints instead.');

    % Check inputs
    if (nargin ~= 2)
        error('Two inputs are required: the image and a label matrix of the staring points.');
    end

    if (nargout > 1)
         error('PTKWatershedMeyerFromStartingPointsMatlab produces one output but you have requested more.');
    end

    % Get the input images
    intensity_matrix = image;
    starting_indices = starting_labels;

    if ~isequal(size(image), size(starting_labels));
        error('The two input matrices must be of the same dimensions.');
    end

    intensity_data = intensity_matrix;
    startingpoints_data = starting_indices;

    % Our set of points uses a custom comparison function so it is automatically sorted by image intensity
    % but is guaranteed uniqueness in the voxel indices
    points_to_do = [];
    intensity_store = [];

    image_size = size(image);
    size_i = image_size(1);
    size_j = image_size(2);
    size_k = image_size(3);
    number_of_points = size_i*size_j*size_k;

    % Linear index offsets to nearest neighbours
    offsets = [1, -1, size_i, -size_i, size_i*size_j, -size_i*size_j];

    iteration_number = 0;
    max_iterations = 1000000000;

    % Initialise the output data
    output_data = startingpoints_data;

    % Populate the initial set of points
    initial_points = find(startingpoints_data > 0);
    for index = 1 : length(initial_points)
        point_index = initial_points(index);

        neighbours = point_index + offsets;
        neighbours = neighbours((neighbours > 0) & (neighbours <= number_of_points) & (output_data(neighbours) == 0));
        points_to_do = [points_to_do, neighbours];
        intensity_store = [intensity_store, intensity_data(neighbours)];
    end

    total_points = sum(starting_labels(:) == 0);

    % Iterate over remaining points
    while ~isempty(points_to_do)

        if (mod(iteration_number, 10000) == 0)
            points_left = sum(output_data(:) == 0);
            percentage_done = 100*(total_points - points_left)/total_points;
            disp(['Percentage done:' num2str(percentage_done)]);
        end

        [~, min_index] = min(intensity_store);
        point_index = points_to_do(min_index);
        points_to_do(min_index) = [];
        intensity_store(min_index) = [];

        label = output_data(point_index);

        % The point may already have been set
        if (label == 0)
            % Check nearest neighbours of this point
            neighbours = point_index + offsets;
            neighbours = neighbours((neighbours > 0) & (neighbours <= number_of_points));

            % Find label values of neighbours
            neighbour_labels = output_data(neighbours);

            % Ignore unset, watershed and boundary points
            neighbour_labels = unique(neighbour_labels(neighbour_labels > 0));

            % No labeled neighbour - this case should not be possible and
            % indidates a program error
            if isempty(neighbour_labels)
                error('No neighbouring point found - this case should never occur.');
            end

            if (numel(neighbour_labels) > 1)
                % More than one type of neighbouring label - mark as watershed point
                output_data(point_index) = -2;
            else

                % One neighbouring label found - mark this point
                output_data(point_index) = neighbour_labels;

                % Add neighbours to points-to-do
                neighbours = neighbours(output_data(neighbours) == 0);
                points_to_do = [points_to_do, neighbours];
                intensity_store = [intensity_store, intensity_data(neighbours)];
            end
        end

        iteration_number = iteration_number + 1;
        if (iteration_number > max_iterations)
            error('Error: Max Iteration number exceeded');
        end
    end
    labeled_output = output_data;
    disp(' - Completed PTKWatershedMeyerFromStartingPointsMatlab');
end


function SimCurveResults = SIRFSE_SimCurve(Fit, Prot, FitOpt, interpolate )
if ~exist('interpolate','var'), interpolate=1; end

FitOpt.R1map = 0;
FitOpt.R1reqR1f = 0;

xFit = [Fit.F, Fit.kr, Fit.R1f, Fit.R1r, -1*Fit.Sf, Fit.Sr, Fit.M0f];
Fit.table = xFit';

if (all(Prot.td == Prot.td(1))) && interpolate
    Prot.ti = sort(Prot.ti);
    Fit.ti = (0.5*Prot.ti(1):0.001:1.5*Prot.ti(end))';
    Fit.td = Prot.td(1)*ones(length(Fit.ti),1);
    Fit.curve = SIRFSE_fun(xFit,[Fit.ti, Fit.td], FitOpt);
else
    [Prot.ti, order] = sort(Prot.ti);
    Fit.ti = Prot.ti;
    Fit.td = Prot.td(order);
    Fit.curve(order,1) = SIRFSE_fun(xFit,[Fit.ti, Fit.td], FitOpt);
end

SimCurveResults = Fit;


% ----- Global evaluation parameters -----
% Range of binning factors used for this evaluation.
binningFactors = [2, 3, 4];
% Range of compression levels (index 1 means uncoded; indices 2-5 mean
% coded with the corresponding QP setting using H.265/HEVC coder.
compressions   = [NaN, 10, 20, 30, 40];
% Range of number of frames for SR at the different binning factors.
numberOfFrames = [5, ...    % Number of frames for binning factor 2
                  11, ...   % Number of frames for binning factor 3
                  17];      % Number of frames for binning factor 4
% Index of the first reference frame for sliding window processing.
startReferenceFrame = 9;

% ----- Settings considered for this evaluation -----
% This is the index of the SR method that is evaluated.
sr_method           = 0:length(SRMethods);
% This is the index of the binning factor that is evaluated.
binning_val         = 1:3;
% This is the index of the compression setting.
compress_val        = 1;
% This is the index that indicates the number of input frames.
numberOfFrames_val  = 1;
% This is the index of the scene according to datasets.mat.
scenes_val          = 1:14;
% This is the index of the sliding window that is evaluated.
sliding_val         = 1;


function [ solutionsValid ] = validateOptForceSol(model,posOptForceSets,typeRegOptForceSets, target)
relreacs = unique(model.rxns(posOptForceSets(:)));
[minRelFluxes,maxRelFluxes] = fluxVariability(model,0,'max',relreacs);

solutionsValid = true;
sol = optimizeCbModel(model);
tempmodel = model;
tempmodel.lb(find(model.c)) = sol.x(find(model.c));
tempmodel.c = double(ismember(model.rxns,target));
tempmodel.osenseStr = 'min';
sol = optimizeCbModel(tempmodel);
ores = sol.x(ismember(model.rxns,target));

%These changes are extreme, and they should only be used for the actual
%test Case. In general they might not be applicable.
changes = {'knockout',@(cmodel,treac) changeRxnBounds(cmodel,treac,0,'b');...
           'upregulation',@(cmodel,treac) changeRxnBounds(cmodel,treac,min(sol.x(ismember(cmodel.rxns,treac))+100,maxRelFluxes(ismember(relreacs,treac))),'l');...
           'downregulation',@(cmodel,treac) changeRxnBounds(cmodel,treac,max(sol.x(ismember(cmodel.rxns,treac))-100,minRelFluxes(ismember(relreacs,treac))),'u')};
for i = 1:size(posOptForceSets,1)
    cmodel = model;
    for j = 1:size(posOptForceSets,2)
        if posOptForceSets(i,j) > 0
            cfunc = changes{ismember(changes(:,1),typeRegOptForceSets{i,j}),2};
            cmodel = cfunc(cmodel,cmodel.rxns(posOptForceSets(i,j)));
        end
    end
    csol = optimizeCbModel(cmodel);
    cmodel.lb(find(cmodel.c)) = csol.x(find(cmodel.c));
    cmodel.c = double(ismember(model.rxns,target));
    cmodel.osenseStr = 'min';
    csol = optimizeCbModel(cmodel);
    if ~(csol.x(ismember(model.rxns,target)) > ores)
        solutionsValid = false;
        return
    end
end


function o = spget(options,name,default,flag)
% SPGET   Get sparse interpolation OPTIONS parameters
%   VAL = SPGET(OPTIONS,'NAME') extracts the value of the named property
%   from the sparse grid options structure OPTIONS, returning an
%   empty matrix if the property value is not specified in
%   OPTIONS. It is sufficient to type only the leading characters
%   that uniquely identify the property. Case is ignored for
%   property names. [] is a valid OPTIONS argument.
%
%   VAL = SPGET(OPTIONS,'NAME',DEFAULT) extracts the named property as
%   above, but returns VAL = DEFAULT if the named property is not
%   specified in OPTIONS. For example
%
%       val = spget(opts,'RelTol',1e-2);
%
%   returns val = 1e-2 if the RelTol property is not specified in opts.
%
%   See also SPSET, SPINTERP, SPVALS.

% Author : Andreas Klimke, Universitaet Stuttgart
% Version: 1.5
% Date   : March 1, 2006

% Change log:
% V1.0   : September 23, 2003
%          Initial version
% V1.1   : January 27, 2004
%          Added "KeepGrid" and "KeepFunctionValues" options for
%          later use.
% V1.2   : Apr 22, 2004
%          Added options for dimension-adaptive sparse grids.
% V1.3   : Feb 22, 2005
%          Added handling of sparse sets of indices (useful for
%          high-dimensional interpolation)
% V1.4   : Feb 2, 2006
%          Added droptol property
% V1.5   : March 1, 2006
%          Added EnableFFT feature

% Note: SPGET is similar in syntax and code to the options
% handling with ODEGET and ODESET of the MATLAB ODE suite by Marc
% Reichelt and Lawrence Shampine.

% ------------------------------------------------------------
% Sparse Grid Interpolation Toolbox
% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart
% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.
% See LICENSE.txt for license.
% email: klimkeas@ians.uni-stuttgart.de
% web  : http://www.ians.uni-stuttgart.de/spinterp
% ------------------------------------------------------------

% undocumented usage for fast access with no error checking
if (nargin == 4) && isequal(flag,'fast')
   o = getknownfield(options,name,default);
   return
end

if nargin < 2
  error('Not enough input arguments.');
end
if nargin < 3
  default = [];
end

if ~isempty(options) && ~isa(options,'struct')
  error('First argument must be an options structure created with SPSET.');
end

if isempty(options)
  o = default;
  return;
end

Names = {'GridType', 'RelTol', 'AbsTol', 'Vectorized', 'MinDepth', ...
				 'MaxDepth', 'VariablePositions', 'NumberOfOutputs', ...
				 'PrevResults', 'FunctionArgType', 'KeepFunctionValues', ...
				 'KeepGrid' 'DimensionAdaptive', 'MinPoints', ...
				 'MaxPoints', 'DimadaptDegree', 'DegreeStrategy', ...
				 'SparseIndices', 'DropTol', 'EnableDCT'};

m = length(Names);
names = cell(m,1);
for k = 1:m
	names{k} = lower(Names{k});
end

lowName = lower(name);
matched = strmatch(lowName,names);
if isempty(matched)               % if no matches
	msg = sprintf(['Unrecognized property name ''%s''.  ' ...
    'See SPSET for possibilities.'], name);
  error(msg);
elseif length(matched) > 1
	msg = sprintf('Ambiguous property name ''%s'' ', name);
	msg = [msg '(' Names{matched}];
	for k = j(2:length(matched))'
		msg = [msg ', ' Names{matched}];
	end
	msg = sprintf('%s).', msg);
	error(msg);
end

if any(strcmp(fieldnames(options),Names{matched}))
  o = options.(Names{matched});
  if isempty(o)
    o = default;
  end
else
  o = default;
end

% -------------------------------------------------------------------
function v = getknownfield(s, f, d)
% GETKNOWNFIELD   Get field f from struct s, or else yield default
% d.

if isfield(s,f)   % s could be empty.
  v = subsref(s, struct('type','.','subs',f));
  if isempty(v)
    v = d;
  end
else
  v = d;
end