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

report_this_filefun(mfilename('fullpath'));

global no1 bo1 inb1 inb2

if sel == 'in'
    % get the grid parameter
    % initial values
    %
    dd = 1.00;
    dx = 1.00 ;
    ni = 100;
    ra = 5;

    % make the interface
    %
    figure_w_normalized_uicontrolunits(...
        'Name','Grid Input Parameter',...
        'NumberTitle','off', ...
        'MenuBar','none', ...
        'units','points',...
        'Visible','off', ...
        'Position',[ wex+200 wey-200 550 300]);
    axis off

    labelList2=['Weighted LS - automatic Mcomp | Weighted LS - no automatic Mcomp '];
    labelPos = [0.2 0.7  0.6  0.08];
    hndl2=uicontrol(...
        'Style','popup',...
        'Position',labelPos,...
        'Units','normalized',...
        'String',labelList2,...
        'Callback','inb2 =get(hndl2,''Value''); ');

    labelList=['Maximum likelihood - automatic Mcomp | Maximum likelihood  - no automatic Mcomp '];
    labelPos = [0.2 0.8  0.6  0.08];
    hndl1=uicontrol(...
        'Style','popup',...
        'Position',labelPos,...
        'Units','normalized',...
        'String',labelList,...
        'Callback','inb1 =get(hndl1,''Value''); ');

    % creates a dialog box to input grid parameters
    %
    freq_field=uicontrol('Style','edit',...
        'Position',[.60 .50 .22 .10],...
        'Units','normalized','String',num2str(ra),...
        'Callback','ra=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ra));');

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

    freq_field3=uicontrol('Style','edit',...
        'Position',[.60 .30 .22 .10],...
        'Units','normalized','String',num2str(dd),...
        'Callback','dd=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dd));');

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

    go_button1=uicontrol('Style','Pushbutton',...
        'Position',[.20 .05 .15 .12 ],...
        'Units','normalized',...
        'Callback','inb1 =get(hndl1,''Value'');inb2 =get(hndl2,''Value'');close,sel =''ca'', bcrossVt',...
        'String','Go');

    text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.20 1.0 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.l ,...
        'FontWeight','bold',...
        'String','Automatically estimate magn. of completeness?   ');

    txt3 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.30 0.65 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.l ,...
        'FontWeight','bold',...
        'String',' Grid Parameter');
    txt5 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0. 0.42 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing along projection [km]');

    txt6 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0. 0.32 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing in depth in km:');

    txt1 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0. 0.53 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m,...
        'FontWeight','bold',...
        'String','Radius in km');

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

end   % if sel == in

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

if sel == 'ca'

    figure_w_normalized_uicontrolunits(xsec_fig)
    hold on

    messtext=...
        ['To select a polygon for a grid.       '
        'Please use the LEFT mouse button of   '
        'or the cursor to the select the poly- '
        'gon. Use the RIGTH mouse button for   '
        'the final point.                      '
        'Mac Users: Use the keyboard "p" more  '
        'point to select, "l" last point.      '
        '                                      '];

    zmap_message_center.set_message('Select Polygon for a grid',messtext);

    hold on
ax = findobj('Tag','main_map_ax');
[x,y, mouse_points_overlay] = select_polygon(ax);
    zmap_message_center.set_info('Message',' Thank you .... ')

    plos2 = plot(x,y,'b-','era','xor');        % plot outline
    sum3 = 0.;
    pause(0.3)

    %create a rectangular grid
    xvect=[min(x):dx:max(x)];
    yvect=[min(y):dd:max(y)];
    gx = xvect;gy = yvect;
    tmpgri=zeros((length(xvect)*length(yvect)),2);
    n=0;
    for i=1:length(xvect)
        for j=1:length(yvect)
            n=n+1;
            tmpgri(n,:)=[xvect(i) yvect(j)];
        end
    end
    %extract all gridpoints in chosen polygon
    XI=tmpgri(:,1);
    YI=tmpgri(:,2);

    ll = polygon_filter(x,y, XI, YI, 'inside');
    %grid points in polygon
    newgri=tmpgri(ll,:);

    % Plot all grid points
    plot(newgri(:,1),newgri(:,2),'+k')

    if length(xvect) < 2 || length(yvect) < 2
        errordlg('Selection too small! (not a matrix)');
        return
    end

    itotal = length(newgri(:,1));

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

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

    % overall b-value
    [bv magco stan av me mer me2,  pr] =  bvalca3(newa,inb1,inb2);
    bo1 = bv; no1 = newa.Count;
    %
    for i= 1:length(newgri(:,1))
        x = newgri(i,1);y = newgri(i,2);
        allcount = allcount + 1.;
        i2 = i2+1;

        % calculate distance from center point and sort wrt distance
        l = sqrt(((xsecx' - x)).^2 + ((xsecy + y)).^2) ;
        %[s,is] = sort(l);
        %b = newa(is(:,1),:) ;       % re-orders matrix to agree row-wise

        % take first ni points
        l = l <= ra;
        b = newa.subset(l);      % new data per grid point (b) is sorted in distance

        if isempty(b) == 1; b = newa.subset(1); end
        if length(b(:,1)) >= 50;
            % call the b-value function
            lt =  b(:,3) >= t1 &  b(:,3) <t2 ;
            if  length(b(lt,1)) > 20;
                [bv magco stan av me mer me2,  pr] =  bvalca3(b(lt,:),inb1,inb2);
                bo1 = bv; no1 = newa.Count;
            else
                bv = NaN; pr = 50;
            end
            lt = b(:,3) >= t3 &  b(:,3) < t4 ;
            if  length(b(lt,1)) > 20;
                [bv2 magco stan av me mer me2,  pr] =  bvalca3(b(lt,:),inb1,inb2);
            else
                bv2 = NaN; pr = 50;
            end
            lt = b(:,3) >= t4 &  b(:,3) < t5 ;
            if  length(b(lt,1)) > 20;
                [bv3 magco stan av me mer me2,  pr2] =  bvalca3(b(lt,:),inb1,inb2);
            else
                bv3 = NaN; pr = 50;
            end

            l2 = sort(l);

            l2 = sort(l);
            b2 = b;
            if inb2 ==  1
                l = b(:,6) >= magco;
                b2 = b(l,:);
            end
            [av2 bv2 stan2 ] =  bmemag(b2);
            if pr >=90
                bvg = [bvg ; bv magco x y length(b(:,1)) bv2 pr av stan  max(b(:,6)) bv-bv2 bv-bv3 bv2-bv3 pr];
            else
                bvg = [bvg ; NaN NaN x y NaN NaN NaN NaN NaN  NaN NaN NaN NaN NaN];
            end
        else
            bvg = [bvg ; NaN NaN x y NaN NaN NaN NaN NaN  NaN NaN NaN NaN NaN];
        end
        waitbar(allcount/itotal)
    end  % for  newgri

    % save data
    %
    %  set(txt1,'String', 'Saving data...')
    drawnow
    gx = xvect;gy = yvect;

    catSave3 =...
        [ 'zmap_message_center.set_info(''Save Grid'',''  '');think;',...
        '[file1,path1] = uiputfile(fullfile(hodi, ''eq_data'', ''*.mat''), ''Grid Datafile Name?'') ;',...
        ' sapa2 = [''save '' path1 file1 '' ll tmpgri bvg xvect yvect gx gy ni dx dd par1 ni newa maex maey maix maiy ''];',...
        ' if length(file1) > 1, eval(sapa2),end , done']; eval(catSave3)

    close(wai)
    watchoff

    % reshape a few matrices
    %
    normlap2=ones(length(tmpgri(:,1)),1)*nan;
    normlap2(ll)= bvg(:,1);
    re3=reshape(normlap2,length(yvect),length(xvect));

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

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

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

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

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

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

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

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

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

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

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

    old = re3;

    % View the b-value map
    view_bvt

end   %  if sel = ca

% Load exist b-grid
if sel == 'lo'
    load_existing_bgrid_version_A
end


D = spm_eeg_load('dspm8_faces_run1.mat');

montage.labelorg = D.chanlabels;

montage.labelnew = [montage.labelorg(1:128), 'HEOG', 'VEOG'];

tra = eye(D.nchannels);
tra(129:end, :) = [];
tra = detrend(tra, 'constant');

% HEOG
tra(129, [131 132]) = [1 -1];

% VEOG
tra(130, [135 136]) = [1 -1];

montage.tra = tra;

save faces_eeg_montage.mat montage


function calpak_test25 ( )

%*****************************************************************************80
%
%% CALPAK_TEST25 tests JED_TO_YMDF_REPUBLICAN and YMDF_TO_JED_REPUBLICAN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 March 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST25\n' );
  fprintf ( 1, '  For the Republican calendar:\n' );
  fprintf ( 1, '  JED_TO_YMDF_REPUBLICAN: JED -> YMDF.\n' );
  fprintf ( 1, '  YMDF_TO_JED_REPUBLICAN: YMDF -> JED.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED (in)    YMDF                JED (out)\n' );
  fprintf ( 1, '\n' );

  jed_epoch = epoch_to_jed_republican ( );

  i = 0;

  while ( 1 )

    i = i + 1;
    jed1 = jed_test ( i );

    if ( jed1 < 0.0 )
      break
    end

    if ( jed_epoch <= jed1 )

      [ y2, m2, d2, f2 ] = jed_to_ymdf_republican ( jed1 );

      s2 = ymdf_to_s_republican ( y2, m2, d2, f2 );

      jed3 = ymdf_to_jed_republican ( y2, m2, d2, f2 );

      fprintf ( 1, '  %11.2f  %20s  %11.2f\n', jed1, s2, jed3 );

    end

  end

  return
end


function midrad(p)
%MIDRAD       Display of polynom in "midrad" mode
%

% written  07/22/02     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  olddisp = intvalinit('display',0);
  intvalinit('displaymidrad',0);
  display(p,inputname(1));
  intvalinit(olddisp,0);


function msm_to_mm_coordinate_complex_hermitian ( output_filename, a )

%*****************************************************************************80
%
%% MSM_TO_MM_COORDINATE_COMPLEX_HERMITIAN writes a "matrix coordinate complex hermitian" Matrix Market file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 November 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the name of the file to which the information
%    should be written.
%
%    Input, sparse matrix A, the NROW by NCOL matrix, stored in MATLAB sparse
%    matrix format, which is to be written to the file.
%
  [ nrow, ncol ] = size ( a );
  nnzeros = nnz ( a );

  fid = fopen ( output_filename, 'wt+' );

  if ( fid < 0 );
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MSM_TO_MM_COORDINATE_COMPLEX_HERMITIAN - Fatal error!\n' );
    fprintf ( 1, '  Cannot open the output file.\n' );
    error ( 'MSM_TO_MM_COORDINATE_COMPLEX_HERMITIAN - Fatal error!');
  end;

  fprintf ( fid, '%%%%MatrixMarket matrix coordinate complex hermitian\n');
  fprintf ( fid, '%%%%  Created by MSM_TO_MM_COORDINATE_COMPLEX_HERMITIAN.M\n' );
  fprintf ( fid, '  %d  %d  %d\n', nrow, ncol, nnzeros );

  for j = 1 : ncol
    [ rows, temp, vals ] = find ( a(:,j) );
    sz = size ( rows );
    for k2 = 1 : sz
      if ( j <= rows(k2) )
        fprintf ( fid, '  %d  %d  %f  %f\n', rows(k2), j, real ( vals(k2) ), imag ( vals(k2) ) );
      end
    end

  end

  fclose ( fid );

  return
end


% This script calculates full-reference and no-reference quality measures
% on the sequence length datasets.

%% Update MATLAB path.
addpath('../algorithms/SRAlgorithms');
addpath('../algorithms/qualityMeasures');

%% Evaluation settings.

% Path to input data and result directory.
inputDir = '../../data';
datasetConfig = 'sequenceLengthDatasets';
resultDir = '../../results/sequenceLengthDatasets';

% Parameters for this evaluation.
initEvaluationParametersForSequenceLength;

% The quality measures that are calculated.
measure_val = 1:length(qualityMeasures);

% Size of the border in pixels that is cropped from super-resolved image to
% evaluate the quality measures without distortion by boundary artifacts.
border = 3;

%% Start evaluation.
calculateQualityMeasures(inputDir, datasetConfig, resultDir, binningFactors, numberOfFrames, numberOfFrames_val, sliding_val, sr_method, binning_val, scenes_val, compressions(compress_val), measure_val, border);


%%*********************************************************************
%% sortA: sort columns of At{p} in ascending order according to the
%%        number of nonzero elements.
%%
%% [At,C,b,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*********************************************************************

function [At,C,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0)

global spdensity smallblkdim
%%
if isempty(spdensity); spdensity = 0.4; end
if isempty(smallblkdim); smallblkdim = 50; end
%%
numblk = size(blk,1);
m = length(b);
nnzA = zeros(numblk,m);
permA = kron(ones(numblk,1),1:m);
permZ = cell(size(blk,1),1);
%%
for p=1:size(blk,1)
    pblk = blk(p,:);
    n = sum(pblk{2});
    % numblk = length(pblk{2});
    if strcmp(pblk{1},'s') && (max(pblk{2}) > smallblkdim)
        % n2 = sum(pblk{2}.*pblk{2});
        n22 = sum(pblk{2}.*(pblk{2}+1))/2;
        m1 = size(At{p,1},2);
        if (length(pblk{2}) == 1)
            tmp = abs(C{p}) + abs(Z0{p});
            if  (~isempty(At{p,1}))
                tmp = tmp + smat(blk(p,:),abs(At{p,1})*ones(m1,1),1);
            end
            if (nnz(tmp) < spdensity*n22);
                per = symamd(tmp);
                invper = zeros(n,1); invper(per) = 1:n;
                permZ{p} = invper;
                if (~isempty(At{p,1}))
                    isspAt = issparse(At{p,1});
                    for k = 1:m1
                        Ak = smat(pblk,At{p,1}(:,k),1);
                        At{p,1}(:,k) = svec(pblk,Ak(per,per),isspAt);
                    end
                end
                C{p}  = C{p}(per,per);
                Z0{p} = Z0{p}(per,per);
                X0{p} = X0{p}(per,per);
            else
                per = [];
            end
            if (length(pblk) > 2) && (~isempty(per))
                % m2 = length(pblk{3});
                P = spconvert([(1:n)', per', ones(n,1)]);
                At{p,2} = P*At{p,2};
            end
        end
        if ~isempty(At{p,1}) && (mexnnz(At{p,1}) < m*n22/2)
            for k = 1:m1
                Ak = At{p,1}(:,k);
                nnzA(p,k) = length(find(abs(Ak) > eps));
            end
            [dummy,permAp] = sort(nnzA(p,1:m1)); %#ok
            At{p,1}  = At{p,1}(:,permAp);
            permA(p,1:m1) = permAp;
        end
    elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u');
        if ~issparse(At{p,1});
            At{p,1} = sparse(At{p,1});
        end
    end
end
%%*********************************************************************


function r8vec_sort_heap_index_d_test ( )

%*****************************************************************************80
%
%% R8VEC_SORT_HEAP_INDEX_D_TEST tests R8VEC_SORT_HEAP_INDEX_D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  n = 20;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8VEC_SORT_HEAP_INDEX_D_TEST\n' );
  fprintf ( 1, '  R8VEC_SORT_HEAP_INDEX_D creates a descending\n' );
  fprintf ( 1, '  sort index for an R8VEC.\n' );

  b = 0.0;
  c = 3.0 * n;
  seed = 123456789;

  [ a, seed ] = r8vec_uniform_ab ( n, b, c, seed );

  r8vec_print_some ( n, a, 1, 10, '  Unsorted array:' );

  indx = r8vec_sort_heap_index_d ( n, a );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  After indexed descending sort:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  I, INDX(I), A(I)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  %6d  %6d  %12f\n', i, indx(i), a(i) );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now use the index array to carry out the\n' );
  fprintf ( 1, '  permutation implicitly.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  INDX(I), ARRAY(INDX(I))\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  %6d  %12f\n', indx(i), a(indx(i)) );
  end

  return
end


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% file: get_rate_diff_ci1.m
% one-sided confidence intervals for the difference of rates

% 030113 tdr created

function ci = get_rate_diff_ci1(x1,A1,x2,A2,alpha,method,verbose)

r1_hat = x1/A1; r2_hat = x2/A2; delta_r_hat = r1_hat - r2_hat;
a = find_lower_limit(x1,A1,x2,A2, alpha);
b = find_upper_limit(x1,A1,x2,A2, alpha);
ci = [delta_r_hat a b];

% ------------------------------------------------------------
% find lower limit

function limit = find_lower_limit(x1,A1,x2,A2,alpha)
% alpha is 1-Pr{delta_r >= a}
r1_hat = x1/A1; r2_hat = x2/A2; delta_r_hat = r1_hat - r2_hat;

% set limits of search
too_big = 1e12; too_small = -1e12;

%check that too_big is indeed too big etc.
alpha_too_big = 1 - rate_diff(x1,A1,x2,A2,too_big);
alpha_too_small = 1 - rate_diff(x1,A1,x2,A2,too_small);
if (alpha_too_big < alpha | alpha_too_small > alpha), error('Failure to set bounds for search'); end;

tolerance = 1e-6;
max_count = 50;
count = 0;

% initial guess for search
guess = (too_big + too_small)/2;
alpha_guess = 1- rate_diff(x1,A1,x2,A2,guess);

% binary search
while (abs(alpha_guess - alpha) > tolerance & (count < max_count))
    if (alpha_guess > alpha)
        too_big = guess;
        guess = (too_small + guess)/2;
    else
        too_small=guess;
        guess = (too_big + guess)/2;
    end;
    count = count+1;
    alpha_guess = 1 - rate_diff(x1,A1,x2,A2,guess);
end;

limit = guess;

% ------------------------------------------------------------
% find upper limit

function limit = find_upper_limit(x1,A1,x2,A2,alpha, bounds)
% alpha is Pr{delta_r >= b}
r1_hat = x1/A1; r2_hat = x2/A2; delta_r_hat = r1_hat - r2_hat;

% set limits for search
too_big = 1e12;  too_small = -1e12;

%check that too_big is indeed too big etc.
alpha_too_big = rate_diff(x1,A1,x2,A2,too_big);
alpha_too_small = rate_diff(x1,A1,x2,A2,too_small);
if (alpha_too_big > alpha | alpha_too_small < alpha), error('Failure to set bounds for search'); end;

tolerance = 1e-6;
max_count = 50;
count = 0;

% initial guess for search
guess = (too_big + too_small)/2;
alpha_guess = rate_diff(x1,A1,x2,A2,guess);

% binary search
while (abs(alpha_guess - alpha) > tolerance & (count < max_count))
    if (alpha_guess < alpha)
        too_big = guess;
        guess = (too_small + guess)/2;
    else
        too_small=guess;
        guess = (too_big + guess)/2;
    end;
    count = count+1;
    alpha_guess = rate_diff(x1,A1,x2,A2,guess);
end;

limit = guess;


function sF = times(sF1,sF2)
% overloads sF1 .* sF2
%
% Syntax
%   sF = sF1.*sF2
%   sF = a.*sF1
%   sF = sF1.*a
%
% Input
%   sF1, sF2 - S2FunHarmonic
%
% Output
%   sF - S2FunHarmonic
%

sF = times@S2FunHarmonic(sF1,sF2);

% try to preserve symmetry
if isa(sF1,'S2FunHarmonicSym') && isa(sF2,'S2FunHarmonicSym')
  sym = disjoint(sF1.CS,sF2.CS);
  sF = S2FunHarmonicSym(sF.fhat,sym);
end


% ZG_rsum(X)
% row sum
%
% Machine Learning Toolbox
% Version 1.0  01-Apr-96
% Copyright (c) by Zoubin Ghahramani
% http://mlg.eng.cam.ac.uk/zoubin/software.html
%
% ------------------------------------------------------------------------------
% The MIT License (MIT)
%
% Copyright (c) 1996, Zoubin Ghahramani
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
% THE SOFTWARE.
% ------------------------------------------------------------------------------

function Z = ZG_rsum(X)

Z = zeros(size(X(:,1)));

for i = 1:length(X(1,:))
    Z = Z + X(:,i);
end

end


%GRIDCHECK Check grid for errors.
%
%   [ N_ERR, CIND ] = GRIDCHECK( G, ISWARN, I_CHECK ) Checks a grid G for errors.
%   N_ERR returns the number of errors found. CIND is a cell array giving the
%   indices to incorrectly oriented cells, collapsed cells (with zero volume/area),
%   and non-convex cells. ISWARN is a flag to enable/disable warnings. I_CHECK is
%   a flag to choose check/test type (1 = test Jacobian determinant (default),
%   2 = test if polygon points are in clockwise order, 3 = split hexahedra into
%   six tetrahedra).
%
%   See also REORIENT_CELLS

% Copyright 2013-2022 Precise Simulation, Ltd.


function [ rgb ] = hex2rgb(hex,range)
% hex2rgb converts hex color values to rgb arrays on the range 0 to 1.
%
%
% * * * * * * * * * * * * * * * * * * * *
% SYNTAX:
% rgb = hex2rgb(hex) returns rgb color values in an n x 3 array. Values are
%                    scaled from 0 to 1 by default.
%
% rgb = hex2rgb(hex,256) returns RGB values scaled from 0 to 255.
%
%
% * * * * * * * * * * * * * * * * * * * *
% EXAMPLES:
%
% myrgbvalue = hex2rgb('#334D66')
%    = 0.2000    0.3020    0.4000
%
%
% myrgbvalue = hex2rgb('334D66')  % <-the # sign is optional
%    = 0.2000    0.3020    0.4000
%
%
% myRGBvalue = hex2rgb('#334D66',256)
%    = 51    77   102
%
%
% myhexvalues = ['#334D66';'#8099B3';'#CC9933';'#3333E6'];
% myrgbvalues = hex2rgb(myhexvalues)
%    =   0.2000    0.3020    0.4000
%        0.5020    0.6000    0.7020
%        0.8000    0.6000    0.2000
%        0.2000    0.2000    0.9020
%
%
% myhexvalues = ['#334D66';'#8099B3';'#CC9933';'#3333E6'];
% myRGBvalues = hex2rgb(myhexvalues,256)
%    =   51    77   102
%       128   153   179
%       204   153    51
%        51    51   230
%
% HexValsAsACharacterArray = {'#334D66';'#8099B3';'#CC9933';'#3333E6'};
% rgbvals = hex2rgb(HexValsAsACharacterArray)
%
% * * * * * * * * * * * * * * * * * * * *
% Chad A. Greene, April 2014
%
% Updated August 2014: Functionality remains exactly the same, but it's a
% little more efficient and more robust. Thanks to Stephen Cobeldick for
% the improvement tips. In this update, the documentation now shows that
% the range may be set to 256. This is more intuitive than the previous
% style, which scaled values from 0 to 255 with range set to 255.  Now you
% can enter 256 or 255 for the range, and the answer will be the same--rgb
% values scaled from 0 to 255. Function now also accepts character arrays
% as input.
%
% * * * * * * * * * * * * * * * * * * * *
% See also rgb2hex, dec2hex, hex2num, and ColorSpec.
%

%% Input checks:

assert(nargin>0&nargin<3,'hex2rgb function must have one or two inputs.')

if nargin==2
    assert(isscalar(range)==1,'Range must be a scalar, either "1" to scale from 0 to 1 or "256" to scale from 0 to 255.')
end

%% Tweak inputs if necessary:

if iscell(hex)
    assert(isvector(hex)==1,'Unexpected dimensions of input hex values.')

    % In case cell array elements are separated by a comma instead of a
    % semicolon, reshape hex:
    if isrow(hex)
        hex = hex';
    end

    % If input is cell, convert to matrix:
    hex = cell2mat(hex);
end

if strcmpi(hex(1,1),'#')
    hex(:,1) = [];
end

if nargin == 1
    range = 1;
end

if size(hex,2) == 3
  % Expand shorthand #abc → #aabbcc
  hex = hex(:,[1 1 2 2 3 3]);
end

%% Convert from hex to rgb:

switch range
    case 1
        rgb = reshape(sscanf(hex.','%2x'),3,[]).'/255;

    case {255,256}
        rgb = reshape(sscanf(hex.','%2x'),3,[]).';

    otherwise
        error('Range must be either "1" to scale from 0 to 1 or "256" to scale from 0 to 255.')
end

end


function sgmga_index_test ( dim_num, importance, level_weight, ...
  level_max_min, level_max_max, rule, growth, np, p, tol )

%****************************************************************************80
%
%% SGMGA_INDEX_TEST tests SGMGA_INDEX.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 June 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, real IMPORTANCE(DIM_NUM), the anisotropic importance of
%    each dimension.
%
%    Input, real LEVEL_WEIGHT(DIM_NUM), the anisotropic weight
%    for each dimension.
%
%    Input, integer LEVEL_MAX_MIN, LEVEL_MAX_MAX, the minimum and
%    maximum values of LEVEL_MAX.
%
%    Input, integer RULE(DIM_NUM), the rule in each dimension.
%     1, "CC",  Clenshaw Curtis, Closed Fully Nested.
%     2, "F2",  Fejer Type 2, Open Fully Nested.
%     3, "GP",  Gauss Patterson, Open Fully Nested.
%     4, "GL",  Gauss Legendre, Open Weakly Nested.
%     5, "GH",  Gauss Hermite, Open Weakly Nested.
%     6, "GGH", Generalized Gauss Hermite, Open Weakly Nested.
%     7, "LG",  Gauss Laguerre, Open Non Nested.
%     8, "GLG", Generalized Gauss Laguerre, Open Non Nested.
%     9, "GJ",  Gauss Jacobi, Open Non Nested.
%    10, "HGK", Hermite Genz-Keister, Open Fully Nested.
%    11, "UO",  User supplied Open, presumably Non Nested.
%    12, "UC",  User supplied Closed, presumably Non Nested.
%
%    Input, integer GROWTH(DIM_NUM), the growth in each dimension.
%    0, "DF", default growth associated with this quadrature rule;
%    1, "SL", slow linear, L+1;
%    2  "SO", slow linear odd, O=1+2((L+1)/2)
%    3, "ML", moderate linear, 2L+1;
%    4, "SE", slow exponential;
%    5, "ME", moderate exponential;
%    6, "FE", full exponential.
%
%    Input, integer NP(DIM_NUM), the number of parameters used by each rule.
%
%    Input, real P(*), the parameters needed by each rule.
%
%    Input, real TOL, a tolerance for point equality.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SGMGA_INDEX_TEST\n' );
  fprintf ( 1, '  SGMGA_INDEX returns index and order vectors that\n' );
  fprintf ( 1, '  identify each point in a multidimensional sparse grid with mixed factors.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Each sparse grid is of spatial dimension DIM_NUM,\n' );
  fprintf ( 1, '  and is made up of product grids of levels up to LEVEL_MAX.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  IMPORTANCE:    ');
  for dim = 1 : dim_num
    fprintf ( 1, '  %14f', importance(dim) );
  end
  fprintf ( 1, '\n' );
  fprintf ( 1, '  LEVEL_WEIGHT:  ');
  for dim = 1 : dim_num
    fprintf ( 1, '  %14f', level_weight(dim) );
  end
  fprintf ( 1, '\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, ' Dimension      Rule       Growth     Parameters\n' );
  fprintf ( 1, '\n' );

  p_index = 1;

  for dim = 1 : dim_num

    if ( rule(dim) == 1 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  2 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  3 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  4 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  5 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  6 )
      fprintf ( 1, '  %8d  %8d  %11d  %14f\n', dim, rule(dim), growth(dim), p(p_index) );
    elseif ( rule(dim) ==  7 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  8 )
      fprintf ( 1, '  %8d  %8d  %11d  %14f\n', dim, rule(dim), growth(dim), p(p_index) );
    elseif ( rule(dim) ==  9 )
      fprintf ( 1, '  %8d  %8d  %11d  %14f  %14f\n', ...
        dim, rule(dim), growth(dim), p(p_index), p(p_index+1) );
    elseif ( rule(dim) == 10 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  11 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    elseif ( rule(dim) ==  12 )
      fprintf ( 1, '  %8d  %8d  %11d\n', dim, rule(dim), growth(dim) );
    end

    p_index = p_index + np(dim);

  end

  for level_max = level_max_min : level_max_max

    point_total_num = sgmga_size_total ( dim_num, level_weight, level_max, ...
      rule, growth );

    point_num = sgmga_size ( dim_num, level_weight, level_max, rule, growth, ...
      np, p, tol );

    sparse_unique_index = sgmga_unique_index ( dim_num, level_weight, ...
      level_max, rule, growth, np, p, tol, point_num, point_total_num );

    [ sparse_order, sparse_index ] = sgmga_index ( dim_num, level_weight, ...
      level_max, rule, growth, point_num, point_total_num, sparse_unique_index );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  For LEVEL_MAX = %d\n', level_max );
    fprintf ( 1, '\n' );
    for point = 1 : point_num
      fprintf ( 1, '  %4d', point );
      for dim = 1 : dim_num
        fprintf ( 1, '  %3d / %3d', sparse_index(dim,point), sparse_order(dim,point) );
      end
      fprintf ( 1, '\n' );
    end

  end

  return
end


function [ n_data, p, q, n, d ] = dedekind_sum_values ( n_data )

%*****************************************************************************80
%
%% DEDEKIND_SUM_VALUES returns some values of the Dedekind sum.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 July 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Hans Rademacher, Emil Grosswald,
%    Dedekind Sums,
%    Mathematics Association of America, 1972,
%    LC: QA241.R2.
%
%  Parameters:
%
%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the
%    first call.  On each call, the routine increments N_DATA by 1, and
%    returns the corresponding data; when there is no more data, the
%    output value of N_DATA will be 0 again.
%
%    Output, integer P, Q, the arguments of the function.
%
%    Output, integer N, D, the numerator and denominator of the function value.
%
  n_max = 95;

  p_vec = [ ...
     1,  1,  1,  1,  1,  1,  1,  1,  1,  1, ...
     1,  1,  1,  1,  1,  1,  1,  1,  1,  1, ...
     2,  2,  2,  2,  2,  2,  2,  2,  2,  2, ...
     3,  3,  3,  3,  3,  3,  3,  3,  3,  3, ...
     3,  3,  3,  3,  4,  4,  4,  4,  4,  4, ...
     4,  4,  4,  4,  5,  5,  5,  5,  5,  5, ...
     5,  5,  5,  5,  5,  5,  5,  5,  5,  5, ...
     6,  6,  6,  6,  6,  6,  6,  7,  7,  7, ...
     7,  7,  7,  7,  7,  7,  7,  7,  7,  7, ...
     7,  7,  7,  7,  7 ...
  ];

  q_vec = [ ...
     1,  2,  3,  4,  5,  6,  7,  8,  9, 10, ...
    11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
     1,  3,  5,  7,  9, 11, 13, 15, 17, 19, ...
     1,  2,  4,  5,  7,  8, 10, 11, 13, 14, ...
    16, 17, 19, 20,  1,  3,  5,  7,  9, 11, ...
    13, 15, 17, 19,  1,  2,  3,  4,  6,  7, ...
     8,  9, 11, 12, 13, 14, 16, 17, 18, 19, ...
     1,  5,  7, 11, 13, 17, 19,  1,  2,  3, ...
     4,  5,  6,  8,  9, 10, 11, 12, 13, 15, ...
    16, 17, 18, 19, 20 ...
  ];

  n_vec = [ ...
     0,  0,  1,  1,  1,  5,  5,  7, 14,  3, ...
    15, 55, 11, 13, 91, 35, 20, 34, 51, 57, ...
     0, -1,  0,  1,  4,  5,  4,  7,  8, 21, ...
     0,  0, -1,  0, -1,  1,  0,  3,  1,  3, ...
     5,  5,  9,  3,  0,  1, -1,  1, -4,  3, ...
    -1, 19,  0, 11,  0,  0, -1,  1, -5, -1, ...
    -1,  4, -5, -1,  0,  3, -5,  1,  2, 11, ...
     0,  1, -5,  5, -4,  5, -9,  0,  0,  1, ...
    -1,  0,  5, -7, -4,  0, -3,  1,  4, -7, ...
    -3,  1, -2,  3,  3 ...
  ];

  d_vec = [ ...
     1,  1, 18,  8,  5, 18, 14, 16, 27,  5, ...
    22, 72, 13, 14, 90, 32, 17, 27, 38, 40, ...
     1, 18,  1, 14, 27, 22, 13, 18, 17, 38, ...
     1,  1,  8,  1, 14, 16,  1, 22, 13, 14, ...
    32, 17, 38,  8,  1, 18,  5, 14, 27, 22, ...
    13, 90,  1, 38,  1,  1, 18,  8, 18, 14, ...
    16, 27, 22, 72,  1, 14, 32, 17, 27, 38, ...
     1,  5, 14, 22, 13, 17, 38,  1,  1, 18, ...
     8,  1, 18, 16, 27,  1, 22, 72, 13, 18, ...
    32, 17, 27, 38,  8 ...
  ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    p = 0;
    q = 0;
    n = 0;
    d = 0;
  else
    p = p_vec(n_data);
    q = q_vec(n_data);
    n = n_vec(n_data);
    d = d_vec(n_data);
  end

  return
end


function model = yalmip2intlinprog(interfacedata)

options = interfacedata.options;
F_struc = interfacedata.F_struc;
c       = interfacedata.c;
K       = interfacedata.K;
Q       = interfacedata.Q;
lb      = interfacedata.lb;
ub      = interfacedata.ub;

ops = options.intlinprog;
switch options.verbose
    case 0
        ops.Display = 'off';
    case 1
        ops.Display = 'final';
    otherwise
        ops.Display = 'iter';
end

if isempty(F_struc)
    Aeq = [];
    beq = [];
    A = [];
    b = [];
else
    Aeq = -F_struc(1:1:K.f,2:end);
    beq = F_struc(1:1:K.f,1);
    A =-F_struc(K.f+1:end,2:end);
    b = F_struc(K.f+1:end,1);
end

intcon = union(interfacedata.integer_variables,interfacedata.binary_variables);
if ~isempty(interfacedata.binary_variables)
    lb(interfacedata.binary_variables) = max(0,lb(interfacedata.binary_variables));
    ub(interfacedata.binary_variables) = min(1,ub(interfacedata.binary_variables));
end

model.c = c;
model.intcon = intcon;
model.A = A;
model.b = b;
model.Aeq = Aeq;
model.beq = beq;
model.lb = lb;
model.ub = ub;
model.ops = ops;


classdef hmx
%+========================================================================+
%|                                                                        |
%|         OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA         |
%|           openHmx 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       : hmx.m                                         |
%|    #    |   VERSION    : 0.61                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2017                                    |
%|  / 0 \  |   LAST MODIF : 05.09.2019                                    |
%| ( === ) |   SYNOPSIS   : H-Matrix class definition and functions       |
%|  `---'  |                                                              |
%+========================================================================+

properties
    typ = [];            % LEAF TYPE (0=H-MATRIX ; 1=COMPRESSED ; 2=FULL/SPARSE)
    pos = [];            % COORDINATES POSITIONS (X,Y)
    row = cell(1,4);     % CHILDREN ROWS INDICES (M11,M12,M21,M22)
    col = cell(1,4);     % CHILDREN COLUMNS INDICES
    chd = cell(1,4);     % CHILDREN
    dat = [];            % LEAF DATA
    tol = [];            % COMPRESSORS ACCURACY
end

methods
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CONSTRUCTOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % CONSTRUCTOR
    function Mh = hmx(varargin)
        % Empty object
        if (nargin == 0)

        % Initialization other H-matrix
        elseif (nargin == 2)
            Mh = hmxCopy(varargin{1},varargin{2});

        % Initialization with dimension and accuracy
        elseif (nargin == 3)
            Mh     = hmx();
            Mh.pos = {varargin{1},varargin{2}};
            Mh.tol = varargin{3};

        % Particles builder with partial and total pivoting
        elseif (nargin == 4)
            X     = varargin{1};
            Y     = varargin{2};
            green = varargin{3};
            acc   = varargin{4};
            Mh    = hmxBuilder(X,Y,green,acc);

        % Compressed builder
        elseif (nargin == 5)
            X      = varargin{1};
            Y      = varargin{2};
            A      = varargin{3};
            B      = varargin{4};
            acc    = varargin{5};
            Mh     = hmx(X,Y,acc);
            Mh.typ = 1;
            Mh.dat = {A,B};

       % Finite element builder
        elseif (nargin == 8)
            Xunk  = varargin{1};
            Yunk  = varargin{2};
            Mx    = varargin{3};
            X     = varargin{4};
            green = varargin{5};
            Y     = varargin{6};
            My    = varargin{7};
            acc   = varargin{8};
            Mh    = hmxBuilderFem(Xunk,Yunk,Mx,X,green,Y,My,acc);

        else
            error('hmx.m : undefined constructor case')
        end
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%% GLOBAL DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % SIZE
    function s = size(varargin)
        Mh = varargin{1};
        s  = [size(Mh.pos{1},1),size(Mh.pos{2},1)];
        if (nargin == 2)
            s = s(varargin{2});
        end
    end

    % LENGTH
    function l = length(Mh)
        l = max(size(Mh));
    end

    % ISLOWER
    function b = islower(Mh)
        if (Mh.typ == 0)
            b = (Mh.chd{2}.typ == 1) && isempty(Mh.chd{2}.dat{1});
        elseif (Mh.typ == 2)
            b = 1;
        else
            error('hmx.m : unavailable case.')
        end
    end

    % ISUPPER
    function b = isupper(Mh)
        if (Mh.typ == 0)
            b = (Mh.chd{3}.typ == 1) && isempty(Mh.chd{3}.dat{1});
        elseif (Mh.typ == 2)
            b = 1;
        else
            error('hmx.m : unavailable case.')
        end
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%% VISUALISATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % STRUCTURE VISUALISATION
    function spy(Mh)
        hmxSpy(Mh);
    end

    % PLOT POSITIONS
    function plot3(Mh)
        plot3(Mh.pos{1}(:,1),Mh.pos{1}(:,2),Mh.pos{1}(:,3),'bo',...
            Mh.pos{2}(:,1),Mh.pos{2}(:,2),Mh.pos{2}(:,3),'*r');
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CONVERSION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % FULL
    function M = full(varargin)
        if (nargin == 1)
            M = hmxFull(varargin{1});
        else
            M = hmxFullSub(varargin{1},varargin{2},varargin{3});
        end
    end

    % SPARSE
    function M = sparse(varargin)
        if (nargin == 1)
            M = hmxSparse(varargin{1});
        elseif (nargin == 2)
            M = hmxSparsify(varargin{1},varargin{2});
        else
            M = hmxSparseSub(varargin{1},varargin{2},varargin{3});
        end
    end

    % LOW-RANK
    function [A,B] = lowrank(varargin)
        if (nargin == 1)
            [A,B] = hmxLowrank(varargin{1});
        else
            [A,B] = hmxLowrankSub(varargin{1},varargin{2},varargin{3});
        end
    end

    % DIAGONAL
    function D = diag(Mh)
        D = hmxDiag(Mh,(1:size(Mh,1))',(1:size(Mh,2))');
        D = full(diag(D));
    end

    % ZEROS
    function Mh = zeros(Mh)
        Mh.typ = 1;
        Mh.row = cell(1,4);
        Mh.col = cell(1,4);
        Mh.chd = cell(1,4);
        Mh.dat = {zeros(size(Mh,1),0),zeros(0,size(Mh,2))};
    end

    % ONES
    function Mh = ones(Mh)
        Mh.typ = 1;
        Mh.row = cell(1,4);
        Mh.col = cell(1,4);
        Mh.chd = cell(1,4);
        Mh.dat = {ones(size(Mh,1),1),ones(1,size(Mh,2))};
    end

    % SINGLE
    function Mh = single(Mh)
        Mh = hmxSingle(Mh);
    end

    % DOUBLE
    function Mh = double(Mh)
        Mh = hmxDouble(Mh);
    end

    % TRANSPOSITION
    function Mh = transpose(Mh)
        Mh = hmxTranspose(Mh);
    end

    % TRANSPOSITION CONJUGATE
    function Mh = ctranspose(Mh)
        Mh = hmxCtranspose(Mh);
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ALGEBRA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % SCALAR PRODUCT
    function Mh = times(Ml,Mr)
        Mh = hmxTimes(Ml,Mr);
    end

    % UMINUS
    function Mh = uminus(Mh)
        Mh = (-1).*Mh;
    end

    % ADDITION
    function Mh = plus(Ml,Mr)
        Mh = hmxPlus(Ml,Mr);
    end

    % SUBSTRACTION
    function Mh = minus(Ml,Mr)
       Mh = Ml + (-Mr);
    end

    % MATRIX PRODUCT
    function Mh = mtimes(Ml,Mr)
        if isnumeric(Ml) && (numel(Ml) == 1)
            Mh = Ml .* Mr;
        elseif isnumeric(Mr) && (numel(Mr) == 1)
            Mh = Ml .* Mr;
        else
            Mh = hmxMtimes(Ml,Mr);
        end
    end

    % ADDITION WITH MATRIX PRODUCT
    function Mh = plusmtimes(Mh,alpha,Ml,Mr)
        Mh = hmxPlusMtimes(Mh,alpha,Ml,Mr);
    end

    % INVERSION
    function Mh = inv(Mh)
        Mh = hmxInv(Mh);
    end

    % CHOLESKY FACTORISATION
    function Mh = chol(Mh)
        Mh = hmxChol(Mh);
    end

    % LDLt FACTORISATION
    function [Mh,Dh] = ldl(Mh)
        [Mh,Dh] = hmxLdl(Mh);
    end

    % LU FACTORISATION
    function [Lh,Uh] = lu(Mh)
        [Lh,Uh] = hmxLU(Mh);
    end

    % MLDIVIDE
    function B = mldivide(Mh,B)
       B = hmxMldivide(Mh,B);
    end

    % MRDIVIDE
    function B = mrdivide(B,Mh)
        B = (Mh.'\B.').';
    end

    % VERTICAL CONCATENATION
    function Mh = vertcat(varargin)
        Mh = varargin{1}.';
        for i = 2:nargin
            Mh = hmxHorzcat(Mh,varargin{i}.');
        end
        Mh = Mh.';
    end

    % HORIZONTAL CONCATENATION
    function Mh = horzcat(varargin)
        Mh = varargin{1};
        for i = 2:nargin
            Mh = hmxHorzcat(Mh,varargin{i});
        end
    end
end
end


%  This program is free software; you can redistribute it and/or modify
%  it under the terms of the GNU General Public License as published by
%  the Free Software Foundation; either version 2 of the License, or
%  (at your option) any later version.
%
%  This program 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 this program; if not, write to the Free Software
%  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
function testall
%TESTALL Test successively all the functions of the
%	Time-Frequency Toolbox.

%	O. Lemoine  March-September 1996.

%  Choice of the Instantaneous Amplitude
   amexpo1t
   amexpo2t
   amgausst
   amrectt
   amtriant

%  Choice of the Instantaneous Frequency
   fmconstt
   fmhypt
   fmlint
   fmodanyt
   fmpart
   fmpowert
   fmsint
   gdpowert

%  Choice of Particular Signals
   altest
   anaaskt
   anabpskt
   anafskt
   anapulst
   anaqpskt
   anasingt
   anastept
   atomst
   dopnoist
   dopplert
   klaudert
   mexhatt

%  Addition of Noise
   noisecgt
   noisecut

%  Modification
   scalet

% Processing Files

%  Time-Domain Processing
   ifestart
   instfret
   loctimet

%  Frequency-Domain Processing
   fmtt
   ifmtt
   locfreqt
   sgrpdlat

%  Linear Time-Frequency Processing
   tfrgabot
   tfrstftt

% Bilinear Time-Frequency Processing in the Cohen's Class
   tfrbjt
   tfrbudt
   tfrcwt
   tfrgrdt
   tfrmhst
   tfrmht
   tfrmmcet
   tfrpaget
   tfrpmht
   tfrppagt
   tfrpwvt
   tfrridbt
   tfrridht
   tfrridnt
   tfrridtt
   tfrrit
   tfrspt
   tfrspwvt
   tfrwvt
   tfrzamt

%  Bilinear Time-Frequency Processing in the Affine Class
   tfrbertt
   tfrdflat
   tfrscalt
   tfrspawt
   tfruntet

%  Reassigned TimeFrequency Processing
   tfrrgabt
   tfrrmsct
   tfrrpmht
   tfrrppat
   tfrrpwvt
   tfrrspt
   tfrrspwt

%  Ambiguity Functions
   ambifunt
   ambifuwt

%  PostProcessing or Help to the Interpretation
   friedmat
   holdert
   htlt
   margtfrt
   midpoitt
   momftfrt
   momttfrt
   renyit
   ridgest

% Other
   dividert
   dwindowt
   integt
   integ2dt
   izakt
   kayttht
   modulot
   oddt
   sigmergt
   zakt


% 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 y = Stunorm4(x)
    y = 1/sqrt(2)*InverseCDF4(x);
end


function h = conv(f, g, varargin)
%CONV   Convolution of CHEBFUN objects.
%   H = CONV(F, G) produces the convolution of CHEBFUN objects F and G:
%                     -
%                    /
%           H(x) =   |    F(t) G(x-t) dt,  x in [a + c, b + d]
%                    /
%                   -
%   where domain(F) is [a, b] and domain(G) is [c, d]. The integral is taken
%   over all t for which the integrand is defined: max(a, x - d) <= t <= min(b,
%   x - c).  The breakpoints of H are all pairwise sums of the breakpoints of F
%   and G.
%
%   H = CONV(F, G, 'same') will truncate the domain of H so that it is the same
%   as F. This is useful when F and G represent rapidly decaying functions on
%   large but finite intervals which are used to approximate infinity.
%
%   If F and G are simple, in the sense that their FUNS are CHEBTECH objects, a
%   fast algorithm due to Hale and Townsend is used [1]. Otherwise, the integral
%   is computed by brute force. CONV(F, G, 'old') forces the brute force
%   approach, even when the fast algorithm may be used.
%
%   Note that CONV only supports piecewise-smooth functions on bounded domains.
%
% Examples:
%     cheb.x; f = 0.8 - abs(x-0.2);
%     phi = @(t) chebfun(@(x) exp(-x^2/(4*t))/sqrt(4*pi*t));
%     fsmooth = conv(f,phi(1e-2),'same');
%     plot(f,'b',fsmooth','r')
%
%     f = chebfun(1/2); g = f;
%     subplot(2, 2, 1), plot(f)
%     for j = 2:4, g = conv(f, g); subplot(2, 2, j), plot(g), end
%     figure, for j = 1:4, subplot(2,2,j), plot(g), g = diff(g); end
%
% Reference:
%   [1] N. Hale and A. Townsend, "An algorithm for the convolution of Legendre
%   series", SIAM Journal on Scientific Computing, Vol. 36, No. 3,
%   pp. A1207-A1220, 2014.

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

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

% Check transpose state:
if ( xor(f(1).isTransposed, g(1).isTransposed) )
    error('CHEBFUN:CHEBFUN:conv:transposed', ...
        'CHEBFUN dimensions do not agree.');
end
transState = f(1).isTransposed;

% Support for quasimatrices:
nf = numColumns(f);
ng = numColumns(g);
if ( nf > 1 || ng > 1 )
    if ( nf == ng )
        f = mat2cell(f);
        g = mat2cell(g);
        h = f;
        for k = 1:nf
            h{k} = conv(f{k}, g{k}, varargin{:});
        end
    elseif ( nf == 1 )
        g = mat2cell(g);
        h = g;
        for k = 1:ng
            h{k} = conv(f, g{k}, varargin{:});
        end
    elseif ( ng == 1 )
        f = mat2cell(f);
        h = f;
        for k = 1:nf
            h{k} = conv(f{k}, g, varargin{:});
        end
    else
        error('CHEBFUN:CHEBFUN:conv:dimagree', 'CHEBFUN dimensions must agree.');
    end
    if ( ~transState )
        h = horzcat(h{:});
    else
        h = vertcat(h{:});
    end
    return
end

% Return empty for an empty input:
if ( isempty(f) || isempty(g) )
    h = chebfun();
    return
end

% Parse inputs:
oldMethod = false;
same = false;
for k = 1:numel(varargin)
    vk = varargin{k};
    if ( strcmpi(vk, 'old') )
        oldMethod = true;
    elseif ( strcmpi(vk, 'same') )
        same = true;
    elseif ( strcmpi(vk, 'full') )
        % Do nothing.
    elseif ( strcmpi(vk, 'valid') )
        % TODO: Supoprt 'valid'. Presumably where domains of f and g overlap?
        error('CHEBFUN:CHEBFUN:conv:validFlag', '''valid'' is not yet supprted.');
    else
        error('CHEBFUN:CHEBFUN:conv:badInput', 'Unknown input option %s.', vk);
    end
end

% Return a warning if F and G have too many pieces (the computation is probably
% going to be very slow):
if ( ( numel(f.funs) + numel(g.funs) ) > 50 )
    % Give a warning and proceed.
   warning('CHEBFUN:CHEBFUN:conv:piecewise',...
       ['Convolving CHEBFUNs with many pieces can be very slow.\n', ...
        'Try calling MERGE() on the inputs before calling CONV().']);
end

% Extract the domain:
[a, b] = domain(f);
[c, d] = domain(g);

% No support for unbounded domains:
if ( any(isinf([a b c d])) )
    error('CHEBFUN:CHEBFUN:conv:bounded', ...
        'CONV only supports CHEBFUN objects on bounded domains.');
end

if ( oldMethod || issing(f) || issing(g) )
    % Call the old (and slow) version of CONV if we are not based on CHEBTECHS.
    h = oldConv(f, g);

else

    % Ensure g is the signal (i.e., on the larger domain) and f is the filter:
    if ( (b - a) > (d - c) )
        h = conv(g, f);
        return
    end

    % Initialize the output:
    h = chebfun(0, [a + c, b + d]);
    % Deal with piecewise CHEBFUN objects by looping over each interaction:
    for j = 1:numel(f.funs)
        for k = 1:numel(g.funs)
            % Compute the contribution of jth fun of f with kth fun of g:
            hjk = conv(f.funs{j}, g.funs{k});
            % Add this contribution:
            h = myplus(h, chebfun(hjk));
        end
    end

    % Make sure that point values are not added twice:
    dom = domain(h);
    intDom = dom(2:end-1);
    h.pointValues(2:end-1) = 1/2*(feval(h, intDom.', 'left') + ...
        feval(h, intDom.', 'right'));

end

% Truncate:
if ( same )
    h = restrict(h, [a, b]);
end

% Transpose:
if ( transState )
    h = h.';
end

% Simplify the result.
h = simplify(h);

end

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

function h = myplus(f, g)
% Modified PLUS() which pads with zeros to fulfil domain requirements.
%  Note f is always on the largest possible domain. g is on a subdomain of f

% Tidy the domains:
[f, g] = tweakDomain(f, g);
[c, d] = domain(g);

fTmp = restrict(f, [c, d]); % f{c, d}
hTmp = fTmp + g;            % h{c, d} = f{c, d} + g;
h = defineInterval(f, [c, d], hTmp);

end

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

function h = oldConv(f, g)
% The old convolution algorithm based on quadrature. See section 2 of [1] for a
% description of the algorithm.

% Find all breakpoints in the convolution:
[A, B] = meshgrid(f.domain, g.domain);
dom = unique(A(:) + B(:)).';

% Coalesce breaks that are close due to roundoff:
dom(diff(dom) < 10*eps*max(abs(dom([1,end])))) = [];
dom(isnan(dom)) = [];

% Combine vertical and horizontal scales:
hs = max(hscale(f), hscale(g));
vs = 2*max([vscale(f), vscale(g)]);

% Set preferences:
%
% TODO:  CHEBFUN is not supposed to set the refinementFunction preference
% because it doesn't belong to the list of "abstract" preferences required of
% all techs.  Do we really need to alter it here?
p = chebfunpref();
p.splitting = false;
p.blowup = false;
p.techPrefs.extrapolate = true;
p.techPrefs.refinementFunction = 'nested';
p.techPrefs.sampleTest = false;

% Construct FUNS:
funs = cell(1, length(dom)-1);
for k = 1:length(dom)-1
    data.domain = dom(k:k+1);
    data.vscale = vs;
    data.hscale = hs;
    newFun = bndfun(@(x) convIntegral(x, f, g), data, p);
    vs = max(get(newFun, 'vscale'), vs);
    funs{k} = newFun;
end

% Construct CHEBFUN:
h = chebfun(funs);
h.isTransposed = f.isTransposed;

end

function out = convIntegral(x, f, g)
%CONVINTEGRAL   Evaluate convolution integral.
%   Y = CONVINTEGRAL(X, F, G) evaluates the convolution of the CHEBFUNs F and G
%   at the points X.

a = f.domain(1);
b = f.domain(end);
c = g.domain(1);
d = g.domain(end);

out = 0*x;
for k = 1:length(x)
    A = max(a, x(k) - d);
    B = min(b, x(k) - c);
    if ( A < B )
        ends = union(x(k) - g.domain, f.domain);
        dom = [A, ends((A < ends) & (ends < B)), B];
        for j = 1:length(dom)-1
            % INTEGRAL is not available in versions of MATLAB prior to R2012a,
            % so if we're running on an older version, fall back to QUADGK.
            integrand = @(t) feval(f, t).*feval(g, x(k) - t);
            if ( verLessThan('matlab', '7.14') )
                out(k) = out(k) + quadgk(integrand, dom(j), dom(j+1), ...
                    'AbsTol', 1e-15, 'RelTol', 100*eps);
            else
                out(k) = out(k) + integral(integrand, dom(j), dom(j+1), ...
                    'AbsTol', 1e-15, 'RelTol', 1e-15);
            end
        end
    end
end

end


function [sts, ids, xs, Costs, cprojall] = cpuMPmuFEAT(Params,data,fW,WtW, mu, lam1, nu, ops)

nt0 = ops.nt0;

WtW     = permute(WtW, [1 3 2]);

NT      = Params(1);
nFilt   = Params(2);
Th      = Params(3);

fdata   = fft(data, [], 1);
proj    = real(ifft(fdata .* fW(:,:), [], 1));
if ops.Nrank > 1
    proj    = sum(reshape(proj, NT, nFilt, ops.Nrank),3);
end
trange = int32([-(nt0-1):(nt0-1)]);

xs      = zeros(Params(4), 1, 'single');
ids     = zeros(Params(4), 1, 'int32');
sts     = zeros(Params(4), 1, 'int32');
Costs    = zeros(Params(4), 1, 'single');
cprojall = zeros(Params(4), nFilt, 'single');

i0 = 0;
for k = 1:30
    Ci = bsxfun(@plus, proj, (mu.*lam1)');
    Ci = bsxfun(@rdivide, Ci.^2,  1 + lam1');
    Ci = bsxfun(@minus, Ci, (lam1 .* mu.^2)');

    [mX, id] = max(Ci,[], 2);

    maX         = -my_min(-mX, 31, 1);
    id          = int32(id);

    st                   = find((maX < mX + 1e-3) & mX > Th*Th);
    st(st>NT-nt0 | st<nt0) = [];

    if isempty(st)
       break;
    end
    id      = id(st);

    % inds = bsxfun(@plus, st', [1:nt0]');

    x       = zeros(size(id));
    Cost    = zeros(size(id));
    nsp     = zeros(nFilt,1);
    cproj   = zeros(size(id,1), nFilt, 'single');
    for j = 1:numel(id)
        x(j)            = proj(st(j), id(j));
        Cost(j)         = maX(st(j));
        nsp(id(j))      = nsp(id(j)) + 1;

        % subtract off WtW
        cproj(j,:) =  proj(st(j) ,:);
        proj(st(j) + trange,:) = proj(st(j) + trange,:)  - x(j) * WtW(:,:,id(j));
    end

    xs(i0 + [1:numel(st)])          = x;
    sts(i0 + [1:numel(st)])         = st;
    Costs(i0 + [1:numel(st)])       = Cost;
    ids(i0 + [1:numel(st)])         = id;
    cprojall(i0 + [1:numel(st)], :) = cproj;
    i0 = i0 + numel(st);
end

ids     = ids(1:i0);
xs      = xs(1:i0);
Costs   = Costs(1:i0);
sts     = sts(1:i0);
cprojall = cprojall(1:i0, :);
cprojall = cprojall';

ids = ids - 1;

% keyboard


function a = ge( x, y )

%Disciplined convex programming information for GE (>=):
%   The right-hand side of a less-than constraint must be convex. The
%   left-hand side must be concave. Of course, real constant and affine
%   expressions are both convex and concave and can be used on either
%   side as well.
%
%Disciplined geometric programming information for GE (>=):å
%   The right-hand side of a less-than constraint must be log-convex---
%   including positive constants, monomials, posynomials, generalized
%   posynomials, and products thereof. The left-hand side must be log-
%   concave---including positive constants, monomials, reciprocals of
%   log-convex expressions, and products thereof.
%
%Note that CVX does not distinguish between strict greater-than (>) and
%greater-than-or-equal (<=) constraints; they are treated identically.
%Feasible interior-point solvers tend to return points which satisfy
%strict inequality, but not all solvers do.

evalin( 'caller', 'cvx_verify' );
b = cvx_pushcnstr( x, y, '>=' );
if nargout, a = b; end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function [meanError, all_rot_preds, all_rot_gts, meanErrors, all_errors, rels_all, seq_ids] = calcIctError(resDir, gtDir)
%CALCICTERROR Summary of this function goes here
%   Detailed explanation goes here

    polhemus = 'polhemusNorm.csv';

    sequences = dir([resDir '*.csv']);

    rotMeanErr = zeros(numel(sequences),3);
    rotRMS = zeros(numel(sequences),3);
    rot = cell(1,numel(sequences));
    rotg = cell(1,numel(sequences));

    rels_all = [];

    seq_ids = {};

    for i = 1:numel(sequences)

        [~, name,~] = fileparts(sequences(i).name);

        fname = [resDir '/' sequences(i).name];
        if(i == 1)
            % First read in the column names
            tab = readtable(fname);
            column_names = tab.Properties.VariableNames;

            confidence_id = cellfun(@(x) ~isempty(x) && x==1, strfind(column_names, 'confidence'));
            rot_ids = cellfun(@(x) ~isempty(x) && x==1, strfind(column_names, 'pose_R'));
        end

        all_params  = dlmread(fname, ',', 1, 0);

        rot{i} = all_params(:, rot_ids);
        rels = all_params(:, confidence_id);

        % the reliabilities of head pose
        rels_all = cat(1, rels_all, rels);
        [txg tyg tzg rxg ryg rzg] =  textread([gtDir name '/'  polhemus], '%f,%f,%f,%f,%f,%f');

        rotg{i} = [rxg ryg rzg];

        % Correct the first frame so it corresponds to (0,0,0), as slightly
        % different pose might be assumed frontal and this corrects for
        % that

        % Work out the correction matrix for ground truth
        rot_corr_gt = Euler2Rot(rotg{i}(1,:));
        for r_e = 1:size(rotg{i},1)
            rot_curr_gt = Euler2Rot(rotg{i}(r_e,:));
            rot_new_gt = rot_corr_gt' * rot_curr_gt;
            rotg{i}(r_e,:) = Rot2Euler(rot_new_gt);
        end

        % Work out the correction matrix for estimates
        rot_corr_est = Euler2Rot(rot{i}(1,:));
        for r_e = 1:size(rot{i},1)
            rot_curr_est = Euler2Rot(rot{i}(r_e,:));
            rot_new_est = rot_corr_est' * rot_curr_est;
            rot{i}(r_e,:) = Rot2Euler(rot_new_est);
        end

        % Convert the ground truth and estimates to degrees
        rot{i} = rot{i} * (180/ pi);
        rotg{i} = rotg{i} * (180/ pi);

        % Now compute the errors
        rotMeanErr(i,:) = mean(abs((rot{i}(:,:)-rotg{i}(:,:))));
        rotRMS(i,:) = sqrt(mean(((rot{i}(:,:)-rotg{i}(:,:))).^2));

        seq_ids = cat(1, seq_ids, repmat({[name 'ict']}, size(rot{i},1), 1));

    end
    allRot = cell2mat(rot');
    allRotg = cell2mat(rotg');
    meanErrors = rotMeanErr;
    meanError = mean(abs((allRot(:,:)-allRotg(:,:))));
    all_errors = abs(allRot-allRotg);
    rmsError = sqrt(mean(((allRot(:,:)-allRotg(:,:))).^2));
    errorVariance = var(abs((allRot(:,:)-allRotg(:,:))));

    all_rot_preds = allRot;
    all_rot_gts = allRotg;
end


function varargout = sameDeltaLocs(f, g, tol)
%SAMEDELTALOCS   Find common locations of delta functions in F and G.
%   IDX1 = SAMEDELTALOCS(F, G) returns a logical vector of of same length as
%   that of F.DELTALOCS indicating which locations are shared with G.
%   [IDX1, IDX2] = SAMEDELTALOCS(F, G) does the same but also returns the
%   vector IDX2 locations of G.
%
%   SAMEDELTALOCS(F, G, TOL) uses the user-specified tolerance TOL for testing.
%
% See also SIMPLIFY, CLEANROWS, CLEANCOLUMNS

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

% Deal with the empty cases:
if ( isempty(f) || isempty(g) )
    if ( nargout == 2 )
        varargout{1} = [];
        varargout{2} = [];
    else
        varargout{1} = [];
    end
    return
end

% Get preferences:
if ( nargin < 3 )
    pref = chebfunpref();
    tol = pref.deltaPrefs.proximityTol;
end

% Initialize variables:
loc1 = f.deltaLoc;
idx1 = zeros(size(loc1));
loc2 = g.deltaLoc;
idx2 = zeros(size(loc2));

% Loop and compare locations:
for i = 1:length(loc1)
    for j = 1:length(loc2)
        % If both entries are equal to zero:
        p = ( (loc1(i) == 0) && (loc2(j) == 0) );
        % Or if they are very close to each other:
        maxLoc = max(abs([loc1(i), loc2(j)]));
        p = p | ( abs((loc1(i) - loc2(j)))/maxLoc < tol );
        if ( p )
            % Mark the indices:
            idx1(i) = 1;
            idx2(j) = 1;
        end
    end
end

% Convert to logical indices:
idx1 = logical(idx1);
idx2 = logical(idx2);

% Output based on the number of outputs:
if ( nargout == 2 )
    varargout{1} = idx1;
    varargout{2} = idx2;
else
    varargout{1} = idx1;
end

end


function pid2 = pid2pid(pid1,direction)
% PID2PID Convert from Form 2 back to Form 1 of PID controller.
%         PID2PID takes the 3 gains of the Form 1 PID controller and
%         converts them into the gains of the Form 2 PID controller.

% Author: Craig Borghesani
% Date: 11/13/94
% Revised:
% Copyright (c) 1999, Prentice-Hall

if direction == 2,
 Kp = pid1(1);
 Ki = pid1(2);
 Kd = pid1(3);

 KP = max(roots([1, -Kp, Kd*Ki]));
 KI = Ki;
 KD = Kd/KP;

 pid2 = [KP,KI,KD,direction*20];

else

 KP = pid1(1);
 KI = pid1(2);
 KD = pid1(3);

 Kp = KP + KD*KI;
 Ki = KI;
 Kd = KD*KP;

 pid2 = [Kp,Ki,Kd,direction*20];
end


% Copyright (C) Daphne Koller, Stanford Univerity, 2012
%
% Author: Huayan Wang, Andrew Duchi

% visualize a configuration the body parts

function img = ShowPose( pose )

% pose 10 x 3. 10 : body parts,
%               3 : y, x, alpha

pose(:,1) = pose(:,1) + 100;
pose(:,2) = pose(:,2) + 150;

pose = reshape(pose, [10 3]);
part_length = [60, 20, 32, 33, 32, 33, 46, 49, 46, 49];
part_width = [18, 10, 7, 5, 7, 5, 10, 7, 10, 7];
img = zeros(300, 300);
for part = 1:10

    startpt = round(pose(part, 1:2));
    axis = [sin(pose(part,3) - pi/2) cos(pose(part,3) - pi/2)];
    xaxis = [cos(pose(part,3) - pi/2) -sin(pose(part,3) - pi/2)];
    endpt = round(startpt + part_length(part) * axis);

    corner1 = round(startpt + xaxis * part_width(part));
    corner2 = round(startpt - xaxis * part_width(part));
    corner3 = round(endpt + xaxis * part_width(part));
    corner4 = round(endpt - xaxis * part_width(part));

   img = func_DrawLine(img, corner1(1), corner1(2), corner2(1), corner2(2),1);
   img = func_DrawLine(img, corner1(1), corner1(2), corner3(1), corner3(2),1);
   img = func_DrawLine(img, corner4(1), corner4(2), corner2(1), corner2(2),1);
   img = func_DrawLine(img, corner4(1), corner4(2), corner3(1), corner3(2),1);

   if startpt(1) > 3 && startpt(1) < 298 && startpt(2) > 3 && startpt(2) < 298
       img(startpt(1)-3 : startpt(1) + 3, startpt(2) - 3 : startpt(2)+3) = ones(7,7);
   end
end


function h = histogram(grains,varargin)
% grain area weighted histogram
%
% Syntax
%   histogram(grains)      % area weighted histogram of the grain area
%
%   prop = grains.equivalentRadius;
%   histogram(grains,prop) % area weighted histogram of property prop
%
%   histogram(grains,prop,n)    % specify number of bins
%   histogram(grains,prop,bins) % specify bin edges
%
%   h = histogram(grains)
%
% Input
%  grains - @grain2d
%  n      - number of bin edges, default ist 15, (number of bins is n-1)
%  bins   - vector of bin edges
%
% Output
%  h - handle to the histogram graphics object
%

[mtexFig,isNew] = newMtexFigure(varargin{:});
mtexFig.keepAspectRatio = false;

% exract area and maybe an aditional property
area = grains.area;
if nargin>1 && isnumeric(varargin{1}) && length(varargin{1}) == length(grains)
  prop = varargin{1};
  varargin(1) = [];
else
    prop = area;
end

% generate bins
if ~isempty(varargin) && isnumeric(varargin{1})
  if numel(varargin{1})==1
    nbins = varargin{1}; %define nbins
  elseif numel(varargin{1})>1
    bins = varargin{1}; %define bin edges automatically
    nbins = numel(varargin{1});
  end
else
  nbins = 15;
end
if ~exist('bins','var'), bins = linspace(0,max(prop)+eps,nbins); end

% loop through all phases
h = [];
for id = grains.indexedPhasesId

  % find for each area the binId
  [~,~,binId] = histcounts(prop(grains.phaseId==id),bins);
  if any(~binId,'all')
    warning([num2str(nnz(~binId)) ' grains outside bin limits not plotted!']);
  end

  % compute the sum of areas belonging to the same bin

  areaPhase = area(grains.phaseId==id);
  cumArea = accumarray(binId(binId>0),areaPhase(binId>0),[length(bins)-1 1],@nansum) ./ sum(area);

  h = [h,optiondraw( histogram('BinEdges',bins,'BinCounts',cumArea,...
    'FaceColor',grains.CSList{id}.color),varargin{:})]; %#ok<AGROW>
  if strcmp(get(h,'DisplayStyle'),'stairs')
    set(h(grains.indexedPhasesId==id),'EdgeColor',grains.CSList{id}.color);
  end
  hold on

end
hold off

% labels and title
if all(prop == area)
  title(mtexFig.gca,'grain size distribution')
  xlabel(mtexFig.gca,'grain area');
end
yticklabels(mtexFig.gca,yticks*100)
ylabel(mtexFig.gca,'relative area (%)')

% legend
min = grains.mineralList(grains.indexedPhasesId);
legend(min{:})

if isNew, mtexFig.drawNow(varargin{:});end

if nargout == 0, clear h; end


function sphere_delaunay_test ( )

%*****************************************************************************80
%
%% SPHERE_DELAUNAY_TEST tests the SPHERE_DELAUNAY library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 May 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPHERE_DELAUNAY_TEST\n' );
  fprintf ( 1, '  MATLAB version:\n' );
  fprintf ( 1, '  Test the SPHERE_DELAUNAY library.\n' );

  sphere_delaunay_test01 ( );
  sphere_delaunay_test02 ( );
  sphere_delaunay_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPHERE_DELAUNAY_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function a = wishart_sample ( m, df, sigma )

%*****************************************************************************80
%
%% WISHART_SAMPLE samples the Wishart distribution.
%
%  Discussion:
%
%    This function requires functions from the PDFLIB and RNGLIB libraries.
%
%    The "initialize()" function from RNGLIB must be called before using
%    this function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 July 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Patrick Odell, Alan Feiveson,
%    A numerical procedure to generate a sample covariance matrix,
%    Journal of the American Statistical Association,
%    Volume 61, Number 313, March 1966, pages 199-203.
%
%    Stanley Sawyer,
%    Wishart Distributions and Inverse-Wishart Sampling,
%    Washington University,
%    30 April 2007, 12 pages.
%
%  Parameters:
%
%    Input, integer M, the order of the matrix.
%
%    Input, integer DF, the number of degrees of freedom.
%    M <= DF.
%
%    Input, real SIGMA(M,M), the covariance matrix, which should be
%    a symmetric positive definite matrix.
%
%    Output, real A(M,M), the sample matrix from the Wishart distribution.
%
  if ( df < m )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'WISHART_SAMPLE - Fatal error!\n' );
    fprintf ( 1, '  DF = %d < M = %d.\n', df, m );
    error ( 'WISHART_SAMPLE - Fatal error!\n' );
  end
%
%  Get R, the upper triangular Cholesky factor of SIGMA.
%
  r = chol ( sigma );
%
%  Get AU, a sample from the unit Wishart distribution.
%
  au = wishart_unit_sample ( m, df );
%
%  Construct the matrix A = R' * AU * R.
%
  a = r' * au * r;

  return
end


function LMstats(D, HOMEIMAGES)

D = LMvalidobjects(D);
%objectnames = lower(LMobjectnames(D));
[D, objectnames] = LMcreateObjectIndexField(D);
objectnames = lower(objectnames);
Nimages = length(D);
Nobjects = length(objectnames);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Collect data:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
instancecounts = sparse(Nobjects, Nimages);
areacounts = sparse(Nobjects, Nimages);
labelingdate = [];
imagendx = [];
objndx = [];

p = 0;
for n = 1:Nimages
    Nimages - n
    if isfield(D(n).annotation, 'object')
        objectsinimage = {D(n).annotation.object.name};

        %a = imfinfo(strrep(fullfile(HOMEIMAGES, D(n).annotation.folder, D(n).annotation.filename), '\', '/'));
        %nrows = a.Width;
        %ncols = a.Height;

        ncols = 0; nrows = 0;
        [TF, ndx] = ismember(strtrim(lower(objectsinimage)), objectnames);
        for m = 1:length(ndx)
            [X,Y] = getLMpolygon(D(n).annotation.object(m).polygon);
            area = polyarea(double(X),double(Y)); % ignores intersections

            instancecounts(ndx(m),n) = instancecounts(ndx(m),n)+1;
            areacounts(ndx(m),n) = areacounts(ndx(m),n) + area;
            nrows = max(nrows, max(Y(:)));
            ncols = max(ncols, max(X(:)));
        end
        areacounts(:,n) = areacounts(:,n) / double(nrows*ncols);

        % Collect date
        if isfield(D(n).annotation.object(1), 'date')
            for m = 1:length(D(n).annotation.object)
                d = D(n).annotation.object(m).date;
                if ~isempty(d)
                    p = p + 1;
                    labelingdate{p} = d(1:11);
                    imagendx(p) = n;
                    objndx(p) = D(n).annotation.object(m).namendx;
                end
            end
        end
    end
end
Labelingdate = datenum(labelingdate);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plots:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OBJECTS
% 1) distribution object labels
frequency = full(sum(instancecounts,2));
[sortedFreq, ndx] = sort(frequency, 'descend');

% Show object counts sorted by frequency
nn = min(40, length(ndx));
figure
subplot(121)
loglog(sortedFreq)
xlabel('rank')
ylabel('counts')
title('Distribution of objects')
axis('square'); axis('tight')
subplot(122)
barh(frequency(ndx(1:nn)))
set(gca, 'YTick', 1:nn)
set(gca, 'YtickLabel', objectnames(ndx(1:nn)))
axis([0 max(frequency)+5 0 nn+1])
grid on
title(sprintf('Most frequent obj. Number polygons: %d, number classes: %d', sum(frequency), length(frequency)))
axis('tight')

% histogram of number of objects per image
valid = find(full(sum(areacounts,1)>.97));
imagesperobject = full(sum(instancecounts,1));
figure
hist(imagesperobject(valid), [1:200])
xlabel('number of objects/image')
ylabel('counts')
title('Histogram of number of objects per image')

% 2) evolution dataset/time
lastDate = max(Labelingdate);
year = [2005 2006 2007 2008 2009 2010]
months = [1:12]
t = 0; dt = [];
counts = [];
countUniqueImages = [];
countObjectClasses = [];
for y = year
    for m = months
        t = t+1;
        d = (datenum(y,m,31));
        if d<lastDate

            dt{t} = datestr(d);
            j = find(Labelingdate<d);
            counts(t) = length(j);
            countUniqueImages(t) = length(unique(imagendx(j)));
            countObjectClasses(t) = length(unique(objndx(j)));
        else
            break
        end
    end
end

if length(dt)>48
init = 5;
figure
subplot(311)
plot(counts(init:end))
set(gca,'Xtick',[1 12 24 36 48]-init+1)
set(gca,'XTickLabel', dt([1 12 24 36 48]));
subplot(312)
plot(countUniqueImages(init:end),'r')
set(gca,'Xtick',[1 12 24 36 48]-init+1)
set(gca,'XTickLabel', dt([1 12 24 36 48]));
subplot(313)
plot(countObjectClasses(init:end),'g')
set(gca,'Xtick',[1 12 24 36 48]-init+1)
set(gca,'XTickLabel', dt([1 12 24 36 48]));
end

% 3) perplexity labels / proportion new labels added every day

% SCENES
% 4) distribution of scenes: if a scene is defined as the 5 largest
% objects: draw distribution of scene types.
Nobj = 4;
valid = find(full(sum(areacounts>0.05,1)>0) & full(sum(areacounts,1)>.97));
valid = find(full(sum(areacounts,1)>.97));
% for each scene collect only the 5 largest objects
scenes = sparse(Nobjects, Nimages);
for i = valid
    s = full(areacounts(:,i));
    jj = find(s>0);
    [ss,j] = sort(s(jj),'descend');

    L = min(length(j),Nobj);
    j = jj(j(1:L));

    scenes(j,i) = 100-(0:L-1);
end
scenes = scenes(:,valid)';

colors = 'rgcb'; k = 0;
figure
for ngram = [1 2 4 8]
    k = k+1;
    S = (scenes>100-ngram);
    % remove scenes with less than ngram objects
    c = sum(S,2);
    svalid = find(c>=ngram);

    [scenesunique, ns, j] = unique(S(svalid,:), 'rows');
    ns = valid(svalid(ns)); % recover initial indexing
    scenesunique = full(scenesunique');
    ju = unique(j);
    counts = hist(j, ju);
    [counts, ndx] = sort(counts, 'descend');

    loglog(counts, colors(k))
    hold on
    title('Distribution of scenes: a scene is a unique N-gram')
    axis('square'); axis('tight')
    drawnow
end
axis([1 3000 .9 3000])

% Create figure with most common scene within each scene type: look at the
% most frequent distribution of the other objects. Take the image closer to
% the mean. Make a figure with 10 different scene types.
ngram = 4;
S = (scenes>100-ngram);
c = sum(S,2);
svalid = find(c>=ngram);
[scenesunique, ns, j] = unique(S(svalid,:), 'rows');
ns = valid(svalid(ns)); % recover initial indexing
scenesunique = full(scenesunique');
ju = unique(j);
counts = hist(j, ju);
[counts, ndx] = sort(counts, 'descend');

figure
k=0;
for n = 1:1:49
    k = k+1;
    % get list of large objects in image
    o = find(scenesunique(:,ndx(n)));
    list = sprintf('%s,',objectnames{o});
    list = sprintf('%s (%d)', list(1:end-1), counts(n));

    % get typical scene from set
    img = LMimread(D, ns(ndx(n)), HOMEIMAGES);
    thumb = LMsceneThumbnail(D(ns(ndx(n))).annotation, HOMEIMAGES, img);

    subplottight(7,7,k,.1)
    imshow(thumb)
    title(list)
    drawnow
end
% 5) perplexity scenes

% TYPICALITY
% Show the most typical scene. Or run Kmeans using the distances and chose the 10 central images. The one with the lowest perplexity.


function sF = drho(sF)
% first derivative in direction rho

s = size(sF);
sF = reshape(sF, []);

fhat = zeros(size(sF.fhat));
for m = 0:sF.bandwidth
  fhat(m*(m+1)+(-m:m)+1, :) = 1i*(-m:m)'.*sF.fhat(m*(m+1)+(-m:m)+1, :);
end
sF = S2FunHarmonic(fhat);

sF = reshape(sF, s);

end


function y = abs( x )

%Disciplined convex/geometric programming information for ABS:
%   ABS(X) is convex and nonmonotonic in X. Therefore, according to
%   the strict rules of DCP, X must be affine. However, because of
%   its special structure, CVX considers the sign of X as well. So,
%   for instance, if X is known to be nonnegative, then ABS(X)=X.

persistent P
if isempty( P ),
    P.map = cvx_remap( { 'constant' }, { 'p_nonconst' }, { 'n_nonconst' }, ...
        { 'r_affine' }, { 'c_affine' } );
    P.funcs = { @abs_cnst, @abs_posn, @abs_negn, @abs_affn, @abs_affn };
end
y = cvx_unary_op( P, x );

function y = abs_cnst( x )
% Constant
y = builtin( 'abs', x );

function y = abs_posn( x )
% Positive any
y = x;

function y = abs_negn( x )
% Negative any
y = -x;

function y = abs_affn( x ) %#ok
% Affine
cvx_begin
    epigraph variable y( size(x) ) nonnegative_
    { x, y } == lorentz( size(x), 0, ~isreal(x) ); %#ok
cvx_end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function ebsd = rotate(ebsd,rot,varargin)
% rotate EBSD
%
% Syntax
%
%   % roate the whoole data set about the z-axis by 90*degree
%   ebsd = rotate(ebsd,10*degree)
%
%   % rotate about the x-axis
%   ebsd = rotate(ebsd,rotation.byAxisAngle(xvector,180*degree))
%
%   % rotate only the spatial data
%   ebsd = rotate(ebsd,180*degree,'keepEuler')
%
%   % rotate about a specific point
%   ebsd = rotate(ebsd,180*degree,'center',[0,0])
%
% Input
%  ebsd - @EBSD
%  angle - double
%  q    - @rotation
%
% Options
%  center - [x,y] center of rotation, default is (0,0)
%
% Flags
%  keepXY    - rotate only the orientation data, i.e. the Euler angles
%  keepEuler - rotate only the spatial data, i.e., the x,y, and z values
%
% Output
%  ebsd - @EBSD

if isa(rot,'double'), rot = rotation.byAxisAngle(zvector,rot); end

% rotate the orientations
if ~check_option(varargin,'keepEuler')
  ebsd.rotations = rotation(rot .* ebsd.rotations);
end

% rotate the spatial data
if ~check_option(varargin,'keepXY')

  center = get_option(varargin,'center',[0,0]);

  ebsd = ebsd - center;

  % store coordinates as vector3d
  V = vector3d(ebsd.prop.x,ebsd.prop.y,0);

  % rotate vertices
  V = rot * V;

  % store back
  ebsd.prop.x = V.x(:);
  ebsd.prop.y = V.y(:);

  ebsd = ebsd + center;

  % rotate the unitcell
  V = vector3d(ebsd.unitCell(:,1),ebsd.unitCell(:,2),0);
  V = rot * V;
  ebsd.unitCell = [V.x(:),V.y(:)];
end


function [residuals,W] = getresiduals (X,T,S,maxorder,order,orderoffset,...
    timelag,exptimelag,zeromean,W)
%
% Compute residuals - useful when using a global model to remove global trends
%
% INPUT
% X             time series
% T             length of series
%
%
% OUTPUT
% residuals
% W
%
% Author: Diego Vidaurre, OHBA, University of Oxford

if nargin<10, W = []; end

N = length(T);

if ~isempty(S) && any(S(:)==0)
    [~,order] = formorders(order,orderoffset,timelag,exptimelag);
    if isempty(W)
        [W,~,~,residuals] = mlmar(X,maxorder,T,double(S==0),order,orderoffset,timelag,...
        exptimelag,zeromean);
    else
        [~,~,~,residuals] = mlmar(X,maxorder,T,double(S==0),order,orderoffset,timelag,...
            exptimelag,zeromean,W);
    end
else
    W = [];
    residuals = zeros(sum(T)-length(T)*maxorder,size(X,2));
    for in=1:N
        t0 = sum(T(1:in-1));
        t = t0 - (in-1)*maxorder;
        residuals(t+1:t+T(in)-maxorder,:) = X(t0+maxorder+1:t0+T(in),:);
    end
end


function [ax, data] = fgplvmFieldPlot(model, YLbls);

% FGPLVMFIELDPLOT 2-D field plot of the dynamics.

% FGPLVM

if isempty(YLbls)
  symbol = [];
else
  symbol = getSymbols(size(YLbls,2));
end

x1 = linspace(min(model.X(:, 1))*1.1, max(model.X(:, 1))*1.1, 150);
x2 = linspace(min(model.X(:, 2))*1.1, max(model.X(:, 2))*1.1, 150);
[X1, X2] = meshgrid(x1, x2);
XTest = [X1(:), X2(:)];

fhandle = str2func([model.type 'PosteriorMeanVar']);
if str2num(version('-release'))>13
  [mu, varsigma] = fhandle(model, XTest);
else
  [mu, varsigma] = feval(fhandle, model, XTest);
end
figure(1)
clf
% Create the plot for the data
clf
ax = axes('position', [0.05 0.05 0.9 0.9]);
hold on

C = log10(reshape(1./varsigma(:, 1), size(X1)));
C = C - min(min(C));
C = C/max(max(C));
C = round(C*63);
image(x1, x2, C);

% [c, h] = contourf(X1, X2, log10(reshape(1./varsigma(:, 1), size(X1))), 128);
% shading flat
colormap gray;
%colorbar
data = lvmtwoDPlot(model.X, YLbls, symbol);
xLim = [min(XTest(:, 1)) max(XTest(:, 1))];
yLim = [min(XTest(:, 2)) max(XTest(:, 2))];
set(ax, 'xLim', xLim);
set(ax, 'yLim', yLim);

set(ax, 'fontname', 'arial');
set(ax, 'fontsize', 20);

function returnVal = lvmtwoDPlot(X, label, symbol)

% LVMTWODPLOT Helper function for plotting the labels in 2-D.

returnVal = [];

if ~isempty(label)
  for i = 1:size(X, 1)
    labelNo = find(label(i, :));
    try
      returnVal = [returnVal; plot(X(i, 1), X(i, 2), symbol{labelNo})];
    catch
      if strcmp(lasterr, 'Index exceeds matrix dimensions.')
	error(['Only ' num2str(length(symbol)) ' labels supported (it''s easy to add more!)'])
      end
    end
  end
else
  returnVal = plot(X(:, 1), X(:, 2), 'rx');
end


function benford_test ( )

%*****************************************************************************80
%
%% BENFORD_TEST tests BENFORD.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BENFORD_TEST\n' );
  fprintf ( 1, '  BENFORD(I) is the Benford probability of the\n' );
  fprintf ( 1, '  initial digit sequence I.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   I     BENFORD(I)\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 9
    fprintf ( 1, '  %2d  %12f\n', i, benford(i) );
  end

  return
end


classdef TestDualTVL1OpticalFlow
    %TestDualTVL1OpticalFlow

    methods (Static)
        function test_1
            im1 = 255*uint8([...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 1 0 1 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
            ]);
            im2 = circshift(im1, [0 1]);
            alg = cv.DualTVL1OpticalFlow();
            flow = alg.calc(im1, im2);
            validateattributes(flow, {'single'}, ...
                {'3d', 'size',[size(im1,1) size(im1,2) 2]});
        end

        function test_2
            prevImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale1.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            nextImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale2.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            alg = cv.DualTVL1OpticalFlow();
            alg.ScaleStep = 0.3;
            alg.MedianFiltering = 3;
            flow = alg.calc(prevImg, nextImg);
            validateattributes(flow, {'single'}, ...
                {'3d', 'size',[size(prevImg,1) size(prevImg,2) 2]});
        end
    end

end


function [nv_stage] = nvars(N, nx, ni, nu, np)

% N control interval which each have states, integrator vars,
% controls, parameters, and timesteps.
% Ends with a single state.
nv_stage = N*nx + N*ni + N*nu + N*np + N + nx + np;


function pf = loadPoleFigure_siemens(fname,varargin)
% load D5000 data file
%
% Syntax
%   pf = loadPoleFigure_D5000(fname)
%
% Input
%  fname - file name
%
% Output
%  pf    - @PoleFigure
%
% See also
% loadPoleFigure ImportPoleFigureData

fid = fopen(fname,'r');
d = {};
allH = {};
p = 0;

try
  while ~feof(fid)
    line = fgetl(fid);

    % new pole figure section
    if strfind(line,'*Pole figure:')
      p = p+1;
      allH{p} = string2Miller(line(14:end));
      d{p} = [];
      theta{p} = [];

      % new theta angle
    elseif strfind(line,'*Khi')
      theta{p} = [theta{p} sscanf(line(7:end),'%f')]; %#ok<*AGROW>
      bg = [];

      % new background line
    elseif strfind(line,'background')
      bg = [bg sscanf(line(end-8:end),'%8f')];
      if numel(bg)>1, bg = mean(bg); end

    elseif strfind(line,'*')
      %other information

    else % load intensities

      dd = cell2mat(textscan(line,'%n'));
      if ~isempty(bg), dd = dd - bg; end
      d{p} = [d{p},dd];
    end

  end
catch
  interfaceError(fname,fid);
end
fclose(fid);

% generate specimen directions
for p=1:length(allH)
  n = numel(d{p})/numel(theta{p});
  allR{p} = regularS2Grid('theta',theta{p}*degree,'rho',linspace(0,2*pi*(n-1/n),n));
end

% generate pole figure variable
pf = PoleFigure(allH,allR,d,varargin{:});


function [ucm_sigmoid, ucm_raw, ws_wt2] = contours2ucm_RGBD(pb_oriented, pb_wt, thr)
% changes:
% - outputs raw ucm also
%
% Creates Ultrametric Contour Map from oriented contours
%
% syntax:
%   [ucm] = contours2ucm(pb_oriented, fmt)
%
% description:
%   Computes UCM by considering
%   the mean pb value on the boundary between regions as dissimilarity.
%
% arguments:
%   pb_oriented: Oriented Probability of Boundary
%   fmt:         Output format. 'imageSize' (default) or 'doubleSize'
%
% output:
%   ucm:    Ultrametric Contour Map in double
%
% Pablo Arbelaez <arbelaez@eecs.berkeley.edu>
% August 2013

% create finest partition and transfer contour strength

[ws_wt] = create_finest_partition(pb_oriented);

if nargin>1,

    % align old and new signal
    pb_wt(2:end,2:end)=pb_wt(1:end-1,1:end-1);
    pb_wt(1,:)=pb_wt(2,:); pb_wt(:,1)=pb_wt(:,2);
    pb_wt = pb_wt.*(ws_wt>0);

    ws_wt(ws_wt>thr)=thr;
    ws_wt=ws_wt+pb_wt;

end

% prepare pb for ucm
ws_wt2 = double(super_contour_4c(ws_wt));
ws_wt2 = clean_watersheds(ws_wt2);
labels2 = bwlabel(ws_wt2 == 0, 8);
labels = labels2(2:2:end, 2:2:end) - 1; % labels begin at 0 in mex file.
ws_wt2(end+1, :) = ws_wt2(end, :);
ws_wt2(:, end+1) = ws_wt2(:, end);

% compute ucm with mean pb.
super_ucm = double(ucm_mean_pb(ws_wt2, labels));

ucm_raw = super_ucm;

% normalize output
ucm_sigmoid = apply_sigmoid(ucm_raw,0.55,10).*(ucm_raw>0);

function [ws_wt] = create_finest_partition(pb_oriented)

pb = max(pb_oriented,[],3);
ws = watershed(pb);
ws_bw = (ws == 0);

contours = fit_contour(double(ws_bw));
angles = zeros(numel(contours.edge_x_coords), 1);

for e = 1 : numel(contours.edge_x_coords)
    if contours.is_completion(e), continue; end
    v1 = contours.vertices(contours.edges(e, 1), :);
    v2 = contours.vertices(contours.edges(e, 2), :);

    if v1(2) == v2(2),
        ang = 90;
    else
        ang = atan((v1(1)-v2(1)) / (v1(2)-v2(2)));
    end
    angles(e) = ang*180/pi;
end

orient = zeros(numel(contours.edge_x_coords), 1);
orient((angles<-78.75) | (angles>=78.75)) = 1;
orient((angles<78.75) & (angles>=56.25)) = 2;
orient((angles<56.25) & (angles>=33.75)) = 3;
orient((angles<33.75) & (angles>=11.25)) = 4;
orient((angles<11.25) & (angles>=-11.25)) =5;
orient((angles<-11.25) & (angles>=-33.75)) = 6;
orient((angles<-33.75) & (angles>=-56.25)) = 7;
orient((angles<-56.25) & (angles>=-78.75)) = 8;

ws_wt = zeros(size(ws_bw));
for e = 1 : numel(contours.edge_x_coords)
    if contours.is_completion(e), continue; end
    for p = 1 : numel(contours.edge_x_coords{e}),
        ws_wt(contours.edge_x_coords{e}(p), contours.edge_y_coords{e}(p)) = ...
            max(pb_oriented(contours.edge_x_coords{e}(p), contours.edge_y_coords{e}(p), orient(e)), ws_wt(contours.edge_x_coords{e}(p), contours.edge_y_coords{e}(p)));
    end
    v1=contours.vertices(contours.edges(e,1),:);
    v2=contours.vertices(contours.edges(e,2),:);
    ws_wt(v1(1),v1(2))=max( pb_oriented(v1(1),v1(2), orient(e)),ws_wt(v1(1),v1(2)));
    ws_wt(v2(1),v2(2))=max( pb_oriented(v2(1),v2(2), orient(e)),ws_wt(v2(1),v2(2)));
end
ws_wt=double(ws_wt);
%%

function [pb2, V, H] = super_contour_4c(pb)

V = min(pb(1:end-1,:), pb(2:end,:));
H = min(pb(:,1:end-1), pb(:,2:end));

[tx, ty] = size(pb);
pb2 = zeros(2*tx, 2*ty);
pb2(1:2:end, 1:2:end) = pb;
pb2(1:2:end, 2:2:end-2) = H;
pb2(2:2:end-2, 1:2:end) = V;
pb2(end,:) = pb2(end-1, :);
pb2(:,end) = max(pb2(:,end), pb2(:,end-1));

%%

function [ws_clean] = clean_watersheds(ws)
% remove artifacts created by non-thin watersheds (2x2 blocks) that produce
% isolated pixels in super_contour

ws_clean = ws;

c = bwmorph(ws_clean == 0, 'clean', inf);

artifacts = ( c==0 & ws_clean==0 );
R = regionprops(bwlabel(artifacts), 'PixelList');

for r = 1 : numel(R),
    xc = R(r).PixelList(1,2);
    yc = R(r).PixelList(1,1);

    vec = [ max(ws_clean(xc-2, yc-1), ws_clean(xc-1, yc-2)) ...
        max(ws_clean(xc+2, yc-1), ws_clean(xc+1, yc-2)) ...
        max(ws_clean(xc+2, yc+1), ws_clean(xc+1, yc+2)) ...
        max(ws_clean(xc-2, yc+1), ws_clean(xc-1, yc+2)) ];

    [nd,id] = min(vec);
    switch id,
        case 1,
            if ws_clean(xc-2, yc-1) < ws_clean(xc-1, yc-2),
                ws_clean(xc, yc-1) = 0;
                ws_clean(xc-1, yc) = vec(1);
            else
                ws_clean(xc, yc-1) = vec(1);
                ws_clean(xc-1, yc) = 0;

            end
            ws_clean(xc-1, yc-1) = vec(1);
        case 2,
            if ws_clean(xc+2, yc-1) < ws_clean(xc+1, yc-2),
                ws_clean(xc, yc-1) = 0;
                ws_clean(xc+1, yc) = vec(2);
            else
                ws_clean(xc, yc-1) = vec(2);
                ws_clean(xc+1, yc) = 0;
            end
            ws_clean(xc+1, yc-1) = vec(2);

        case 3,
            if ws_clean(xc+2, yc+1) < ws_clean(xc+1, yc+2),
                ws_clean(xc, yc+1) = 0;
                ws_clean(xc+1, yc) = vec(3);
            else
                ws_clean(xc, yc+1) = vec(3);
                ws_clean(xc+1, yc) = 0;
            end
            ws_clean(xc+1, yc+1) = vec(3);
        case 4,
            if ws_clean(xc-2, yc+1) < ws_clean(xc-1, yc+2),
                ws_clean(xc, yc+1) = 0;
                ws_clean(xc-1, yc) = vec(4);
            else
                ws_clean(xc, yc+1) = vec(4);
                ws_clean(xc-1, yc) = 0;
            end
            ws_clean(xc-1, yc+1) = vec(4);
    end
end

%%
function cmap_proba = apply_sigmoid(cmap, thr, fq)
cmap_proba=cmap;
cmap_proba(:) = 1./(1+exp(-fq*(cmap(:)-thr)));


function prob = cwp2Fn(paramS,doseBinsC,volHistC)
% prob = cwp2Fn(paramS,doseBinsC,volHistC);
% ----------------------------------------------------------------------
% AI, 1/31/19

%Extract parameters and corresponding weights
[weight,x,parListC] = getParCoeff(paramS,'weight',doseBinsC,volHistC);

%Compute TCP/NTCP
constIdx = strcmpi(parListC,'constant');
gx = sum(weight(~constIdx).*x(~constIdx));
const = weight(constIdx).*x(constIdx);
prob = 1- exp(const*exp(gx));

%%--- Functions to extract model parameters and weights ----
    function [coeff,par,keepParC] = getParCoeff(paramS,fieldName,doseBinsC,volHistC)

        %Extract relevant parameters
        genFieldC = fields(paramS);
        for i = 1:numel(genFieldC)
            if strcmpi(genFieldC{i},'structures')
                structS = paramS.(genFieldC{i});
                structListC = fieldnames(structS);
                for j = 1:length(structListC)
                    strParamS = structS.(structListC{j});
                    strParamListC = fieldnames(strParamS);
                    for k = 1 : numel(strParamListC)
                        if isfield(strParamS.(strParamListC{k}),'cteg') |  isfield(strParamS.(strParamListC{k}),'weight')
                            parName = [structListC{j},strParamListC{k}];
                            keepParS.(parName) = strParamS.(strParamListC{k});
                        end
                    end
                end
            else
                 if isfield(paramS.(genFieldC{i}),'cteg') |  isfield(paramS.(genFieldC{i}),'weight')
                     parName = genFieldC{i};
                     keepParS.(parName) = paramS.(genFieldC{i});
                 end
            end
        end

       %Compute parameters, extract coefficients
        keepParC = fieldnames(keepParS);
        numStr = 0;
        par = zeros(1,length(keepParC));
        coeff = zeros(1,length(keepParC));
        for n = 1:length(keepParC)
            coeff(n) = keepParS.(keepParC{n}).(fieldName);
            if isnumeric(keepParS.(keepParC{n}).val)
               par(n) = keepParS.(keepParC{n}).val;
            else
                if ~iscell(doseBinsC)  %For single-structure models
                    doseBinsV = doseBinsC;
                    volHistV = volHistC;
                else
                numStr = numStr+1;
                doseBinsV = doseBinsC{numStr};
                volHistV = volHistC{numStr};
                end
                if ~isfield(keepParS.(keepParC{n}),'params')
                    par(n) = eval([keepParS.(keepParC{n}).val,...
                        '(doseBinsV, volHistV)']);
                else
                    %Copy number fo fractions, abRatio
                    keepParS.(keepParC{n}).params.numFractions.val = paramS.numFractions;
                    if isfield(paramS,'abRatio')
                        keepParS.(keepParC{n}).params.abRatio.val = paramS.abRatio;
                    end
                    par(n) = eval([keepParS.(keepParC{n}).val,...
                        '(doseBinsV, volHistV,keepParS.(keepParC{n}).params)']);
                end
            end
        end
    end

end


function [accgvs, accpps] = iccvEvaluateGeometry(imsegs)

resdir = './data4/smallsegs/3/';

totalgvs = 0;
accgvs = 0;

totalpps = 0;
accpps = 0;

for f = 1:numel(imsegs)
    fn = imsegs(f).imname;
    load([resdir strtok(fn, '.') '_seg.mat']);

    gvsgt = imsegs(f).vert_labels(imsegs(f).segimage);
    ppsgt = imsegs(f).horz_labels(imsegs(f).segimage);
    ppsgt = (ppsgt<=3) + (ppsgt==4)*2 + (ppsgt==5)*3;

    pg = bndinfo.result.geomProb;
    gvspg = [pg(:, 1) sum(pg(:, 2:4),2) pg(:, 5)];
    ppspg = pg(:, 2:4);
    [tmp, gvsres] = max(gvspg, [], 2);
    [tmp, ppsres] = max(ppspg, [], 2);

    gvsres = gvsres(bndinfo.wseg);
    ppsres = ppsres(bndinfo.wseg);

    accgvs = accgvs + sum(gvsres(:)==gvsgt(:)) / sum(gvsgt(:)>0);
    totalgvs = totalgvs + mean(gvsgt(:)>0);

    accpps = accpps + sum(ppsres(:)==ppsgt(:)) / sum(ppsgt(:)>0);
    totalpps = totalpps + mean(ppsgt(:)>0);

    disp(num2str([accgvs/totalgvs accpps/totalpps]));

end


function [ t_start, y_start ] = p18_start ( neqn )

%*****************************************************************************80
%
%% P18_START returns the starting point for problem p18.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real T_START, Y_START(NEQN,1), the initial data.
%
  y_start = zeros ( neqn, 1 );

  t_start = 0.0;
  delta = p18_param ( 'GET', 'DELTA', [] );
  y_start(1) = 1.0 - delta;
  y_start(2) = 0.0;
  y_start(3) = 0.0;
  y_start(4) = sqrt ( ( 1.0 + delta ) / ( 1.0 - delta ) );

  return
end


function t=collision_time(s,t,x,T);
% finds the collsion time between x(1) at t(1) with speed s(s) and x(2)
% at t(2) with speed s(2).
%
if nargin<4
  T=1e6;
end;
sl=s(1); sr=s(2);
tl=t(1); tr=t(2);
xl=x(1); xr=x(2);
if sr > sl,
  t=T+1;
elseif sr < sl,
  h1=sl*tl;
  h2=sr*tr;
  h3=xl-xr;
  h4=sl-sr;
  h1=(h1-h2-h3);
  t=h1/h4;
elseif xl==xr&tl==tr,
  t=tl;
else
  t=T+1;
end;