function spm_dem_cue_movie(DEM,q)
% creates a movie of cued pointing
% FORMAT spm_dem_cue_movie(DEM,q)
%
% DEM - DEM structure from reaching simulations
% q   - flag switching from true to perceived reaching
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_dem_set_movie.m 4231 2011-03-07 21:00:02Z karl $

% Dimensions
%--------------------------------------------------------------------------
N    = size(DEM.pU.v{1},2);
n    = size(DEM.pP.P{1},2);

% evaluate true location (targets)
%----------------------------------------------------------------------
for i = 1:N
    L(:,:,i) = DEM.pP.P{1};
end

if nargin > 1

    % evaluate perceived positions (motor plant)
    %----------------------------------------------------------------------
    x    = tan(DEM.qU.v{1}(1:2,:));                  % finger location
    c    = DEM.qU.v{1}(4 + (1:n),:);                 % target contrast

else

    % evaluate true positions (motor plant)
    %----------------------------------------------------------------------
    x    = tan(DEM.pU.v{1}(1:2,:));                  % finger location
    c    = DEM.pU.v{1}(4 + (1:n),:);                 % target contrast

end
c    = c - min(c(:)) + 1/32;
c    = c/max(c(:));
fin  = imread('pointfinger.jpg');

% movie
%--------------------------------------------------------------------------
s     = 2;
for i = 1:N

    cla
    axis image ij
    hold on

    % finger
    %----------------------------------------------------------------------
    imagesc(([-1 0] + .68)*s + x(1,i),([-1 0] + .96)*s + x(2,i),fin);
    hold on

    % trajectory
    %----------------------------------------------------------------------
    plot(x(1,1:i),x(2,1:i),'k:')

    % targets
    %----------------------------------------------------------------------
    for j = 1:n
        plot(L(1,j,i),L(2,j,i),'.','MarkerSize',64,'color',[c(j,i) (1 - c(j,i)) 0])
    end
    axis([-1 1 -1 1]*2)
    hold off
    drawnow

    % save
    %----------------------------------------------------------------------
    M(i) = getframe(gca);

end

% set ButtonDownFcn
%--------------------------------------------------------------------------
h = findobj(gca,'type','image');
set(h(1),'Userdata',{M,16})
set(h(1),'ButtonDownFcn','spm_DEM_ButtonDownFcn')


function plot_PointInfo(params)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% ginput(nPoints);

fYear=params.fTstart;
fMc=params.fMc;
fMc=2.0
[fLon0,fLat0]=ginput(1);
hold on;plot(fLon0,fLat0,'kx','MarkerSize',10);

%calculate nearest grid point
mDistance=distance(repmat(fLat0,size(params.mPolygon,1),1),...
    repmat(fLon0,size(params.mPolygon,1),1),...
    params.mPolygon(:,2),params.mPolygon(:,1));
[Xi,Ni]=sort(mDistance);
nCenter=Ni(1)
vPoly0=params.mPolygon(nCenter,:)
hold on;plot(vPoly0(1),vPoly0(2),'r*','MarkerSize',10);

for i=1:size(params.mNumDeclus,2)
    nIndices=params.caNodeIndices{nCenter}(logical(params.mNumDeclus(:,i)));
    nIndices2=params.caNodeIndices{nCenter};
%     nIndices=params.caNodeIndices{nCenter};
    mSample=params.mCatalog(nIndices,:);
    mSample2=params.mCatalog(nIndices2,:);
    vSel=((mSample(:,3)>=fYear) & (mSample(:,6)>=fMc));
    vSel2=((mSample2(:,3)>=fYear) & (mSample2(:,6)>=fMc));
    mSample=mSample(vSel,:);
    mSample2=mSample2(vSel2,:);
    mSample=mSample(1:params.vN,:);
    mSample2=mSample2(1:params.vN,:);
    % hold on;plot(mSample(:,1),mSample(:,2),'w*')

    if i==1
        figure;
    else
        hold on;
    end
i;
    plot(sort(mSample(:,3)),(1:size(mSample,1)),'LineWidth',2);
    if i==1
        hold on;plot(sort(mSample2(:,3)),(1:size(mSample,1)),...
        'r','LineWidth',2);
    end
end

    plotshape;

   function plotshape
        xlabel('Time [Yrs]','FontSize',14);
        ylabel('Cum # of Earthquakes','FontSize',14);
        set(gca,'FontSize',12);
%         set(gcf,'Renderer','zbuffer');
%         shading interp;

%
%
% for i=1:size(params.mNumDeclus,2)
%     vSel=( (params.mCatalog(:,3)>=fYear) & ...
%     (params.mCatalog(:,6)>=fMc) & ...
%     (params.mNumDeclus(:,i)==1) );
%     if i==1
%         figure;
%         plot(params.mCatalog(vSel,3),...
%             cumsum(params.mNumDeclus(vSel,i)),...
%             '-','LineWidth',1,'Color',[.8 .8 .8]);
%     else
%         hold on;
%         plot(params.mCatalog(vSel,3),...
%             cumsum(params.mNumDeclus(vSel,i)),...
%             '-','LineWidth',1,'Color',[.8 .8 .8]);
%     end
% end
%
% set(gca,'FontSize',16)
% xlabel('Years','fontsize',20)
% ylabel('Cum # Earthquakes','fontsize',20)
% % legend('Reasenberg 1985, Xmeff=3.0',...
% %     'Reasenberg (Helmstetter 2007), Xmeff=3.0',...
% %     'Reasenberg 1985, Xmeff=2.5',...
% %     'Reasenberg 1985, Xmeff=2.0',...
% %     'Reasenberg 1985, Xmeff=1.5',...
% %     'Gardner & Knopoff 1974',...
% %     'Utsu 2002',...
% %     'Uhrhammer 1986');


function sdc_coeff = mfcc2sdc(CepCoeff,N,d,P,K)
%--------------------------------------------------------------------------
%Function for Shifted Delta Coefficient Computation.
%
% If you have any query or suggestion please mail to sahidullahmd@gmail.com
% Ussage: sdc_coeff = mfcc2sdc(CepCoeff,N,d,P,k)
%         CepCoeff: MFCC Coefficients stored in row-wise
%         N: NoOfCepstrum i.e. no of column of CepCoeff
%         d: Amount of shift for delta computation
%         P: Amount of shift for next frame whose deltas are to be
%            computed.
%         K: No of frame whose deltas are to be stacked.
%
%         sdc_coeff: Shifted delta coefficient of CepCoeff.
%                    Dimension of the output: NumberOfFrame x N*K
% Example:
% CepCoeff=rand(1000,19); % Randomly generate MFCC of 1000 frames
% sdc_coeff = mfcc2sdc(CepCoeff,7,1,3,7); %Compute SDC Coefficients.
%
%Details of shifted delta computation is available in W.M. Campbell, J.P.
%    Campbell, D.A. Reynolds, E. Singer, P.A. Torres-Carrasquillo, Support
%    vector machines for speaker and language recognition,
%    Computer Speech & Language, Volume 20, Issues 2-3,
%    Odyssey 2004: The speaker and Language Recognition
%    Workshop - Odyssey-04, April-July 2006, Pages 210-229.
%--------------------------------------------------------------------------
ToT=size(CepCoeff,1); %Actual Number of Frames
CepCoeff=(horzcat(CepCoeff', CepCoeff(1:P*(K-1),:)'))'; %Circular padding
[NoOfFrame NoOfCoeff]=size(CepCoeff); %Note the number of frames and
%                                             number of coefficients (N).
% % N=7; d=1; P=3; k=7;      %Default values are hard-coded if necessary.
delt=(mfcc2delta(CepCoeff,d))';   %Delta Feature Computation
sd_temp=cell(1,K);                %Preparation of a cell array for delta's
for i=1:K                         %For k number of shifts
    temp=delt(:,P*(i-1)+1:1:end); %P: Size of shift
    sd_temp{i}=temp(:,1:ToT);     %Take only desired (i.e. ToT) no of deltas.
end
sdc_coeff=cell2mat(sd_temp');     %Stacking the SDCs in a single variable
sdc_coeff=sdc_coeff';
%--------------------------------------------------------------------------


%==============================================================================
% 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/
%==============================================================================
% Artificial data motivated by mass-preserving imaging
%==============================================================================

checkDataFile
if expfileExists, return; end;

viewPara = {'viewImage','viewImage2D','colormap',gray(256)};
imgPara  = {'imgModel','splineInter','regularizer','moments','theta',1e-2};
traPara  = {'trafo','affine2D'};
disPara  = {'distance','SSD'};
regPara  = {'regularizer', 'mbHyperElastic','alpha',1,...
  'alphaLength',1000,'alphaArea',0,'alphaVolume',100};

expfile = jpgs2data('','Gauss-T.jpg','Gauss-R.jpg', ...
  'omega',[0,1,0,1],'m',[256,256],...
  'viewPara',viewPara,'imgPara',imgPara);

save(expfile,'-append','viewPara','imgPara','traPara','disPara','regPara');
checkDataFile
%==============================================================================


function [imageCha, ssim_map, metrics] = algo_FCSA_SLEP_2D_real( obj,input )
% 2D real-valued variant of FCSA
% based on Huang et al. paper on FCSA
% with Liu and Ye's idea to use the Moreau-Yosida regularization to solve the group lasso problem, using the SLEP package.
%
% input:
% obj           CS reconstruction object (holding all parameters)
% input         struct containing recon parameters and image
%
% output:
% imageCha      reconstructed channel individual image
% ssim_map      structural similarity map
% metrics       evaluation metrics
%
% (c) Marc Fischer, Thomas Kuestner, May 2015
% -------------------------------------------------------------------------

timer_SLEP = tic;

%% variables:
% internal flags
flag_wavetree = true;
flag_fast = true;
flag_extendImage = true;

% internal variables:
L = 1;
t_old = 1;
NLTV_struct.kernelratio = 3;
NLTV_struct.windowratio = 6;
NLTV_struct.nThreads = 1;  % mind this option if used with -singleCompThread on BWCluster
itrNLTV = obj.maxitr - 5;
% chambolle tv:
parsin.MAXITER=100; parsin.tv='iso'; % 'iso' or 'l1'

% from obj:
% maxitr = obj.maxitr;
maxitr = obj.iNINNER;
% n1 = obj.measPara.dim(1);
% n2 = obj.measPara.dim(2);
n1 = input.n1;
n2 = input.n2;
% nSlices = obj.measPara.dim(3);
nCha = obj.measPara.dim(5);
lambdaWave = obj.lambda;
lambdaTV = obj.lambdaTV;
lambdaGroup = obj.lambdaGroup;
NLTV_struct.filterstrength = obj.lambdaNLTV_h; % 0.03 % converted from NLTV h = 0.01 %old: used: 3e-10
lambdaNLTV = obj.lambdaNLTV;
lambdaNLTV_h = obj.lambdaNLTV_h;
regularizerWeights = obj.regularizerWeights;
flagTV = obj.flagTV;
flagTV_iso = obj.flagTV_iso;
flagWave = obj.flagWave;
flagGroup = obj.flagGroup;
flagNLTV = obj.flagNLTV;
flagSBNLTV = obj.flagSBNLTV;
waveletStages = obj.trafo.waveletStages;
waveletFilterName_l1 = obj.trafo.waveletFilterName_l1;
waveletFilterName_l12 = obj.trafo.waveletFilterName_l12;

% from input:
b=input.b;
mask = input.mask;
G_slep = input.G_slep;
Gt_slep = input.Gt_slep;
ind = input.ind;
nodesize = input.nodesize;
waveS_l1 = input.waveS_l1;
waveS_l12 = input.waveS_l12;
waveS_SLEP = input.waveS_SLEP; % also change name in CS_2D
SLEP_extend_y = waveS_SLEP(waveletStages+2,1) - waveS_l12(waveletStages+2,1);
SLEP_extend_x = waveS_SLEP(waveletStages+2,2) - waveS_l12(waveletStages+2,2);
z_proxA = cell(1,nCha);

% im_ref = input.im_ref;
% im_ref_full = zeros(n1,n2);
% for j = 1:nCha
%     im_ref_full = im_ref_full + abs(im_ref{1,j}).^2;
% end;
% im_ref_full = sqrt(im_ref_full);
clear input

% initialize cells/vectors
for j=1:nCha
    FTb{1,j} = real(iFFT2D(b{1,j}));
    % y{1,j} = real(FTb{1,j});
    % y{1,j+nCha} = imag(FTb{1,j});
end;
z = FTb; % starting point

x_wave = cell(1,nCha);
x_helper = x_wave;
x_wave_helper = x_wave;
x_tv = x_wave;
x_nltv = x_wave;
for j=1:nCha
    x_nltv{1,j} = 0;
end;
x_g = x_wave;
x_g_helper = x_wave;
x_g_proxA = x_wave;
y = x_wave;
slep_thresh = x_wave;

%% MAD dependent lambdas:
flag_MAD = true;
if flag_MAD
    x_wavedec = cell(1,nCha);
    threshold = zeros(1:nCha);
    for j=1:nCha % 2*nCha
        x_wavedec{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l1); % atm only based on l1-daubechie
        x_wave_fine_scale = size(x_wavedec{1,j},2) - (3*waveS_l1(waveletStages+1,1)*waveS_l1(waveletStages+1,2));
        threshold(j) = mad(x_wavedec{1,j}(x_wave_fine_scale:end),1);
    end;
    clear x_wavedec
else
    threshold(1:nCha) = 1;
end;

threshold_wave(j) = lambdaWave * threshold(j) * 2/L;
threshold_TV(j) = lambdaTV * threshold(j) * 2/L;
threshold_group(j) = lambdaGroup * threshold(j) * 2/L;
ind(3,:) = threshold_group(j)* ind(3,:); % weights of slep tree
threshold_NLTV(j) = lambdaNLTV; % * threshold(j) * 2/L;
threshold_NLTV_h(j) = lambdaNLTV_h; %*threshold(j); % adjust carefully or NLTV won't find a solution. lambdaNLTV_h should be < 0.01

%% initialize metrics:
    itr = 0;
   	metrics.xtime(itr+1)= 0;
%     [metrics, ssim_map{1,1}] = get_metrics_itr( im_ref, im_ref_full, z, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );
    ssim_map = [];

%% recon
dispProgress('Proximal Average', 0, maxitr);
for itr = 1:maxitr  % total iter counter

    t_new = (1+sqrt(1+4*t_old^2))/2;
    t_old = t_new;

    y_old = z;   % y_old = y for complex case

%% landweber step
    for j = 1:nCha
        x_helper{1,j} = real(iFFT2D(FFT2D_mask(z{1,j},mask))) -FTb{1,j} ;
        z{1,j} = z{1,j} - real(x_helper{1,j})/L;
    end;

%% l1-Wavelet
    if flagWave
            for j = 1:nCha % 2*nCha
                    x_wave_helper{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l1);
                    x_wave_helper{1,j} = softthresh_real(x_wave_helper{1,j},threshold_wave(j));
                    x_wave{1,j} = waverec2(x_wave_helper{1,j},waveS_l1,waveletFilterName_l1);
            end;
    end;

%% TV
    if flagTV
        if ~flagTV_iso
            for j = 1:nCha
                    x_tv{1,j} = MTV_2D(z{1,j},threshold_TV(j),n1,n2);
            end;
        else
            for j = 1:nCha
                if (itr==1)
                    [x_tv{1,j}, P]=denoise_TV_One((z{1,j}), threshold_TV(j),-inf,inf,[],parsin);
                else
                    [x_tv{1,j}, P]=denoise_TV_One((z{1,j}), threshold_TV(j),-inf,inf,P,parsin);
                end;
            end;
        end;
    end;

%% NLTV
    if flagNLTV
        if itr >= itrNLTV
            if flagSBNLTV
                for j = 1:nCha
                    x_nltv{1,j} = SB_NLTVfunc_slim_rescale(z{1,j},n1,n2, threshold_NLTV(j), threshold_NLTV_h(j) );
                end;
            else
                for j = 1:nCha
                    % if mod(itr,5) == 0 || itr == 1
                        x_nltv{1,j} = NLMF(z{1,j},NLTV_struct);
                        x_nltv{1,j} = (L.*z{1,j} + 2*threshold_NLTV(j)*x_nltv{1,j})./(L+2*threshold_NLTV(j));
                    % end;
                end;
            end;
        else
            x_nltv{1,j} = 0;
       end;
    end;

%% l12-Wavelet - via SLEP
    if flagGroup
        for j = 1:nCha
            if flag_extendImage
                z_proxA{1,j} = extend_image(z{1,j}, waveS_SLEP, waveletStages, SLEP_extend_y, SLEP_extend_x);
                x_g_helper{1,j} = wavedec2(z_proxA{1,j},waveletStages,waveletFilterName_l12);
            else
                x_g_helper{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l12);
            end;

            slep_thresh{1,j} = x_g_helper{1,j}(G_slep);
            slep_thresh{1,j} = altra( slep_thresh{1,j}, size(slep_thresh{1,j},2), ind, nodesize);
            slep_thresh{1,j} = slep_thresh{1,j}';
            slep_thresh{1,j} = slep_thresh{1,j}(Gt_slep);

            x_g_proxA{1,j} = waverec2(slep_thresh{1,j},waveS_SLEP,waveletFilterName_l12);
            x_g{1,j} =  x_g_proxA{1,j}(1:end-SLEP_extend_y,1:end-SLEP_extend_x);
        end;
    end;

%% add prox(.)
    for j = 1:nCha
        y{1,j} = zeros(n1,n2);
        if flagWave y{1,j} = y{1,j} + x_wave{1,j}.*regularizerWeights(1); end;
        if flagTV y{1,j} = y{1,j} + x_tv{1,j}.*regularizerWeights(2); end;
        if flagGroup y{1,j} = y{1,j} + x_g{1,j}.*regularizerWeights(3); end;
        if flagNLTV y{1,j} = y{1,j} + x_nltv{1,j}.*regularizerWeights(4); end;

        if itr < itrNLTV
            y{1,j} = y{1,j}/(flagTV.*regularizerWeights(2) + flagWave.*regularizerWeights(1) + flagGroup.*regularizerWeights(3));
        else
            y{1,j} = y{1,j}/(flagTV.*regularizerWeights(2) + flagNLTV.*regularizerWeights(4) + flagWave.*regularizerWeights(1) + flagGroup.*regularizerWeights(3));
        end;

        if flag_fast
        y{1,j}=y{1,j}+((t_old-1)/t_new).*(y{1,j}-y_old{1,j});
        end;
    end;

%% metrics of current itr:
%     disp(itr);
    dispProgress('Proximal Average', itr/maxitr);

   	metrics.xtime(itr+1)= toc(timer_SLEP);
    for j = 1:nCha
        z{1,j} = y{1,j};
    end;
%     [metrics, ssim_map{1,2}] = get_metrics_itr( im_ref, im_ref_full, z, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );

end;
dispProgress('Proximal Average', 'Close');

    imageCha = z;
    for j = 1:nCha
        imageCha{1,j} = turn_image( imageCha{1,j} );
    end;
%     for j = 1:nCha+1
%         ssim_map{1,1}{1,j} = turn_image( ssim_map{1,1}{1,j} );
%         ssim_map{1,2}{1,j} = turn_image( ssim_map{1,2}{1,j} );
%     end;

end


function [strika,dipa,rakea,dipdia,strikb,dipb,rakeb,dipdib,ierr] = pt2pl(trendp,plungp,trendt,plungt)

    % compute strike dip and rake (and dip direction) of two nodal planes from trend and plung of P and T axes
    %
    %     usage:
    %     call pt2pl(trendp,plungp,trendt,plungt,strika,dipa,rakea
    %    1,dipdia,strikb,dipb,rakeb,dipdib,ierr)
    %
    %     arguments:
    %     trendp         trend of P axis in degrees (INPUT)
    %     plungp         plunge of P axis in degrees (INPUT)
    %     trendt         trend of P axis in degrees (INPUT)
    %     plungt         plunge of P axis in degrees (INPUT)
    %     strika         strike angle of first nodal plane in degrees (OUTPUT)
    %     dipa           dip angle of first nodal plane in degrees (OUTPUT)
    %     rakea          rake angle of first nodal plane in degrees (OUTPUT)
    %     dipdia         dip direction angle of first nodal plane in degrees (OUTPUT)
    %     strikb         strike angle of second nodal plane in degrees (OUTPUT)
    %     dipb           dip angle of second nodal plane in degrees (OUTPUT)
    %     rakeb          rake angle of second nodal plane in degrees (OUTPUT)
    %     dipdib         dip direction angle of second nodal plane in degrees (OUTPUT)
    %     ierr           error indicator (OUTPUT)
    %
    %     errors:
    %     1              input TREND angle of P axis out of range
    %     2              input PLUNGE angle P axis out of range
    %     3              1+2
    %     4              input TREND angle of P axis out of range
    %     5              input PLUNGE angle P axis out of range
    %     6              4+5
    %     8,9,10         internal errors
    %
    % c
    %      call fpsset
    amistr=-360.;
    amastr=360.;
    amidip=0.;
    amadip=90.;
    amirak=-360.;
    amarak=360.;
    amitre=-360.;
    amatre=360.;
    amiplu=0.;
    amaplu=90.;
    orttol=2.;
    ovrtol=0.001;
    tentol=0.0001;
    dtor=0.017453292519943296;
    c360=360.;
    c90=90.;
    c0=0.;
    c1=1.;
    c2=2.;
    c3=3.;
    % c
    %      call ax2ca(trendp,plungp,px,py,pz,ierr)
    [px,py,pz,ierr] = focal_ax2ca(trendp,plungp);
    if (ierr ~= 0)
        disp(['PT2PL: ierr=' num2str(ierr)]);
        return;
    end

    %      call ax2ca(trendt,plungt,tx,ty,tz,ierr)
    [tx,ty,tz,ierr] = focal_ax2ca(trendt,plungt);
    if (ierr ~= 0)
        ierr = ierr + 3;
        disp(['PT2PL: ierr=' num2str(ierr)]);
        return;
    end

    [anx,any,anz,dx,dy,dz,ierr] = focal_pt2nd(px,py,pz,tx,ty,tz);
    if (ierr ~= 0)
        ierr = 8;
        disp(['PT2PL: ierr=' num2str(ierr)]);
        return;
    end
    [strika,dipa,rakea,dipdia,ierr] = focal_nd2pl(anx,any,anz,dx,dy,dz);
    if (ierr ~= 0)
        ierr = 9;
        disp(['PT2PL: ierr=' num2str(ierr)]);
        return;
    end
    [strikb,dipb,rakeb,dipdib,ierr] = focal_nd2pl(dx,dy,dz,anx,any,anz);
    if (ierr ~= 0)
        ierr = 10;
        disp(['PT2PL: ierr=' num2str(ierr)]);
        return;
    end
end


%% show_3dtensors(T1,...,Tn)
%
function show_3dtensors(varargin)
  n = nargin;
  % display(['Number of tensors: ' num2str(n)]);
  V = varargin{1};
  for i = 1:size(V,3)
    for j = 1:n
      T = varargin{j};
      if(isa(T,'tensor'))
        T = double(T);
      end
      switch(n)
        case 1
          imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {2,3}
          subplot(1,n,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case 4
          subplot(2,2,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {5,6}
          subplot(2,3,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {8}
          subplot(2,4,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        case {7,9}
          subplot(3,3,j), imshow(T(:,:,i),[],'InitialMagnification','fit');
        otherwise
          error('Not supported operation!');
      end
    end
    pause(0.01);
  end
end


function h=mybar(f,s,xstr,ystr,col,lineWidth,w,we)
%
% mybar(f,[s],[xstr],[ystr],[color],[lineWidth],[barwidth],[errorbarwidth])
%
%  Draws a bar graph with heights determined by f
%  and error-bars determined by s.
%
%  if input matrices are 2d, the ROWS are plotted as
%  separate sub-bars in different colors.
%
%  xlabels set to 'xstr' (columns)
%  legend set to 'ystr' (rows)
%
%  color is a string of colors, one for each subbar
%  (default is 'brgmyc')
%
%  lineWidth (default 2)
%
%  barwidth (default 0.65)
%  errorbarWidth (default 0.3)
%
%  Example:
%    f = rand(5,1)+1;
%    s = rand(5,1)/2;
%    xstr = str2mat('one','two','three','four','five');
%    ystr = '';
%    mybar(f,s,xstr,ystr,'g');
%  7/11/95  gmb Wrote it.
%  4/11/96  gmb Revised it to plot 2d data sets
%  11/19/97 gmb Converted it to Matlab version 5.0
%  12/30/97 djh Fixed bug in xlabels, for some reason it was
%               putting the 1st label under the 2nd bar, and so on.
%  1/24/97  djh Added lineWidth as optional input arg
%  3/15/01  dbr Made legend size allocation a bit more intelligent.
%
%  05/2004  arw Modified so that if you pass in a list of colors for a
%  single data vector, it applies those colors to the individual bars.
%           EXAMPLE:
%          a=rand(4,1);b=rand(4,1)/5; h=mybar(a,b,[],[],'rgby');
% OR:      mybar(a,b,[],[],[1 0 0;0 1 0;0 0 1;1 1 0]);
%
%  06/2005  ras now allows col, xstr, and ystr to be entered as cells

%%%%%% parse inputs %%%%%
if nargin==1, s=zeros(size(f));                                 end
if ~exist('col','var') | isempty(col), col='brgmyck';           end
if ~exist('lineWidth','var') | isempty(lineWidth), lineWidth=2; end
if ~exist('w','var') | isempty(w), w=0.65;                      end
if ~exist('we','var') | isempty(we), we=0.3;                    end

if(size(f,1)==1),
    % row vector instead of column -- be flexible:
    f=f';
    s=conj(s');
end

if (isreal(s)),   s = s+sqrt(-1)*s;                             end

% if col is a cell, convert to N x 3 color table
if iscell(col),   col = cell2ColorOrder(col);                   end
% size(col)
% size(f)

% ensure col spans all columns in f -- repeat colors if needed
if ischar(col)
    while length(col) < max(size(f))
        col = [col,col];
    end
else
    while size(col,1) < max(size(f))
        col = [col; col];
    end
end

sizeShift=.01; % creates space between bars in histogram ADDED LGA 10-11-05

nsubbars=size(f,2);
we=we/nsubbars;

heldstate=ishold;
plot(0,0)
set(gca,'XLim',[1-w,size(f,1)+w]);

yhilim = max(max(f+s))*1.2;
if ~isnan(yhilim)
    %set(gca,'YLim',[0,yhilim]);
end

subx=linspace(-w/2,w/2,nsubbars+1);

newplot(gca)
hold off;
hIndex=1;
for subbar=1:nsubbars
    x=[];
    y=[];
    for i=1:size(f,1);
        tempx= [i+subx(subbar),i+subx(subbar),(i+subx(subbar+1))-sizeShift,(i+subx(subbar+1))-sizeShift];
        tempy= [0,f(i,subbar),f(i,subbar),0];

        % I can find a way to add some spacing here is I want!!! - LGA
        % 101105

        if size(f,2)==1
            % single column -- each bar a diff't color
            if ischar(col)
                thisCol=col(i);
            else
                thisCol=col(i,:);

            end

            h{hIndex}=fill(tempx',tempy',thisCol);
            hold on;

        else
            % multiple columns -- each sub-bar a diff't color
            if ischar(col)
                thisCol=col(subbar);
            else
                thisCol=col(subbar,:);
            end

            h{hIndex}=fill(tempx',tempy',thisCol);
            hold on;

        end
        hIndex=hIndex+1;
        x=[x';tempx]';
        y=[y';tempy]';
    end
    %   if ((length(col)==size(f,1)) & (size(f,2)==1))
    %      % do somethign!
    %   end
    %
    %   h(subbar)={fill(x,y,col(subbar))};
    %
    a=line(get(gca,'XLim'),[0,0]);
    set(a,'Color','k');

    errx=mean([subx(subbar),subx(subbar+1)]);

    for i=1:size(f,1)

        line([i+subx(subbar),i+subx(subbar),i+subx(subbar+1)-sizeShift,i+subx(subbar+1)-sizeShift], ...
            [0,f(i,subbar),f(i,subbar),0],'Color','k','lineWidth',2);

        g=line([i+errx-sizeShift/2,i+errx-sizeShift/2],[f(i,subbar)-imag(s(i,subbar)),f(i,subbar)+real(s(i,subbar))],...
            'Color','k','lineWidth',lineWidth);
        g=line([i+errx-we/2-sizeShift/2,i+errx+we/2-sizeShift/2],[f(i,subbar)-imag(s(i,subbar)),f(i,subbar)-imag(s(i,subbar))],...
            'Color','k','lineWidth',lineWidth);
        g=line([i+errx-we/2-sizeShift/2,i+errx+we/2-sizeShift/2],[f(i,subbar)+real(s(i,subbar)),f(i,subbar)+real(s(i,subbar))],...
            'Color','k','lineWidth',lineWidth);
    end
    %     for i=1:size(f,1)
    %         line([i+subx(subbar),i+subx(subbar),i+subx(subbar+1),i+subx(subbar+1)], ...
    %             [0,f(i,subbar),f(i,subbar),0],'Color','k','lineWidth',lineWidth);
    %         g=line([i+errx,i+errx],[f(i,subbar)-imag(s(i,subbar)),f(i,subbar)+real(s(i,subbar))],...
    %             'Color','k','lineWidth',lineWidth);
    %         g=line([i+errx-we/2,i+errx+we/2],[f(i,subbar)-imag(s(i,subbar)),f(i,subbar)-imag(s(i,subbar))],...
    %             'Color','k','lineWidth',lineWidth);
    %         g=line([i+errx-we/2,i+errx+we/2],[f(i,subbar)+real(s(i,subbar)),f(i,subbar)+real(s(i,subbar))],...
    %             'Color','k','lineWidth',lineWidth);
    %     end
    %hold on
end 					%subbars

% Xlabels
set(gca,'xLimMode','manual');
set(gca,'XTick',[1:size(f,1)]);
if (exist('xstr')) & ~isempty(xstr)
    if ~isempty(xstr)
        set(gca,'XTickLabel',xstr);
    end
end

% Legend
if (exist('ystr')) & ~isempty(ystr)

    %heighten the graph
    ylim=get(gca,'Ylim');
    nLines = length(ystr);
    yMult = 1 + nLines/4; % Each legend line uses about 1/8th of the window height
    set(gca,'YLim',[ylim(1),ylim(2)*yMult]);
    bs=8;

    posgca=get(gca,'Position');
    posgcf=get(gcf,'Position');
    dx=diff(get(gca,'XLim'))/(posgca(3)*posgcf(3));
    dy=diff(get(gca,'YLim'))/(posgca(4)*posgcf(4));

    bw=bs*dx; 				%box width
    bh=bs*dy; 				%box height

    yspace=3.5*bh; 			%vertical spacing

    xlim=get(gca,'Xlim');
    ylim=get(gca,'Ylim');

    xc=xlim(1)+50*dx;
    yc=ylim(2)-30*dy;
    bx=[xc-bw,xc+bw,xc+bw,xc-bw,xc-bw];
    by=[yc+bh,yc+bh,yc-bh,yc-bh,yc+bh];

    textx=xc+bw+10*dx;
    texty=yc;

    %draw box and text
    for i=1:nLines
        if iscell(ystr)
            label = ystr{i};
        else
            label = ystr(i,:);
        end
        if size(col, 1) == 1
            fill(bx,by,col(i));
        else
            fill(bx,by,col(i,:));
        end
        line(bx,by,'lineWidth',lineWidth,'Color','k');
        text(textx,texty,label);
        by=by-yspace;
        texty=texty-yspace;

    end
end
set(gca,'XLim',[1-w,size(f,1)+w]);

if (heldstate==0)
    hold off
end

return


function P=caesar_D(C,k)
% P=plain text
% k=key (can be 0 to 26); k=0 mean No encryption
% Example: P='Hello World' k=3
% C=caesar(P,k), C=Khoor Zruog
%If you have any problem or feedback please contact me @
%%===============================================
% NIKESH BAJAJ
% Asst. Prof., Lovely Professional University, India
% Almameter: Aligarh Muslim University, India
% +919915522564, bajaj.nikkey@gmail.com
%%===============================================

P=double(C)-k;
l=find(P<65);
P(l)=P(l)+26;

l=find(P<97);
l=find(P(l)>90)
P(l)=P(l)+26;

l=find(C==32);
P(l)=32;

P=char(P);
disp(' ')
disp('Cipher Text C =')
disp(C)
disp(' ')
disp('Plain Text')


function dM = Bloch(t, M, Param, Pulse)
%BLOCH Bloch-McConnell ordinary differential equations.
%   dM = Bloch(t, M, Param, Pulse)
%
%   --args--
%   t: Function handle variable, represents the time.
%   M : magnetization vector [Mxf, Myf, Mzf, Mzr]
%   Param: Tissue parameter structure.
%
%          -fields-
%          M0f: Free pool equilibrium magnetization.
%          M0r: Restricted pool equilibrium magnetization. (M0r = F*M0f)
%          R1f: Free pool longitudinal relaxation rate.
%          R1r: Restricted pool longitudinal relaxation rate.
%          R2f: Free pool transverse relaxation rate.
%          kf: Free pool magnetization exchange rate.
%          kr: Restricted pool magnetization exchange rate. (= kf/F)
%          G: Lineshape value of the restricted pool (generated by
%             computeG.m)
%
%   Pulse: RF Pulse structure (generated by GetPulse.m).
%
%   Reference: R. Mark Henkelman, Xuemei Huang, Qing-San Xiang, G. J.
%               Stanisz, Scott D. Swanson, Michael J. Bronskill.
%               Quantitative Interpretation of Magnetization Transfer,Mag.
%               Res. in Med., 29, 759-766, Eqs. 1-6, (1993)
%
%
%   See also COMPUTEG, GETPULSE, BLOCH, BLOCHNOMT.
%

dM = zeros(4,1);

if (nargin < 4)
    omega  = 0;
    omega2 = 0;
    delta  = 0;
else
    omega  = Pulse.omega(t);
    omega2 = Pulse.omega2(t);
    delta  = Pulse.delta;
end

W = pi*Param.G.*omega2;

if isfield(Param,'T2f')
    R2f = 1./Param.T2f;
else
    R2f = Param.R2f;
end

if isfield(Param,'F')
    kf = Param.kr*Param.F;
    M0r = Param.M0f*Param.F;
else
    kf = Param.kf;
    M0r = Param.M0r;
end

dM(1) = -R2f*M(1) - 2*pi*delta*M(2);
dM(2) = -R2f*M(2) + 2*pi*delta*M(1) + omega*M(3);
dM(3) =  Param.R1f*(Param.M0f-M(3)) - kf*M(3) + Param.kr*M(4) - omega*M(2);
dM(4) =  Param.R1r*(M0r-M(4)) + kf*M(3) - Param.kr*M(4) - W*M(4);

end


function [ sym ] = search_symmetryset( candidate_list, obblist, Rmat, Dmat, LABELLEN )

objnum = size(obblist,1);
sym = {};
height_thre = 0.1*7;

%% search for the symmetry without central object
for i = 1:length(candidate_list)
    clist = candidate_list{i};
    clabellist = zeros(size(clist));
    csublists = {};
    for j = 1:length(clist)
        label = obblist(clist(j),end-LABELLEN+1:end);
        label = binary2dec(label);
        clabellist(j) = label;
    end
    ls = unique(clabellist);
    for j = 1:length(ls)
        label = ls(j);
        idx = find(clabellist==label);
        csublists{length(csublists)+1} = clist(idx);
        % "csublists" stores the sublists with same labels (and same size)
    end

    for j = 1:length(csublists)
        cslist = csublists{j};
        if(length(cslist)<=1)
            continue;
        end
        dists = Dmat(cslist, cslist);
        symdist_thre = 0.05*7;

        dl = unique(dists);
        dl = sort(dl);

        ismatched = zeros(1,length(cslist));
        for k = 1:length(dl)
            mind = dl(k);

            cssublists = {};
            for p = 1:length(cslist)
                for q = 1:length(cslist)
                    if(p~=q&&abs(Dmat(cslist(p),cslist(q))-mind)<symdist_thre)
                        isadded = -1;
                        for v = 1:size(cssublists,1)
                            if(ismember(cslist(p),cssublists{v,1})&&isadded==-1)
                                if(ismatched(q)~=1)
                                    if(abs(obblist(cslist(p),2)-obblist(cslist(q),2))<height_thre)
                                        cssublists{v,1} = union(cssublists{v,1},cslist(q));
                                        ismatched(q)=1;
                                        isadded = 1;
                                        break;
                                    end
                                end
                            end
                            if(ismember(cslist(q),cssublists{v,1})&&isadded==-1)
                                if(ismatched(p)~=1)
                                    if(abs(obblist(cslist(p),2)-obblist(cslist(q),2))<height_thre)
                                        cssublists{v,1} = union(cssublists{v,1},cslist(p));
                                        ismatched(p)=1;
                                        isadded = 1;
                                        break;
                                    end
                                end
                            end
                        end
                        if(isadded==-1)
                            if(ismatched(p)~=1&&ismatched(q)~=1)
                                if(abs(obblist(cslist(p),2)-obblist(cslist(q),2))<height_thre)
                                    cssublists{size(cssublists,1)+1,1} = [cslist(p),cslist(q)];
                                    cssublists{size(cssublists,1),2} = mind;
                                    ismatched(p)=1;
                                    ismatched(q)=1;
                                end
                            end
                        end
                    end
                end
            end
            for v = 1:size(cssublists,1)
                csslist = cssublists{v,1};
                % add sym
                sym{size(sym,1)+1,1} = csslist;
                sym{size(sym,1),2} = cssublists{v,2};
            end
        end

    end
end

final_sym = {};
% one object can be involved in one symmetry relation
isinvolved = zeros(1,objnum);
for i = 1:objnum
    if(isinvolved(i)~=1)
        symlist = {};
        symdist = [];
        if(size(sym,1)>0)
            for j = 1:size(sym,1)
                if(ismember(i,sym{j,1}))
                    symlist{length(symlist)+1}= sym{j,1};
                    sdist = Dmat(i,sym{j,1});
                    maxd = max(sdist(:));
                    for k = 1:size(sdist,1)
                        sdist(k,k) = k+maxd;
                    end
                    symdist(length(symlist)) = min(sdist);
                end
            end
            if(length(symdist)>0)
                [md,I] = min(symdist);
                symlist = symlist{I};
            end
        end

        if(length(symlist)>1)
            final_sym{size(final_sym,1)+1,1} = symlist;
            final_sym{size(final_sym,1),2} = md;
            isinvolved(symlist) = 1;
        end
    end
end
sym = final_sym;

end


function [alpha_fin,b_fin] = rsp_max(K,Y,C,T,S_min),
% Recursive Stabilization Procedure
bias_eps=10^(-7);
m= size(K,1);
k = ceil(log(m/S_min)/log(T/(T-1)));
current_position = [0,0];
Node_done = zeros(k,T);
Current_Path = zeros(k*T,m);
not_finished = 1;
count = 0;
Path_from_root = zeros(k,1);
%%
%% Computation of the kernel
%%
while not_finished,

    cp1 = current_position(1);
    cp2 = current_position(2);

    if (cp1~=k),
        active = find(Node_done(cp1+1,1:T)==0);
    else
        active = [];
    end;%if (cp1~=k)

    if ~isempty(active),

        % The part of the execution tree is not completely explored
        if cp1==0,
            tmp=[1:m];
        else
            tmp = find(Current_Path(cp2 + (cp1-1)*T,:)==1);
        end; % if cp1==0,

        % Build the training set for the node
        tab_tmp = zeros(1,m);
        train_ind_tmp = tmp([1:floor((active(1)-1)*length(tmp)/T),floor(active(1)*length(tmp)/T):length(tmp)]);
        %% If all the points are from the same class then do not go further
        is_plus = find(Y(train_ind_tmp)==1);

        if (length(is_plus)==0|(length(is_plus)==length(train_ind_tmp))),
            Node_done(cp1+1,1:T)=1;
            Current_Path([1:T] + (cp1)*T,:) = zeros(T,m);
        else
            tab_tmp(train_ind_tmp)=1;
            current_position(1) = cp1+1;
            Path_from_root(current_position(1)) = current_position(2);
            current_position(2) = active(1);
            Current_Path(current_position(2) + (current_position(1)-1)*T,:) = tab_tmp;
        end;
    else
        if (cp1==0),
            tmp = [1:m];
        else
            tmp = find(Current_Path(current_position(2)+(current_position(1)-1)*T,:)==1);
        end;
        Ylearn = Y(tmp,:);
        Clearn = C*m/length(tmp);
        Klearn = K(tmp,tmp);

        if current_position(1)==k,
            %keyboard;
            [alpha] = quadsolve(Klearn,-ones(length(tmp),1),Ylearn',0,Clearn);
            alpha_bias=alpha;
        else
            A = Current_Path(current_position(1)*T+1:current_position(1)*T+T,tmp);
            for t=1:T,
                g(t) = A(t,:)*(Klearn*A(t,:)');
            end;
            % scale the values of gamma_i (related to the way the optimization is done)
            if C==Inf,
                scc = 1;
            else
                scc = Clearn;
            end;
            H = [[Klearn, Klearn*A'/scc];[A*Klearn/scc,A*Klearn*A'/scc^2]];
            c = -[ones(length(tmp),1);0.5*g'/scc];
            A = [[Ylearn',zeros(1,T)];[zeros(1,length(tmp)),ones(1,T)]];
            %keyboard;
            btmp = [0;scc];
            [alpha_tmp,y] = quadsolve(H,c,A,btmp,Clearn);
            alpha_bias=alpha_tmp;
           % keyboard;
            alpha = alpha_tmp(1:length(tmp)) + Current_Path(current_position(1)*T+1:current_position(1)*T+T,tmp)'*alpha_tmp(length(tmp)+1:length(alpha_tmp))/scc;
%            checka = -alpha'*Klearn*Current_Path(current_position(1)*T+1:current_position(1)*T+T,tmp)' + 0.5*g;
            %keyboard;
        end; % if current_pos...==k-1

        if current_position ~=0,
            Current_Path(current_position(2)+(current_position(1)-1)*T,tmp) = alpha';
            Node_done(current_position(1)+1,1:T)=0;
            Node_done(current_position(1),current_position(2)) = 1;
            count=count+1;
            current_position(2) = Path_from_root(current_position(1));
            current_position(1) = current_position(1)-1;
        else,
            not_finished=0;
            alpha_fin = alpha;
            b_fin = -y(1);
        end; % if current_pos...~=0

    end;% if ~isempty(active)
end; %while not_finished
% End function


function eect2k = eect2000 (date1, date2)

%  equation of the equinoxes complementary terms, consistent with
%  iau 2000 resolutions.

%  annexe to iers conventions 2000, chapter 5

%  capitaine, n., wallace, p.t., & mccarthy, d.d. (2003). astron. &
%  astrophys. 406, pp. 1135-1149, table 3.
%  iers conventions (2010), chapter 5, p. 60, table 5.2e.
%  (table 5.2e presented in the printed publication is a truncated
%  series. the full series, which is used in novas, is available on
%  the iers conventions center website in file tab5.2e.txt.)
%  ftp://tai.bipm.org/iers/conv2010/chapter5/

%  input

%   date1, date2 = tt date (jd = date1 + date2)

%  output

%   eect2k = complementary terms (radians)

%  this revision:  2002 november 13
%                  references updated 2010 november 26

% ported from NOVAS 3.1

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

% 2 pi

d2pi = 6.283185307179586476925287d0;

% arc seconds to radians

das2r = 4.848136811095359935899141d-6;

% reference epoch (j2000), jd

dj0 = 2451545.0d0;

% days per julian century

djc = 36525.0d0;

%  -----------------------------------------
%  the series for the ee complementary terms
%  -----------------------------------------

%  number of terms in the series

ne0 = 33;

ne1 = 1;

%  argument coefficients for t^0

ke0 = [0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  0,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2, -2,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2, -2,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2, -2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2,  0,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  0,  0,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1,  2, -2,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1,  2, -2,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  4, -4,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  1, -1,  1,  0, -8, 12,  0,  0,  0,  0,  0,  0;
    0,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  2,  0,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  2,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2, -2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1, -2,  2, -3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1, -2,  2, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  0,  0,  0,  0,  8,-13,  0,  0,  0,  0,  0, -1;
    0,  0,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    2,  0, -2,  0, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  0, -2,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  1,  2, -2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0,  0, -2, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  4, -2,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    0,  0,  2, -2,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0, -2,  0, -3,  0,  0,  0,  0,  0,  0,  0,  0,  0;
    1,  0, -2,  0, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0;];

% transpose

ke0 = ke0';

%  argument coefficients for t^1

ke1 = [0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0];

% transpose

ke1 = ke1';

%  sine and cosine coefficients for t^0

se0 = [+2640.96d-6,          -0.39d-6;
    +63.52d-6,          -0.02d-6;
    +11.75d-6,          +0.01d-6;
    +11.21d-6,          +0.01d-6;
    -4.55d-6,          +0.00d-6;
    +2.02d-6,          +0.00d-6;
    +1.98d-6,          +0.00d-6;
    -1.72d-6,          +0.00d-6;
    -1.41d-6,          -0.01d-6;
    -1.26d-6,          -0.01d-6;
    -0.63d-6,          +0.00d-6;
    -0.63d-6,          +0.00d-6;
    +0.46d-6,          +0.00d-6;
    +0.45d-6,          +0.00d-6;
    +0.36d-6,          +0.00d-6;
    -0.24d-6,          -0.12d-6;
    +0.32d-6,          +0.00d-6;
    +0.28d-6,          +0.00d-6;
    +0.27d-6,          +0.00d-6;
    +0.26d-6,          +0.00d-6;
    -0.21d-6,          +0.00d-6;
    +0.19d-6,          +0.00d-6;
    +0.18d-6,          +0.00d-6;
    -0.10d-6,          +0.05d-6;
    +0.15d-6,          +0.00d-6;
    -0.14d-6,          +0.00d-6;
    +0.14d-6,          +0.00d-6;
    -0.14d-6,          +0.00d-6;
    +0.14d-6,          +0.00d-6;
    +0.13d-6,          +0.00d-6;
    -0.11d-6,          +0.00d-6;
    +0.11d-6,          +0.00d-6;
    +0.11d-6,          +0.00d-6;];

se0 = se0';

%  sine and cosine coefficients for t^1

se1 = [-0.87d-6, +0.00d-6];

% transpose

se1 = se1';

%  interval between fundamental epoch j2000.0 and current date (jc)

t = ((date1 - dj0) + date2) / djc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  fundamental arguments (from iers conventions 2000)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%  mean anomaly of the moon

fa(1) = anmp ((485868.249036d0 + (715923.2178d0 + (31.8792d0 ...
    + (0.051635d0 + (-0.00024470d0) * t) * t) * t) * t) * das2r ...
    + mod (1325.0d0 * t, 1.0d0) * d2pi);

%  mean anomaly of the sun

fa(2) = anmp ((1287104.793048d0 + (1292581.0481d0 + (-0.5532d0 ...
    + (+0.000136d0 + (-0.00001149d0) * t) * t) * t) * t) * das2r ...
    + mod (99.0d0 * t, 1.0d0) * d2pi);

%  mean longitude of the moon minus mean longitude of the ascending
%  node of the moon

fa(3) = anmp (( 335779.526232d0 + (295262.8478d0 + (-12.7512d0 ...
    + (-0.001037d0 + (0.00000417d0) * t) * t) * t) * t) * das2r ...
    + mod (1342d0 * t, 1d0) * d2pi);

%  mean elongation of the moon from the sun

fa(4) = anmp ((1072260.703692d0 + (1105601.2090d0 + (-6.3706d0 ...
    + (0.006593d0 + (-0.00003169d0) * t) * t) * t) * t) * das2r ...
    + mod (1236d0 * t, 1d0) * d2pi);

%  mean longitude of the ascending node of the moon

fa(5) = anmp ((450160.398036d0 + (-482890.5431d0 + (7.4722d0 ...
    + (0.007702d0 + (-0.00005939d0) * t) * t) * t) * t) * das2r ...
    + mod (-5.0d0 * t, 1.0d0) * d2pi);

fa(6) = anmp (4.402608842d0 + 2608.7903141574d0 * t);
fa(7) = anmp (3.176146697d0 + 1021.3285546211d0 * t);
fa(8) = anmp (1.753470314d0 +  628.3075849991d0 * t);
fa(9) = anmp (6.203480913d0 +  334.0612426700d0 * t);
fa(10) = anmp (0.599546497d0 +   52.9690962641d0 * t);
fa(11) = anmp (0.874016757d0 +   21.3299104960d0 * t);
fa(12) = anmp (5.481293872d0 +    7.4781598567d0 * t);
fa(13) = anmp (5.311886287d0 +    3.8133035638d0 * t);
fa(14) =      (0.024381750d0 +    0.00000538691d0 * t) * t;

%  evaluate the ee complementary terms

s0 = 0.0d0;

s1 = 0.0d0;

for i = ne0: -1: 1

    a = 0.0d0;

    for j = 1:14

        a = a + ke0(j, i) * fa(j);

    end

    s0 = s0 + (se0(1, i) * sin(a) + se0(2, i) * cos(a));

end

for i = ne1: -1: 1

    a = 0.0d0;

    for j = 1:14

        a = a + ke1(j, i) * fa(j);

    end

    s1 = s1 + (se1(1, i) * sin(a) + se1(2, i) * cos(a));

end

eect2k = (s0 + s1 * t) * das2r;


filename='Cantilever_triangle_fine';
%filename='Cantilever_quad_fine';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance','perimeterInterior'};
%cost = {'compliance','perimeter'};
%cost = {'compliance'};
weights = [1, 0.2];
%weights = 1;
constraint = {'volumeConstraint'};
optimizerUnconstrained = 'SLERP';
incrementFactor = 1;
designVariable = 'LevelSet';
filterType = 'P1';
optimizer = 'DualNestedInPrimal';
%optimizer = 'AlternatingPrimalDual';

nsteps = 5;
Vfrac_final = 0.4;
Perimeter_target = 1;
optimality_final = 1e-4;
constr_final =1e-4;

Vfrac_initial = 0.4;
optimality_initial = 1e-4;
constr_initial = 1e-4;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

plotting = true;
printing = true;
monitoring = true;
monitoring_interval = 15;

maxiter = 300;


function tri_surface_write ( node_file_name, triangle_file_name, dim_num, ...
  node_num, order_num, triangle_num, node_xyz, triangle_node )

%*****************************************************************************80
%
%% TRI_SURFACE_WRITE writes graphics information to a pair of TRI_SURFACE files.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string NODE_FILE_NAME, the name of the node file.
%
%    Input, string TRIANGLE_FILE_NAME, the name of the triangle file.
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer NODE_NUM, the number of points.
%
%    Input, integer ORDER_NUM, the order of the triangles.
%
%    Input, integer TRIANGLE_NUM, the number of triangles.
%
%    Input, real NODE_XYZ(DIM_NUM,NODE_NUM), the node coordinates.
%
%    Input, integer TRIANGLE_NODE(ORDER_NUM,TRIANGLE_NUM),
%    the nodes that form the triangles.
%
  header = 0;

  r8mat_write ( node_file_name, dim_num, node_num, node_xyz );

  i4mat_write ( triangle_file_name, order_num, triangle_num, ...
    triangle_node, header );

  return
end


function [x0] = unpackStereoParams(camK, camKc, prjK, prjKc, R, T)
% Unpack parameters for camera and projector calibration using lsqnonlin
% This function unpacks vectorized camera and projector parameters from
% matrices.
% See also: lsqnonlin, Calibration.packStereoParams

%% License
% ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
% Copyright (c) 2018 Bingyao Huang
% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:

% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.

% If you publish results obtained using this software, please cite our paper.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.

%% camera

% intrinsics
fx0_c = camK(1,1);
fy0_c = camK(2,2);
cx0_c = camK(1,3);
cy0_c = camK(2,3);

%% projector
% intrinsics
fx0_p = prjK(1,1);
fy0_p = prjK(2,2);
cx0_p = prjK(1,3);
cy0_p = prjK(2,3);
% sk0_p = prjK(1,2);

if(nargin == 2)
    x0 = [fx0_c, fy0_c, cx0_c, cy0_c, fx0_p, fy0_p, cx0_p, cy0_p]; % ignore skew
else
    if(nargin > 4)
        % rotation matrix to rotation vector
        % rvec = rotationMatrixToVector(R);

        rvec = cv.Rodrigues(R)';
        x0 = [fx0_c, fy0_c, cx0_c, cy0_c, camKc, fx0_p, fy0_p, cx0_p, cy0_p, prjKc, rvec, T']; % ignore skew
    else
        x0 = [fx0_c, fy0_c, cx0_c, cy0_c, camKc, fx0_p, fy0_p, cx0_p, cy0_p, prjKc]; % ignore skew
    end
end

end


function [data,units] = compute_angle_shortest_wing(trx,n)

flies = trx.exp2flies{n};
nflies = numel(flies);
data = cell(1,nflies);
for i = 1:nflies,
  fly = flies(i);

  data{i} = -trx(fly).wing_anglel;
  idx = trx(fly).wing_lengthr_mm < trx(fly).wing_lengthl_mm;
  data{i}(idx) = trx(fly).wing_angler(idx);

end
units = parseunits('rad');


% This is material illustrating the methods from the book
% Financial Modelling  - Theory, Implementation and Practice with Matlab
% source
% Wiley Finance Series
% ISBN 978-0-470-74489-5
%
% Date: 02.05.2012
%
% Authors:  Joerg Kienitz
%           Daniel Wetterau
%
% Please send comments, suggestions, bugs, code etc. to
% kienitzwetterau_FinModelling@gmx.de
%
% (C) Joerg Kienitz, Daniel Wetterau
%
% Since this piece of code is distributed via the mathworks file-exchange
% it is covered by the BSD license
%
% This code is being provided solely for information and general
% illustrative purposes. The authors will not be responsible for the
% consequences of reliance upon using the code or for numbers produced
% from using the code.

function [c,fc] = FInvSABR4_2(x,x_sabr,y_sabr)
% This function computes the inverse of a SABR cumulative distribution
% Since it is based on FSABR2 it is very fast and works for vectors!
f2 = @(t) (x - FSABR2_2(t,x_sabr,y_sabr));

% Use simple bisection
a = 0.00001 * ones(1,length(x)); % left starting points
b = 1*ones(1,length(x));        % right starting points

eps = 1e-3;                     % accuracy level
k = 0;                          % init iteration counter

c=(b+a)/2;
fc = f2(c);
%Ind = -eps <= fc & fc <= eps;
while(k <= 200)
    k = k+1;                            % increase iteration counter
    if( (-eps <= min(fc)) & (max(fc) <= eps))
        break;                          % end if all values have been found
    else
        b(fc<0) = 0.5*(b(fc<0)+a(fc<0));               % update right boundary
        a(fc>=0) = 0.5*(b(fc>=0)+a(fc>=0));            % update left boundary
    end
    c = 0.5*(b+a);
    fc = f2(c);                         % evaluate function at new c
end

end


% ------------------------------------------------------
% SwarmOps - Heuristic optimization for Matlab
% Copyright (C) 2003-2010 Magnus Erik Hvass Pedersen.
% Please see the file license.txt for license details.
% SwarmOps on the internet: http://www.Hvass-Labs.org/
% ------------------------------------------------------

% Many Optimizing Liaisons (MOL) optimization method is a
% simplification of PSO originally by Eberhart et al. (1, 2).
% MOL does not have any attraction to the particle's own best
% known position. It is similar to the "Social Only" PSO
% suggested by Kennedy (3) and was studied more thoroguhly
% by Pedersen et al. (4) who found it to sometimes outperform
% PSO and have behavioural parameters that were easier to tune.
% Literature references:
% (1) J. Kennedy and R. Eberhart. Particle swarm optimization.
%     In Proceedings of IEEE International Conference on Neural
%     Networks, volume IV, pages 1942-1948, Perth, Australia, 1995
% (2) Y. Shi and R.C. Eberhart. A modified particle swarm optimizer.
%     In Proceedings of the IEEE International Conference on
%     Evolutionary Computation, pages 69-73, Anchorage, AK, USA, 1998.
% (3) J. Kennedy. The particle swarm: social adaptation of knowledge,
%     In: Proceedings of the IEEE International Conference on
%     Evolutionary Computation, Indianapolis, USA, 1997.
% (4) M.E.H. Pedersen and A.J. Chipperfield. Simplifying particle swarm
%     optimization. Applied Soft Computing, volume 10, pages 618-628, 2010.
% Parameters:
%     problem; name or handle of optimization problem, e.g. @myproblem.
%     data; data-struct, see e.g. the file myproblemdata.m
%     parameters; behavioural parameters for optimizer,
%                 see file molparameters.m
% Returns:
%     bestX; best found position in the search-space.
%     bestFitness; fitness of bestX.
%     evaluations; number of fitness evaluations performed.
function [bestX, bestFitness, evaluations] = mol(problem, data, parameters)

    % Copy data contents to local variables for convenience.
    n = data.Dim;
    acceptableFitness = data.AcceptableFitness;
    maxEvaluations = data.MaxEvaluations;
    lowerBound = data.LowerBound;
    upperBound = data.UpperBound;

    % Behavioural parameters for this optimizer.
    s = parameters(1);        % Swarm-size
    omega = parameters(2);    % Inertia weight.
    phiG = parameters(3);     % Swarm's best weight.

    % Initialize the velocity boundaries.
    range = upperBound-lowerBound;
    lowerVelocity = -range;
    upperVelocity = range;

    % Initialize swarm.
    x = initpopulation(s, n, data.LowerInit, data.UpperInit);    % Particle positions.
    v = initpopulation(s, n, lowerVelocity, upperVelocity);      % Velocities.

    % Determine swarm's best-known position and its fitness.
    bestFitness = Inf;
    for i=1:s
        % Compute fitness for i'th agent.
        fitness = feval(problem, x(i,:), data);

        % If improvement, update best-known position and fitness.
        if fitness < bestFitness
            bestFitness = fitness;
            bestX = x(i,:);
        end
    end

    % Perform optimization iterations until acceptable fitness
    % is achieved or the maximum number of fitness evaluations
    % has been performed.
    evaluations = s; % Fitness evaluations above count as iterations.
    while (evaluations < maxEvaluations) && (bestFitness > acceptableFitness)

        % Pick index for a random particle from the swarm.
        i = randindex(s);

        % Pick random weight.
        rG = rand(1, 1);

        % Update velocity for i'th particle.
        v(i,:) = omega * v(i,:) + rG * phiG * (bestX - x(i,:));

        % Bound velocity.
        v(i,:) = bound(v(i,:), lowerVelocity, upperVelocity);

        % Update position for i'th particle.
        x(i,:) = x(i,:) + v(i,:);

        % Bound position to search-space.
        x(i,:) = bound(x(i,:), lowerBound, upperBound);

        % Compute fitness.
        fitness = feval(problem, x(i,:), data);

        % Update swarm's best-known position.
        if fitness < bestFitness
            % Update swarm's best-known fitness.
            bestFitness = fitness;

            % Update swarm's best-known position.
            % This must be copied because the particles
            % will continue to move in the search-space.
            bestX = x(i,:);
        end

        % Increment counter.
        evaluations = evaluations + 1;
    end
end

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


function [Tcell, Fcell, Ycell, meanf, peakf] = spectrogram( w, varargin )
%SPECTROGRAM Plot an IceWeb-style spectrogram
%   spectrogram(w, s) Creates an IceWeb style spectrogram by wrapping the
%   function iceweb.spectrogram_iceweb(). If s is omitted it defaults to:
%       spectralobject(1024, 924, 10, [60 120])
%   where [60 120] are the dB limits that correspond to the color map used.
%   If this is a blank vector, [], the spectrogram is autoscaled in absolute
%   amplitude, not plotted in dB with absolute dB limits.
%
%   spectrogram(w, s, 'plot_metrics', 1) Will add frequency metrics computed
%   by the waveform/amplitude_spectrum function.
%
% For greater control, call
%   iceweb.spectrogram_iceweb() directly, or use spectralobject/specgram or
%   spectralobject/specgram2 (not clear how these differ). Note that
%   spectrogram_iceweb() is significantly faster.

% Glenn Thompson 2016/05/19 to provide a simple, fast way to geenrate nice
% spectrograms without having to delve into specgram and specgram2
figure
nfft = 1024;
overlap = 924;
fmax = 10;
dbLims = [60 120];
p = inputParser;
p.addRequired('w');
p.addParameter('spectralobject', spectralobject(nfft, overlap, fmax, dbLims));
p.addParameter('plot_metrics', 0, @isnumeric);
p.parse(w, varargin{:});
w=p.Results.w;
s=p.Results.spectralobject;

% if ~class(s, 'spectralobject')
%     disp('Oops, you did not give a valid spectralobject. Using default')
    if numel(w)>1
        w = reshape(w, numel(w), 1);
    end

    if p.Results.plot_metrics
        [result,Tcell,Fcell,Ycell, meanf, peakf] = iceweb.spectrogram_iceweb(s, w, 'plot_metrics',1);
    else
        [result,Tcell,Fcell,Ycell, meanf, peakf] = iceweb.spectrogram_iceweb(s, w);
    end

end


function fem1d_heat_explicit_test ( )

%*****************************************************************************80
%
%% FEM1D_HEAT_EXPLICIT_TEST tests the FEM1D_HEAT_EXPLICIT library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2012
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FEM1D_HEAT_EXPLICIT_TEST\n' );
  fprintf ( 1, '  MATLAB version.\n' );
  fprintf ( 1, '  Test the FEM1D_HEAT_EXPLICIT library.\n' );

  fem1d_heat_explicit_test01 ( );
  fem1d_heat_explicit_test02 ( );
  fem1d_heat_explicit_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FEM1D_HEAT_EXPLICIT_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


% DEMO1 - Basic ncdataset data access
echo('on')
% STARTING DEMO1 ----------------------------------------------------------
% Basic usage of ncdataset

%% ---- Open your data
% Can be NetCDF, NetCDF on webserver, or OpenDAP
ds = ncdataset('http://geoport.whoi.edu/thredds/dodsC/examples/OS_M1_20081008_TS.nc');
%% ---- You can access a list of the variables available to you
ds.variables

%% Lets fetch time in Matlab's native format
t = ds.time('TIME');

%% ---- Now lets get the data
temp = double(ds.data('TEMP')); % Convert to Double!!
depth = ds.data('DEPTH');

%% ---- Plot the data
figure;
surf(t, depth, temp.');...
view(2);shading interp;...
datetick('x', 2);set(gca, 'YDir', 'reverse');...
grid('on');ch = colorbar;...
set(get(ch, 'YLabel'), 'String', '^oC');...
title({'Temperature at M1 Mooring in Monterey Bay',ds.attribute('references'),ds.location},'interpreter','none')

shg

echo('off') % ENDING DEMO1 ------------------------------------------------


% STEP 1: Use getHSVColorFromDirectory(dirName) in order to estimate the
% average HSV values of your objects of interest.

HSV = getHSVColorFromDirectory('train');

%
% The above function call will let the user choose manually (through simple
% mouse clicks) several "seeds" from each image.
% At the end the HSV matrix contains M rows (M is the total number of jpeg files
% in dirName): each row corresponds to the average HSV value of the
% selected seeds in the respective image.
% The average (or median) value of this matrix (column-wise) can be used,
% in the sequence for detecting the speficic color values.
%

% STEP 2: Use the estimated (average) hsv value for detecting the specified
% color in a specific image.

colorDetectHSV('test/face01.jpg', median(HSV), [0.05 0.05 0.2]);


disp('Starting tests...')
test_digamma
test_gammaln
test_trigamma
test_int_hist
%test_inv_posdef
test_java
test_logmulexp
test_logsumexp
test_mutable
%test_ndsum
%test_normcdf
test_normpdf
test_randgamma
test_randbeta
test_randbinom
test_randwishart
test_repmat
test_row_sum
test_sameobject
test_scale
test_solve_tri
test_sorted
test_sparse
test_sqdist
disp('All tests completed')


function rayPlot(ray,ord)
%+========================================================================+
%|                                                                        |
%|           OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING            |
%|           openRay is part of the GYPSILAB toolbox for Matlab           |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2018.                             |
%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |
%| LICENCE   : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or    |
%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT   : matthieu.aussal@polytechnique.edu                          |
%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab                 |
%|                                                                        |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it.                                                      |
%|________________________________________________________________________|
%|   '&`   |                                                              |
%|    #    |   FILE       : rayPlot.m                                     |
%|    #    |   VERSION    : 0.41                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2017                                    |
%|  / 0 \  |   LAST MODIF : 01.04.2018                                    |
%| ( === ) |   SYNOPSIS   : Plot trajectory and last direction            |
%|  `---'  |                                                              |
%+========================================================================+

% Graphical configuration
figure(gcf)
off = ~ishold;
if off
    hold on
end

% Plot trajectory
if (ord > -1)
    for i = 2:ord+1
        Pim1 = ray.pos{i-1};
        Pi   = ray.pos{i};
        plot3([Pim1(:,1) Pi(:,1)]',[Pim1(:,2) Pi(:,2)]',[Pim1(:,3) Pi(:,3)]','o-b')
    end
end

% Plot direction
if (ord == -1) || (length(ray.pos) == 1)
    P = ray.pos{end};
    U = ray.dir;
    quiver3(P(:,1),P(:,2),P(:,3),U(:,1),U(:,2),U(:,3),'r')
end

% Hold
if off
    hold off
end
end


%compute dyheadsm_mm

function [data,units]=compute_dyheadsm_mm(trx,n)

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

units=parseunits('mm/s');
data=dyheadsm_mm;


% e = mohsst5_performance_rmsew(Yh, I)

function e = mohsst5_performance_rmsew(Yh, I)

load('mohsst5_data.mat', 'observations');

Y = observations;

if all(size(Yh) == [1727 1632])
  % The seas have been removed
  disp('Adding the land areas to the matrix.')
  sea = sum(~isnan(Y),2) > 0;
  F = nan(size(Y));
  F(sea,:) = Yh;
  Yh = F;
  Itmp = false(size(Y));
  Itmp(sea,:) = I;
  I = Itmp;
end

Y(~I) = nan;

e = mohsst5_rmsew(Y,Yh);


function [ycorr,yfit] = bf(y,varargin)
% Baseline Fit each column in "x".
% Syntax: [ycorr,yfit] = bf(y,pts,avgpts,method,confirm);
%   ycorr = bf(y);  ycorr = bf(y,method); ycorr = bf(y,avgpts);
%   ycorr = bf(y,pts);  ycorr = bf(y,pts,avgpts);
% A baseline fit is interpolated from selected points and then applied to the data.
%   "y" is a vector or array.
%       If an array, the baseline fit is performed for each column of data (dim 1).
%   Arguments following "y" may be in any order.
%   "pts" is vector specifying the indices of the points for a baseline fit.
%       If not specified then a plot is displayed and the user is instructed to
%       interactively select points for the baseline fit.
%       End points are always automatically included for interactive "pts" selection,
%       and do not need to explicitly selected. It is recommended that the end points
%       be included in any list of "pts".
%       It is not necessary to order or sort "pts" before use.
%   "avgpts" determines the width in points for the calculation of the mean y(x)
%       value, where x is a selected point in "pts". (Default = 3).
%       This can be helpful for noisy data.
%   "method" controls the algorithm applied for the baseline fit. The routine uses
%       Matlab's interp1 command. "method" must be one of the methods supported by
%       interp1. (Default is 'spline').
%   "confirm", if specified as the string 'confirm', will allow the user to see the
%       result and to confirm it is acceptable. If not the user can reslect "pts".
%   "ycorr" is the baseline corrected data in the same format as "y".
%   "yfit" is a vector or array with the interpolated baseline fit.
%
% Examples:
%   [y,yfit] = bf(y,'confirm','linear');
%       "y" will be plotted and the user is instructed to select points for the fit.
%       A baseline will be linearly interpolated from the selected points and will be
%       plotted together with "y". The user is prompted as to whether to redo the
%       baseline selection. Upon completion, the corrected data "y" and the fitted
%       baseline "yfit" are output.
%   ycorr = bf(y,5);
%      "y" is plotted and the user is instructed to select points for the fit.
%       The baseline fit is based on the mean value of "y" over 5 points centered on
%       the selected points. Cubic spline interpolation is used for the baseline fit.
%       The corrected data "ycorr" is output.
%   ycorr = bf(y,[5,10,15,30,35,40],'pchip');
%       Points with the specified indices are used to calculate a baseline fit using
%       the piecewise cubic Hermite interpolation method. No data is plotted.
%       The baseline fit is based on the mean value of "y" over 3 points centered on
%       the selected points. The corrected data "ycorr" is output.
%
% See Also:   interp1, spline, ginput

% Copyright 2009 Mirtech, Inc.
% Created by    Mirko Hrovat    08/01/2009  contact:mhrovat@email.com

def_method  = 'spline';
def_avgpts  = 3;

method = [];
avgpts = [];
pts    = [];
confirm = false;
for n = 2:nargin,
    f = varargin{n-1};
    if ischar(f),
        if strcmpi(f,'confirm'),
            confirm = true;
        else
            method = f;
        end
    elseif isnumeric(f) && numel(f) == 1,
        avgpts = f;
    elseif isnumeric(f) && numel(f) > 1,
        pts = f;
    elseif isempty(f),
        continue
    else
        error ('  Invalid input argument!')
    end
end
if isempty(method),     method = def_method;        end
if isempty(avgpts),     avgpts = def_avgpts;        end
dimy = size(y);
lst = dimy(1);
newdimy = [dimy(1),prod(dimy(2:end))];
y = reshape(y,newdimy);
x = 1:lst;
if isempty(pts),
    interactive = true;
else
    interactive = false;
end
if interactive || confirm,
    bffig = figure;
else
    bffig = 0;
end
ok = false;
while ~ok,
    if interactive,
        plot(x,real(y(:,1)))
        set(bffig,'Name','Baseline Fit - Select points')
        fprintf(['\n Now select baseline points to fit by positioning cursor,',...
            '\n   and selecting points with mouse button or key press.',...
            '\n Press Enter key when done.\n'])
        [a,b] = ginput;                                 %#ok
        pts = round(a.');
    end
    pts = sort(pts);
    pts(diff(pts)==0) = [];         % delete duplicate points
    if pts(1)~=1,       pts = [1,pts];          end     %#ok
    if pts(end)~=lst,   pts = [pts,lst];        end     %#ok
    npts = numel(pts);
    pss = zeros(npts,2);
    pss(:,1) = pts - floor(avgpts/2);
    pss(:,2) = pss(:,1) + avgpts;
    pss(pss < 1) = 1;
    pss(pss > lst) = lst;
    yavg = zeros([npts,newdimy(2)]);
    for n = 1:npts,
        yavg(n,:) = mean(y(pss(n,1):pss(n,2),:),1);
    end
    yfit = interp1(pts,yavg,x,method);
    if size(yfit,1) ==1,
        yfit = shiftdim(yfit,1);    % make yfit a column if it is a row vector
    end
    if confirm,
        interactive = true;
        figure(bffig)
        plot(x,real(y(:,1)),'b',x,real(yfit(:,1)),'r',pts,real(yavg(:,1)),'ob')
        set(bffig,'Name','Baseline Fit - Verify baseline')
        answer = input('  Do you to redo fit and reselect baseline points?[N] ','s');
        if isempty(answer),     answer = 'n';   end
        if strcmpi(answer,'y'),
            ok = false;
        else
            ok = true;
        end
    else
        ok = true;
    end
end
if any(findobj('Type','figure')==bffig),
    close(bffig),                   % close figure if it exists
end
ycorr = y - yfit;
ycorr = reshape(ycorr,dimy);
yfit = reshape(yfit,dimy);


classdef la

methods(Static)

function no = nonorthogonality(U)
    % Computes the deviation from orthogonality of a basis
    [m, k] = size(U);
    gap = U' * U - eye(k);
    no = norm(gap);
end

end % methods

end % classdef


function [analMu, analCov, diffMu, diffCov] = gpPosteriorMeanCovarTest(model, X)
% GPPOSTERIORMEANCOVARTEST Test the gradients of the mean and covariance.
% FORMAT
% DESC tests the gpPosteriorMeanCovar and gpPosteriorGradMeanCovar
% functions.
% ARG model : the model to test the gradients for.
% ARG X : the input locations to test the gradients for.
% RETURN analMu : the analytical gradients of the mean with respect
% to X.
% RETURN analCov : the analytical gradients of the covariance with respect
% to X.
% RETURN diffMu : the numerical gradients of the mean with respect
% to X.
% RETURN diffCov : the numerical gradients of the covariance with respect
% to X.
% RETURN delta : erros between the numerical and analytical
% gradients.
%
% SEEALSO : gpPosteriorMeanCovar, gpPosteriorGradMeanCovar
%
% COPYRIGHT : Neil D. Lawrence, 2006

% GP

[analMu, analCov] = gpPosteriorGradMeanCovar(model, X);
origX = X;
change = 1e-6;
for i = 1:size(X, 1)
  for j = 1:size(X, 2)
    X(i, j) = origX(i, j) - change;
    [muMinus, covMinus] = gpPosteriorMeanCovar(model, X);
    X(i, j) = origX(i, j) + change;
    [muPlus, covPlus] = gpPosteriorMeanCovar(model, X);
    X(i, j) = origX(i, j);
    diffMu{j}(i, :) = (muPlus(i, :) - muMinus(i, :))/(2*change);
    for k = 1:model.d
      % Not sure why the transpose is need here ... hope it isn't
      % two wrongs making a right ...
      diffCov{j, k}(:, i) = (covPlus{k}(i, :) - covMinus{k}(i, :))'/(2*change);
    end

  end
end


function c=recalculate_points(b)
% function c=recalculate_points(b)

if ~strcmpi(class(b),'bezier')
  error('Expecting a bezier object');
end

c=b;

c.x1=c.x0+c.cx/3;
c.x2=c.x1+(c.cx+c.bx)/3;
c.x3=c.x0+c.cx+c.bx+c.ax;

c.y1=c.y0+c.cy/3;
c.y2=c.y1+(c.cy+c.by)/3;
c.y3=c.y0+c.cy+c.by+c.ay;


function t_opf_dc_ot(quiet)
%T_OPF_DC_OT  Tests for DC optimal power flow using Opt Tbx solvers.

%   MATPOWER
%   Copyright (c) 2004-2021, 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.

if nargin < 1
    quiet = 0;
end

matlab = have_feature('matlab');
if matlab
    if have_feature('quadprog_ls')
        if have_feature('optimoptions')
            if have_feature('linprog_ds')
                if have_feature('quadprog', 'vnum') >= 7.005  %% R2016b and later
                    algs  = {'interior-point', 'dual-simplex'};
                else
                    algs  = {'interior-point', 'active-set', 'simplex', 'dual-simplex'};
                end
            else
                algs  = {'interior-point', 'simplex'};
            end
        else
            algs  = {'interior-point', 'active-set'};
        end
    else
        algs  = {''};
    end
else
    algs  = {'default'};
end

num_tests = 43 * length(algs);

t_begin(num_tests, quiet);

[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;

casefile = 't_case9_opf';
if quiet
    verbose = 0;
else
    verbose = 0;
end
if have_feature('octave')
    if have_feature('octave', 'vnum') >= 4
        file_in_path_warn_id = 'Octave:data-file-in-path';
    else
        file_in_path_warn_id = 'Octave:load-file-in-path';
    end
    s1 = warning('query', file_in_path_warn_id);
    warning('off', file_in_path_warn_id);
end

mpopt = mpoption('out.all', 0, 'verbose', verbose);
mpopt = mpoption(mpopt, 'opf.dc.solver', 'OT');

warning off optim:linprog:IgnoreStartPoint;
warning off optim:linprog:AlgOptsWillError;

%% run DC OPF
if have_feature('quadprog')
  for k = 1:length(algs)
    if matlab
        if ~isempty(algs)
            mpopt = mpoption(mpopt, 'linprog.Algorithm', algs{k});
        else
            mpopt = mpoption(mpopt, 'linprog', []);
        end
    end
    if strcmp(algs{k}, 'dual-simplex') && strcmp(have_feature('fmincon', 'vstr'), '7.1')
        have_prices = 0;    %% dual-simplex did not return prices in MATLAB R2014b!?!
    else
        have_prices = 1;
    end
    t0 = sprintf('DC OPF (OT %s): ', algs{k});

    %% set up indices
    ib_data     = [1:BUS_AREA BASE_KV:VMIN];
    ib_voltage  = [VM VA];
    ib_lam      = [LAM_P LAM_Q];
    ib_mu       = [MU_VMAX MU_VMIN];
    ig_data     = [GEN_BUS QMAX QMIN MBASE:APF];
    ig_disp     = [PG QG VG];
    ig_mu       = (MU_PMAX:MU_QMIN);
    ibr_data    = (1:ANGMAX);
    ibr_flow    = (PF:QT);
    ibr_mu      = [MU_SF MU_ST];
    ibr_angmu   = [MU_ANGMIN MU_ANGMAX];

    %% get solved DC power flow case from MAT-file
    load soln9_dcopf;       %% defines bus_soln, gen_soln, branch_soln, f_soln

    %% run OPF
    t = t0;
    [baseMVA, bus, gen, gencost, branch, f, success, et] = rundcopf(casefile, mpopt);
    t_ok(success, [t 'success']);
    t_is(f, f_soln, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);
    if have_prices
        t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);
    else
        t_skip(1, [t 'bus lam: lambdas not computed']);
    end
    if have_prices
        t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);
    else
        t_skip(1, [t 'bus mu: lambdas not computed']);
    end
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);
    if have_prices
        t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);
    else
        t_skip(1, [t 'gen mu: lambdas not computed']);
    end
    t_is(branch(:,ibr_data  ), branch_soln(:,ibr_data  ), 10, [t 'branch data']);
    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);
    if have_prices
        t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);
    else
        t_skip(1, [t 'branch mu: lambdas not computed']);
    end

    %%-----  test OPF with angle difference limits  -----
    t = [t0 'w/angle diff lims : '];
    mpc = loadcase(casefile);
    mpc.branch(4, ANGMAX) = 3;
    mpc.branch(7, ANGMIN) = -4.5;
    r = rundcopf(mpc, mpopt);
    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);
    t_ok(success, [t 'success']);
    t_is(   f, 6456.7213, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,PG        ),    [99.98497;89.35133;125.66371], 4, [t 'gen dispatch']);
    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);
    e = zeros(size(branch, 1), 1);
    e(4) = 297.83776;
    e(7) = -26.94788;
    if have_prices
        t_is(branch(:,MU_ANGMAX )-branch(:,MU_ANGMIN ), e, 4, [t 'branch ang diff mu']);
    else
        t_skip(1, [t 'branch ang diff mu: lambdas not computed']);
    end

    t = [t0 'w/ignored angle diff lims : '];
    mpopt1 = mpoption(mpopt, 'opf.ignore_angle_lim', 1);
    r = rundcopf(mpc, mpopt1);
    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);
    t_ok(success, [t 'success']);
    t_is(f, f_soln, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);
    if have_prices
        t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);
    else
        t_skip(1, [t 'bus lam: lambdas not computed']);
    end
    if have_prices
        t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);
    else
        t_skip(1, [t 'bus mu: lambdas not computed']);
    end
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);
    if have_prices
        t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);
    else
        t_skip(1, [t 'gen mu: lambdas not computed']);
    end
    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);
    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);
    if have_prices
        t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);
    else
        t_skip(1, [t 'branch mu: lambdas not computed']);
    end

    %%-----  run OPF with extra linear user constraints & costs  -----
    %% two new z variables
    %%      0 <= z1, P3 - P1 <= z1
    %%      0 <= z2, P3 - P2 <= z2
    %% with A and N sized for DC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1;1;2;2;2],[10;12;13;12;11;14],[-1;1;-1;1;-1;-1],2,14);
    mpc.u = [0; 0];
    mpc.l = [-Inf; -Inf];
    mpc.zl = [0; 0];

    mpc.N = sparse([1;2], [13;14], [1;1], 2, 14);   %% new z variables only
    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z
    mpc.H = sparse(2,2);                            %% no quadratic term
    mpc.Cw = [1000;1];

    t = [t0 'w/extra constraints & costs 1 : '];
    [r, success] = rundcopf(mpc, mpopt);
    t_ok(success, [t 'success']);
    t_is(r.gen(1, PG), 116.15974, 5, [t 'Pg1 = 116.15974']);
    t_is(r.gen(3, PG), 116.15974, 5, [t 'Pg3 = 116.15974']);
    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);
    t_is(r.cost.usr, 0.3348, 4, [t 'user costs']);

    %% with A and N sized for AC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1;1;2;2;2],[19;21;25;21;20;26],[-1;1;-1;1;-1;-1],2,26);
    mpc.u = [0; 0];
    mpc.l = [-Inf; -Inf];
    mpc.zl = [0; 0];

    mpc.N = sparse([1;2], [25;26], [1;1], 2, 26);   %% new z variables only
    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z
    mpc.H = sparse(2,2);                            %% no quadratic term
    mpc.Cw = [1000;1];

    t = [t0 'w/extra constraints & costs 2 : '];
    [r, success] = rundcopf(mpc, mpopt);
    t_ok(success, [t 'success']);
    t_is(r.gen(1, PG), 116.15974, 5, [t 'Pg1 = 116.15974']);
    t_is(r.gen(3, PG), 116.15974, 5, [t 'Pg3 = 116.15974']);
    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);
    t_is(r.cost.usr, 0.3348, 4, [t 'user costs']);

    t = [t0 'infeasible : '];
    %% with A and N sized for DC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1], [10;11], [1;1], 1, 14);   %% Pg1 + Pg2
    mpc.u = Inf;
    mpc.l = 600;
    %% Opt Tbx 5.1 has fatal bug here!
    try
        [r, success] = rundcopf(mpc, mpopt);
    catch
        success = 0;
    end
    t_ok(~success, [t 'no success']);

    %% OPF with all buses isolated
    t = [t0 'all buses isolated : '];
    mpc = loadcase(casefile);
    mpc.bus(:, BUS_TYPE) = NONE;
    try
        r = rundcopf(mpc, mpopt);
        t_is(r.success, 0, 12, [t 'success = 0']);
    catch
        t_ok(0, [t 'unexpected fatal error']);
    end
  end
else
    t_skip(num_tests, 'Optimization Toolbox not available');
end

if have_feature('octave')
    warning(s1.state, file_in_path_warn_id);
end

t_end;


function L = ldlrowmodify(L, c2, k)
%LDLROWMODIFY  Function to modify the sparse cholesky factorization
%              L*D*L' = C, when a row and column k of C have changed
%
%  Description
%    L = rowmodify(L, c2, k)
%    Function to modify the Cholesky factorization L*D*L' = C
%    (which is stored in L), when a row and column k of C have
%    changed from c to c2. The change in C is assumed to be such
%    that the sparsity structure of C is remained the same. c is
%    the old kth column of C and c2 is the new column.
%
%    See GPEP_E for usage
%
%  Reference
%    See Davis and Hager 2005 (Row Modification of a sparse
%    Cholesky factorization) section 4 for details of the
%    algorithm.

%  Copyright (c) 2009-2010 Jarno Vanhatalo

% 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.

% First evaluate the l_21 vector. That is the kth row vector of L

% Evaluate the old c. NOTE! The C-version (mex-file) of this algorithm
% does not need the old c. However, this m-version is an old
% implementation
    [L2, D] = ldlsplit(L);
    c = L2(k,:)*D(k)*L2(k,:)';

    n = size(L,1);
    if k>1
        deltac12 = c2(1:k-1)-c(1:k-1);
        [L2, D] = ldlsplit(L);

        %deltal12 = D(1:k-1,1:k-1) \ (L2(1:k-1,1:k-1)\deltac12);

        x = deltac12;
        [I,J,ld] = find(L);
        a2 = cumsum(histc(J,1:n));
        Lp=zeros(n,1);
        Lp(1) = 1; Lp(2:end) = a2(1:end-1) + 1; Lp(end+1) = a2(end);
        Li = I;
        Lx = ld;

        for j=1:k-1
            x(j) = x(j);
            for p = Lp(j)+1:Lp(j+1)-1
                if Li(p) >= k
                    break
                end
                x(Li(p)) = x(Li(p))-Lx(p).*x(j);
            end
            x(j) = x(j)./Lx(Lp(j));
        end

        deltal12 = x;

        l12 = L(k,1:k-1)';
        l12b = l12 + deltal12;
        L(k,1:k-1) = l12b;

        d = D(k,k);
        db = d + c2(k)-c(k) - sum( deltal12.*(l12 + l12b).*diag(D(1:k-1,1:k-1)));
        L(k,k) = db;
    else
        d = L(k,k);
        db = d + c2(k)-c(k);
        L(k,k) = db;
    end

    if k < n
        deltac32 = c2(k+1:n)-c(k+1:n);
        l32 = L(k+1:n,k);
        if k>1
            l32b = (deltac32 + l32.*d - L(k+1:n,1:k-1)*D(1:k-1,1:k-1)*deltal12)./db;
        else
            l32b = (deltac32 + l32.*d )./db;
        end

        w = L(:,k).*sqrt(d);
        L(k+1:n,k) = l32b;
        w2 =L(:,k).*sqrt(db);

        % Then update the L_33 part. That is L(k+1:n, k+1:n)
        alpha = 1;
        alpha2 = 1;
        for i = k+1:n    % Li(Lp(k)+1:Lp(k+1)-1)

            if w(i) ~= 0
                beta = alpha + w(i).^2 / L(i,i);
                gamma = w(i) / (beta*L(i,i));
                L(i,i) = (beta/alpha)*L(i,i);
                alpha = beta;

                beta2 = alpha2 - w2(i).^2 /L(i,i);
                gamma2 = w2(i) / (beta2*L(i,i));
                L(i,i) = (beta2/alpha2)*L(i,i);
                alpha2 = beta2;

                if (i == n) return, end

                w(i+1:n) = w(i+1:n) - w(i).*L(i+1:n, i);
                L(i+1:n,i) = L(i+1:n,i) + gamma.*w(i+1:n);

                w2(i+1:n) = w2(i+1:n) - w2(i).*L(i+1:n, i);
                L(i+1:n,i) = L(i+1:n,i) - gamma2.*w2(i+1:n);
            end
        end
    end
end


function [out] = ratioScore(x,Prob)

ration = Prob.user.ration;
ratiod = Prob.user.ratiod;
% x should be in alpha coordinates.
% expdata = Prob.user.expdata;
% model = Prob.user.model;
% N = model.N;

out = (ration'*x)/(ratiod'*x);

return;


function p = spm_LAP_pg(x,v,h,M);
% default precision function for LAP models (hidden states)
% FORMAT p = spm_LAP_pg(x,v,h,M);
%
% x  - hidden states
% v  - causal states
% h  - precision parameters
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_LAP_pg.m 3694 2010-01-22 14:16:51Z karl $

% fixed components
%--------------------------------------------------------------------------
p = sparse(M.n,1);
try
    W = diag(M.W);
    if all(W)
        p = log(W);
    end
end

% free components
%--------------------------------------------------------------------------
for i = 1:length(M.R)
    p = p + h(i)*diag(M.R{i});
end


%% dependencies

addpath(fullfile(pwd, 'camera_pipeline_simple'));
addpath(fullfile(pwd, 'RBF_ThinPlate_image_warping'));
addpath(fullfile(pwd, 'efficient_subpixel_registration'));

%% data and parameters (replace with your preferences)

dngDir = fullfile(pwd, 'DNGs'); % contains only 3 images
defectivePixelsMask = load(fullfile(dngDir, 'DefectivePixelsMask.mat'));
defectivePixelsMask = defectivePixelsMask.DefectivePixelsMask;
% if not available, use an empty array
% defectivePixelsMask = [];
refIdx = 1; % use first image as reference for spatial alignment

%% prepare parallel pool

NUM_WORKERS = 4;
prepare_parallel_pool(NUM_WORKERS);

%% ground truth image estimation

[MeanUnprocessed, AlignedMeanImage, RobustMeanImage, ...
    MeanUnprocessedSrgb, AlignedMeanImageSrgb, RobustMeanImageSrgb, ...
    refImage, refImageSrgb, refMetadata] ...
    = EstimateGroundTruthImage(dngDir, defectivePixelsMask, refIdx);

%% saving outputs

parsave(fullfile(pwd, 'output', 'MeanUnprocessed.mat'), MeanUnprocessed);
parsave(fullfile(pwd, 'output', 'AlignedMeanImage.mat'), AlignedMeanImage);
parsave(fullfile(pwd, 'output', 'GT_RAW.mat'), RobustMeanImage);

imwrite(MeanUnprocessedSrgb, ...
    fullfile(pwd, 'output', 'MeanUnprocessedSrgb.png'));
imwrite(AlignedMeanImageSrgb, ...
    fullfile(pwd, 'output', 'AlignedMeanImageSrgb.png'));
imwrite(RobustMeanImageSrgb, ...
    fullfile(pwd, 'output', 'GT_SRGB.png'));

parsave(fullfile(pwd, 'output', 'NOISY_RAW.mat'), refImage);
imwrite(refImageSrgb, fullfile(pwd, 'output', 'NOISY_SRGB.png'));
parsave(fullfile(pwd, 'output', 'METADATA_RAW.mat'), refMetadata);

%% Display

Display(refImageSrgb, RobustMeanImageSrgb);


function a=d_logit(p)
%DREX subfunction
%Written by Issam El Naqa 2003-2005
%Extracted for generalized use 2005, AJH
%
% Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.
%
% This file is part of the Dose Response Explorer System (DREES).
%
% DREES development has been led by:  Issam El Naqa, Aditya Apte, Gita Suneja, and Joseph O. Deasy.
%
% DREES has been financially supported by the US National Institutes of Health under multiple grants.
%
% DREES is distributed under the terms of the Lesser GNU Public License.
%
%     This version of DREES 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.
%
% DREES is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with DREES.  If not, see <http://www.gnu.org/licenses/>.

a = 1 ./ max(eps, (p .* (1-p)));

return


function Psi0 = linard2VardistPsi0Compute(linard2kern, vardist)

% LINARD2VARDISTPSI0COMPUTE Description

% VARGPLVM

A = linard2kern.inputScales;
Psi0 = sum(A.*sum((vardist.means.*vardist.means) + vardist.covars,1));

%Psi0covs = sum(A.*sum(vardist.covars,1));

%psi00 = kernCompute(linard2kern,vardist.means);
%ok = 0;
%for n=1:size(vardist.means,1)
%    ok = ok + trace(diag(A)*(vardist.means(n,:)'*vardist.means(n,:))) + trace(diag(A)*diag(vardist.covars(n,:)));
%end
%ok
%pause
%Psi0 = Psi0means + Psi0covs;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Q=SELECT_CLOSEST_CONFIGURATION(ROBOT, Qinv, CONF)
% Returns the joint coordinates Q that are closest with the axes configuration
% vector CONF, given a set of solutions of the inverse kinematic problem Qinv.
% For 6DOF or less manipulators, the variable CONF={CF1, CF4, CF6, CFX}
% specifies univoquely only one of the solutions. The first axis has
% priority over the rest.
%
% See also:
%   COMPUTE_CONFIGURATION, SELECT_CONFIGURATION , GET_CONF_DATA
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE 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.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function q=select_closest_configuration(robot, qinv, conf)

q=qinv(:,1);

distance=64;

for i=1:size(qinv,2),
    confi=compute_configuration(robot, qinv(:,i));

    d = abs(conf(1)-confi(1)) + abs(conf(2)-confi(2)) + abs(conf(3)-confi(3));

    if d < distance
       q =  qinv(:,i);
       distance=d;
    end
end

if d ~= 0
    disp('WARNING: RAPID/select_closest_configuration: No solutions complies with the specified configuration ');
end


function [gX, kern] = pathKernDiagGradSym(kern, X)

% PATHKERNDIAGGRADSYM Compute the gradient of the PATH kernel's diagonal wrt parameters.
% FORMAT
% DESC computes the gradient of functions of the diagonal of the
% path kernel matrix with respect to the parameters of the
% symmetric kernel.
% ARG kern : the kernel structure for which the gradients are
% computed.
% ARG x : the input data for which the gradient is being computed.
% RETURN gX : gradients of the relevant function with respect to each
% of the parameters.
% RETURN kern : the updated kernel structure
%
% SEEALSO : pathKernParamInit, pathDiagGradient, pathKernExtractParam, pathKernGradient
%
% COPYRIGHT : Andrea Baisero, Carl Henrik Ek, 2013

% SHEFFIELDML

maxl=max(cellfun(@(x)size(x,1),X));
kern=pathKernUpdateWMat(kern,maxl);

num=length(X);

gX=cell(1,num);
for i=1:num
    gX{i}=pathKernDiagGradSymSeq(kern,X{i});
end

function gX = pathKernDiagGradSymSeq(kern, x)

l=size(x,1);
dim=size(x,2);

t=kernGradX(kern.gkern,x,x);
kw=kern.wmat(1:l,1:l);

gX=zeros(size(x));
for i=1:l
    gX(i,:)=sum((kw(i,:)'*ones(1,dim)).*t(:,:,i));
end


function pf = calcPoleFigure(pf,odf,varargin)
% simulate pole figure
%
% Syntax
%   pf = calcPoleFigure(pf,odf)
%
% Input
%  pf  - meassured @PoleFigure
%  odf - @SO3Fun
%
% Output
%  pf - recomputed @PoleFigure
%
% See also
% SO3Fun/calcPoleFigure

pf = calcPoleFigure(odf,pf.allH,pf.allR,'superposition',pf.c,varargin{:});


function comp_infos = normal_mser2(src,info)
%this script use the normal version of mser extract regions
%default: one channel
img = imadjust(rgb2gray(src));
%mser
[bbox,pixelsList,bright_dark_flag] = mser(img,info);
%record
comp_infos={};
for kk=1:size(bbox,1)
    box=bbox(kk,:);
    comp_infos(kk).box=box;
    comp_infos(kk).center=floor([box(1)+box(3)/2,box(2)+box(4)/2]);
    comp_infos(kk).pixelList = pixelsList{kk,1};
    comp_infos(kk).bright_dark_flag = bright_dark_flag(kk);
end

%%%%%%%% function %%%%%%%%
function  [bbBox,pixelsList,bright_dark_flag] = mser(I,info)
 %
[h,w]=size(I);
%phase-1: 'BrightOnDark'
[r,f] = vl_mser(I,'MinDiversity',info.minDiversity,'MaxVariation',info.maxVariation,...
				'MaxArea',info.maxArea,'MinArea',info.minArea,'BrightOnDark',1,'DarkOnBright',0,...
				'Delta',info.delta);
M =zeros(size(I));
for x=r'
    s = vl_erfill(I,x);
    M(s) = M(s) + 1;%if s belong to one region, add 1.
end
mCount = max(max(M));
bbBox = [];
pixelsList = {};
bright_dark_flag=[];
nCount = 1;
for ii=mCount:-1:1
    MM = M;
    MM(find(MM<ii))=0;
    MM(find(MM>=ii))=1;
    mContours = bwlabel(MM,8);
    mNum = max(max(mContours));
    for jj=1:mNum
        [idx,idy,~] = find(mContours == jj);
        ww = max(idx) - min(idx) + 1;%note me: ww & hh are reverse
        hh = max(idy) - min(idy) + 1;
		%condition
		if (ww/(hh+eps)<0.3)||(hh/(ww+eps)<0.3)
			continue;
		end
		if (ww<4||hh<4) || (ww>400|| hh>400)
			continue;
        end
        if ww*hh< 20
            continue;
        end
		%update
		bbBox(nCount,:)=[min(idx),min(idy),ww,hh];
		pixelsList{nCount,1}=[idx,idy];
        bright_dark_flag(nCount)=1;
		nCount = nCount + 1;
    end
end

%phase-2: 'DarkOnBright'
[r,f] = vl_mser(I,'MinDiversity',info.minDiversity,'MaxVariation',info.maxVariation,...
				'MaxArea',info.maxArea,'MinArea',info.minArea,'BrightOnDark',0,'DarkOnBright',1,...
				'Delta',info.delta);
M =zeros(size(I));
for x=r'
    s = vl_erfill(I,x);
    M(s) = M(s) + 1;%if s belong to one region, add 1.
end
mCount = max(max(M));
for ii=mCount:-1:1
    MM = M;
    MM(find(MM<ii))=0;
    MM(find(MM>=ii))=1;
    mContours = bwlabel(MM,8);
    mNum = max(max(mContours));
    for jj=1:mNum
        [idx,idy,~] = find(mContours == jj);
        ww = max(idx) - min(idx) + 1;%note me: ww & hh are reverse
        hh = max(idy) - min(idy) + 1;
		%condition
		if (ww/(hh+eps)<0.3)||(hh/(ww+eps)<0.3)
			continue;
		end
		if (ww<4||hh<4) || (ww>400|| hh>400)
			continue;
        end
        if ww*hh< 20
            continue;
        end
		%update
		bbBox(nCount,:)=[min(idx),min(idy),ww,hh];
		pixelsList{nCount,1}=[idx,idy];
        bright_dark_flag(nCount)=0;
		nCount = nCount + 1;
    end
end
end

end