function makeplot(out,varargin)

%MAKEPLOT makes plots for the main functions. These figures can also be obtained
% by setting 'plots = 1' in those functions.
%
% Required input:
%  out = a structure containing the output of one of the following classes:
%        MCDCOV, LS, LTS, MLR, MCDREG, CPCA,CPCR, CSIMPLS, RAPCA, ROBPCA,
%        RPCR, RSIMPLS, CDA, RDA
%
% Optional input:
%  nameplot  :  0         : menu of plots     (default = 0)
%              'all'      : all possible plots
%              'scree'    : scree plot
%              'pcadiag'  : Score outlier map
%              'regdiag'  : Regression outlier map
%              '3ddiag'   : 3D Regression outlier map
%              'robdist'  : A plot of the robust distances
%              'qqmcd'    : A qq-plot of the robust distances versus the quantiles of the chi-squared distribution
%              'dd'       : A DD-plot: Robust distances versus Mahalanobis distances
%              'ellipse'  : A tolerance ellipse
%              'resfit'   : Standardized LTS Residuals versus fitted values
%              'resindex' : Standardized LTS Residuals versus index
%              'qqlts'    : Normal QQ-plot of the LTS residuals
%              'scatter'  : Scatterplot with LTS line
%              'da'       : Tolerance ellipses of a discrimant analysis
%              'simca'    : Scatterplot with boundaries defined by the number of PC's from a simca method
%  labod   : number of points to be identified in score plots
%            with largest orthogonal distance.
%  labsd   : number of points to be identified in score and regression plots
%            with largest score distance.
%  labresd : number of points to be identified in regression plots
%            with largest residual distance.
%  labmcd  : number of points to be identified in MCD plots
%            with the largest robust distance.
%  lablts  : number of points to be identified in LTS plots
%            with the largest absolute standardized residual.
%  classic : In case of a robust analysis, classic can be set to 0 to avoid classical plots (default).
%            If set to one, the inputargument 'out' must contain a field called 'classic' which is a structure.
%
% I/O: makeplot(out,'nameplot',0,'labsd',3,'labod',3,'labresd',3,'classic',0)
%  The user should only give the input arguments that have to change their default value.
%  The name of the input arguments needs to be followed by their value. The order of
%  the input arguments is of no importance.
%
% Example: outrpcr=rpcr(x,y,'plots',0,'classic',1);
%          makeplot(outrpcr,'labsd',5, 'classic',1)
%          makeplot(outrpcr,'nameplot','scree')
%
%          outmcd=mcdcov(x);
%          makeplot(outmcd,'labmcd',6)
%          makeplot(outmcd,'labmcd',4,'nameplot','dd')
%
%          outls=libra_ols(x,y);
%          makeplot(outls)
%
% This function is part of the Matlab Library for Robust Analysis (LIBRA),
% available at:
%              www.wis.kuleuven.ac.be/stat/robust.html
%
% Written by Sabine Verboven  09/04/2003
% Last Updated : 29/01/2008
%
% Uses functions:  screeplot, scorediagplot, regresdiagplot,
%                  regresdiagplot3d, plotnumbers, plotnumbers3d,
%                  distplot, chiqqplot, ddplot, ellipsplot, residualplot,
%                  normqqplot, lsscatter, menureg, menuscoreg,
%                  menupls, menucov, menuls,menuda, menusimca
%

%INTITIALISATION%
if isstruct(out)
    innames=fieldnames(out);
    if strmatch('class',innames,'exact')
        attrib=out.class;
    else
        error('The method had no class identifier.')
    end
    if strmatch('classic',innames,'exact')
        classic=out.classic;
    elseif ismember(attrib,{'CPCA','CPCR','CSIMPLS','MLR','CDA','LS','CSIMCA'})
        classic= 1;
    else
        classic=0;
    end
else
    error('The first inputargument is not a structure.')
end
counter=1;
default=struct('nameplot',0,'labsd',3,'labod',3,'labresd',3,'labmcd',3,'lablts',3,'classic',1);
list=fieldnames(default);
options=default;
IN=length(list);
i=1;
%
if nargin>1
    %
    %placing inputfields in array of strings
    %
    for j=1:nargin-1
        if rem(j,2)~=0
            chklist{i}=varargin{j};
            i=i+1;
        end
    end
    %
    %Checking which default parameters have to be changed
    % and keep them in the structure 'options'.
    %
    while counter<=IN
        index=strmatch(list(counter,:),chklist,'exact');
        if ~isempty(index) %in case of similarity
            for j=1:nargin-2 %searching the index of the accompanying field
                if rem(j,2)~=0 %fieldnames are placed on odd index
                    if strcmp(chklist{index},varargin{j})
                        I=j;
                    end
                end
            end
            options=setfield(options,chklist{index},varargin{I+1});
            index=[];
        end
        counter=counter+1;
    end
    choice=options.nameplot;
    if choice~=0
        ask=0;
    else
        ask=1; %menu of plots
    end
    labsd=options.labsd;
    labod=options.labod;
    labresd=options.labresd;
    labmcd=options.labmcd;
    lablts=options.lablts;
    classicplots=options.classic;
    if ~isstruct(classic) & options.classic==1
        mess=sprintf(['The classical output is not available. Only robust plots will be shown.\n',...
                'Please rerun the preceeding analysis with the option ''classic'' set to 1',...
              '\n if the classical plots are required.']);
        disp(mess)
        classicplots=0;
    end
else
    ask=1; %menu of plots
    choice=0;
    labsd=3;
    labod=3;
    labresd=3;
    labmcd=3;
    lablts=3;
    if ~isstruct(classic) & options.classic==1
       % mess=sprintf(['The classical output is not available. Only robust plots will be shown.\n',...
         %       'Please rerun the preceeding analysis with the option ''classic'' set to 1',...
           %     '\n if the classical plots are required.']);
        %disp(mess)
        classicplots=0;
    else
        classicplots=1;
    end
end

%to initialize the correct menu of plots
exitno=0;
switch attrib
case 'CPCA'
    exitno=4;
    if ismember({char(choice)},{'regdiag','3ddiag','robdist','qqmcd','dd','ellipse','resfit','resindex','qqlts','diag','scatter',...
                'da','simca'})
         error('That kind of plot is not available for this method.')
    end
case 'CPCR'
    exitno=6;
    if ismember({char(choice)},{'robdist','qqmcd','dd','ellipse','resfit','resindex','qqlts','diag','scatter','da','simca'})
         error('That kind of plot is not available for this method.')
    end
case 'LS'
    exitno=7;
     if ismember({char(choice)},{'scree','pcadiag','3ddiag','robdist','qqmcd','dd','ellipse','simca','da'})
         error('That kind of plot is not available for this method.')
    end
case 'MCDREG'
    exitno=3;
     if ismember({char(choice)},{'scree','pcadiag','3ddiag','robdist','qqmcd','dd','ellipse',...
             'resfit','resindex','qqlts','diag','scatter','da','simca'})
         error('That kind of plot is not available for this method.')
    end
case 'MLR'
    exitno=3;
     if ismember({char(choice)},{'scree','pcadiag','3ddiag','robdist','qqmcd','dd','ellipse',...
             'resfit','resindex','qqlts','diag','scatter','da','simca'})
         error('That kind of plot is not available for this method.')
    end
case 'LTS'
    exitno=7;
    if ismember({char(choice)},{'scree','pcadiag','3ddiag',...
            'robdist','qqmcd','dd','ellipse','da','simca'})
         error('That kind of plot is not available for this method.')
    end
    if ~isfield(out,'rd')
        error('Please rerun the LTS-regression again with the option plots equal to 1.')
    end
case {'RAPCA','ROBPCA'}
    exitno=4;
   if ismember({char(choice)},{'regdiag','3ddiag','robdist','qqmcd','dd','ellipse','resfit',...
           'resindex','qqlts','diag','scatter','da','simca'})
        error('That kind of plot is not available for this method.')
   end
case 'RPCR'
      exitno=6;
      if ismember({char(choice)},{'robdist','qqmcd','dd','ellipse','resfit','resindex','qqlts','diag','scatter',...
              'da','simca'})
         error('That kind of plot is not available for this method.')
    end
case {'RSIMPLS','CSIMPLS'}
    exitno=5;
     if ismember({char(choice)},{'scree','robdist','qqmcd','dd','ellipse','resfit','resindex','qqlts','diag','scatter',...
             'da','simca'})
         error('That kind of plot is not available for this method.')
    end
case 'MCDCOV'
    if ismember({char(choice)},{'scree','pcadiag','regdiag','3ddiag','resfit','resindex','qqlts','diag','scatter',...
                'da','simca'})
         error('That kind of plot is not available for this method.')
    end
    exitno=6;
case {'RDA','CDA'}
    exitno=3;
    if ismember({char(choice)},{'scree','pcadiag','3ddiag','robdist','qqmcd','dd','ellipse',...
             'resfit','resindex','qqlts','diag','scatter','regdiag','simca'})
        error('That kind of plot is not available for this method.')
    end
    if size(out.center,2)>2
        disp('Warning: Tolerance ellipses are only drawn for two-dimensional data sets.')
        return
    end
case {'CSIMCA','RSIMCA'}
    exitno=3;
    if ismember({char(choice)},{'scree','pcadiag','3ddiag','robdist','qqmcd','dd','ellipse',...
             'resfit','resindex','qqlts','diag','scatter','regdiag','da'})
        error('That kind of plot is not available for this method.')
    end
    if size(out.pca{1}.P,1) > 3
        disp('Warning: The dimension of the dataset is larger than 3.')
        return
    end
end
if exitno==0
    error(['Your attribute identifier must be one of the following names:',...
            'CPCA, RAPCA, ROBPCA, CPCR, RPCR, LS, LTS, MCDREG, RSIMPLS, CSIMPLS, MCDCOV, CDA,RDA,CSIMCA,RSIMCA'])
end

%plotting what is asked for
if ask==0
    whichplot(out,choice,attrib,exitno,labsd,labod,labresd,labmcd,lablts,classic,classicplots)
else
    %make menu of plots
    while (choice~=exitno)
        switch attrib
            case {'CPCA','ROBPCA','RAPCA'}
                choice=menuscore(out,attrib,exitno,labsd,labod,classic,classicplots);
            case {'MCDREG','MLR'}
                choice=menureg(out,attrib,exitno,labsd,labresd,classic,classicplots);
            case {'COV','MCDCOV'}
                choice=menucov(out,attrib,exitno,labmcd,classic,classicplots);
            case {'RSIMPLS','CSIMPLS'}
                choice=menupls(out,attrib,exitno,labsd,labod,labresd,classic,classicplots);
            case {'CPCR','RPCR'}
                choice=menuscoreg(out,attrib,exitno,labsd,labod,labresd,classic,classicplots);
            case {'LTS','LS'}
                 choice=menuls(out,attrib,exitno,labsd,labresd,lablts,classic,classicplots);
            case{'CDA','RDA'}
                    choice=menuda(out,attrib,exitno,classic,classicplots);
            case{'CSIMCA','RSIMCA'}
                    choice=menusimca(out,attrib,exitno,classic,classicplots);
           end
    end
end

%%%%%%%%%%%%% MAIN FUNCTION %%%%%%%%%%%%%%%
function whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,labmcd,lablts,classic,classicplots)

%Initializing variables

switch attrib

case {'ROBPCA','RAPCA'}
    Xdist=out.sd;
    cutoffX=out.cutoff.sd;
    cutoffO=out.cutoff.od;
    OD=out.od;
    k=out.k;
    L=out.L;
    %classical output
    if isstruct(classic)
        Lcl=classic.L;
        Xdistcl=classic.sd;
        ODcl=classic.od;
        cutoffXcl=classic.cutoff.sd;
        cutoffOcl=classic.cutoff.od;
        attribcl='CPCA';
    end
case 'MCDREG'
    fitted=out.fitted;
    Rdist=out.resd;
    cutoffR=out.cutoff.resd;
    if size(fitted,2)~=1
        multi=1;
    else
        multi=0;
    end
    res=out.res;
    Xdist=out.rd;
    Rsquared=out.rsquared;
    cutoffX=out.cutoff.rd;
    Se=out.cov;
    k=size(out.slope,1);
    %classical output
    if isstruct(classic)
        attribcl=classic.class;
        fittedcl=classic.fitted;
        Rdistcl=classic.resd;
        standrescl=classic.stdres;
        cutoffRcl=classic.cutoff.resd;
        rescl=classic.res;
        Xdistcl=classic.md;
        cutoffXcl=classic.cutoff.md;
        Rsquaredcl=classic.rsquared;
        Secl=classic.cov;
    end
case 'MLR'
    fittedcl=out.fitted;
    Rdistcl=out.resd;
    cutoffRcl=out.cutoff.resd;
    if size(fittedcl,2)~=1
        multi=1;
    else
        multi=0;
    end
    rescl=out.res;
    Xdistcl=out.md;
    cutoffXcl=out.cutoff.md;
    Rsquaredcl=out.rsquared;
    Secl=out.cov;
    k=size(out.slope,1);
    attribcl=out.class;
case 'RPCR'
    fitted=out.fitted;
    Rdist=out.resd;
    cutoffR=out.cutoff.resd;
    if size(fitted,2)~=1
        multi=1;
    else
        multi=0;
    end
    res=out.res;
    Xdist=out.sd;
    Rsquared=out.rsquared;
    cutoffX=out.cutoff.sd;
    cutoffO=out.cutoff.od;
    OD=out.od;
    Se=out.cov;
    k=out.k;
    L=out.robpca.L;
    %classical output
    if isstruct(classic)
        attribcl='CPCR';
        Lcl=classic.cpca.L;
        Xdistcl=classic.sd;
        ODcl=classic.od;
        cutoffOcl=classic.cutoff.od;
        cutoffXcl=classic.cutoff.sd;
        Rdistcl=classic.resd;
        cutoffRcl=classic.cutoff.resd;
    end
case 'LTS'
    resid=out.res;
    fitted=out.fitted;
    scale=out.scale;
    standres=resid/scale;
    n=length(resid);
    if isfield(out,'X')
        x=out.X;
        y=out.y;
    else
        x=0;
        y=0;
    end
    Xdist=out.rd;
    cutoffX=out.cutoff.rd;
    cutoffY=out.cutoff.rd;
    k=size(out.slope,1);
    %classical output
    if isstruct(classic)
        attribcl='LS';
        residcl=classic.res;
        fittedcl=classic.fitted;
        scalecl=classic.scale;
        standrescl=residcl/scalecl;
        Xdistcl=classic.md;
        cutoffXcl=classic.cutoff.md;
        ncl=length(residcl);
        if isfield(classic,'X')
            xcl=classic.X;
            ycl=classic.y;
        else
            xcl=0;
            ycl=0;
        end
    end
case 'LS'
    attribcl=attrib;
    residcl=out.res;
    fittedcl=out.fitted;
    scalecl=out.scale;
    Xdistcl=out.md;
    cutoffXcl=out.cutoff.md;
    standrescl=out.resd;
    ncl=length(residcl);
    if isfield(out,'X')
        xcl=out.X;
        ycl=out.y;
    else
        xcl=0;
        ycl=0;
    end
    k=size(out.slope,1);
case 'CPCA'
    Lcl=out.L;
    Xdistcl=out.sd;
    ODcl=out.od;
    cutoffOcl=out.cutoff.od;
    cutoffXcl=out.cutoff.sd;
    k=out.k;
    attribcl=attrib;
case 'CPCR'
    fitted=out.fitted;
    Lcl=out.cpca.L;
    k=out.k;
    Xdistcl=out.sd;
    ODcl=out.od;
    cutoffOcl=out.cutoff.od;
    cutoffXcl=out.cutoff.sd;
    Rdistcl=out.resd;
    cutoffRcl=out.cutoff.resd;
    if size(fitted,2)~=1
        multi=1; %multivariate analysis
    else
        multi=0; %univariate analysis
        stdrescl=out.resd;
        cutoffRcl=out.cutoff.resd;
    end
    attribcl=attrib;
case 'RSIMPLS'
    fitted=out.fitted;
    Rdist=out.resd;
    cutoffR=out.cutoff.resd;
    if size(fitted,2)~=1
        multi=1;
    else
        multi=0;
    end
    res=out.res;
    Xdist=out.sd;
    cutoffX=out.cutoff.sd;
    cutoffO=out.cutoff.od;
    OD=out.od;
    Se=out.cov;
    k=out.k;
    %classical output
    if isstruct(classic)
        attribcl='CSIMPLS';
        Xdistcl=classic.sd;
        ODcl=classic.od;
        cutoffOcl=classic.cutoff.od;
        cutoffXcl=classic.cutoff.sd;
        Rdistcl=classic.resd;
        cutoffRcl=classic.cutoff.resd;
    end
case 'CSIMPLS'
    fittedcl=out.fitted;
    if size(fittedcl,2)~=1
        multi=1;
    else
        multi=0;
    end
    Xdistcl=out.sd;
    ODcl=out.od;
    k=out.k;
    cutoffXcl=out.cutoff.sd;
    cutoffOcl=out.cutoff.od;
    attribcl=attrib;
    Rdistcl=out.resd;
    cutoffRcl=out.cutoff.resd;
case 'MCDCOV'
    if ~isempty(out.plane)
        disp('Warning (makeplot): The MCD covariance matrix is singular. No plots can be drawn.')
        return
    end
    covar=out.cov;
    md=out.md;
    rd=out.rd;
    if isfield(out,'X')
        data=out.X;
    else
        data=0;
    end
    center=out.center;
    cutoffR=out.cutoff.rd;
    cutoffM=out.cutoff.md;
    if isstruct(classic)
        if isfield(out,'X')
            datacl=out.X;
        else
            datacl=0;
        end
        centercl=out.classic.center;
        covcl=out.classic.cov;
        mdcl=out.classic.md;
        attribcl=out.classic.class;
    end
case 'COV'
   %only available inside the mcdcov function.
case 'CDA'
    if isfield(out,'x')
        xcl=out.x;
        groupcl=out.group;
    else
        xcl=0;
        groupcl=0;
    end
    methodcl=out.method;
    centercl=out.center;
    covcl=out.cov;
    classcl=out.class;
case 'RDA'
    if isfield(out,'x')
        x=out.x; group=out.group;
    else
        x=0;group=0;
    end
    method=out.method;
    center=out.center;
    covar=out.cov;
    class=out.class;
    if isstruct(classic)
        if isfield(out.classic,'x')
            xcl=out.classic.x;
            groupcl=out.classic.group;
        else
            xcl=0;
            groupcl=0;
        end
        methodcl=out.classic.method;
        centercl=out.classic.center;
        covcl=out.classic.cov;
        classcl=out.classic.class;
    end
case 'RSIMCA'
    if isstruct(classic)
        resultcl=out.classic;
    else
        resultcl=0;
    end
end

%determination of the number of plots (robust or/and classic)
if strcmp(attrib,'LS') | strcmp(attrib,'CPCR') | strcmp(attrib,'CPCA') | strcmp(attrib,'MLR') | strcmp(attrib,'CDA') | strcmp(attrib,'CSIMPLS')|strcmp(attrib,'CSIMCA')
    oneplot=1; %only classical plots possible
elseif  (strcmp(attrib,'RAPCA') |strcmp(attrib,'MCDREG') | strcmp(attrib,'RPCR')|strcmp(attrib,'ROBPCA')| strcmp(attrib,'RSIMPLS')| strcmp(attrib,'MCDCOV')|strcmp(attrib,'LTS')|strcmp(attrib,'RDA')|strcmp(attrib,'RSIMCA'))  &  classicplots==0
    oneplot=2; %only robust plots possible
else
    oneplot=0; %both robust and classical plot in the middle of the screen
    bdwidth=5;
    topbdwidth=30;
    set(0,'Units','pixels');
    scnsize=get(0,'ScreenSize');
    pos1=[bdwidth, 1/3*scnsize(4)+bdwidth, scnsize(3)/2-2*bdwidth, scnsize(4)/2-(topbdwidth+bdwidth)];
    pos2=[pos1(1)+scnsize(3)/2, pos1(2), pos1(3), pos1(4)];
end

switch plotn
case 'all' %all possible plots
    close
    switch attrib
        case {'MCDREG','MLR'}
            if oneplot==0
                figure('Position',pos1)
                regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
                figure('Position',pos2)
                regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
            elseif oneplot==1
                figure
                regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd) %multi stond op 2
            elseif oneplot==2
                figure
                regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
            end
        case {'CPCA', 'ROBPCA'}
            if oneplot==0
                figure('Position',pos1)
                screeplot(L,attrib)
                figure('Position',pos2)
                screeplot(Lcl,attribcl)
                pos1(2)=pos1(2)-40;
                pos2(2)=pos2(2)-40;
                figure('Position',pos1)
                scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
                figure('Position',pos2)
                scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
            elseif oneplot==1
                figure
                screeplot(Lcl,attrib)
                figure
                scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
            else
                figure
                screeplot(L,attrib)
                figure
                scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
            end
        case {'RSIMPLS','CSIMPLS'}
                if oneplot==0
                    figure('Position',pos1)
                    scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
                    figure('Position',pos2)
                    scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
                    pos1(2)=pos1(2)-40;
                    pos2(2)=pos2(2)-40;
                    figure('Position',pos1)
                    regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attribcl,labsd,labresd)
                    figure('Position',pos2)
                    regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                     if exist('OD')
%                         Nihil=(OD <= 1.e-06);
%                         OD(Nihil)=0;
%                         help=OD;
%                     elseif exist('ODcl')
%                         Nihil=(ODcl <= 1.e-06);
%                         ODcl(Nihil)=0;
%                         helpcl=ODcl;
%                     end

%                     pos1(2)=pos1(2)-80;
%                     pos2(2)=pos2(2)-80;
%                     if ~all(help) %in case k=rank(T)=r then OD = zero
%                         figure('Position',pos1)
%                         regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%                         figure('Position',pos2)
%                         regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%                     else
%                         figure('Position',pos1)
%                         regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
%                         title(['Robust 3D outlier map based on ',num2str(k),' LV'])
%                         figure('Position',pos2)
%                         regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
%                         title(['Classical 3D outlier map based on ',num2str(k),' LV'])
%                     end
                elseif oneplot==1
                    figure
                    scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
                    figure
                    regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                     if exist('ODcl')
%                         Nihil=(ODcl <= 1.e-06);
%                         ODcl(Nihil)=0;
%                         helpcl=ODcl;
%                     end
%                     figure
%                     if ~all(helpcl) %in case k=rank(T)=r then OD = zero
%                         regresdiagplot(Rdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,'CPCR',labsd,labresd)
%                     else
%                         regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
%                         title(['Classical 3D outlier map based on ',num2str(k),' LV'])
%                     end
                else
                    figure
                    scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
                    figure
                    regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                     if exist('OD')
%                         Nihil=(OD <= 1.e-06);
%                         OD(Nihil)=0;
%                         help=OD;
%                     end
%                     figure
%                     if ~all(help) %in case k=rank(T)=r then OD = zero % nog verfijnen is niet volledig nul is zeer klein (<10^-6)
%                         regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%                     else
%                         regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
%                         title(['Robust 3D outlier map based on ',num2str(k),' LV'])
%                     end
                end
            case {'CPCR','RPCR'}
            if oneplot==0
                figure('Position',pos1)
                screeplot(L,attrib)
                figure('Position',pos2)
                screeplot(Lcl,attrib)
                pos1(2)=pos1(2)-40;
                pos2(2)=pos2(2)-40;
                figure('Position',pos1)
                scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
                figure('Position',pos2)
                scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
                pos1(2)=pos1(2)-80;
                pos2(2)=pos2(2)-80;
                figure('Position',pos1)
                regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attribcl,labsd,labresd)
                figure('Position',pos2)
                regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                 if exist('OD')
%                     Nihil=(OD <= 1.e-06);
%                     OD(Nihil)=0;
%                     help=OD;
%                 elseif exist('ODcl')
%                     Nihil=(ODcl <= 1.e-06);
%                     ODcl(Nihil)=0;
%                     helpcl=ODcl;
%                 end
%                 if ~all(help) %in case k=rank(T)=r then OD = zero
%                     figure('Position',pos1)
%                     regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%                     figure('Position',pos2)
%                     regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%                 else
%                     figure('Position',pos1)
%                     regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
%                     title(['Robust 3D outlier map based on ',num2str(k),' LV'])
%                     figure('Position',pos2)
%                     regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
%                     title(['Classical 3D outlier map based on ',num2str(k),' LV'])
%                 end
            elseif oneplot==1
                figure
                screeplot(Lcl,attrib)
                figure
                scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attrib,labsd,labod)
                figure
                regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                 if exist('ODcl')
%                     Nihil=(ODcl <= 1.e-06);
%                     ODcl(Nihil)=0;
%                     helpcl=ODcl;
%                 end
%                 figure
%                 if ~all(helpcl) %in case k=rank(T)=r then OD = zero
%                     regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,'CPCR',labsd,labresd)
%                 else
%                     regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
%                     title(['Classical 3D outlier map based on ',num2str(k),' LV'])
%                 end
            else
                figure
                screeplot(L,attrib)
                figure
                scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
                figure
                regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%3D plot is still highly memory consuming 08/04/04
%                 figure
%                 if exist('OD')
%                     Nihil=(OD <= 1.e-06);
%                     OD(Nihil)=0;
%                     help=OD;
%                 end
%                 if ~all(help) %in case k=rank(T)=r then OD = zero
%                     regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
%                 else
%                     regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
%                     title(['Robust 3D outlier map based on ',num2str(k),' LV'])
%                 end
            end
        case 'MCDCOV'
            if oneplot==0
                figure('Position',pos1)
                distplot(rd,cutoffR,attrib,labmcd)
                figure('Position',pos2)
                distplot(md,cutoffM,attribcl,labmcd)
                figure('Position',pos1)
                chiqqplot(rd,size(data,2),attrib)
                figure('Position',pos2)
                chiqqplot(md,size(data,2),attribcl)
                figure
                ddplot(md,rd,cutoffM,attrib,labmcd)
                figure
                if size(data,2)~=2|data==0
                    axes
                    box on
                    text(0.05,0.5,'Tolerance ellipse is only available for bivariate data','color','r')
                else
                    ellipsplot(center,covar,data,rd,labmcd)
                    set(findobj('color','r'),'color','m');
                    hold on
                    ellipsplot(centercl,covcl,data,md,labmcd)
                    set(findobj('color','r'),'color','b','linestyle',':');
                    hold off
                    legend_handles=[findobj('color','m'); findobj('color','b','linestyle',':')];
                    legend(legend_handles,'robust','classical','Location','best')
                end
            elseif oneplot==2
                figure
                distplot(rd,cutoffM,attrib,labmcd)
                figure
                chiqqplot(rd,size(data,2),attrib)
                figure
                ddplot(md,rd,cutoffM,attrib,labmcd)
                figure
                if size(data,2)~=2|data==0
                    axes
                    box on
                    text(0.05,0.5,'Tolerance ellipse is only available for bivariate data','color','r')
                else
                    ellipsplot(center,covar,data,rd,labmcd,'MCDCOV')
                end
            end
        case {'LTS','LS'}
            if oneplot==0
                figure('Position',pos1)
                residualplot(fitted,standres,attrib,'Fitted values','Standardized LTS residual',lablts)
                figure('Position',pos2)
                residualplot(fittedcl,standrescl,attribcl,'Fitted value','Standardized LS residual',lablts)
                pos1(2)=pos1(2)-40;
                pos2(2)=pos2(2)-40;
                figure('Position',pos1)
                residualplot(1:n,standres,attrib,'Index','Standardized LTS residual',lablts)
                figure('Position',pos2)
                residualplot(1:ncl,standrescl,attribcl,'Index','Standardized LS residual',lablts)
                pos1(2)=pos1(2)-80;
                pos2(2)=pos2(2)-80;
                figure('Position',pos1)
                normqqplot(resid,attrib)
                figure('Position',pos2)
                normqqplot(residcl,attribcl)
                pos1(2)=pos1(2)-100;
                pos2(2)=pos2(2)-100;
                figure('Position',pos1)
                if strcmp(attrib,'LTS')
                    regresdiagplot(Xdist,standres,cutoffX,cutoffY,k,0,attrib,labsd,labresd);
                else
                    regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,1,attrib,labsd,labresd);
                end
                figure('Position',pos2)
                if strcmp(attribcl,'LS')
                    regresdiagplot(Xdistcl,standrescl,cutoffXcl,0,k,0,attribcl,labsd,labresd);
                else
                    regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,1,attribcl,labsd,labresd);
                end
                pos1(2)=pos1(2)-120;
                pos2(2)=pos2(2)-120;
                figure('Position',pos1)
                if size(x,2)~=1|x==0
                    axes
                    box on
                    text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
                else
                    lsscatter(x,y,fitted,attrib)
                end
                figure('Position',pos2)
                if size(xcl,2)~=1|xcl==0
                    axes
                    box on
                    text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
                else
                    lsscatter(xcl,ycl,fittedcl,attribcl)
                end
            elseif oneplot ==1
                figure
                residualplot(fittedcl,standrescl,attribcl,'Fitted value','Standardized LS residual',lablts) ;
                figure
                residualplot(1:ncl,standrescl,attribcl,'Index','Standardized LS residual',lablts) ;
                figure
                normqqplot(residcl,attrib);
                figure
                if strcmp(attrib,'LS')
                    regresdiagplot(Xdistcl,standrescl,cutoffXcl,0,k,0,attrib,labsd,labresd);
                else
                    regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,1,attrib,labsd,labresd);
                end
                figure
                if size(xcl,2)~=1|xcl==0
                    axes
                    box on
                    text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
                else
                    lsscatter(xcl,ycl,fittedcl,attribcl)
                end
              elseif oneplot==2
                figure
                residualplot(fitted,standres,attrib, 'Fitted value','Standardized LTS residual',lablts)
                figure
                residualplot(1:n,standres,attrib,'Index','Standardized LTS residual',lablts)
                figure
                normqqplot(resid,attrib)
                figure
                if strcmp(attrib,'LTS')
                    regresdiagplot(Xdist,standres,cutoffX,0,k,0,attrib,labsd,labresd);
                else
                    regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,1,attrib,labsd,labresd);
                end
                figure
                if size(x,2)~=1|x==0
                    axes
                    box on
                    text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
                else
                    lsscatter(x,y,fitted,attrib)
                end
            end
        case{'RDA','CDA'}
            if oneplot==0
                    figure('Position',pos1)
                    daplot(x,group,center,covar,class,method)
                    figure('Position',pos2)
                    daplot(xcl,groupcl,centercl,covcl,classcl,methodcl)
                elseif oneplot==1
                    figure
                    daplot(xcl,groupcl,centercl,covcl,classcl,methodcl)
                elseif oneplot==2
                    figure
                    daplot(x,group,center,covar,class,method)
                end
            case{'RSIMCA','CSIMCA'}
                if oneplot==0
                    figure('Position',pos1)
                    simcaplot(result)
                    figure('Position',pos2)
                    simcaplot(resultcl)
                elseif oneplot==1
                    figure
                    simcaplot(resultcl)
                elseif oneplot==2
                    figure
                    simcaplot(result)
                end
        end
    choice=exitno;
case 'scree' %screeplot
    close
    if oneplot==0
        figure('Position',pos1)
        screeplot(L,attrib)
        figure('Position',pos2)
        screeplot(Lcl,attribcl)
    elseif oneplot==1
        screeplot(Lcl,attribcl)
    else
        screeplot(L,attrib)
    end
case 'pcadiag' %diagnostic Scoreplot (Xdist-Odist)
    %close
    if oneplot==0
        figure('Position',pos1)
        scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
        figure('Position',pos2)
        scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
    elseif oneplot==1
        figure
        scorediagplot(Xdistcl,ODcl,k,cutoffXcl,cutoffOcl,attribcl,labsd,labod)
    else
        figure
        scorediagplot(Xdist,OD,k,cutoffX,cutoffO,attrib,labsd,labod)
    end
case '3ddiag' %3D-plot: highly memory consuming!!!!
    close
    if oneplot==0
        if exist('OD')
            Nihil=(OD <= 1.e-06);
            OD(Nihil)=0;
            help=OD;
        elseif exist('ODcl')
            Nihil=(ODcl <= 1.e-06);
            ODcl(Nihil)=0;
            helpcl=ODcl;
        end
        if ~all(help)%in case k=rank(T)=r then OD = zero
            figure('Position',pos1)
            regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
            figure('Position',pos2)
            regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
        else
            figure('Position',pos1)
            regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
            title(['Robust 3D outlier map based on ',num2str(k),' LV'])
            figure('Position',pos2)
            regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
            title(['Classical 3D outlier map based on ',num2str(k),' LV'])
        end
    elseif oneplot==1
        if exist('ODcl')
            Nihil=(ODcl <= 1.e-06);
            ODcl(Nihil)=0;
            helpcl=ODcl;
        end
        if ~all(helpcl) %in case k=rank(T)=r then OD = zero
            regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd)
        else
            regresdiagplot3d(Xdistcl,ODcl,Rdistcl,cutoffXcl,cutoffOcl,cutoffRcl,k,attribcl,multi,labsd,labod,labresd,0)
            title(['Classical 3D outlier map based on ',num2str(k),' LV'])
        end
    else
        if exist('OD')
            Nihil=(OD <= 1.e-06);
            OD(Nihil)=0;
            help=OD;
        end
        if ~all(help) %in case k=rank(T)=r then OD = zero
            regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd)
        else
            regresdiagplot3d(Xdist,OD,Rdist,cutoffX,cutoffO,cutoffR,k,attrib,multi,labsd,labod,labresd,0)
            title(['Robust 3D outlier map based on ',num2str(k),' LV'])
        end
    end
case {'Idist','robdist'}
    close
    if oneplot==0
        figure('Position',pos1)
        distplot(rd,cutoffM,'MCDCOV',labmcd)
        figure('Position',pos2)
        distplot(md,cutoffM,'COV',labmcd)
        %elseif oneplot==1 not available since 'COV' is only called inside
        %the MCDCOV function
    elseif oneplot==2
        distplot(rd,cutoffM,'MCDCOV',labmcd)
    end
case 'qqmcd'
    close
    if oneplot==0
        figure('Position',pos1)
        chiqqplot(rd,size(data,2),'MCDCOV')
        figure('Position',pos2)
        chiqqplot(md,size(data,2),'COV')
    elseif oneplot==2
        chiqqplot(rd,size(data,2),'MCDCOV')
    end
case 'dd'
    close
    ddplot(md,rd,cutoffM,attrib,labmcd)
case 'ellipse'
    close
    if oneplot==0
        if size(data,2)~=2|data==0
            axes
            box on
            text(0.05,0.5,'Tolerance ellipse plot is only available for bivariate data','color','r')
        else
            ellipsplot(center,covar,data,rd,labmcd)
            set(findobj('color','r'),'color','m');
            hold on
            ellipsplot(centercl,covcl,data,md,labmcd)
            set(findobj('color','r'),'color','b','linestyle',':');
            hold off
            legend_handles=[findobj('color','m'); findobj('color','b','linestyle',':')];
            legend(legend_handles,'robust','classical','Location','best')
        end
    elseif oneplot==2
        if size(data,2)~=2|data==0
            axes
            box on
            text(0.05,0.5,'Tolerance ellipse plot is only available for bivariate data','color','r')
        else
            ellipsplot(center,covar,data,rd,labmcd)
        end
    end
case 'resfit'
    close
    if oneplot==0
        figure('Position',pos1)
        residualplot(fitted,standres,attrib,'Fitted value','Standardized LTS residual',lablts)
        figure('Position',pos2)
        residualplot(fittedcl,standrescl,attribcl,'Fitted value','Standardized LS residual',lablts)
    elseif oneplot==1
        residualplot(fittedcl,standrescl,attribcl,'Fitted value','Standardized LS residual',lablts)
    elseif oneplot==2
        residualplot(fitted,standres,attrib,'Fitted value','Standardized LTS residual',lablts)
    end
case 'resindex'
    close
    if oneplot==0
        figure('Position',pos1)
        residualplot(1:n,standres,attrib,'Index','Standardized LTS residual',lablts)
        figure('Position',pos2)
        residualplot(1:ncl,standrescl,attribcl,'Index','Standardized LS residual',lablts)
    elseif oneplot==1
        residualplot(1:ncl,standrescl,attribcl,'Index','Standardized LS residual',lablts)
    elseif oneplot==2
        residualplot(1:n,standres,attrib,'Index','Standardized LTS residual',lablts)
    end
case 'qqlts'
    close
    if oneplot==0
        figure('Position',pos1)
        normqqplot(resid,'LTS')
        figure('Position',pos2)
        normqqplot(residcl,'LS')
    elseif oneplot==1
        normqqplot(residcl,'LS')
    elseif oneplot==2
        normqqplot(resid,'LTS')
    end
case 'regdiag'
    %close
    if oneplot==0
        figure('Position',pos1)
        if strcmp(attrib,'LTS')
            regresdiagplot(Xdist,standres,cutoffX,0,k,0,attrib,labsd,labresd);
        else
            regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd);
        end
        figure('Position',pos2)
        if strcmp(attribcl,'LS')
            regresdiagplot(Xdistcl,standrescl,cutoffXcl,0,k,0,attribcl,labsd,labresd);
        else
            regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attribcl,labsd,labresd);
        end
    elseif oneplot==1
        if strcmp(attrib,'LS')
            regresdiagplot(Xdistcl,standrescl,cutoffXcl,0,k,0,attrib,labsd,labresd);
        else
            regresdiagplot(Xdistcl,Rdistcl,cutoffXcl,cutoffRcl,k,multi,attrib,labsd,labresd);
        end
    elseif oneplot==2
        if strcmp(attrib,'LTS')
            regresdiagplot(Xdist,standres,cutoffX,0,k,0,attrib,labsd,labresd);
        else
            regresdiagplot(Xdist,Rdist,cutoffX,cutoffR,k,multi,attrib,labsd,labresd);
        end
    end
case 'scatter'
    close
    if oneplot==0
        figure('Position',pos1)
        if size(x,2)~=1|x==0
            axes
            box on
            text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
        else
            lsscatter(x,y,fitted,attrib)
        end
        figure('Position',pos2)
        if size(xcl,2)~=1|xcl==0
            axes
            box on
            text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
        else
            lsscatter(xcl,ycl,fittedcl,attribcl)
        end
    elseif oneplot==1
        if size(xcl,2)~=1|xcl==0
            axes
            box on
            text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
        else
            lsscatter(xcl,ycl,fittedcl,attribcl)
        end
    elseif oneplot==2
        if size(x,2)~=1|x==0
            axes
            box on
            text(0.05,0.5,'Scatter plot is only available for bivariate data','color','r')
        else
            lsscatter(x,y,fitted,attrib)
        end
    end
case 'da'
    close
    if oneplot==0
        figure('Position',pos1)
        daplot(x,group,center,covar,class,method)
        figure('Position',pos2)
        daplot(xcl,groupcl,centercl,covcl,classcl,methodcl)
    elseif oneplot==1
        daplot(xcl,groupcl,centercl,covcl,classcl,methodcl)
    elseif oneplot==2
        daplot(x,group,center,covar,class,method)
    end
case 'simca'
    close
    if oneplot==0
        figure('Position',pos1)
        simcaplot(out)
        figure('Position',pos2)
        simcaplot(resultcl)
    elseif oneplot==1
        simcaplot(out)
    elseif oneplot==2
        simcaplot(out)
    end
end

%---------------------------------------------------------------------------------------------------------------------------
function choice= menucov(out,attrib,exitno,labmcd,classic,classicplots)
choice=menu('Covariance plots: ','All','Index plot of the distances','Quantile-Quantile plot of the distances','Distance-distance plot',...
             'Tolerance ellipse (for bivariate data)','Exit');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,3,3,3,labmcd,3,classic,classicplots)
    case 2
        plotn='Idist';
        whichplot(out,'Idist',attrib,exitno,3,3,3,labmcd,3,classic,classicplots)
    case 3
        plotn='qqmcd';
        whichplot(out,plotn,attrib,exitno,3,3,3,labmcd,3,classic,classicplots)
    case 4
        plotn='dd';
        whichplot(out,plotn,attrib,exitno,3,3,3,labmcd,3,classic,classicplots)
    case 5
        plotn='ellipse';
        whichplot(out,plotn,attrib,exitno,3,3,3,labmcd,3,classic,classicplots)
    case 6
        choice=exitno;
    end
%---------------------------------------------------------------------------------------------------------------------------
function choice = menureg(out,attrib,exitno,labsd,labresd,classic,classicplots)
choice=menu('Regression Plots: ','All ','Regression outlier map', 'Exit ');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,labsd,3,labresd,3,3,classic,classicplots)
    case 2
        plotn='regdiag';
        whichplot(out,plotn,attrib,exitno,labsd,3,labresd,3,3,classic,classicplots)
    case 3
        choice=exitno;
    end
%---------------------------------------------------------------------------------------------------------------------------
function choice =  menuscore(out,attrib,exitno,labsd,labod,classic,classicplots)
choice=menu('Score Plots: ','All ','Scree plot','Score outlier map', 'Exit ');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,labsd,labod,3,3,3,classic,classicplots)
    case 2
        plotn='scree';
        whichplot(out,plotn,attrib,exitno,labsd,labod,3,3,3,classic,classicplots)
    case 3
        plotn='pcadiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,3,3,3,classic,classicplots)
    case 4
        choice=exitno;
    end

%---------------------------------------------------------------------------------------------------------------------------
function choice = menupls(out,attrib,exitno,labsd,labod,labresd,classic,classicplots)
choice=menu('PLS Plots: ','All ','Score outlier map',...
                     'Regression outlier map', '3D outlier map (Highly memory consuming)','Exit ');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 2
        plotn='pcadiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 3
        plotn='regdiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 4
        plotn='3ddiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 5
        choice=exitno;
    end
%---------------------------------------------------------------------------------------------------------------------------
function choice=menuscoreg(out,attrib,exitno,labsd,labod,labresd,classic,classicplots)
choice=menu('Score and Regression Plots: ','All ','Scree plot','Score outlier map',...
        'Regression outlier map', '3D outlier map  (Highly memory consuming)', 'Exit ');

switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 2
        plotn='scree';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 3
        plotn='pcadiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 4
        plotn='regdiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 5
        plotn='3ddiag';
        whichplot(out,plotn,attrib,exitno,labsd,labod,labresd,3,3,classic,classicplots)
    case 6
        choice=exitno;
    end
%---------------------------------------------------------------------------------------------------------------------------
function choice= menuls(out,attrib,exitno,labsd,labresd,lablts,classic,classicplots)
choice=menu('Residual plots: ', 'All', 'Standardized residuals versus fitted values',...
             'Index plot of standardized residuals','Normal QQplot of residuals',...
             'Diagnostic plot of residuals versus robust distances',...
             'Scatter plot with regression line','Exit');
switch choice
case 1
    plotn='all';
    whichplot(out,plotn,attrib,exitno,labsd,3,labresd,3,lablts,classic,classicplots)
case 2
    plotn='resfit';
    whichplot(out,plotn,attrib,exitno,3,3,3,3,lablts,classic,classicplots)
case 3
    plotn='resindex';
    whichplot(out,plotn,attrib,exitno,3,3,3,3,lablts,classic,classicplots)
case 4
    plotn='qqlts';
    whichplot(out,plotn,attrib,exitno,3,3,3,3,lablts,classic,classicplots)
case 5
    plotn='regdiag';
    whichplot(out,plotn,attrib,exitno,labsd,3,labresd,3,lablts,classic,classicplots)
case 6
    plotn='scatter';
    whichplot(out,plotn,attrib,exitno,3,3,3,3,lablts,classic,classicplots)
case 7
    choice=exitno;
end
%---------------------------------------------------------------------------------------------------------------------------
function choice = menuda(out,attrib,exitno,classic,classicplots)
choice=menu('Discriminant analysis: ','All ','Tolerance ellipses (for bivariate data)', 'Exit ');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,3,3,3,3,3,classic,classicplots)
    case 2
        plotn='da';
        whichplot(out,plotn,attrib,exitno,3,3,3,3,3,classic,classicplots)
    case 3
        choice=exitno;
end
%------------------------------------------------------------------------------------------------------------------------------
function choice = menusimca(out,attrib,exitno,classic,classicplots)
choice=menu('SIMCA analysis: ','All ','Scatter plot', 'Exit ');
switch choice
    case 1
        plotn='all';
        whichplot(out,plotn,attrib,exitno,3,3,3,3,3,classic,classicplots)
    case 2
        plotn='simca';
        whichplot(out,plotn,attrib,exitno,3,3,3,3,3,classic,classicplots)
    case 3
        choice=exitno;
end


function [V,F] = triangle_strip(P,E)
  % TRIANGLE_STRIP build a strip of triangles given a curve
  %
  % [V,F] = triangle_strip(P,E)
  %
  % Inputs:
  %   P  #points by 2 list of 2d points
  %   E  #edges by 2 list of edge indices into P
  % Outputs:
  %   V  #points*2 by 3 list of 3d points
  %   F  #edges*2 by 3 list of triangle indices
  %
  n = size(P,1);
  V = [P -ones(n,1);P ones(n,1)];
  F = [E n+E(:,1);n+fliplr(E) E(:,2)];
end


classdef SuperEllipseExponentTxiRhoPlotter < handle

    properties (Access = public)

    end

    properties (Access = private)

    end

    properties (Access = private)
        fileName
        title
        rhoV
        xiV
        value
    end

    methods (Access = public)

        function obj = SuperEllipseExponentTxiRhoPlotter(cParams)
            obj.init(cParams);
        end

        function plot(obj)
            obj.plotContour();
            obj.plotTriSurf();
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.fileName = [cParams.fileName,'XiRho'];
            obj.title = cParams.title;
            obj.rhoV = cParams.rhoV;
            obj.xiV  = cParams.xiV;
            obj.value = cParams.value;
        end

        function plotTriSurf(obj)
            s.fileName = obj.fileName;
            s.title = obj.title;
            s.axisAdder = XiRhoAxisAdder();
            s.view = [-223 67];
            p =  SuperEllipseExponentTriSurfPlotter(s);
            x = obj.xiV;
            y = obj.rhoV;
            z = obj.value;
            p.plot(x,y,z);
        end

        function plotContour(obj)
            s.fileName = obj.fileName;
            s.title = obj.title;
            s.axisAdder = XiRhoAxisAdder();
            p =  SuperEllipseExponentContourPlotter(s);
            x = obj.xiV;
            y = obj.rhoV;
            z = obj.value;
            p.plot(x,y,z);
        end

        function addAxis(obj)
            zlabel('q');
        end

    end

end


function [Nv, VX, VY, VZ, K, EToV] = MeshReaderGambit3D(FileName)

% function [Nv, VX, VY, VZ, K, EToV] = MeshReaderGambit3D(FileName)
% Purpose  : Read in basic grid information to build grid
% NOTE     : gambit *.neu format is assumed

Fid = fopen(FileName, 'rt');

% read intro
for i=1:6
  line = fgetl(Fid);
end

% fine number of nodes and number of elements
dims = fscanf(Fid, '%d');

Nv = dims(1); K = dims(2);

for i=1:2
  line = fgetl(Fid);
end

% read node coordinates
xyz = fscanf(Fid, '%lf', [4, Nv]);
xyz = xyz(2:4, :);
VX = xyz(1,:); VY = xyz(2,:); VZ = xyz(3,:);

for i=1:3
  line = fgetl(Fid);
end

% read element to node connectivity
EToV = zeros(K, 4);
for k = 1:K
  line   = fgetl(Fid);
  tmpcon = sscanf(line, '%lf');
  EToV(k,1:4) = tmpcon(4:7);
end
return


function M = rmCompareModelsGUI_sortVoxels(criterion, modelNum, M);
% Sort voxels in rmCompareModelsGUI.
%
% M = rmCompareModelsGUI_sortVoxels([criterion], [modelNum=dialog], [M=get from cur figure]);
%
% INPUTS:
%	criterion: can be one of 'ecc', 'pol', 'sigma', 'varexp', or 'beta'.
%	Will sort the voxels in ascending order for the specified parameter and
%	model #.
%	[default: get criterion from dialog]
%
%	modelNum: index of model in the comparison GUI from which to take the
%	voxel data to use for sorting.
%	[default: get model number from dialog]
%
%	M: comparison GUI struct, created by rmCompareModelsGUI_getData.
%	[default: get from cur figure, assumes you've already opened a
%	comparison GUI.]
%
%
%
% ras, 09/2008.
if notDefined('M'), M = get(gcf, 'UserData'); end
if notDefined('modelNum'),
	modelNum = listdlg('PromptString', 'Sort by Which Model?', ...
						'ListString', M.dtList, 'InitialValue', 1);
end

if notDefined('criterion'),
	cList = {'Variance Explained' 'Eccentricity' 'Polar Angle' ...
			 'x0' 'y0' 'pRF Size (sigma)' 'Scale Factor (beta)'};
	fieldList = {'varexp' 'ecc' 'pol' 'x0' 'y0' 'sigma' 'beta'};
	cNum = listdlg('PromptString', 'Sort by Which Criterion?', ...
						'ListString', cList, 'InitialValue', 1);
	criterion = fieldList{cNum};
end

% lookup for alternate names for criteria
switch lower(criterion)
	case 'eccentricity', criterion = 'ecc';
	case 'polar angle', criterion = 'pol';
	case 'prf size (sigma)', criterion = 'sigma';
	case 'scale factor (beta)', criterion = 'beta';
end

% get the values for the criterion
vals = M.(criterion){modelNum};

% special case: for beta, we want the first beta value (for the pRF, not
% the trend terms) in the model
if isequal(criterion, 'beta')
	vals = vals(:,1);
end

% sort the values, getting I -- the new voxel order
[sortedVals I] = sort(vals);

% reorder the ROI coordinates and data fields to match this:
M.roi.coords = M.roi.coords(:,I);
for f = {'x0' 'y0' 'sigma' 'pol' 'ecc' 'varexp'}
	for m = 1:M.nModels
		M.(f{1}){m} = M.(f{1}){m}(I);
	end
end

for m = 1:M.nModels
	M.beta{m} = M.beta{m}(I,:);
end

% reoder time series
for m = 1:M.nModels
	M.tSeries{m} = M.tSeries{m}(:,I);
end

% udpate the GUI
set(gcf, 'UserData', M);
% rmCompareModelsGUI_update;

return


function matching_channels = match_nirs_labels(labels)
% MATCHING_CHANNELS finds the labels of the signals associated to the
% same combination of receiver and transmitter and provides as output a
% binary matrix where 1 represents that channels in the corresponding
% row-column combination match.
%
% OUTPUT
%  matching_channels: nChan x nChan binary matrix; where 1 represents that
% channels in the corresponding row-column combination match, and 0 represents
% the cases where they do not match.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

num_channels=numel(labels);
matching_channels = ones(num_channels, num_channels);

for n = 1 : num_channels
    label_check1 = labels{n};
    label_check1_split = split(label_check1, ' [');
    label_check1_split = label_check1_split{1};
    for m = 1 : num_channels
        if(n == m)
            continue
        end
        label_check2 = labels{m};
        label_check2_split = split(label_check2, ' [');
        label_check2_split = label_check2_split{1};
        matching_channels(n,m) = strcmp(label_check1_split, label_check2_split);
    end
end


  function b = ir_mid3_pic1(x, file, varargin)
%|function b = ir_mid3_pic1(x, file, varargin)
%|
%| write 'mid3' type picture to .png file
%|
%| in
%|	x	[nx ny nz]	3D image
%|	file	char		file name
%|
%| option
%|	'clim'			display limit, default [800 1200]
%|
%| out
%|	b	[nx+nz ny+nz]	2D 'mid3' image, uint8
%|
%| 2012-10-01, Jeff Fessler

if nargin < 1, ir_usage, end
if streq(x, 'test'), ir_mid3_pic1_test, return, end

arg.clim = [800 1200];
arg = vararg_pair(arg, varargin);

y = jf_mip3(x, 'type', 'mid');

clim = arg.clim;
b = 255 * (y - clim(1)) / (clim(2) - clim(1));
b = min(b,255);
b = max(b,0);
b = uint8(b);

if exist(file, 'file')
	warn('file "%s" exists already.', file)
	yn = input('over-write? y|n ', 's');
	if ~streq(yn, 'y', 1)
		error('file name')
	end
end
imwrite(b', file); % trick: transpose

% ir_mid3_pic1_test
function ir_mid3_pic1_test

ig = image_geom('nx', 64, 'nz', 30, 'dx', 1, 'dz', 2);
x = ellipsoid_im(ig, [], 'hu_scale', 1000);

file = 'test.png';
b = ir_mid3_pic1(x, file, 'clim', [950 1050]);

%h = im(y, arg.clim);
%z = get(h, 'cdata');
%minmax(b)

tmp = imread(file)'; % trick
jf_equal(tmp, b)

% !xv test.png &


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
% Tutorial for FAIR: shows how to visulaize 3D data with FAIR.
%
% - load data             (here 3D MRI)
% - setup viewer          (viewImage2D)
% - view  data
%==============================================================================

clear, %close all,
help(mfilename),

% setup data
fprintf('%s\n','generate data (here: MRI)');
load mri;
omega = [0,20,0,20,0,10];    % specify physical domain
T     = double(squeeze(D));
m     = size(T);             % get size of data

%%
fprintf('%s\n','use image montage for visualization of data')
FAIRfigure(1); clf;
imgmontage(T,omega,m,'colormap',gray(100),'numbering','on');
title('visualization of 3D data - imgmontage','fontsize',30)

%%
fprintf('%s\n','use a volumetric view')
FAIRfigure(2); clf;
volView(T,omega,m,'facecolor',[240,140,100]/256,'facealpha',0.75); hold on;
colormap(gray(100))
%%
fprintf('%s\n','use a volumetric view + slices')
FAIRfigure(3); clf;
volView(T,omega,m,'facecolor',[240,140,100]/256,'facealpha',0.75); hold on;
colormap(gray(100))
vh = viewSlices(T,omega,m);

%%
FAIRfigure(4); clf; colordef(gcf,'black'); colormap(gray(100));
for j=1:m(3);
  vh = viewSlices(T,omega,m,'s1',64,'s2',64,'s3',[j]);
  FAIRpause(1/10);
end;
echo off
%==============================================================================


function clusters = xyz2clusters(xyz,P)
% Converts a 3-column x, y, z list of mm coordinates to a clusters
% structure given P, the filename of an analyze .img file to provide
% dimensions and voxel sizes.
%
% :Usage:
% ::
%
%    function cl = xyz2clusters(xyz,P)
%
% Uses this info from the image:
%   - VOL.M     - spm-style mat matrix
%   - VOL.VOX   - voxel sizes
%
%   - SPM.Z     - now 1s; could stores values in the original image in clusters.Z
%
% The following is created internally:
%   - SPM.XYZmm - mm coords, you input these
%   - SPM.XYZ   - voxel coords
%

V = spm_vol(P);

%wh = strmatch('Thalamus',L3); whos wh

VOL.M = V.mat;
VOL.VOX = diag(V.mat(1:3,1:3));

fprintf(1,'Converting mm to voxels -> ');
XYZ = mm2voxel(xyz,VOL,2);  % unique reordered
fprintf(1,'%3.0f voxels -> ',size(XYZ,1));
fprintf(1,'Converting voxels to mm -> ');
%XYZ = unique(XYZ,'rows');
XYZ = XYZ';

SPM.XYZmm = voxel2mm(XYZ,VOL.M);
SPM.XYZ = XYZ;
SPM.Z = ones(1,size(XYZ,2));

fprintf(1,'Making clusters.\n');

%cl = tor_extract_rois([],SPM,VOL);

% stuff from tor_extract_rois -- omit where it gets each region separately

    % ----------------------------------------------------------------------------------
    % define each cluster as cell in array.
    % ----------------------------------------------------------------------------------
    clusters = [];
cl_index = spm_clusters(SPM.XYZ);
%cl_index = SPM.Z;    %:size(SPM.XYZ,2);
cl.title = 'xyz';

    for i = 1:max(cl_index)
      %  if verbose, fprintf(1,['\nExtracting cluster ' num2str(i) ' of ' num2str(max(cl_index))]),end
        a = find(cl_index == i);

        %if isfield(SPM,'u'), cl.title = SPM.title;,else, cl.title = 'Untitled';,end
        %if isfield(SPM,'u'), cl.threshold = SPM.u;,else, cl.threshold = NaN;,end
        cl(i).voxSize = VOL.VOX;
        cl(i).M = VOL.M;
        cl(i).name = [cl.title '_' num2str(i) '_' mat2str(size(a,2)) '_voxels'];
        cl(i).numVox = size(a,2);
        cl(i).Z = SPM.Z(a);
        cl(i).XYZmm = SPM.XYZmm(:,a);
        cl(i).XYZ = SPM.XYZ(:,a);

        cl(i).center = mean(cl(i).XYZ');
        if size(cl(i).XYZmm,2) > 1, cl(i).mm_center = center_of_mass(cl(i).XYZmm,cl(i).Z);  % mean(cl.XYZmm');
        else cl(i).mm_center = cl(i).XYZmm';
        end
        clusters = [clusters, cl];

    end

return


% Using A Binary Sensor Mask Example
%
% This example demonstrates how to use a binary sensor mask for the
% detection of the pressure field generated by an initial pressure
% distribution within a two-dimensional homogeneous propagation medium. It
% builds on the Homogeneous Propagation Medium Example.
%
% author: Bradley Treeby
% date: 29th June 2009
% last update: 22nd September 2012
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

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

clear all;

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

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

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

% create initial pressure distribution using makeDisc
disc_magnitude = 5; % [Pa]
disc_x_pos = 50;    % [grid points]
disc_y_pos = 50;    % [grid points]
disc_radius = 8;    % [grid points]
disc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);

disc_magnitude = 3; % [Pa]
disc_x_pos = 80;    % [grid points]
disc_y_pos = 60;    % [grid points]
disc_radius = 5;    % [grid points]
disc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);

source.p0 = disc_1 + disc_2;

% define a binary sensor mask
sensor_x_pos = Nx/2;        % [grid points]
sensor_y_pos = Ny/2;        % [grid points]
sensor_radius = Nx/2 - 22;  % [grid points]
sensor_arc_angle = 3*pi/2;  % [radians]
sensor.mask = makeCircle(Nx, Ny, sensor_x_pos, sensor_y_pos, sensor_radius, sensor_arc_angle);

% run the simulation
sensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor);

% reorder the simulation data
sensor_data_reordered = reorderSensorData(kgrid, sensor, sensor_data);

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

% plot the initial pressure and sensor distribution
figure;
imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, source.p0 + disc_magnitude*sensor.mask, [-1 1]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;

% plot the simulated sensor data
figure;
imagesc(sensor_data, [-1, 1]);
colormap(getColorMap);
ylabel('Sensor Position');
xlabel('Time Step');
colorbar;

% plot the re-ordered sensor data
figure;
imagesc(sensor_data_reordered, [-1, 1]);
colormap(getColorMap);
ylabel('Sensor Position');
xlabel('Time Step');
colorbar;


classdef bndfun < classicfun
%BNDFUN   Represent global functions on a bounded interval [a, b].
%
%   Class for representing global functions on a bounded interval [a, b].
%   Functions are approximated via a ONEFUN object, which lives on the interval
%   [-1, 1], stored in the BNDFUN. Forward and inverse maps stored in the
%   BNDFUN object map the interval [-1, 1] to [a, b], and vice versa.
%
% Constructor inputs:
%   BNDFUN(OP) constructs a BNDFUN object from the function handle OP on the
%   domain determined by the default in CHEBFUNPREF by mapping the domain to
%   [-1, 1] and constructing a ONEFUN object to represent the function
%   prescribed by OP.  OP should be vectorised (i.e., accept a vector input)
%   and output a vector of the same length as its input.
%
%   BNDFUN(OP, DATA) constructs a BNDFUN object using the data supplied in the
%   DATA structure.  DATA fields used by BNDFUN are:
%     DATA.DOMAIN    (Default:  Determined by CHEBFUNPREF)
%         A row vector with two elements in increasing order defining the
%         construction domain.  Both elements must be finite.
%   In addition, BNDFUN may modify the following DATA fields before passing
%   them on to the ONEFUN constructor:
%     DATA.HSCALE    (Default:  Determined by DATA.DOMAIN)
%         Horizontal construction scale.
%   If any fields in DATA are empty or not supplied, or if DATA itself is empty
%   or not supplied, appropriate default values are set.  Any fields in DATA
%   which are not recognized will be passed as-is to the ONEFUN constructor.
%
%   BNDFUN(OP, DATA, PREF) overrides the default behavior with that given by
%   the preferences in the structure or CHEBFUNPREF object PREF. See
%   CHEBFUNPREF for details.
%
% See also CLASSICFUN, CHEBFUNPREF, ONEFUN.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BNDFUN Class Description:
%
% The BNDFUN class is a class for representations of globally smooth functions
% on a finite interval [a, b]. It achieves this by taking a ONEFUN on [-1, 1]
% and applying a linear mapping to re-scale its domain.
%
% Note that all binary BNDFUN operators (methods which can take two BNDFUN
% arguments) assume that the domains of the BNDFUN objects agree. The methods
% will not issue warnings if this condition is violated, but the results will
% not be meaningful.
%
% Class diagram: [<<CLASSICFUN>>] <>-- [<<onefun>>]
%                   ^
%                   |
%                [bndfun]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS CONSTRUCTOR:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = false )

        function obj = bndfun(op, data, pref)
            % Parse inputs.
            if ( (nargin < 1) || isempty(op) )
                obj.domain = [];
                obj.mapping = [];
                obj.onefun = [];
                return
            end

            if ( (nargin < 2) || isempty(data) )
                data = struct();
            end

            if ( (nargin < 3) || isempty(pref) )
                pref = chebfunpref();
            else
                pref = chebfunpref(pref);
            end

            data = parseDataInputs(data, pref);

            % Check the domain input.
            if ( ~all(size(data.domain) == [1, 2]) || (diff(data.domain) <= 0) )
                error('CHEBFUN:BNDFUN:bndfun:badDomain', ...
                    ['Domain argument should be a row vector with two ', ...
                    'entries in increasing order.']);
            elseif ( any(isinf(data.domain)) )
                error('CHEBFUN:BNDFUN:bndfun:unboundedDomain', ...
                    'Should not encounter unbounded domain in bndfun class.');
            end

            % TODO:  Why do we rescale the hscale like this?
            data.hscale = data.hscale / diff(data.domain);

            % Remap the OP to be a function on [-1, 1].
            linmap = bndfun.createMap(data.domain);
            if ( isa(op, 'function_handle') && ~all(data.domain == [-1, 1]) ...
                    && ~isnumeric(op) )
                op = @(x) op(linmap.For(x));
            end

            % Call the ONEFUN constructor:
            obj.onefun = onefun.constructor(op, data, pref);

            % Add the domain and mapping:
            obj.domain = data.domain;
            obj.mapping = linmap;
        end
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% STATIC METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = true )

        % Linear map from [-1, 1] to the domain of the BNDFUN.
        m = createMap(domain);

        % Make a BNDFUN (constructor shortcut):
        f = make(varargin);

    end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% METHODS IMPLEMENTED IN THIS FILE:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function data = parseDataInputs(data, pref)
%PARSEDATAINPUTS   Parse inputs from the DATA structure and assign defaults.

if ( ~isfield(data, 'domain') || isempty(data.domain) )
    data.domain = pref.domain;
end

if ( ~isfield(data, 'hscale') || isempty(data.hscale) )
    % TODO:  Or should this be 1?  What does chebfun pass down?
    data.hscale = norm(data.domain, inf);
end

end


%   GeomCG Tensor Completion. Copyright 2013 by
%   Michael Steinlechner
%   Questions and contact: michael.steinlechner@epfl.ch
%   BSD 2-clause license, see LICENSE.txt

disp('                ___   ___      |    geomCG: Tensor completion by Riemannian Optimization')
disp('   _  _  _     / __|/ __|      |    ')
disp('  / \/_\/ \|\/| (__ |(_/\      |    Daniel Kressner')
disp('  \_|\__\_/|  |\___|\___/      |    Michael Steinlechner')
disp('  \_|                          |    Bart Vandereycken')
disp('     ')
disp('geomCG is licensed under a BSD 2-clause license, see LICENSE.txt')
disp('For an explanation of the algorithm, we refer to')
disp('   ')
disp('      D. Kressner, M. Steinlechner, B. Vandereycken:')
disp('      Low-Rank Tensor Completion by Riemannian Optimization.')
disp('      MATHICSE Technical Report 20.2013, June 2013. Submitted to BIT Numerical Mathematics.')

disp('   ')

disp('Compiling mex files...')
mex calcFunction_mex.c
mex calcGradient_mex.c
mex calcInitial_mex.c
mex calcProjection_mex.c
mex getValsAtIndex_mex.c

addpath( cd )
addpath( [cd, filesep, 'examples'] )
disp('Make sure that the Tensor Toolbox is also properly installed and loaded into the current path')
disp('You can download the Tensor Toolbox from Sandia Labs. GeomCG was tested with version 2.5 only!')

disp('Finished. Try out the example code simpleGeomCG.m')


%  Figure 9.47      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
%% fig9.47.m
%% Simulink Simulation for Position Control
clf;
[t,x,y]=sim('fig9_46');
plot(t',x');
grid;
xlabel('Time (sec)');
ylabel('Amplitude');
title('Fig. 9.47: Position Control');
text(5,0.95,'Output');
text(3.5,0.3,'x_2');


function han = m_scatter(lon, lat, varargin)
% function m_scatter(lon, lat, S, C)

m_proj('miller','lat',82);
%m_grid('linestyle','none','box','on','tickdir','out');
[x,y] = m_ll2xy(lon, lat);
%drawnow
h = scatter(x, y, varargin{:});
line(x(1:10), y(1:10))
%plot(x,y,'.')
%get(gca,
z = findobj(gca, 'type', 'scattergroup')
m_grid('linestyle','none','box','on','tickdir','out')
%h = scatter(x, y, varargin{:});

if nargout == 1
  han = h;
end


function [both, pos, neg] = visualizePathwayInEpistasis(Nall, radius, pathwayNames)
% This function creates a circular network such that all the nodes are
% arranged in a circle. The nodes represent a pathway, the color of the
% node represents whether the interactions within a pathway are none, positive,
% negative, or mixed. The size of the node represents the number of interactions.
% The edges represent which pathways are sharing which
% type of interaction. The color of the edge represents if the interactions
% are positive negative or mixed. The with of the edge represent the total number
% of interactions between any two given pathways.
%
% USAGE:
%
%     [both,pos,neg]=visualizePathwayInEpistasis(Nall,radius,pathwayNames)
%
% INPUT:
%     Nall:          a structure representing the epistatic interaction networks:
%                    Nall.pos: a square matrix representing number of positive interactions shared by any two pathways.
%                    Nall.neg: a square matrix representing number of negative interactions shared by any two pathways.
%     radius:        radius of the generic circles for clock diagram.
%     pathwayNames:  subSystem names corresponding to matrices in Nall
%                    structure
%
% OUTPUT:
%     both:          contains both positive and negative interactions
%     pos:           contains only positive interactions
%     neg:           contains only negative interactions
%
% NOTE:
%    See figures in following publication:
%    Joshi CJ and Prasad A, 2014, "Epistatic interactions among metabolic genes
%    depend upon environmental conditions", Mol. BioSyst., 10, 2578-2589.
%
% .. Authors:
%      - Chintan Joshi 10/26/2018
%      - Chintan Joshi; made modifications to label the nodes using pathway names, 10/26/2018

if nargin < 2
    radius = 40;
end

pos = Nall.pos;
neg = Nall.neg;
both = Nall.pos + Nall.neg;
indn = []; indp = []; mix_ = [];
ps = find(diag(pos) ~= 0); ns = find(diag(neg) ~= 0); nps = find(diag(both) ~= 0);
if ~isempty(nps) && ~isempty(ps)
    indp = intersect(ps, nps);
end
if ~isempty(nps) && ~isempty(ns)
    indn = intersect(ns, nps);
end
if isempty(indn)
    p_ = indp; n_ = []; mix_ = [];
elseif isempty(indp)
    p_ = []; n_ = indn; mix_ = [];
else
    p_ = setdiff(indp, indn); n_ = setdiff(indn, indp); mix_ = intersect(indp, indn);
end
% keeps only those that have both but not either type of interactions alone
c = 0;
for i = 1:length(both)
    for j = 1:length(both)
        if both(i, j) ~= 0 && pos(i, j) ~= 0 && neg(i, j) ~= 0
            c = c + 1;
            indm1(c, 1) = i;
            indm2(c, 1) = j;
        end
    end
end
% conversion to circular cordinates
theta = linspace(0, 2 * pi, length(pos) + 1);
theta = theta(1:end - 1);
[x, y] = pol2cart(theta, 1);
tx = x; ty = y;
x = x * 0.9; y = y * 0.9;
[indp1, indp2] = ind2sub(size(pos), find(pos(:)));
[indn1, indn2] = ind2sub(size(neg), find(neg(:)));
gc = [0.23 0.44 0.34];
rc = [0.58 0.39 0.39];
yc = [255 204 102] / 255;
subplot(3, 3, 5);
% plot the structure of the clock diagram
plot(x, y, '.', 'MarkerEdgeColor', [150 150 150]./255, 'markersize', 1); hold on
% label the the texts for each point in clock diagram
for i = 1:length(x)
    textAngle = (i - 1) * 360 / length(x);  % calculate the angle for text
    text(tx(i), ty(i), pathwayNames(i), 'Rotation', textAngle);
end
if ~isempty(indp1)
    arrayfun(@(p, q)line([x(p), x(q)], [y(p), y(q)], 'Color', gc, 'LineWidth', pos(p, q)), indp1, indp2);  % plot inter-pathway positive interactions
end
if ~isempty(indn1)
    arrayfun(@(p, q)line([x(p), x(q)], [y(p), y(q)], 'Color', rc, 'LineWidth', neg(p, q)), indn1, indn2);  % plot inter-pathway negative interactions
end
if exist('indm1')
    arrayfun(@(p, q)line([x(p), x(q)], [y(p), y(q)], 'Color', yc, 'LineWidth', both(p, q)), indm1, indm2);  % plot inter pathway both types of interactions
end
% plot intra-pathway interactions
plot(x, y, '.', 'MarkerEdgeColor', [150 150 150]./255, 'markersize', radius);
plot(x(p_), y(p_), '.', 'MarkerEdgeColor', gc, 'markersize', radius + length(p_) * 3);
plot(x(n_), y(n_), '.', 'MarkerEdgeColor', rc, 'markersize', radius + length(n_) * 3);
plot(x(mix_), y(mix_), '.', 'MarkerEdgeColor', yc, 'markersize', radius + length(mix_) * 3);
set(gca, 'DataAspectRatio', [1 1 1]);

axis equal off;
hold off;


classdef mme_reserve_zone < mp.mm_element

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

%     properties
%     end

    methods
        function name = name(obj)
            name = 'reserve_zone';
        end

        function obj = add_constraints(obj, mm, nm, dm, mpopt)
            dme = obj.data_model_element(dm);
            rgen_dme = dm.elements.reserve_gen;
            igr = rgen_dme.gen; %% index of online gen for each online reserve gen

            Areq = dme.zones(:, igr);
            lreq = dme.req;

            mm.add_lin_constraint('Rreq', Areq, lreq, [], {'R'});
        end

        function obj = data_model_update(obj, mm, nm, dm, mpopt)
            dme = obj.data_model_element(dm);

            %% get reserve zone prices
            ll = mm.get_idx('lin');
            prc = mm.soln.lambda.mu_l(ll.i1.Rreq:ll.iN.Rreq) / dm.base_mva;

            %% update in the data model
            dme.tab.prc(dme.on) = prc;
        end
    end     %% methods
end         %% classdef


function [maps,data,stats] = RippleStats(filtered,ripples,varargin)

%RippleStats - Compute descriptive stats for ripples (100~200Hz oscillations).
%
%  USAGE
%
%    [maps,data,stats] = RippleStats(filtered,ripples,<options>)
%
%    filtered       ripple-band filtered samples (one channel)
%    ripples        ripple timing information (obtained using FindRipples)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'frequency'   sampling rate (in Hz) (default = 1250Hz)
%     'durations'   durations before and after ripple peak (in s)
%                   (default = [-0.5 0.5])
%    =========================================================================
%
%  OUTPUT
%
%    maps.ripples               instantaneous amplitude (one ripple per row)
%    maps.frequency             instantaneous frequency
%    maps.phase                 instantaneous phase
%    maps.amplitude             enveloppe amplitude
%    data.peakFrequency         frequency at peak
%    data.peakAmplitude         amplitude at peak
%    data.duration              durations
%    stats.durationAmplitude    correlation between duration and amplitude (rho, p)
%    stats.durationFrequency    correlation between duration and frequency (rho, p)
%    stats.amplitudeFrequency   correlation between amplitude and frequency (rho, p)
%    stats.acg.data             autocorrelogram data
%    stats.acg.t                autocorrelogram time bins
%
%  SEE
%
%    See also FindRipples, SaveRippleEvents, PlotRippleStats.

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

% Default values
samplingRate = 1250;
durations = [-50 50]/1000;
nCorrBins = 50;
%  corrBinSize = 400;
corrDuration = 20;
corrBinSize = 0.01;

% Check number of parameters
if nargin < 2,
  error('Incorrect number of parameters (type ''help RippleStats'' for details).');
end

% Check parameter sizes
if size(filtered,2) ~= 2,
	error('Parameter ''filtered'' is not a Nx2 matrix (type ''help RippleStats'' for details).');
end
%  if size(ripples,2) ~= 4,
%  	error('Parameter ''ripples'' is not a Nx4 matrix (type ''help RippleStats'' for details).');
%  end
if size(ripples,2) < 3,
	error('Parameter ''ripples'' is not a Nx4 or Nx4 matrix (type ''help RippleStats'' for details).');
end

% Parse parameter list
for i = 1:2:length(varargin),
	if ~ischar(varargin{i}),
		error(['Parameter ' num2str(i+2) ' is not a property (type ''help RippleStats'' for details).']);
	end
	switch(lower(varargin{i})),
		case 'frequency',
			samplingRate = varargin{i+1};
			if ~isdscalar(samplingRate,'>0'),
				error('Incorrect value for property ''frequency'' (type ''help RippleStats'' for details).');
			end
		case 'durations',
			durations = varargin{i+1};
			if ~isdvector(durations,'#2','<'),
				error('Incorrect value for property ''durations'' (type ''help RippleStats'' for details).');
			end
		otherwise,
			error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help RippleStats'' for details).']);
	end
end

nBins = floor(samplingRate*diff(durations)/2)*2+1; % must be odd
nHalfCenterBins = 3;
centerBin = ceil(nBins/2);
centerBins = centerBin-nHalfCenterBins:centerBin+nHalfCenterBins;

% Compute instantaneous phase and amplitude
h = hilbert(filtered(:,2));
phase(:,1) = filtered(:,1);
phase(:,2) = angle(h);
amplitude(:,1) = filtered(:,1);
amplitude(:,2) = abs(h);
unwrapped(:,1) = filtered(:,1);
unwrapped(:,2) = unwrap(phase(:,2));
% Compute instantaneous frequency
frequency = Diff(unwrapped,'smooth',0);
frequency(:,2) = frequency(:,2)/(2*pi);

% Compute ripple map
[r,i] = Sync(filtered,ripples(:,2),'durations',durations);
maps.ripples = SyncMap(r,i,'durations',durations,'nbins',nBins,'smooth',0);

% Compute frequency Map
[f,i] = Sync(frequency,ripples(:,2),'durations',durations);
maps.frequency = SyncMap(f,i,'durations',durations,'nbins',nBins,'smooth',0);

% Compute phase map
[p,i] = Sync(phase,ripples(:,2),'durations',durations);
maps.phase = SyncMap(p,i,'durations',durations,'nbins',nBins,'smooth',0);

% Compute amplitude map
[a,i] = Sync(amplitude,ripples(:,2),'durations',durations);
maps.amplitude = SyncMap(a,i,'durations',durations,'nbins',nBins,'smooth',0);

% Ripple frequency and amplitude at peak
data.peakFrequency = maps.frequency(:,centerBin);
data.peakAmplitude = maps.amplitude(:,centerBin);

% Ripple durations
data.duration = ripples(:,3)-ripples(:,1);

% Autocorrelogram and correlations
%  if nargin > 2,
%  	[stats.acg.data,stats.acg.t] = CCG(ripples(:,2),1,'binSize',corrBinSize,'halfBins',nCorrBins/2);
	[stats.acg.data,stats.acg.t] = CCG(ripples(:,2),1,'binSize',corrBinSize);
	[stats.amplitudeFrequency.rho,stats.amplitudeFrequency.p] = corrcoef(data.peakAmplitude,data.peakFrequency);
	[stats.durationFrequency.rho,stats.durationFrequency.p] = corrcoef(data.duration,data.peakFrequency);
	[stats.durationAmplitude.rho,stats.durationAmplitude.p] = corrcoef(data.duration,data.peakAmplitude);
%  end


function p = prior_gaussian(varargin)
%PRIOR_GAUSSIAN  Gaussian prior structure
%
%  Description
%    P = PRIOR_GAUSSIAN('PARAM1', VALUE1, 'PARAM2', VALUE2, ...)
%    creates Gaussian prior structure in which the named
%    parameters have the specified values. Any unspecified
%    parameters are set to default values.
%
%    P = PRIOR_GAUSSIAN(P, 'PARAM1', VALUE1, 'PARAM2', VALUE2, ...)
%    modify a prior structure with the named parameters altered
%    with the specified values.
%
%    Parameters for Gaussian prior [default]
%      mu       - location [0]
%      s2       - scale squared (variance) [1]
%      mu_prior - prior for mu [prior_fixed]
%      s2_prior - prior for s2 [prior_fixed]
%
%  See also
%    PRIOR_*

% Copyright (c) 2000-2001,2010 Aki Vehtari
% Copyright (c) 2010 Jaakko Riihim�ki

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  ip=inputParser;
  ip.FunctionName = 'PRIOR_GAUSSIAN';
  ip.addOptional('p', [], @isstruct);
  ip.addParamValue('mu',0, @(x) isscalar(x) && x>0);
  ip.addParamValue('mu_prior',[], @(x) isstruct(x) || isempty(x));
  ip.addParamValue('s2',1, @(x) isscalar(x) && x>0);
  ip.addParamValue('s2_prior',[], @(x) isstruct(x) || isempty(x));
  ip.parse(varargin{:});
  p=ip.Results.p;

  if isempty(p)
    init=true;
    p.type = 'Gaussian';
  else
    if ~isfield(p,'type') && ~isequal(p.type,'Gaussian')
      error('First argument does not seem to be a valid prior structure')
    end
    init=false;
  end

  % Initialize parameters
  if init || ~ismember('mu',ip.UsingDefaults)
    p.mu = ip.Results.mu;
  end
  if init || ~ismember('s2',ip.UsingDefaults)
    p.s2 = ip.Results.s2;
  end
  % Initialize prior structure
  if init
    p.p=[];
  end
  if init || ~ismember('mu_prior',ip.UsingDefaults)
    p.p.mu=ip.Results.mu_prior;
  end
  if init || ~ismember('s2_prior',ip.UsingDefaults)
    p.p.s2=ip.Results.s2_prior;
  end

  if init
    % set functions
    p.fh.pak = @prior_gaussian_pak;
    p.fh.unpak = @prior_gaussian_unpak;
    p.fh.lp = @prior_gaussian_lp;
    p.fh.lpg = @prior_gaussian_lpg;
    p.fh.recappend = @prior_gaussian_recappend;
  end
end

function [w, s] = prior_gaussian_pak(p)

  w=[];
  s={};
  if ~isempty(p.p.mu)
    w = p.mu;
    s=[s; 'Gaussian.mu'];
  end
  if ~isempty(p.p.s2)
    w = [w log(p.s2)];
    s=[s; 'log(Gaussian.s2)'];
  end
end

function [p, w] = prior_gaussian_unpak(p, w)

  if ~isempty(p.p.mu)
    i1=1;
    p.mu = w(i1);
    w = w(i1+1:end);
  end
  if ~isempty(p.p.s2)
    i1=1;
    p.s2 = exp(w(i1));
    w = w(i1+1:end);
  end
end

function lp = prior_gaussian_lp(x, p)

  lp = 0.5*sum(-log(2*pi) -log(p.s2)- 1./p.s2 .* sum((x-p.mu).^2,1));

  if ~isempty(p.p.mu)
    lp = lp + p.p.mu.fh.lp(p.mu, p.p.mu);
  end
  if ~isempty(p.p.s2)
    lp = lp + p.p.s2.fh.lp(p.s2, p.p.s2) + log(p.s2);
  end
end

function lpg = prior_gaussian_lpg(x, p)

  lpg = (1./p.s2).*(p.mu-x);

  if ~isempty(p.p.mu)
    lpgmu = sum((1./p.s2).*(x-p.mu)) + p.p.mu.fh.lpg(p.mu, p.p.mu);
    lpg = [lpg lpgmu];
  end
  if ~isempty(p.p.s2)
    lpgs2 = (sum(-0.5*(1./p.s2-1./p.s2.^2.*(x-p.mu).^2 )) + p.p.s2.fh.lpg(p.s2, p.p.s2)).*p.s2 + 1;
    lpg = [lpg lpgs2];
  end
end

function rec = prior_gaussian_recappend(rec, ri, p)
% The parameters are not sampled in any case.
  rec = rec;
  if ~isempty(p.p.mu)
    rec.mu(ri,:) = p.mu;
  end
  if ~isempty(p.p.s2)
    rec.s2(ri,:) = p.s2;
  end
end


clear;
data = importdata('road1_fiber_ms50_r10.csv');
data = data.data;

figure('DefaultAxesFontSize',16);
ax = gca;

hold on;plot(1:144,data(1:144,4),'k-.','linewidth',0.5);
hold on;plot(144+1:2*144,data(144+1:2*144,4),'color',[0,0.4470,0.7410],'linewidth',2);
hold on;plot(2*144+1:3*144,data(2*144+1:3*144,4),'k-.','linewidth',0.5);
hold on;plot(3*144+1:5*144,data(3*144+1:5*144,4),'color',[0,0.4470,0.7410],'linewidth',2);
hold on;plot(5*144+1:6*144,data(5*144+1:6*144,4),'k-.','linewidth',0.5);
hold on;plot(6*144+1:7*144,data(6*144+1:7*144,4),'color',[0,0.4470,0.7410],'linewidth',2);

ax.XTick = [144,2*144,3*144,4*144,5*144,6*144,7*144];
ax.XTickLabel = [' ';' ';' ';' ';' ';' ';' '];
ax.YTick = [0,60];
ax.YTickLabel = [' ';' '];
x = [144,2*144,2*144,144];
y = [10,10,50,50];

v1 = [144,0; 2*144,0; 2*144,60; 144,60];
v2 = v1; v2(:,1)=v1(:,1)+2*144;
v3 = v2; v3(:,1)=v2(:,1)+144;
v4 = v3; v4(:,1)=v3(:,1)+2*144;
f = [1,2,3,4];
patch('faces',f,'vertices',v1,'edgecolor',[0.5 0.5 0.5],'facecolor','green','facealpha',0.1);
patch('faces',f,'vertices',v2,'edgecolor',[0.5 0.5 0.5],'facecolor','green','facealpha',0.1);
patch('faces',f,'vertices',v3,'edgecolor',[0.5 0.5 0.5],'facecolor','green','facealpha',0.1);
patch('faces',f,'vertices',v4,'edgecolor',[0.5 0.5 0.5],'facecolor','green','facealpha',0.1);
xlim([10,50]);
xlim([0,7*144]);

grid on;
box off;

set(gcf, 'PaperSize', [6 2]);
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperPosition', [0 0 6 2]);
saveas(gcf,'curve1','pdf');


function y = cvx_s_sparse( m, n, i, j )
%CVX_S_SPARSE Matrices with a fixed sparsity pattern.

if nargin < 3,
    error( 'Sparsity structure missing.' );
elseif ~isnumeric( i ) || ~isnumeric( j ),
    error( 'Sparsity arguments must be vectors of nonnegative integers.' );
end
i = i(:);
j = j(:);
if any( i <= 0 ) || any( j <= 0 ) || any( i ~= floor( i ) ) || any( j ~= floor( j ) ),
    error( 'Sparsity arguments must be vectors nonnegative integers.' );
elseif length( i ) ~= 1 && length( j ) ~= 1 && length( i ) ~= length( j ),
    error( 'Sparsity arguments have incompatible size.' );
elseif any( i > m ) || any( j > n ),
    error( 'One or more indices are out of range.' );
end
nz = max( length( i ), length( j ) );
y = min( sparse( 1 : nz, i + ( j - 1 ) * m, 1, nz, m * n ), 1 );

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


function [dA,twt]=diffrd3(fname)
% diffs an rd3 file... (requires the .rad file to be present)
% syntax: [dA,twt]=loadrd3('prof4')
%
% Aslak Grinsted 2002
%

% load details from .RAD file

fname=strrep(lower(fname),'.rd3','');

tracecount=inf;
starttrace=1;
stack=0;

infos=rd3info(fname,'scans','samples','timewindow');
sz=infos{2};
timewindow=infos{3};

twt=((1:sz)'-1)*timewindow*1e-9/sz;

%loads the rd3 file
fid=fopen([fname '.rd3'],'r');
if (starttrace>1)
   fseek(fid,(starttrace-1)*sz*2,0);
end

blocksize=1+fix(1000000/sz); %number of traces to read at a time...

lastTrace=[];
traceIdx=1;
dA=zeros(1,1);
tracesread=0;
while ((~feof(fid))&(tracesread<tracecount))
    B=fread(fid,[sz blocksize],'short');
    if isempty(lastTrace)
        lastTrace=B(:,1); %ugly hack! (but ok)
    end
    for ii=1:size(B,2)
        dA(traceIdx)=sum(abs(lastTrace-B(:,ii)).*twt); %maybe multiply by twt to do some correction for decay of amps...
        traceIdx=traceIdx+1;
        lastTrace=B(:,ii);
    end
    tracesread=tracesread+size(B,2);
end

dA=dA/mean(dA);

fclose(fid);


% sensors.m
%   Compute the output of rate gyros, accelerometers, and pressure sensors
%
%  Revised:
%   3/5/2010  - RB
%   5/14/2010 - RB

function y = sensors(uu, P)

    % relabel the inputs
%    pn      = uu(1);
%    pe      = uu(2);
    pd      = uu(3);
%    u       = uu(4);
%    v       = uu(5);
%    w       = uu(6);
    phi     = uu(7);
    theta   = uu(8);
%    psi     = uu(9);
    p       = uu(10);
    q       = uu(11);
    r       = uu(12);
    F_x     = uu(13);
    F_y     = uu(14);
    F_z     = uu(15);
%    M_l     = uu(16);
%    M_m     = uu(17);
%    M_n     = uu(18);
    Va      = uu(19);
%    alpha   = uu(20);
%    beta    = uu(21);
%    wn      = uu(22);
%    we      = uu(23);
%    wd      = uu(24);

    % simulate rate gyros (units are rad/sec)
    y_gyro_x = p + P.sigma_gyro * randn;
    y_gyro_y = q + P.sigma_gyro * randn;
    y_gyro_z = r + P.sigma_gyro * randn;

    % simulate accelerometers (units of g)
    y_accel_x = F_x / P.mass / P.gravity + sin(theta) + P.sigma_accel * randn;
    y_accel_y = F_y / P.mass / P.gravity - cos(theta) * sin(phi) + P.sigma_accel * randn;
    y_accel_z = F_z / P.mass / P.gravity - cos(theta) * cos(phi) + P.sigma_accel * randn;

    % simulate pressure sensors
    y_static_pres = P.rho * P.gravity * (-pd) + P.beta_abs_pres + P.sigma_abs_pres * randn;
    y_diff_pres = P.rho * Va^2 / 2 + P.beta_diff_pres + P.sigma_diff_pres * randn;

    % construct total output
    y = [...
        y_gyro_x;...
        y_gyro_y;...
        y_gyro_z;...
        y_accel_x;...
        y_accel_y;...
        y_accel_z;...
        y_static_pres;...
        y_diff_pres;...
    ];

end


function vis_debug_bbox_pred(imdb, rcnn_model, bbox_reg, cls)
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

image_ids = imdb.image_ids;
min_overlap = 0.3;
feat_opts = bbox_reg.training_opts;

roidb = imdb.roidb_func(imdb);
class_id = imdb.class_to_id(cls);

bbox_regressor = bbox_reg.models{class_id};

perm1 = randperm(length(image_ids));
%for i = 1:length(image_ids)
for i = perm1
  fprintf('%s: debug (%s) %d/%d\n', procid(), imdb.name, i, length(image_ids));

  if exist('cls','var')
    if isempty(find(roidb.rois(i).class == class_id))
      continue;
    end
  end

  d = rcnn_load_cached_pool5_features(feat_opts.cache_name, ...
      imdb.name, image_ids{i});
  if isempty(d.feat)
    continue;
  end

  d.feat = rcnn_pool5_to_fcX(d.feat, feat_opts.layer, rcnn_model);
  d.feat = rcnn_scale_features(d.feat, feat_opts.feat_norm_mean);

  if feat_opts.binarize
    d.feat = (d.feat > 0);
  end

  im = imread(imdb.image_at(i));

  if exist('cls','var')
    sel_gt = find(d.class == class_id);
  else
    sel_gt = find(d.class > 0);
  end
  gt_boxes = d.boxes(sel_gt, :);
  gt_classes = d.class(sel_gt);

  if exist('cls','var')
    max_ov = d.overlap(:, class_id);
  else
    max_ov = max(d.overlap, [], 2);
  end
  sel_ex = find(max_ov >= min_overlap);
  ex_boxes = d.boxes(sel_ex, :);
  ex_feat = d.feat(sel_ex, :);

  %for j = 1:size(ex_boxes, 1)
  perm = randperm(size(ex_boxes,1), min(10, size(ex_boxes,1)));
  for j = perm
    ex_box = ex_boxes(j, :);
    ov = boxoverlap(gt_boxes, ex_box);
    [max_ov, assignment] = max(ov);
    gt_box = gt_boxes(assignment, :);
    cls = gt_classes(assignment);

    src_w = ex_box(3) - ex_box(1) + eps;
    src_h = ex_box(4) - ex_box(2) + eps;
    src_ctr_x = ex_box(1) + 0.5*src_w;
    src_ctr_y = ex_box(2) + 0.5*src_h;

    gt_w = gt_box(3) - gt_box(1) + eps;
    gt_h = gt_box(4) - gt_box(2) + eps;
    gt_ctr_x = gt_box(1) + 0.5*gt_w;
    gt_ctr_y = gt_box(2) + 0.5*gt_h;

%    dst_ctr_x = (gt_ctr_x - src_ctr_x) * 1/src_w;
%    dst_ctr_y = (gt_ctr_y - src_ctr_y) * 1/src_h;
%    dst_scl_w = log(gt_w / src_w);
%    dst_scl_h = log(gt_h / src_h);
%
%    target = [dst_ctr_x dst_ctr_y dst_scl_w dst_scl_h];

    pred_box = rcnn_predict_bbox_regressor(bbox_regressor, ex_feat(j,:), ex_box);

    pred_box(1) = max(pred_box(1), 1);
    pred_box(2) = max(pred_box(2), 1);
    pred_box(3) = min(pred_box(3), size(im,2));
    pred_box(4) = min(pred_box(4), size(im,1));

    ovs = boxoverlap(cat(1, pred_box, ex_box), gt_box);

    showboxesc(im, gt_box, 'g', '-');
    showboxesc([], ex_box, 'b', '-');
    showboxesc([], pred_box, 'r', '-');
    hold on;
    plot(gt_ctr_x, gt_ctr_y, 'gd');
    plot(src_ctr_x, src_ctr_y, 'rd');
    hold off;
    title(sprintf('green = GT box;  blue = original box;  red = predicted box;  orig %.3f  pred %.3f', ovs(2), ovs(1)));

    pause;
  end
end