function [f,h] = extractPole(f)
%EXTRACTPOLE  Removes from F the term accounting for non-zero pole/origin
%
% [G,H] = EXTRACTPOLE(F) if F is non-zero at the origin, then this function
% returns DISKFUNs G and H, such that H is rank 1, G = F - H, and G is
% zero at the origin. If F is zero at the origin then G is an empty
% DISKFUN.

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

if ( ~isempty(f) && f.nonZeroPoles )
    h = f;
    % The col and row for the pole is always assumed to be at the first
    % index
    h.cols = f.cols(:,1);
    h.rows = f.rows(:,1);
    h.pivotValues = f.pivotValues(1);
    h.idxPlus = 1;
    h.idxMinus = [];
    h.pivotLocations = f.pivotLocations(1,:);

    % Now remove these rows and columns from f
    if size(f.cols,2) > 1
        f.cols = f.cols(:,2:end);
        f.rows = f.rows(:,2:end);
    else     % Bug in chebfun requires checking for these cases.
        f.cols = [];
        f.rows = [];
    end
    f.pivotValues = f.pivotValues(2:end);
    f.idxPlus = f.idxPlus(2:end)-1;
    f.idxMinus = f.idxMinus - 1;
    f.pivotLocations = f.pivotLocations(2:end,:);
    f.nonZeroPoles = 0;
else
    h = diskfun([]);
end

end


function sgmga_aniso_balance_test ( alpha_max, dim_num, level_weight )

%*****************************************************************************80
%
%% SGMGA_ANISO_BALANCE_TEST calls SGMGA_ANISO_BALANCE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 February 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SGMGA_ANISO_BALANCE_TEST\n' );
  fprintf ( 1, '  ALPHA_MAX = %f\n', alpha_max );
  fprintf ( 1, '  Input weight sum: %f\n', sum ( level_weight(1:dim_num) ) );
  for dim = 1 : dim_num
    fprintf ( 1, '  %12f', level_weight(dim) );
  end
  fprintf ( 1, '\n' );

  level_weight2 = sgmga_aniso_balance ( alpha_max, dim_num, level_weight );

  fprintf ( 1, '  Output weight sum: %f\n', sum ( level_weight2(1:dim_num) ) );
  for dim = 1 : dim_num
    fprintf ( 1, '  %12f', level_weight2(dim) );
  end
  fprintf ( 1, '\n' );

  return
end


function test_suite = test_distancePointEdge3d
%TEST_DISTANCEPOINTEDGE3D  Test case for the file distancePointEdge3d
%
%   Test case for the file distancePointEdge3d

%   Example
%   test_distancePointEdge3d
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2012-04-29,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function test_Simple(testCase) %#ok<*DEFNU>
% Test call of function without argument

edge = [10 10 10 30 10 10];

p0 = [10 10 10];
exp0 = 0;
testCase.assertEqual(exp0, distancePointEdge3d(p0, edge), 'AbsTol', .01);

p1 = [30 10 10];
exp1 = 0;
testCase.assertEqual(exp1, distancePointEdge3d(p1, edge), 'AbsTol', .01);

p2 = [0 0 0];
exp2 = 10 * sqrt(3);
testCase.assertEqual(exp2, distancePointEdge3d(p2, edge), 'AbsTol', 1e-14);

p3 = [40 20 20];
exp3 = 10 * sqrt(3);
testCase.assertEqual(exp3, distancePointEdge3d(p3, edge), 'AbsTol', 1e-14);

function testArray(testCase)

edge = [10 10 10 30 10 10];
pts = [10 10 10;30 10 10;0 0 0;40 20 20];
exp = [0 0 10*sqrt(3) 10*sqrt(3)]';
testCase.assertEqual(exp, distancePointEdge3d(pts, edge), 'AbsTol', 1e-14);


%% Machine Learning Online Class
%  Exercise 8 | Anomaly Detection and Collaborative Filtering
%
%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  exercise. You will need to complete the following functions:
%
%     estimateGaussian.m
%     selectThreshold.m
%     cofiCostFunc.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% =============== Part 1: Loading movie ratings dataset ================
%  You will start by loading the movie ratings dataset to understand the
%  structure of the data.
%
fprintf('Loading movie ratings dataset.\n\n');

%  Load data
load ('ex8_movies.mat');

%  Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies on
%  943 users
%
%  R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a
%  rating to movie i

%  From the matrix, we can compute statistics like average rating.
fprintf('Average rating for movie 1 (Toy Story): %f / 5\n\n', ...
        mean(Y(1, R(1, :))));

%  We can "visualize" the ratings matrix by plotting it with imagesc
imagesc(Y);
ylabel('Movies');
xlabel('Users');

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============ Part 2: Collaborative Filtering Cost Function ===========
%  You will now implement the cost function for collaborative filtering.
%  To help you debug your cost function, we have included set of weights
%  that we trained on that. Specifically, you should complete the code in
%  cofiCostFunc.m to return J.

%  Load pre-trained weights (X, Theta, num_users, num_movies, num_features)
load ('ex8_movieParams.mat');

%  Reduce the data set size so that this runs faster
num_users = 4; num_movies = 5; num_features = 3;
X = X(1:num_movies, 1:num_features);
Theta = Theta(1:num_users, 1:num_features);
Y = Y(1:num_movies, 1:num_users);
R = R(1:num_movies, 1:num_users);

%  Evaluate cost function
J = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...
               num_features, 0);

fprintf(['Cost at loaded parameters: %f '...
         '\n(this value should be about 22.22)\n'], J);

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============== Part 3: Collaborative Filtering Gradient ==============
%  Once your cost function matches up with ours, you should now implement
%  the collaborative filtering gradient function. Specifically, you should
%  complete the code in cofiCostFunc.m to return the grad argument.
%
fprintf('\nChecking Gradients (without regularization) ... \n');

%  Check gradients by running checkNNGradients
checkCostFunction;

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ========= Part 4: Collaborative Filtering Cost Regularization ========
%  Now, you should implement regularization for the cost function for
%  collaborative filtering. You can implement it by adding the cost of
%  regularization to the original cost computation.
%

%  Evaluate cost function
J = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...
               num_features, 1.5);

fprintf(['Cost at loaded parameters (lambda = 1.5): %f '...
         '\n(this value should be about 31.34)\n'], J);

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ======= Part 5: Collaborative Filtering Gradient Regularization ======
%  Once your cost matches up with ours, you should proceed to implement
%  regularization for the gradient.
%

%
fprintf('\nChecking Gradients (with regularization) ... \n');

%  Check gradients by running checkNNGradients
checkCostFunction(1.5);

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ============== Part 6: Entering ratings for a new user ===============
%  Before we will train the collaborative filtering model, we will first
%  add ratings that correspond to a new user that we just observed. This
%  part of the code will also allow you to put in your own ratings for the
%  movies in our dataset!
%
movieList = loadMovieList();

%  Initialize my ratings
my_ratings = zeros(1682, 1);

% Check the file movie_idx.txt for id of each movie in our dataset
% For example, Toy Story (1995) has ID 1, so to rate it "4", you can set
my_ratings(1) = 4;

% Or suppose did not enjoy Silence of the Lambs (1991), you can set
my_ratings(98) = 2;

% We have selected a few movies we liked / did not like and the ratings we
% gave are as follows:
my_ratings(7) = 3;
my_ratings(12)= 5;
my_ratings(54) = 4;
my_ratings(64)= 5;
my_ratings(66)= 3;
my_ratings(69) = 5;
my_ratings(183) = 4;
my_ratings(226) = 5;
my_ratings(355)= 5;

fprintf('\n\nNew user ratings:\n');
for i = 1:length(my_ratings)
    if my_ratings(i) > 0
        fprintf('Rated %d for %s\n', my_ratings(i), ...
                 movieList{i});
    end
end

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ================== Part 7: Learning Movie Ratings ====================
%  Now, you will train the collaborative filtering model on a movie rating
%  dataset of 1682 movies and 943 users
%

fprintf('\nTraining collaborative filtering...\n');

%  Load data
load('ex8_movies.mat');

%  Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies by
%  943 users
%
%  R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a
%  rating to movie i

%  Add our own ratings to the data matrix
Y = [my_ratings Y];
R = [(my_ratings ~= 0) R];

%  Normalize Ratings
[Ynorm, Ymean] = normalizeRatings(Y, R);

%  Useful Values
num_users = size(Y, 2);
num_movies = size(Y, 1);
num_features = 10;

% Set Initial Parameters (Theta, X)
X = randn(num_movies, num_features);
Theta = randn(num_users, num_features);

initial_parameters = [X(:); Theta(:)];

% Set options for fmincg
options = optimset('GradObj', 'on', 'MaxIter', 100);

% Set Regularization
lambda = 10;
theta = fmincg (@(t)(cofiCostFunc(t, Ynorm, R, num_users, num_movies, ...
                                num_features, lambda)), ...
                initial_parameters, options);

% Unfold the returned theta back into U and W
X = reshape(theta(1:num_movies*num_features), num_movies, num_features);
Theta = reshape(theta(num_movies*num_features+1:end), ...
                num_users, num_features);

fprintf('Recommender system learning completed.\n');

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% ================== Part 8: Recommendation for you ====================
%  After training the model, you can now make recommendations by computing
%  the predictions matrix.
%

p = X * Theta';
my_predictions = p(:,1) + Ymean;

movieList = loadMovieList();

[r, ix] = sort(my_predictions, 'descend');
fprintf('\nTop recommendations for you:\n');
for i=1:10
    j = ix(i);
    fprintf('Predicting rating %.1f for movie %s\n', my_predictions(j), ...
            movieList{j});
end

fprintf('\n\nOriginal ratings provided:\n');
for i = 1:length(my_ratings)
    if my_ratings(i) > 0
        fprintf('Rated %d for %s\n', my_ratings(i), ...
                 movieList{i});
    end
end


function [phi,theta,r] = sofa_get_head_orientations(sofa,idx)
%SOFA_GET_HEAD_ORIENTATIONS returns phi, theta and r from the given SOFA data set
%
%   Usage: [phi,theta,r] = sofa_get_head_orientations(sofa,[idx])
%
%   Input parameters:
%       sofa   - impulse response data set (SOFA struct/file)
%       idx    - index of measurement for which head orientation should be
%                returned (default: return all head orientations)
%
%   Output parameters:
%       phi    - head orientations in the horizontal plane / rad
%       theta  - head orientations in the median plane / rad
%       r      - head orientations radii / m
%
%   SOFA_GET_HEAD_ORIENTATIONS(sofa,idx) returns head orientation [phi,theta,r]
%   as defined in the given SOFA file or struct, specified by idx. If no idx is
%   specified, all head orientations are returned.
%
%   See also: get_ir, sofa_get_header, sofa_get_secondary_sources

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

%% ===== Checking of input  parameters ==================================
nargmin = 1;
nargmax = 2;
narginchk(nargmin,nargmax)
if nargin==nargmax-1
    idx = ':';
else
    isargvector(idx);
end

%% ===== Computation ====================================================
header = sofa_get_header(sofa);
listener_view = SOFAconvertCoordinates(header.ListenerView, ...
                                       header.ListenerView_Type,'spherical');
phi = correct_azimuth(rad(listener_view(idx,1)));
theta = correct_elevation(rad(listener_view(idx,2)));
r = listener_view(idx,3);


% MATLAB RRT*FN package for solving path/motion planning problems.
% Version 0.0.1 23-Aug-2013
%
% RRT and RRT* implementations are included as well
%
% FILES:
%   README.md                        - readme file, read it please.
%   rrt                              - Rapidly-Exploring Random Tree (RRT)
%   rrt_star                         - RRT*
%   rrt_star_fn                      - RRT*FN (Fixed Nodes)
%   FNRedundantManipulator           - Model of "n" DOF planar redundant
%                                      manipulator.
%   FNSimple2D                       - Model of 2D mobile robot
%   GridBased2Dimrotate              - Initial work on model of KUKA youbot
%                                      GPU usage employed (faster)
%   benchmark2D                      - benchmark script for 2D mobile robot
%   benchmarkRedundant               - benchmark script for nDOF redundant planar manipulator
%
% CONFIGURATION FILES:
%   configure_FNRedundantManipulator - Default configuration for Redundant Robotic Manipulator nDOF
%   configure_FNSimple2D             - Default configuration for 2D case
%   configure_GridBased2Dimrotate    - Default configuration for 2D case


function dt = niftiClass2DataType(matlabType)
% Transform the string matlabType into a numerical codes used by NIFTI-1
%
%  dt = niftiClass2DataType(matlabType)
%
% Here is the table showing the assocation between Matlab type and NIFTI-1
% data type.
%
%  String (Matlab) ----> NIFTI-1
% -------------------------------
%            uint8 ----> 2
%            int16 ----> 4
%            int32 ----> 8
%  single, float32 ----> 16
%        complex64 ----> 32
%  double, float64 ----> 64
%            RGB24 ----> 128
%             int8 ----> 256
%           unit16 ----> 512
%           uint32 ----> 768
%       complex128 ----> 1792
%
% Franco (c) Stanford Vista team, 2012

matlabType = mrvParamFormat(matlabType);
switch matlabType
    case {'uint8'},      dt = 2;
    case {'int16'},      dt = 4;
    case {'int32'},      dt = 8;
    case {'float32','single'}, dt = 16;
    case {'complex64'},  dt = 32';
    case {'float64','double'}, dt = 64;
    case {'rgb64'},      dt = 128;
    case {'int8'},       dt = 256;
    case {'uint16'},     dt = 512;
    case {'uint32'},     dt = 768;
    case {'complex128'}, dt = 1792;
    otherwise,
        error('Unknown string %s\n',matlabType);

end

end


%% Copyright (C) 2016-2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published
%% by the Free Software Foundation; either version 3 of the License,
%% or (at your option) any later version.
%%
%% This software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym acsc (@var{x})
%% Symbolic acsc function.
%%
%% Example:
%% @example
%% @group
%% syms x
%% y = acsc (x)
%%   @result{} y = (sym) acsc(x)
%% @end group
%% @end example
%%
%% Note: this file is autogenerated: if you want to edit it, you might
%% want to make changes to 'generate_functions.py' instead.
%%
%% @end defmethod

function y = acsc(x)
  if (nargin ~= 1)
    print_usage ();
  end
  y = elementwise_op ('acsc', x);
end

%!error acsc (sym(1), 2)
%!assert (isequaln (acsc (sym(nan)), sym(nan)))

%!shared x, d
%! d = 1;
%! x = sym('1');

%!test
%! f1 = acsc(x);
%! f2 = acsc(d);
%! assert( abs(double(f1) - f2) < 1e-15 )

%!test
%! D = [d d; d d];
%! A = [x x; x x];
%! f1 = acsc(A);
%! f2 = acsc(D);
%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))

%!test
%! % round trip
%! y = sym('y');
%! A = acsc (d);
%! f = acsc (y);
%! h = function_handle (f);
%! B = h (d);
%! assert (A, B, -eps)


function [ y, m, d ] = day_borrow_roman ( y, m, d )

%*****************************************************************************80
%
%% DAY_BORROW_ROMAN borrows days from months in a Roman date.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input/output, integer Y, M, D, a year, month, and day
%    representing a date.  On input, D might be negative.  On output,
%    M should have decreased by one month, and D gone up by the
%    number of days in the month we "cashed in".  Y may be affected
%    if the input value of M was 1.
%
  while ( d <= 0 )

    m = m - 1;

    [ y, m ] = month_borrow_roman ( y, m );

    days = month_length_roman ( y, m );

    d = d + days;

  end

  return
end


function d2fdx2 = hessian(f,x)
% HESSIAN Hessian of scalar polynomial SDPVAR object
%
% J = HESSIAN(p)    Hessian w.r.t all variables in p
% J = HESSIAN(p,x)  Hessian w.r.t the SDPVAR variables x
%
% See also INT, JACOBIAN, LINEARIZE, SDISPLAY

if nargin==1
    if isa(f,'sdpvar')
        x = recover(depends(f));
    else
        x = 0;
    end
else
    if length(getvariables(x))<length(x)
        error('x should be a vector of scalar independant variables');
    end
end

if prod(size(f))>1
    error('Hessian only defined for scalars.')
end

if any(ismember([getvariables(f) depends(f)],yalmip('extvariables')))
    error('Hessian is only applicable to polynomial expressions');
end

if isa(f,'double')
    d2fdx2 = zeros(length(x));
    return
end

d2fdx2 = jacobian(jacobian(f,x)',x);


function [density, pressure, temperature] = getAtmoDensityAtAltitude(bodyInfo, altitude, lat, ut, long)
%getAtmoDensityAtAltitude Summary of this function goes here
%   Detailed explanation goes here
%   See here for math: https://forum.kerbalspaceprogram.com/index.php?/topic/142686-modeling-atmospheres-in-ksp/

    if(altitude <= bodyInfo.atmohgt && altitude >= 0)
%         pressure = getPressureAtAltitude(bodyInfo, altitude);
        pressure = bodyInfo.getBodyAtmoPressure(altitude);

        if(pressure > 0)
            temperature = bodyInfo.getBodyAtmoTemperature(ut, lat, long, altitude);

            density = getDensityFromIdealGasLaw(pressure, temperature, bodyInfo.atmomolarmass);
            if(density < 0)
                density = 0;
                pressure = 0;
                temperature = 0;
            end
        else
            density = 0;
            pressure = 0;
            temperature = 0;
        end
    elseif(altitude <= 0)
        density = 0;
        pressure = 0;
        temperature = 0;
    else
        density = 0;
        pressure = 0;
        temperature = 0;
    end
end


        % Rezolvarea unei ecuatii cu derivate partiale
        % direct din programul MAPLE
Sol=maple('pdesolve( diff(f(x,y),x,x)+5*diff(f(x,y),x,y)=3, f(x,y) )')


function [restr,tpl]=create_restrictions_and_markov_chains1(tpl)
% create_restrictions_and_markov_chains1 -- creates linear restrictions and
% markov chains for the SVAR model in which coefficients are switching
% across all equations (synchronized case)
%
% ::
%
%
%   [restr,tpl]=create_restrictions_and_markov_chains1(tpl)
%
% Args:
%
%    - **tpl** [struct]: template created for SVAR objects
%
% Returns:
%    :
%
%    - **restr** [cell]: two column-cell (see below). The first column
%    contains COEF objects or linear combinations of COEF objects, which are
%    themselves COEF objects.
%
%    - **tpl** [struct]: modified template
%
% Note:
%
%    - The syntax to construct an advanced COEF object is
%    a=coef(eqtn,vname,lag,chain_name,state)
%      - **eqtn** [integer|char]: integer or variable name
%      - **vname** [integer|char]: integer or variable name
%      - **lag** [integer]: integer or variable name
%      - **chain_name** [char]: name of the markov chain
%      - **state** [integer]: state number
%
%    - RISE sorts the endogenous variables alphabetically and use this order
%    to tag each equation in SVAR and RFVAR models.
%
%    - The lag coefficients are labelled a0, a1, a2,...,ak, for a model with k
%    lags. Obviously, a0 denotes the contemporaneous coefficients.
%
%    - The constant terms labelled c_1_1, c_2_2,...,c_n_n, for a model with n
%    endogenous variables.
%
%    - The standard deviations labelled sig_1_1, sig_2_2,...,sig_n_n, for a
%    model with n endogenous variables.
%
% Example:
%    coef('pi','ygap',0,'policy',1)
%
%    coef(2,3,0,'policy',1)
%
%    coef(2,'ygap',0,'policy',1)
%
%    coef('pi',3,0,'policy',1)
%
%    See also:

% We add a Markov chain to the template
%----------------------------------------
% N.B: The chain controls the coefficients of all equations but not the
% variance, which remains constant.
last=numel(tpl.markov_chains);
tpl.markov_chains(last+1)=struct('name','syncoef',...
    'states_expected_duration',[3+1i,3+1i],...
    'controlled_parameters',{{'c','a0','a1','a2'}});

% syntax is coef(eqtn,vname,lag,chain_name,state)
%------------------------------------------------
restr=cell(0,2);

numberOfStates=numel(tpl.markov_chains(end).states_expected_duration);

for istate=1:numberOfStates
    restr=[restr
        {
        % first equation or "FFR" equation:
        %----------------------------------
        coef(1,'pi',1,'syncoef',istate),0
        coef(1,'pi',2,'syncoef',istate),0
        coef(1,'ygap',1,'syncoef',istate),0
        coef(1,'ygap',2,'syncoef',istate),0
        coef(1,'FFR',2,'syncoef',istate),0
        % second equation or "pi" equation
        %----------------------------------
        coef(2,'FFR',0,'syncoef',istate),0
        coef(2,'FFR',1,'syncoef',istate),0
        coef(2,'FFR',2,'syncoef',istate),0
        coef(2,'ygap',1,'syncoef',istate),0
        coef(2,'ygap',2,'syncoef',istate),0
        % third equation or "ygap" equation
        %-----------------------------------
        coef(3,'FFR',1,'syncoef',istate),0
        coef(3,'FFR',2,'syncoef',istate),0
        coef(3,'pi',1,'syncoef',istate),0
        coef(3,'pi',2,'syncoef',istate),0
        coef(3,'pi',0,'syncoef',istate)+coef(3,'FFR',0,'syncoef',istate),0
        }
        ]; %#ok<AGROW>
end

end


% X = canlab_glm_convolve(stimObj, dsgn, nscan, basis)
%
% This function takes an spm style conditions object (see below), a canlab
% DSGN object (see below), a frame count and a basis function type and
% returns a timeseries vector corresponding to onsets and durations
% specified in stimObj and any modulations specified in dsgn, convolved
% with the basis function specified by basis. Useful if you want to treat
% experimental factors as confounds in a multiple regressors matrix instead
% of treating them as events in SPM. Primarly desinged to allow for
% multiple different basis functions to be used for different design
% factors (e.g. spline interpolation for factors of interest and canonical
% interpolation for confounding factors; here you would implement the
% confounding factors as multiple regressor columns instead after
% convolution).
%
% Input ::
%
%   stimObj     - an SPM-stype condition object. see
%                   canlab_glm_subject_levels('dsgninfo') under
%                   DSGN.conditions for an example
%
%   dsgn        - see canlab_glm_subject_levels('dsgninfo') for how to
%                   format this object.
%
%   nscan       - number of TRs in the scan for which stimObj applies.
%
%   basis       - currently only 'hrf' is supported, although others could
%                   be implemented easily enough. See spm_get_bf.m for some
%                   example implementations of other basis functions. The
%                   implementation here follows that function closely.
% Optional Input ::
%
%   hrfParam    - a struct following the basis argument. If specifying
%                   spline or hrf you will need to specify a structure with
%                   windowlength, order, and (for splines) degree
%                   properties.
%
% Output ::
%
%   X           - A timeseries vector corresponding to the stimuli
%                   specified in stimObj.
%
% Written by Bogdan Petre, 5/19/2021

function [X, bf] = canlab_glm_convolve(stimObj, dsgn, nscan, basis, varargin)
if ~isempty(varargin)
    hrfParams = varargin{1};
end

% we're going to manually convolve stimFactor
spm('defaults','fmri')
spm_jobman('initcfg')

fMRI_T = spm_get_defaults('stats.fmri.t');
if ismember('fmri_t',fieldnames(dsgn))
	if ~isempty(dsgn.fmri_t), fMRI_T = dsgn.fmri_t; end
end

T = dsgn.tr;
dt = dsgn.tr/fMRI_T;

xBF.dt = dt;
xBF.UNITS = 'secs';
xBF.T     = fMRI_T;
xBF.T0    = dsgn.fmri_t0;

if strcmp(basis,'hrf')
    xBF.name = 'hrf';
else
    switch basis
        case 'spline'
            xBF.name   = 'Spline set';
            xBF.degree = hrfParams.degree;
        case 'fourier'
            xBF.name = 'Fourier set';
        case 'fourier_han'
            xBF.name = 'Fourier set (Hanning)';
        case 'gamma'
            xBF.name = 'Gamma functions';
        case 'fir'
            xBF.name = 'Finite Impulse Response';
    otherwise
        error('Unknown basis functions.');
    end
    xBF.length = hrfParams.windowlength;
	xBF.order  = hrfParams.order;
end

switch basis
    case 'hrf'
        [bf, p] = spm_hrf(dt,[],fMRI_T);

        % time derivative (untested)
        try
            if logical(dsgn.convolution.derivs(1))
                dp       = 1;
                p(6)     = p(6) + dp;
                D        = (bf(:,1) - spm_hrf(dt,p,fMRI_T))/dp;
                bf       = [bf D(:)];
                p(6)     = p(6) - dp;
            end
        end

        % dispersion derivative (untested)
        try
            if logical(dsgn.convolution.derivs(2))
                dp   = 0.01;
                p(3) = p(3) + dp;
                D    = (bf(:,1) - spm_hrf(dt,p,fMRI_T))/dp;
                bf   = [bf D(:)];
            end
        end

    case {'spline','fir'}
        xBF = spm_get_bf(xBF);
        bf = xBF.bf;
    otherwise
        error('Only Canonical HRF, spline or FIR convolution is currently supported');
end

if ~strcmp(xBF.name,'Spline set')
    bf = spm_orth(bf);
end

U = [struct(...
    'name','',...
    'ons',[],...
    'dur',[],...
    'orth', 1,...
    'P', struct('name','none','h',0))];

if isempty(stimObj)
    X = [];
else
    % rating and cue convolution
    U(1).name = {'manualConvFactor'};
    U(1).ons = stimObj.onset{1}(:);
    U(1).dur = stimObj.duration{1}(:);

    % this borrws from spm_fMRI_design.m which implements the
    % convolution when spm is invoked directly.
    xBF = struct('T',fMRI_T,'T0',dsgn.fmri_t0,'dt',dt,'UNITS','secs');
    this = struct('Sess',struct('U',U), 'nscan', nscan, 'xBF', xBF);

    U = spm_get_ons(this,1);

    [X,Xn,Fc] = spm_Volterra(U, bf, 1);

    if ~isempty(X)
        X = X((0:(this.nscan - 1))*fMRI_T + dsgn.fmri_t0 + 32,:);
    end
    %{
    switch xBF.name
        case {'hrf', 'fir'}
            %-Orthogonalise (within trial type)
            %----------------------------------------------------------------------
            for i = 1:length(Fc)
                if i<= numel(U) && ... % for Volterra kernels
                        (~isfield(U(i),'orth') || U(i).orth)
                    p = ones(size(Fc(i).i));
                else
                    p = Fc(i).p;
                end
                for j = 1:max(p)
                    X(:,Fc(i).i(p==j)) = spm_orth(X(:,Fc(i).i(p==j)));
                end
            end
    end
    %}

end

end


function feaMap = rescaleFeaMap(feaMap)
feaMap = feaMap - min(feaMap(:));
feaMap = feaMap ./ max(feaMap(:));


function [ point_num, face_num, face_data_num ] = xyf_example_size (  )

%*****************************************************************************80
%
%% XYF_EXAMPLE_SIZE sizes the data to be created by XYF_EXAMPLE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer POINT_NUM, the number of points.
%
%    Output, integer FACE_NUM, the number of faces.
%
%    Output, integer FACE_DATA_NUM, the number of face items.
%
  n_t = 13;
  n_r = 5;

  face_data_num = 4 * ( n_t - 1 ) * ( n_r - 1 );
  face_num = ( n_t - 1 ) * ( n_r - 1 );
  point_num = n_t * n_r;

  return
end


function [w, W_f, W_v] = fromFrameVec(F,v)

% FROMFRAMEVEC  From frame function for vectors.
%   FROMFRAMEVEC(F,V) transforms the 3d vector V from frame F to the global
%   frame.
%
%   [w, W_f, W_v] = FROMFRAMEVEC(...) returns the Jacobians wrt F and V.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

w = F.R*v;

if nargout > 1   % Jacobians.

    if size(v,2) == 1

        s = 2*q2Pi(F.q)*v;

        W_q = [...
            s(2) -s(1)  s(4) -s(3)
            s(3) -s(4) -s(1)  s(2)
            s(4)  s(3) -s(2) -s(1)];
        W_v = F.R;
        W_f = [zeros(3) W_q];

    else % multiple points
        error('??? Can''t give Jacobians for multiple points');
    end
end

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function pd = prtEvalPdAtPf(classifier,dataSet,pfDesired,nFolds)
% prtEvalPdAtPf   Returns the probability of false alarm at a desired
%   probability of detection on the receiver operating curve.
%
%   PD = prtEvalPdAtPf(prtClassifier, prtDataSet, pfDesired) returns the
%   probabilty of detection PD.  prtDataSet must be a labeled, binary
%   prtDataSetStandard object. prtClassifier must be a prtClass object.
%   pfDesired is the desired probability of false alarm and must be between
%   0 and 1.
%
%   pfDesired = prtEvalPdAtPf(prtClassifier, prtDataSet, pfDesired, nFolds)
%   returns the probabilty of false alarm pfDesired on the receiver
%   operating curve with K-fold cross-validation. prtDataSet must be a
%   labeled, binary prtDataSetStandard object. prtClassifier must be a
%   prtClass object. pfDesired is the desired probability of detection and
%   must be between 0 and 1. nFolds is the number of folds in the K-fold
%   cross-validation.
%
%   pfDesired = prtEvalPdAtPf(prtClassifier, prtDataSet, pfDesired,
%   xValInds) same as above, but use crossValidation with specified indices
%   instead of random folds.
%
%   Example:
%   dataSet = prtDataGenSpiral;
%   classifier = prtClassDlrt;
%   pf = prtEvalPdAtPf(classifier, dataSet,.01)
%
%   See Also: prtEvalAuc, prtEvalPfAtPd, prtEvalPercentCorrect,
%   prtEvalMinCost

if nargin < 4 || isempty(nFolds)
    nFolds = 1;
end
results = prtUtilEvalParseAndRun(classifier,dataSet,nFolds);

[pf,pd] = prtScoreRoc(results.getObservations,dataSet.getTargets);

[pf,sortInd] = sort(pf(:),'ascend');
pd = pd(sortInd);

ind = find(pf >= pfDesired);
if ~isempty(ind)
    pd = pd(ind(1));
else
    pd = nan;
end


function [Xcs,Ycs,Zcs]=contourRegulariseAngle(varargin)

switch nargin
    case 2
        Vcs=varargin{1};
        np=varargin{2};
        thetaStart=0; %Default angle
        interpMethod='pchip'; %Default method
    case 3
        Vcs=varargin{1};
        np=varargin{2};
        thetaStart=varargin{3};
        interpMethod='pchip'; %Default method
            case 4
        Vcs=varargin{1};
        np=varargin{2};
        thetaStart=varargin{3};
        interpMethod=varargin{4}; %Default method
    otherwise
        error('Wrong number of input arguments');
end

%% CONTROL PARAMETERS
closeLoopOpt=1;

numContours=numel(Vcs);

%Allocate coordinate matrices
Xcs=nan(numContours,np); Ycs=nan(numContours,np); Zcs=nan(numContours,np);
startDefined=0;
for q=1:1:numContours

    %Join goups if present N.B. assumes they belong to the same curve!
    Vs=[];
    for qGroup=1:1:numel(Vcs{q})
        Vss=Vcs{q}{qGroup};
        if ~isempty(Vss)
            if isPolyClockwise(Vss)
                Vss=flipud(Vss);
            end
            Vs=[Vs; Vss];
        end
    end

    %Resample curve so they have the same number of points
    if ~isempty(Vs)

        numDigitsMerge=6-numOrder(mean(sum(diff(Vs,[],1).^2,2)));
        [~,ind1,ind2]=unique(pround(Vs,numDigitsMerge),'rows');

        Vs=Vs(ismember(1:size(Vs,1),ind1),:);

%         figure; plotV(Vs,'k.-'); hold on;
%         plotV(Vs(1,:),'r.');
%         plotV(Vs(end,:),'b.-');

        [Vs]=evenlySampleCurve(Vs,np,interpMethod,closeLoopOpt);

        %Reorder curve so that start points are close
         %%
%         if startDefined==0 %After 1 contour has been added
%             [thetaAll,~,~] = cart2pol(Vs(:,1),Vs(:,2),Vs(:,3));
%             thetaDiff=thetaAll-thetaStart;
%             [~,indMin]=min(thetaDiff);
%             V_start=Vs(indMin,:);
%             %Reorder first curve
%             Vs=[Vs(indMin:size(Vs,1),:); Vs(1:indMin-1,:)];
%             startDefined=1;
%         else
%             %Reorder curves so start and end points match closely
%             D=sqrt(sum((Vs-V_start(ones(1,size(Vs,1),1),:)).^2,2));
%             [~,indMin]=min(D);
%             if indMin~=1
%                 Vs=[Vs(indMin:size(Vs,1),:); Vs(1:indMin-1,:)];
%             end
%             V_start=Vs(1,:);
%         end

        %%
        meanVs=mean(Vs,1);
        Vsc=Vs-meanVs(ones(size(Vs,1),1),:);
        [thetaAll,~,~] = cart2pol(Vsc(:,1),Vsc(:,2),Vsc(:,3));
        thetaDiff=thetaAll-thetaStart;
        [~,indMin]=min(thetaDiff);

        if indMin~=1
            Vs=[Vs(indMin:size(Vs,1),:); Vs(1:indMin-1,:)];
        end

        %%

        %Store coordinates
        [Xcs(q,:),Ycs(q,:),Zcs(q,:)]=getColumns(Vs);
%         any(isnan(Zcs(q,:)))
    end
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% 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, see <http://www.gnu.org/licenses/>.


function mesh = mfmAdjustSpacing(mesh, unfoldMesh, params, unfolded2D, insideNodes);
%
%  mesh = mfmAdjustSpacing(mesh, unfoldMesh, params, unfolded2D,
%  insideNodes);
%
% Author: Winawer
% Purpose:
%   Adjust the spacing of the points in a flattened mesh so they don't
%   bunch up too much.  The method is to find a cartesian grid within the
%   data, find a Delaunay triangulation of this grid, and then use a series
%   of affine transformations to transform each of the triangles to an
%   equal area representation with the proper grid topology.  This is
%   explained in more detail in flatAdjustSpacing
%
%   Sub-routine derived from Alex's unfoldMeshFromGUI code.
%
% See Also:  unfoldMeshFromGUI

% Get all the variables we may need
meshFileName     = params.meshFileName;
grayFileName     = params.grayFileName;
flatFileName     = params.flatFileName;
startCoords      = params.startCoords;
scaleFactor      = params.scaleFactor;
perimDist        = params.perimDist;
statusHandle     = params.statusHandle;
busyHandle       = params.busyHandle;
spacingMethod    = params.spacingMethod;
adjustSpacing    = params.adjustSpacing;
gridSpacing      = params.gridSpacing;
showFigures      = params.showFigures;
saveExtra        = params.saveExtra;
truePerimDist    = params.truePerimDist;
hemi             = params.hemi;
nperims          = params.NPERIMS;
saveIntermeidate = params.SAVE_INTERMEDIATE;
numberOfSteps    = params.NUMBEROFSTEPS;

if (adjustSpacing)
    str = sprintf('Spacing points (method = %s)',spacingMethod);
    statusStringAdd(statusHandle,str);

    unfoldMesh.maxFractionDist = 0.8;
    unfoldMesh.gridSpacing = gridSpacing;
    unfoldMesh.locs2d = unfolded2D(:,1:2);
    unfoldMesh.startCoords = startCoords;
    unfoldMesh.scaleFactor = scaleFactor;

    % The user can select Cartesian or Polar spacing methods.  Only
    % Cartesian is working now, though, I think -- BW
    [newLocs2d,goodIdx] = flatAdjustSpacing(unfoldMesh,spacingMethod);
end

if (showFigures)
    statusStringAdd(statusHandle,['Displaying unfolded mesh']);
    h = unfoldMeshFigure(unfoldMesh);

	[p f] = fileparts(flatFileName);
    ensureDirExists(p);
	savePath = fullfile(p, [f,'_Unfolded Mesh.png']);
	saveas(gcf, savePath);
	fprintf('[%s]: Saved %s.\n', mfilename, savePath);
end

% Finally - the mapping of grey to mesh points takes place using the entire mesh.
% Therefore, we need to generate X for the mesh as well as the unfold mesh

% insideNodes is an array of indices into the original (non-bounded) mesh.
% Each entry in insideNodes relates a point in the unfoldMesh to a point in
% the original mesh

% Recover the perimeter and internal points
mesh.X=zeros(length(mesh.uniqueVertices),2);

% In order to deal with a cropped mesh (as generated by flatAdjustSpacing)
% we need to compute the ... Alex?
if (adjustSpacing)

    mesh.X(insideNodes(goodIdx),:)=newLocs2d;
    hasCoords=[insideNodes(goodIdx)];

else

    unfoldToOrigPerimeter=insideNodes(unfoldMesh.orderedUniquePerimeterPoints);
    unfoldToOrigInside=insideNodes(unfoldMesh.internalNodes);

    mesh.X(unfoldToOrigPerimeter,:)=unfoldMesh.X_zero;
    mesh.X(unfoldToOrigInside,:)=unfoldMesh.X;
    hasCoords=[unfoldToOrigPerimeter(:);unfoldToOrigInside(:)];

end

coords=mesh.X(hasCoords,:);
dists=mesh.dist(hasCoords);

% use griddata to image the distance map
warning off MATLAB:griddata:DuplicateDataPoints;
mesh.distMap=makeMeshImage(coords,dists,128);
warning on MATLAB:griddata:DuplicateDataPoints;

ZI=mesh.distMap;

if (showFigures),
	h = unfoldDistFigure(mesh);

	[p f ext] = fileparts(flatFileName);
	savePath = fullfile(p, [f ' Unfold Distance.png']);
	saveas(h, savePath);
	fprintf('[%s]: Saved %s.\n', mfilename, savePath);
end

% Record which nodes in the big mesh are in the unfold
mesh.insideNodes=insideNodes;

if (saveIntermeidate)
    statusStringAdd(statusHandle,'Saving intermediate data.');
    save ('meshOutTemp.mat','mesh');
end

return

%----------------------------------
% ---- SUBROUTINES
%----------------------------------
%----------------------------------
function h = unfoldMeshFigure(unfoldMesh);
h = figure;
hold off;
gplot(unfoldMesh.N,unfoldMesh.X);
title ('Unfolded mesh'); axis equal; axis off; zoom on
return;

%----------------------------------
function h = unfoldDistFigure(mesh)
h = figure;
imagesc(mesh.distMap);
axis image; colormap hot; title('Manifold distance map'); colorbar;

% Added the abs to cope with the fact that we sometimes get -ve numbers here...
% imagesc(abs(log(areaErrorMap)));
% axis image;
% colorbar;
% title('Log 3D/2D area');
% colormap hot;

return;


function [At,b,Z] = getequation(symexpr,vartable,decvartable,varmat)
%function [At,b,Z] = getequation(symexpr,vartable,decvartable,decvartablename)
%
% GETEQUATION --- Convert a symbolic expression to At, b, and Z
%         used in an SOS program.

% This file is part of SOSTOOLS - Sum of Squares Toolbox ver 3.00.
%
% Copyright (C)2002, 2004, 2013  A. Papachristodoulou (1), J. Anderson (1),
%                                G. Valmorbida (1), S. Prajna (2),
%                                P. Seiler (3), P. A. Parrilo (4)
% (1) Department of Engineering Science, University of Oxford, Oxford, U.K.
% (2) Control and Dynamical Systems - California Institute of Technology,
%     Pasadena, CA 91125, USA.
% (3) Aerospace and Engineering Mechanics Department, University of
%     Minnesota, Minneapolis, MN 55455-0153, USA.
% (4) Laboratory for Information and Decision Systems, M.I.T.,
%     Massachusetts, MA 02139-4307
%
% Send bug reports and feedback to: sostools@cds.caltech.edu
%
% 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, see <http://www.gnu.org/licenses/>.
%

% 03/01/02 - SP
% 03/10/02 - SP -- Use Maple
% 07/10/13 - JA&GV -- Use the matlab's symbolic engine
% 09/11/13 - PJS -- Addition for multipoly objects

if isa(symexpr,'polynomial')
    % PJS: Handle Polynomial Objects including the Matrix Case
    decvarnum = numel(decvartable);
    vartable = [vartable; varmat];
    cvartable = char(vartable);
    dimp = size(symexpr,2);

    % Collect symexpr = g(c)*h(x) where x are the vars in vartable,
    % c are the decision variables, and h(x) is a vector of monoms.
    % in the actual polynomial vars.  Use this to find unique
    % monomials in the polynomial variables.
    [g0,g,h] = collect(symexpr(:),setdiff(symexpr.varname,cvartable));
    g = g(:);
    if ~isequal(g0,0)
        g = [g0;g];
        h = [1; h];
    end
    [nmon,nvar] = size(h.degmat);

    % Reorder the monomials matrix with variables in the order
    % listed in cvartable and sorted monomials
    Z = zeros(nmon,nvar);
    [~,idx]=ismember(h.varname,cvartable);
    Z(:,idx) = full(h.degmat);
    Z = sortNoRepeat([],Z);

    % Initialize coefficient variables
    [nmon,nvar] = size(Z);
    coeffnts = sparse(nmon*dimp,dimp);
    if decvarnum>0
        coeffnts_decvar = polynomial(sparse(nmon*dimp,dimp));
    end

    % Define coefficients
    for i = 1:dimp
        for j = i:dimp
            exprij = symexpr(i,j);
            [g0,g,h] = collect(exprij,setdiff(exprij.varname,cvartable));
            g = g(:);
            if ~isequal(g0,0)
                g = [g0;g];
                h = [1; h];
            end
            coefmatr = double(subs(g,decvartable,zeros(decvarnum,1)));
            monmatr = zeros(length(h),nvar);
            [~,idx]=ismember(h.varname,cvartable);
            monmatr(:,idx) = h.coef'*h.degmat;

            for k = 1:length(h);
                s_ijk = coefmatr(k,1);
                s_ijk_decvar = g(k);
                mon_k= monmatr(k,:);

                [val,ind_k] = max(sum((Z == kron(ones(nmon,1),mon_k)),2));
                coeffnts((ind_k-1)*dimp+i,j) = s_ijk;
                coeffnts((ind_k-1)*dimp+j,i) = s_ijk;

                coeffnts_decvar((ind_k-1)*dimp+i,j) = s_ijk_decvar;
                coeffnts_decvar((ind_k-1)*dimp+j,i) = s_ijk_decvar;
            end
        end
    end

    % Constructing At and b matrices
    At = sparse(decvarnum,size(Z,1)*dimp^2);
    if decvarnum>0
        for i=1:nmon
            Mivec = reshape(coeffnts_decvar((i-1)*dimp+1:i*dimp,:),dimp^2,1);
            At(:,(i-1)*dimp^2+1:i*dimp^2) = sparse(-double(jacobian(Mivec,decvartable))');
        end
    end
    b = sparse(coeffnts);

else
    % PJS: Original Code to Handle Symbolic Objects

    if strcmp(decvartable,'[]');
        decvarnum = 0;
    else
        decvarnum = length(find(decvartable == ','))+1;
    end;
    expr = evalin(symengine,symexpr);
    %vartable = evalin(symengine,vartable);
    if  length(varmat)==2
        vartable = evalin(symengine,vartable);
    else
        vartable = evalin(symengine,[vartable(1:end-1),',',varmat(2:end)]);  %JA&GV 07/06/13
    end

    decvartable = evalin(symengine,decvartable);
    charvartable = converttochar([vartable]);

    FPexpr = feval(symengine,'expand',expr);

    %JA&GV 07/13 commented the below to implement the matrix case
    %FPexpr = feval(symengine,'collect',FPexpr,charvartable);

    dimp = size(FPexpr,2);%JA&GV jul/04/2013 sets the dimension of the matrix of polynomials

    for i = 1:size(FPexpr,1)
        for j = 1:dimp
            FPexpr(i,j) = feval(symengine,'collect',FPexpr(i,j),charvartable);
        end
    end

    if isempty(decvartable)==0%JA&GV 07/13 the code below  addresses the matrix case

        Zfull = [];
        for i = 1:dimp
            for j = i:dimp
                coefmon = feval(symengine,'poly2list',FPexpr(i,j),charvartable);
                coefmonmatr = subs(coefmon.',decvartable,zeros(1,length(decvartable)));
                Z = double(coefmonmatr(:,2:end));
                Zfull = sortNoRepeat(Zfull,Z);
            end
        end
        Z = Zfull;
        [nmon,nvar] = size(Z);
        coeffnts = sparse(nmon*dimp,dimp);
        coeffnts_decvar = sym(sparse(nmon*dimp,dimp));

        for i = 1:dimp
            for j = i:dimp
                coefmon = feval(symengine,'poly2list',FPexpr(i,j),charvartable);
                coefmonmatr = subs(coefmon.',decvartable,zeros(1,length(decvartable)));
                for k = 1:size(coefmonmatr,1)
                    s_ijk = coefmonmatr(k,1);

                    dummy_decvar = reshape(coefmon(k),2,1);
                    s_ijk_decvar = dummy_decvar;

                    mon_k= double(coefmonmatr(k,2:end));
                    [val,ind_k] = max(sum((Zfull == kron(ones(nmon,1),mon_k)),2));
                    coeffnts((ind_k-1)*dimp+i,j) = s_ijk;
                    coeffnts((ind_k-1)*dimp+j,i) = s_ijk;

                    coeffnts_decvar((ind_k-1)*dimp+i,j) = s_ijk_decvar;
                    coeffnts_decvar((ind_k-1)*dimp+j,i) = s_ijk_decvar;

                end

            end
        end

    else%JA&GV 07/2013 the code below  addresses the matrix case

        Zfull = [];
        for i = 1:dimp
            for j = i:dimp
                coefmon = feval(symengine,'poly2list',FPexpr(i,j),charvartable);
                coefmon = coefmon.';
                for k = 1:length(coefmon)
                    dummyvar = reshape(coefmon(k),2,1);
                    Z(k,:) = double(dummyvar(2));
                end
                Zfull = sortNoRepeat(Zfull,Z);
                Z = [];
            end
        end
        Z = sparse(Zfull);
        [nmon,nvar] = size(Z);
        coeffnts = sparse(nmon*dimp,dimp);

        for i = 1:dimp
            for j = i:dimp
                coefmon = feval(symengine,'poly2list',FPexpr(i,j),charvartable);
                coefmon = coefmon.';
                for k = 1:length(coefmon)
                    dummyvar = reshape(coefmon(k),2,1);
                    s_ijk = double(dummyvar(1));
                    mon_k= double(dummyvar(2));
                    [val,ind_k] = max(sum((Zfull == kron(ones(nmon,1),mon_k))'));
                    coeffnts((ind_k-1)*dimp+i,j) = s_ijk;
                    coeffnts((ind_k-1)*dimp+j,i) = s_ijk;
                end
            end
        end

    end

    % Constructing At and b matrices
    At = sparse(decvarnum,size(Z,1)*dimp^2);

    %JA&GV may/2013 uses the jacobian function to derive the expression
    if isempty(decvartable)==0
        for i = 1:size(Z,1)
            Mivec = reshape(coeffnts_decvar((i-1)*dimp+1:i*dimp,:),dimp^2,1);
            At(:,(i-1)*dimp^2+1:i*dimp^2) = sparse(-double(jacobian(Mivec,decvartable))');
        end
    end

    b = sparse(coeffnts);
end


%% FUNCTION Logistic_Lasso
%   Sparse Structure-Regularized Learning with Logistic Loss.
%
%% OBJECTIVE
%   argmin_{W,C} { sum_i^t (- sum(log (1./ (1+ exp(-X{i}*W(:, i) - Y{i} .* C(i)))))/length(Y{i}))
%            + rho1 * \|W\|_1 + opts.rho_L2 * \|W\|_F^2}
%
%% INPUT
%   X: {n * d} * t - input matrix
%   Y: {n * 1} * t - output matrix
%   rho1: sprasity controlling parameter
%   opts.rho_L2: L2-norm regularization parameter
%
%% OUTPUT
%   W: model: d * t
%   C: model: 1 * t
%   funcVal: function value vector.
%
%% LICENSE
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   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, see <http://www.gnu.org/licenses/>.
%
%   Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye
%
%   You are suggested to first read the Manual.
%   For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu
%
%   Last modified on June 3, 2012.
%
%% Related papers
%
%   [1] Tibshirani, J. Regression shrinkage and selection via
%   the Lasso, Journal of the Royal Statistical Society. Series B 1996
%
%% Related functions
%   Least_Lasso, init_opts

%% Code starts here
function [W, C, funcVal] = Logistic_Lasso(X, Y, rho1, opts)

if nargin <3
    error('\n Inputs: X, Y, and rho1 should be specified!\n');
end
X = multi_transpose(X);

if nargin <4
    opts = [];
end

% initialize options.
opts=init_opts(opts);

if isfield(opts, 'rho_L2')
    rho_L2 = opts.rho_L2;
else
    rho_L2 = 0;
end

task_num  = length (X);
dimension = size(X{1}, 1);
funcVal = [];

%initialize a starting point
C0_prep = zeros(1, task_num);
for t_idx = 1: task_num
    m1 = nnz(Y{t_idx} == 1);
    m2 = nnz(Y{t_idx} == -1);
    if ( m1==0 || m2==0 )
        C0_prep(t_idx) = 0;
    else
        C0_prep(t_idx) = log(m1/m2);
    end
end

if opts.init==2
    W0 = zeros(dimension, task_num);
    %C0 = zeros(1, task_num);
    C0 = C0_prep;
elseif opts.init== 0
    W0 = randn(dimension, task_num);
    C0 = C0_prep;
else
    if isfield(opts,'W0')
        W0=opts.W0;
        if (nnz(size(W0)-[dimension, task_num]))
            error('\n Check the input .W0');
        end
    else
        W0 = zeros(dimension, task_num);
    end
    if isfield(opts,'C0')
        C0=opts.C0;
    else
        C0=C0_prep;
    end
end

bFlag=0; % this flag tests whether the gradient step only changes a little

Wz= W0;
Cz= C0;
Wz_old = W0;
Cz_old = C0;

t = 1;
t_old = 0;
iter = 0;
gamma = 1;
gamma_inc = 2;

while iter < opts.maxIter
    alpha = (t_old - 1) /t;

    Ws = (1 + alpha) * Wz - alpha * Wz_old;
    Cs = (1 + alpha) * Cz - alpha * Cz_old;

    %Ws = Wz;
    %Cs = Cz;

    % compute function value and gradients of the search point
    [gWs, gCs, Fs ]  = gradVal_eval(Ws, Cs);

    % the Armijo Goldstein line search scheme
    while true
        [Wzp l1c_wzp] = l1_projection(Ws - gWs/gamma, 2 * rho1 / gamma);
        Czp = Cs - gCs/gamma;
        Fzp = funVal_eval  (Wzp, Czp);

        delta_Wzp = Wzp - Ws;
        delta_Czp = Czp - Cs;
        nrm_delta_Wzp = norm(delta_Wzp, 'fro')^2;
        nrm_delta_Czp = norm(delta_Czp, 'fro')^2;
        r_sum = (nrm_delta_Wzp+nrm_delta_Czp)/2;

        %         Fzp_gamma = Fs + trace(delta_Wzp' * gWs)...
        %             + trace(delta_Czp' * gCs)...
        %             + gamma/2 * nrm_delta_Wzp ...
        %             + gamma/2 * nrm_delta_Czp;

        Fzp_gamma = Fs + sum(sum(delta_Wzp .* gWs))...
            + sum(sum(delta_Czp .* gCs))...
            + gamma/2 * nrm_delta_Wzp ...
            + gamma/2 * nrm_delta_Czp;

        if (r_sum <=1e-20)
            bFlag=1; % this shows that, the gradient step makes little improvement
            break;
        end

        if (Fzp <= Fzp_gamma)
            break;
        else
            gamma = gamma * gamma_inc;
        end
    end

    Wz_old = Wz;
    Cz_old = Cz;
    Wz = Wzp;
    Cz = Czp;

    funcVal = cat(1, funcVal, Fzp + rho1 * l1c_wzp);

    if (bFlag)
        % fprintf('\n The program terminates as the gradient step changes the solution very small.');
        break;
    end

    % test stop condition.
    switch(opts.tFlag)
        case 0
            if iter>=2
                if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)
                    break;
                end
            end
        case 1
            if iter>=2
                if (abs( funcVal(end) - funcVal(end-1) ) <=...
                        opts.tol* funcVal(end-1))
                    break;
                end
            end
        case 2
            if ( funcVal(end)<= opts.tol)
                break;
            end
        case 3
            if iter>=opts.maxIter
                break;
            end
    end

    iter = iter + 1;
    t_old = t;
    t = 0.5 * (1 + (1+ 4 * t^2)^0.5);

end

W = Wzp;
C = Czp;

% private functions

    function [z, l1_comp_val] = l1_projection (v, beta)
        % this projection calculates
        % argmin_z = \|z-v\|_2^2 + beta \|z\|_1
        % z: solution
        % l1_comp_val: value of l1 component (\|z\|_1)

        z = sign(v).*max(0,abs(v)- beta/2);

        l1_comp_val = sum(sum(abs(z)));
    end

    function [grad_W, grad_C, funcVal] = gradVal_eval(W, C)
        grad_W = zeros(dimension, task_num);
        grad_C = zeros(1, task_num);
        lossValVect = zeros (1 , task_num);

        for i = 1:task_num
            [ grad_W(:, i), grad_C(:, i), lossValVect(:, i)] = unit_grad_eval( W(:, i), C(i), X{i}, Y{i});
        end

        grad_W = grad_W + rho_L2 * 2 * W;
        % here when computing function value we do not include
        % l1 norm.
        funcVal = sum(lossValVect) + rho_L2 * norm(W, 'fro')^2;
    end

    function [funcVal] = funVal_eval (W, C)
        funcVal = 0;
        for i = 1: task_num
            funcVal = funcVal + unit_funcVal_eval( W(:, i), C(i), X{i}, Y{i});
        end

        % here when computing function value we do not include
        % l1 norm.
        funcVal = funcVal + rho_L2 * norm(W, 'fro')^2;
    end

end

function [ grad_w, grad_c, funcVal ] = unit_grad_eval( w, c, x, y)
%gradient and logistic evaluation for each task
m = length(y);
weight = ones(m, 1)/m;
weighty = weight.* y;
aa = -y.*(x'*w + c);
bb = max( aa, 0);
%funcVal = weight' * log(exp(-bb) + exp(aa-bb) + bb); %bug!!!
funcVal = weight'* ( log( exp(-bb) +  exp(aa-bb) ) + bb );
pp = 1./ (1+exp(aa));
b = -weighty.*(1-pp);
grad_c = sum(b);
grad_w = x * b;
end

function [ funcVal ] = unit_funcVal_eval( w, c, x, y)
%function value evaluation for each task
m = length(y);
weight = ones(m, 1)/m;
aa = -y.*(x'*w + c);
bb = max( aa, 0);
%funcVal = weight' * log(exp(-bb) + exp(aa-bb) + bb); % BUG!!!!
funcVal = weight'* ( log( exp(-bb) +  exp(aa-bb) ) + bb );
end


% Test file for trigtech/any.m.

function pass = test_any(pref)

if ( nargin < 1 )
    pref = trigtech.techPref();
end

testclass = trigtech();

% Check behavior for any() down columns.
pass(1) = ~any(testclass);

f = testclass.make(@(x) [sin(pi*x) 0*x cos(pi*x)]);
pass(2) = isequal(any(f), [1 0 1]);

% Check behavior for any() across rows.
g = any(f, 2);
pass(3) = isequal(g.coeffs, 1);

f = testclass.make(@(x) [0*x 0*x]);
g = any(f, 2);
pass(4) = isequal(g.coeffs, 0);

end


% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).
% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)
% Copyright: ETH Zurich, 2014
% Author: Romano Cicchetti

% parameters
dataset = 'thun';
granularity = 1;
appliance_name = 'Laptop';
households = [2];
dates = ['2012-07-01'];
start_date = '2012-07-01';
end_date = '2012-07-01';
consumptionArray = zeros((24*60*60)/granularity,5);

% obtain consumption data
appliance_id =  getApplianceID(appliance_name);
houses = intersect(findHouseholds(appliance_id), households);
numOfDaysPerHousehold = zeros(length(houses), 1);
counter = 0;
for house = houses
    consumption = read_plug_data(dataset, house, appliance_id, dates, granularity );
    counter = counter + 1;
    consumptionArray(1:length(consumption),counter) = consumption;
end

% plot consumption data
f = figure();
startDate = datenum(strcat(start_date, ' 00:00:00'));
endDate = datenum(strcat(end_date, ' 23:59:59'));
timeTics = linspace(startDate,endDate,86400/granularity);
plot(timeTics, consumptionArray);
datetickzoom('x', 'HH:MM');
ylabel('Power [W]');
xlabel('Time of day');
%legend('Household 1', 'Household 2', 'Household 4', 'Household 5', 'Household 6');
grid on;
%title(sprintf('Power Consumption of %s', appliance_name));
axis tight;


function [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
    = cornk(fid, data, varargins, opts)
% This program starts the CORN-K algorithm
% CORN-K is a top-K combination of CORN experts
%
% function [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ....
%           = cornk_start(fid, data, varargins, opts)
%
% cum_ret: a number representing the final cumulative wealth.
% cumprod_ret: cumulative return until each trading period
% daily_ret: individual returns for each trading period
% daily_portfolio: individual portfolio for each trading period
%
% data: market sequence vectors
% fid: handle for write log file
% varargins: variable parameters
% opts: option parameter for behvaioral control
%
% Example: [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
%          = cornk_start(fid, data, {5, 10, 0.1, 0}, opts);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Bin LI, Steven C.H. Hoi
% Contributors:
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Extract the parameters
K  = varargins{1};
L  = varargins{2};
pc  = varargins{3};      % percentage of top-k
tc = varargins{4};      % transaction cost fee rate

% Run the CORN-K algorithm
[cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
    = cornk_run(fid, data, K, L, pc, tc, opts);

end


function fgsegment = dtiFiberExcludeDiscontinuous(fg, threshold)

% Remove the fascicles which has discontinuity by VOI-based fiber clipping
%
% Sometimes we create fascicles/streamlines which is discontinuous when we
% clip the fascicles using VOI/ROI (e.g. feConnectomeClip.m in LiFE). This function
% excludes the discontinuous fascicles from the connectome.
%
% INPUT:
% fg: fg structure for input
% threshold: If the nodal spacing exceeds this threshold, the fascicle will
%           be removed
%
% (C) Hiromasa Takemura, 2015 CiNet HHS/Stanford Vista Team

% The matrix to define fascicles to exclude
fascicletoremove = ones(length(fg.fibers),1);

for i=1:length(fg.fibers)

    x = fg.fibers{i}(1,:);
    y = fg.fibers{i}(2,:);
    z = fg.fibers{i}(3,:);

    try
        % Compute the 3d distance on each node
        for k=1:(length(x)-1)
            nodalspace(k) = sqrt((x(k+1)-x(k))^2 + (y(k+1)-y(k))^2 + (z(k+1)-z(k))^2);

            % Remove fascicles when the nodal spacing exceeds the threshold
            if nodalspace(k) > threshold
                fascicletoremove(i) = 0;
            end

        end

    catch
        % Remove fascicles if the code could not execute the process above
        % This happens when fascicle only contains one node as a consequence of the
        % clipping
        fascicletoremove(i) = 0;

    end
    clear nodalspace x y z k

end

% Remove fascicles having longer nodal spacing
fgsegment = fgExtract(fg, logical(fascicletoremove), 'keep');


function [eV] = Nm2eV(Nm)
% Convert energy or work from newton-meters to electron volts.
% Chad A. Greene 2012
eV = Nm*6241506480000000000;


function result = analyzeHardStop(debug, ground_truth, tFailure_s, PerformanceSpec)

% Author: Alexander Wischnewski     Date: 24-02-2019
%
% Description:
%   scans the debug data and ground truth whether a hard stop
%   was performed within the given specifications
%
% Input:
%   debug:          Debug structure of the vehicle
%   ground_truth:   Physical ground truth data from simulation
%   tFailure_s:     Timestamp where the failure occured
%   PerformanceSpec Structure with fields:
%       AccxMin_mps2        Minimum mean negative acceleration applied until vehicle
%                           stops
%       tDetectionMax_s     Maximum time to detect the hard stop
%
% Outputs:
%   result:       1 if a valid emergency stop was detected, 0 otherwise

result = 1;

disp(' ');
disp('------------------------------');
disp('Check Hard Stop: ');
disp('------------------------------');
% find timestamp where vehicle has gone to hard stop
idxDetect = find(uint16(debug.debug_mloc_statemachine_debug_TUMVehicleState.Data) == 60, 1);
if isempty(idxDetect)
    disp('The vehicle did not detect the hard stop');
    result = 0;
    return
else
    tFailuredDetected_s = debug.debug_mloc_statemachine_debug_TUMVehicleState.Time(idxDetect);
    disp(['The vehicle took ' num2str(tFailuredDetected_s - tFailure_s) ' s to detect the failure.']);
end
% check if fault detection time was within spec
if(tFailuredDetected_s <= 0 && tFailuredDetected_s >= PerformanceSpec.tDetectionMax_s)
    disp('The vehicle did not detect the emergency within the specified time');
    result = 0;
    return
end
% find point where failure was detected
idxDetect_gt = find(ground_truth.SimRealState_ax_mps2.Time > tFailuredDetected_s, 1);
% find timestamp where velocity has gone to new stopped
% for very low velocites, the stop controller does not behave precisly in
% sim, therefore its tested against roughly 5kph.
idxStop = find(ground_truth.SimRealState_vx_mps.Data(idxDetect_gt:end) < 2, 1) + idxDetect_gt;
if isempty(idxStop)
    disp('The vehicle did not stop.');
    result = 0;
    return
else
    tStop_s = ground_truth.SimRealState_vx_mps.Time(idxStop);
    disp(['The vehicle took ' num2str(tStop_s - tFailure_s) ' s to stop.']);
end
% check if control performance was ok
meanAccX = mean(ground_truth.SimRealState_ax_mps2.Data(idxDetect_gt:idxStop));
disp(['The mean longitudinal accleeration was: ' num2str(meanAccX)]);
if(meanAccX > PerformanceSpec.AccxMin_mps2)
    disp('The vehicle did not stay within the specified deceleration bounds.');
    result = 0;
    return
end

disp(' ');
disp('All checks passed.');


% The COBRAToolbox: testDetectDeadEnds.m
%
% Purpose:
%     - Tests whether all dead ends are correctly determined from a given
%       model
%
% Authors:
%     - Thomas Pfau, April 2017
%     - CI integration: Laurent Heirendt

% save the current path
currentDir = pwd;

% The testmodel used is structured as follows:
%
%   <=> A -> F ---> H <=> J ->
%        \     /          ^
%         -> E            |
%            | \          L
%            v   -> I     |
%   <=> B -> D       \    v
%        \             -> K <=>
%         -> G <=>
%   <=> C
% Thus, C, D, and L are dead ends, and C is also an exchanged metabolite
% and should thus be detected by removeExternalMets set to true.

fileDir = fileparts(which('testDetectDeadEnds'));
cd(fileDir);

% load the test models
load('DeadEndTestModel','model')

%Determine all dead end metabolites
[mets] = detectDeadEnds(model);
assert(all(ismember(model.mets(mets),{'D','L','C'})));

%When detectDeadEnds is changed according to Ronans suggestion, we need to test
%multiple solvers.
solverPkgs = {'gurobi', 'tomlab_cplex', 'glpk'};

for k = 1:length(solverPkgs)

    % set the solver
    solverOK = changeCobraSolver(solverPkgs{k}, 'LP', 0);

    if solverOK == 1

        %Only determine those, which are not involved in an exchange reaction
        [mets] = detectDeadEnds(model,1);
        assert(all(ismember(model.mets(mets),{'D','L'})));
    end
end
%Clean up after test
clear mets
clear model

cd(currentDir)


function [varargout] = dcopf(varargin)
%DCOPF  Solves a DC optimal power flow.
%   This is a simple wrapper function around OPF that sets the 'model'
%   option to 'DC' before calling OPF.
%   See OPF for the details of input and output arguments.
%
%   See also RUNDCOPF.

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

[mpc, mpopt] = opf_args(varargin{:});
mpopt = mpoption(mpopt, 'model', 'DC');
[varargout{1:nargout}] = opf(mpc, mpopt);


function sparse_grid_mixed_write ( dim_num, rule, alpha, beta, point_num, ...
  sparse_weight, sparse_point, file_name )

%*****************************************************************************80
%
%% SPARSE_GRID_MIXED_WRITE writes a sparse grid rule to five files.
%
%  Discussion:
%
%    The files are:
%    * the "A" file stores the ALPHA values, as a DIM_NUM x 1 list.
%    * the "B" file stores the BETA values, as a DIM_NUM x 1 list.
%    * the "R" file stores the region, as a DIM_NUM x 2 list.
%    * the "W" file stores the weights as a POINT_NUM list;
%    * the "X" file stores the abscissas as a DIM_NUM x POINT_NUM list;
%
%    The entries in the "R" file are the two corners of the DIM_NUM dimensional
%    rectangle that constitutes the integration region.  Coordinates that
%    should be infinite are set to 1.0E+30.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 March 2011
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Fabio Nobile, Raul Tempone, Clayton Webster,
%    A Sparse Grid Stochastic Collocation Method for Partial Differential
%    Equations with Random Input Data,
%    SIAM Journal on Numerical Analysis,
%    Volume 46, Number 5, 2008, pages 2309-2345.
%
%  Parameters:
%
%    Input, int DIM_NUM, the spatial dimension.
%
%    Input, integer RULE(DIM_NUM), the rule in each dimension.
%     1, "CC",  Clenshaw Curtis, Closed Fully Nested rule.
%     2, "F2",  Fejer Type 2, Open Fully Nested rule.
%     3, "GP",  Gauss Patterson, Open Fully Nested rule.
%     4, "GL",  Gauss Legendre, Open Weakly Nested rule.
%     5, "GH",  Gauss Hermite, Open Weakly Nested rule.
%     6, "GGH", Generalized Gauss Hermite, Open Weakly Nested rule.
%     7, "LG",  Gauss Laguerre, Open Non Nested rule.
%     8, "GLG", Generalized Gauss Laguerre, Open Non Nested rule.
%     9, "GJ",  Gauss Jacobi, Open Non Nested rule.
%    10, "GW",  Golub Welsch, (presumed) Open Non Nested rule.
%    11, "CC_SE", Clenshaw Curtis Slow Exponential, Closed Fully Nested rule.
%    12, "F2_SE", Fejer Type 2 Slow Exponential, Closed Fully Nested rule.
%    13, "GP_SE", Gauss Patterson Slow Exponential, Closed Fully Nested rule.
%    14, "CC_ME", Clenshaw Curtis Moderate Exponential, Closed Fully Nested rule.
%    15, "F2_ME", Fejer Type 2 Moderate Exponential, Closed Fully Nested rule.
%    16, "GP_ME", Gauss Patterson Moderate Exponential, Closed Fully Nested rule.
%    17, "CCN", Clenshaw Curtis Nested, Linear, Closed Fully Nested rule.
%
%    Input, real ALPHA(DIM_NUM), BETA(DIM_NUM), parameters used for
%    Generalized Hermite, Generalized Laguerre, and Jacobi rules.
%
%    Input, int POINT_NUM, the number of points in the grid.
%
%    Input, real SPARSE_WEIGHT(POINT_NUM), the weights.
%
%    Input, real SPARSE_POINT(DIM_NUM,POINT_NUM), the points.
%
%    Input, string FILE_NAME, the main part of the file name.
%
  for dim = 1 : dim_num
    if ( rule(dim) == 1 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 2 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 3 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 4 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 5 )
      sparse_region(dim,1) = - r8_huge ( );
      sparse_region(dim,2) = + r8_huge ( );
    elseif ( rule(dim) == 6 )
      sparse_region(dim,1) = - r8_huge ( );
      sparse_region(dim,2) = + r8_huge ( );
    elseif ( rule(dim) == 7 )
      sparse_region(dim,1) = 0.0;
      sparse_region(dim,2) = r8_huge ( );
    elseif ( rule(dim) == 8 )
      sparse_region(dim,1) = 0.0;
      sparse_region(dim,2) = r8_huge ( );
    elseif ( rule(dim) == 9 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 10 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'SPARSE_GRID_MIXED_WRITE - Fatal error!\n' );
      fprintf ( 1, '  Do not know how to specify region for rules of type 10.\n');
      error ( 'SPARSE_GRID_MIXED_WRITE - Fatal error!' );
    elseif ( rule(dim) == 11 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 12 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 13 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 14 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 15 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 16 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    elseif ( rule(dim) == 17 )
      sparse_region(dim,1) = -1.0;
      sparse_region(dim,2) = +1.0;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'SPARSE_GRID_MIXED_WRITE - Fatal error!\n' );
      fprintf ( 1, '  Unexpected value of RULE = %d\n', rule(dim) );
      error ( 'SPARSE_GRID_MIXED_WRITE - Fatal error!' );
    end
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPARSE_GRID_MIXED_WRITE:\n' );

  file_name_a = strcat ( file_name, '_a.txt' );
  r8mat_write ( file_name_a, dim_num, 1, alpha );
  fprintf ( 1, '  Wrote the A file = "%s".\n', file_name_a );

  file_name_b = strcat ( file_name, '_b.txt' );
  r8mat_write ( file_name_b, dim_num, 1, beta );
  fprintf ( 1, '  Wrote the B file = "%s".\n', file_name_b );

  file_name_r = strcat ( file_name, '_r.txt' );
  r8mat_write ( file_name_r, dim_num, 2, sparse_region );
  fprintf ( 1, '  Wrote the R file = "%s".\n', file_name_r );

  file_name_w = strcat ( file_name, '_w.txt' );
  r8mat_write ( file_name_w, 1, point_num, sparse_weight );
  fprintf ( 1, '  Wrote the W file = "%s".\n', file_name_w );

  file_name_x = strcat ( file_name, '_x.txt' );
  r8mat_write ( file_name_x, dim_num, point_num, sparse_point );
  fprintf ( 1, '  Wrote the X file = "%s".\n', file_name_x );

  return
end


function L = ivmLogLikelihood(model, x, y);

% IVMLOGLIKELIHOOD Return the log-likelihood for the IVM.
% FORMAT
% DESC computes the log likelihood of the given data points under
% the IVM and the given noise model.
% ARG model : the model for which the log likelihood is computed.
% ARG x : the input locations.
% ARG y : the target values.
%
% SEEALSO : ivmNegLogLikelihood, ivmPosteriorMeanVar,
% noiseLogLikelihood
%
% COPYRIGHT : Neil D. Lawrence

% IVM

if nargin < 3
  % This implies evaluate for the training data.
  mu = model.mu;
  varsigma = model.varSigma;
  y = model.y;
else
  [mu, varsigma] = ivmPosteriorMeanVar(model, x);
end

L = noiseLogLikelihood(model.noise, mu, varsigma, y);

% check if there is a prior over kernel parameters
if isfield(model.kern, 'priors')
  fhandle = str2func([model.kern.type 'KernExpandParams']);
  params = fhandle(model.kern);
  for i = 1:length(model.kern.priors)
    index = model.kern.priors(i).index;
    L = L + priorLogProb(model.kern.priors(i), params(index));
  end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is a demo execution of ECC image alignment algorithm
% It shows results in the case of a partial overlap and shows
% how the algortihm refines the results of feature-based matching
%
%
% 20/2/2013, Georgios Evangelidis, georgios.evangelidis@inria.fr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

transform = 'homography';

NoI = 20; % number of iterations
NoL = 1;  % number of pyramid-levels

im_demo=imread('wallImage.png'); % ... or try your image

[A,B,C]=size(im_demo);

if C==3
    im_demo=rgb2gray(im_demo);
end
imu8 = im_demo;

im_demo=double(im_demo);

template_demo = imread('wallTemplate.png');
[A2, B2, C2] = size(template_demo);

if C2==3
    template_demo = rgb2gray(template_demo);
end
tempu8 = template_demo;
template_demo = double (template_demo);

%initialization by feature-based matching (use 1 iteration to see the
%initial registration)
    init = [0.7 -0.6 -34;
        0.7 0.8 -70;
        0.001 -0.001 1];

%call ECC
[results, final_warp, warped_image]=ecc(im_demo, template_demo, NoL, NoI, transform, init);
mask = spatial_interp(ones(A,B),final_warp, 'linear', transform, 1:B2, 1:A2);

figure; imshow(imu8);title('Input Image');
figure; imshow(tempu8); title('Template Image');
figure; imshow(uint8(warped_image)); title('Final Warped Image');

clear align1 align2;

% alignment based on initial warp
warped_init = spatial_interp(im_demo, init, 'linear', transform, 1:B2, 1:A2);
align1 = double(tempu8).*mask;
align1(:,:,2) = double(warped_init).*mask;
align1(:,:,3) = double(tempu8).*mask;
figure;imshow(uint8(align1)); title('Initial alignment');

% alignment based on final warp
align2 = align1;
align2(:,:,2) = double(warped_image).*mask;
figure;imshow(uint8(align2)); title('Final alignment');


%%*****************************************************************************
%% HSDsqlp: solve an semidefinite-quadratic-linear program
%%   by infeasible path-following method on the homogeneous self-dual model.
%%
%%  [obj,X,y,Z,info,runhist] =
%%      HSDsqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);
%%
%%  Input: blk: a cell array describing the block diagonal structure of SQL data.
%%          At: a cell array with At{p} = [svec(Ap1) ... svec(Apm)]
%%         b,C: data for the SQL instance.
%%     OPTIONS: a structure that specifies parameters required in HSDsqlp.m,
%%              (if it is not given, the default in sqlparameters.m is used).
%%
%%  (X0,y0,Z0): an initial iterate (if it is not given, the default is used).
%%
%%  Output: obj  = [<C,X> <b,y>].
%%          (X,y,Z): an approximately optimal solution or a primal or dual
%%                   infeasibility certificate.
%%          info.termcode = termination-code
%%          info.iter     = number of iterations
%%          info.obj      = [primal-obj, dual-obj]
%%          info.cputime  = total-time
%%          info.gap      = gap
%%          info.pinfeas  = primal_infeas
%%          info.dinfeas  = dual_infeas
%%          runhist.pobj    = history of primal objective value.
%%          runhist.dobj    = history of dual   objective value.
%%          runhist.gap     = history of <X,Z>.
%%          runhist.pinfeas = history of primal infeasibility.
%%          runhist.dinfeas = history of dual   infeasibility.
%%          runhist.cputime = history of cputime spent.
%%----------------------------------------------------------------------------
%%  The OPTIONS structure specifies the required parameters:
%%      vers  gam  predcorr  expon  gaptol  inftol  steptol
%%      maxit  printlevel  ...
%%      (all have default values set in sqlparameters.m).
%%
%%*************************************************************************
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************

function [obj,X,y,Z,info,runhist] = ...
    HSDsqlp(blk,At,C,b,OPTIONS,X0,y0,Z0,kap0,tau0,theta0)

if (nargin < 5); OPTIONS = []; end

isemptyAtb = 0;
if isempty(At) && isempty(b);
    %% Add redundant constraint: <-I,X> <= 0
    b = 0;
    At = ops(ops(blk,'identity'),'*',-1);
    numblk = size(blk,1);
    blk{numblk+1,1} = 'l'; blk{numblk+1,2} = 1;
    At{numblk+1,1} = 1; C{numblk+1,1} = 0;
    isemptyAtb = 1;
end
%%
%%-----------------------------------------
%% get parameters from the OPTIONS structure.
%%-----------------------------------------
%%
% warning off;

matlabversion = sscanf(version,'%f');
if strcmp(computer,'PCWIN64') || strcmp(computer,'GLNXA64')
    par.computer = 64;
else
    par.computer = 32;
end
par.matlabversion = matlabversion(1);
par.vers        = 0;
par.predcorr    = 1;
par.gam         = 0;
par.expon       = 1;
par.gaptol      = 1e-8;
par.inftol      = 1e-8;
par.steptol     = 1e-6;
par.maxit       = 100;
par.printlevel  = 3;
par.stoplevel   = 1;
par.scale_data  = 0;
par.spdensity   = 0.4;
par.rmdepconstr = 0;
par.smallblkdim = 50;
par.schurfun     = cell(size(blk,1),1);
par.schurfun_par = cell(size(blk,1),1);
%%
parbarrier  = cell(size(blk,1),1);
for p = 1:size(blk,1)
    pblk = blk(p,:);
    if strcmp(pblk{1},'s') || strcmp(pblk{1},'q')
        parbarrier{p} = zeros(1,length(pblk{2}));
    elseif strcmp(pblk{1},'l') || strcmp(pblk{1},'u' )
        parbarrier{p} = zeros(1,sum(pblk{2}));
    end
end
parbarrier_0 = parbarrier;
%%
if nargin > 4,
    if isfield(OPTIONS,'vers');        par.vers     = OPTIONS.vers; end
    if isfield(OPTIONS,'predcorr');    par.predcorr = OPTIONS.predcorr; end
    if isfield(OPTIONS,'gam');         par.gam      = OPTIONS.gam; end
    if isfield(OPTIONS,'expon');       par.expon    = OPTIONS.expon; end
    if isfield(OPTIONS,'gaptol');      par.gaptol   = OPTIONS.gaptol; end
    if isfield(OPTIONS,'inftol');      par.inftol   = OPTIONS.inftol; end
    if isfield(OPTIONS,'steptol');     par.steptol  = OPTIONS.steptol; end
    if isfield(OPTIONS,'maxit');       par.maxit    = OPTIONS.maxit; end
    if isfield(OPTIONS,'printlevel');  par.printlevel  = OPTIONS.printlevel; end
    if isfield(OPTIONS,'stoplevel');   par.stoplevel   = OPTIONS.stoplevel; end
    if isfield(OPTIONS,'scale_data');  par.scale_data  = OPTIONS.scale_data; end
    if isfield(OPTIONS,'spdensity');   par.spdensity   = OPTIONS.spdensity; end
    if isfield(OPTIONS,'rmdepconstr'); par.rmdepconstr = OPTIONS.rmdepconstr; end
    if isfield(OPTIONS,'smallblkdim'); par.smallblkdim = OPTIONS.smallblkdim; end
    if isfield(OPTIONS,'parbarrier');
        parbarrier = OPTIONS.parbarrier;
        if isempty(parbarrier); parbarrier = parbarrier_0; end
        if ~iscell(parbarrier);
            tmp = parbarrier; clear parbarrier; parbarrier{1} = tmp;
        end
        if (length(parbarrier) < size(blk,1))
            len = length(parbarrier);
            parbarrier(len+1:size(blk,1)) = parbarrier_0(len+1:size(blk,1));
        end
    end
    if isfield(OPTIONS,'schurfun');
        par.schurfun = OPTIONS.schurfun;
        if ~isempty(par.schurfun); par.scale_data = 0; end
    end
    if isfield(OPTIONS,'schurfun_par'); par.schurfun_par = OPTIONS.schurfun_par; end
    if isempty(par.schurfun);     par.schurfun = cell(size(blk,1),1); end
    if isempty(par.schurfun_par); par.schurfun_par = cell(size(blk,1),1); end
end
if (size(blk,2) > 2); par.smallblkdim = 0; end
%%
%%-----------------------------------------
%% convert matrices to cell arrays.
%%-----------------------------------------
%%
if ~iscell(At); At = {At}; end;
if ~iscell(C);  C = {C}; end;
if all(size(At) == [size(blk,1), length(b)]);
    convertyes = zeros(size(blk,1),1);
    for p = 1:size(blk,1)
        if strcmp(blk{p,1},'s') && all(size(At{p,1}) == sum(blk{p,2}))
            convertyes(p) = 1;
        end
    end
    if any(convertyes)
        if (par.printlevel);
            fprintf('\n sqlp: converting At into required format');
        end
        At = svec(blk,At,ones(size(blk,1),1));
    end
end
%%
%%-----------------------------------------
%% validate SQLP data.
%%-----------------------------------------
%%
% tstart = cputime;
[blk,At,C,b,blkdim,numblk] = validate(blk,At,C,b,par);
[blk,At,C,b,iscmp] = convertcmpsdp(blk,At,C,b);
if (iscmp) && (par.printlevel>=2)
    fprintf('\n SQLP has complex data');
end
if (nargin <= 5) || (isempty(X0) || isempty(y0) || isempty(Z0));
    if (max([ops(At,'norm'),ops(C,'norm'),norm(b)]) > 1e2)
        [X0,y0,Z0] = infeaspt(blk,At,C,b,1);
    else
        [X0,y0,Z0] = infeaspt(blk,At,C,b,2,1);
    end
end
if ~iscell(X0);  X0 = {X0}; end;
if ~iscell(Z0);  Z0 = {Z0}; end;
if (length(y0) ~= length(b))
    error('HSDsqlp: length of b and y0 not compatible');
end
[X0,Z0] = validate_startpoint(blk,X0,Z0,par.spdensity);
%%
if (nargin <= 8) || (isempty(kap0) || isempty(tau0) || isempty(theta0))
    if (max([ops(At,'norm'),ops(C,'norm'),norm(b)]) > 1e6)
        kap0 = 10*blktrace(blk,X0,Z0);
    else
        kap0 = blktrace(blk,X0,Z0);
    end
    tau0 = 1; theta0 = 1;
end
%%
if (par.printlevel>=2)
    fprintf('\n num. of constraints = %2.0d',length(b));
    if blkdim(1);
        fprintf('\n dim. of sdp    var  = %2.0d,',blkdim(1));
        fprintf('   num. of sdp  blk  = %2.0d',numblk(1));
    end
    if blkdim(2);
        fprintf('\n dim. of socp   var  = %2.0d,',blkdim(2));
        fprintf('   num. of socp blk  = %2.0d',numblk(2));
    end
    if blkdim(3); fprintf('\n dim. of linear var  = %2.0d',blkdim(3)); end
    if blkdim(4); fprintf('\n dim. of free   var  = %2.0d',blkdim(4)); end
end
%%
%%-----------------------------------------
%% detect unrestricted blocks in linear blocks
%%-----------------------------------------
%%
user_supplied_schurfun = 0;
for p = 1:size(blk,1)
    if ~isempty(par.schurfun{p}); user_supplied_schurfun = 1; end
end
if (user_supplied_schurfun == 0)
    [blk2,At2,C2,ublkinfo,parbarrier2,X02,Z02] = ...
        detect_ublk(blk,At,C,parbarrier,X0,Z0,par.printlevel);
else
    blk2 = blk; At2 = At; C2 = C;
    parbarrier2 = parbarrier; X02 = X0; Z02 = Z0;
    ublkinfo = cell(size(blk2,1),1);
end
ublksize = blkdim(4);
for p = 1:size(ublkinfo,1)
    ublksize = ublksize + length(ublkinfo{p});
end
%%
%%-----------------------------------------
%% detect diagonal blocks in semidefinite blocks
%%-----------------------------------------
%%
if (user_supplied_schurfun==0)
    [blk3,At3,C3,diagblkinfo,diagblkchange,parbarrier3,X03,Z03] = ...
        detect_lblk(blk2,At2,C2,b,parbarrier2,X02,Z02,par.printlevel); %#ok
else
    blk3 = blk2; At3 = At2; C3 = C2;
    % parbarrier3 = parbarrier2;
    X03 = X02; Z03 = Z02;
    diagblkchange = 0;
    diagblkinfo = cell(size(blk3,1),1);
end
%%
%%-----------------------------------------
%% main solver
%%-----------------------------------------
%%
%exist_analytic_term = 0;
%for p = 1:size(blk3,1);
%    idx = find(parbarrier3{p} > 0);
%    if ~isempty(idx); exist_analytic_term = 1; end
%end
%%
if (par.vers == 0);
    if blkdim(1); par.vers = 1; else par.vers = 2; end
end
par.blkdim = blkdim;
par.ublksize = ublksize;
[obj,X3,y,Z3,info,runhist] = ...
    HSDsqlpmain(blk3,At3,C3,b,par,X03,y0,Z03,kap0,tau0,theta0);
%%
%%-----------------------------------------
%% recover semidefinite blocks from linear blocks
%%-----------------------------------------
%%
if any(diagblkchange)
    X2 = cell(size(blk2,1),1); Z2 = cell(size(blk2,1),1);
    count = 0;
    for p = 1:size(blk2,1)
        pblk = blk2(p,:);
        n = sum(pblk{2});
        blkno      = diagblkinfo{p,1};
        idxdiag    = diagblkinfo{p,2};
        idxnondiag = diagblkinfo{p,3};
        if ~isempty(idxdiag)
            len = length(idxdiag);
            Xtmp = [idxdiag,idxdiag,X3{end}(count+1:count+len); n, n, 0];
            Ztmp = [idxdiag,idxdiag,Z3{end}(count+1:count+len); n, n, 0];
            if ~isempty(idxnondiag)
                [ii,jj,vv] = find(X3{blkno});
                Xtmp = [Xtmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
                [ii,jj,vv] = find(Z3{blkno});
                Ztmp = [Ztmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
            end
            X2{p} = spconvert(Xtmp);
            Z2{p} = spconvert(Ztmp);
            count = count + len;
        else
            X2(p) = X3(blkno); Z2(p) = Z3(blkno);
        end
    end
else
    X2 = X3; Z2 = Z3;
end
%%
%%-----------------------------------------
%% recover linear block from unrestricted block
%%-----------------------------------------
%%
numblk = size(blk,1);
numblknew = numblk;
X = cell(numblk,1); Z = cell(numblk,1);
for p = 1:numblk
    n = blk{p,2};
    if isempty(ublkinfo{p,1})
        X{p} = X2{p}; Z{p} = Z2{p};
    else
        Xtmp = zeros(n,1); Ztmp = zeros(n,1);
        Xtmp(ublkinfo{p,1}) = max(0,X2{p});
        Xtmp(ublkinfo{p,2}) = max(0,-X2{p});
        Ztmp(ublkinfo{p,1}) = max(0,Z2{p});
        Ztmp(ublkinfo{p,2}) = max(0,-Z2{p});
        if ~isempty(ublkinfo{p,3})
            numblknew = numblknew + 1;
            Xtmp(ublkinfo{p,3}) = X2{numblknew};
            Ztmp(ublkinfo{p,3}) = Z2{numblknew};
        end
        X{p} = Xtmp; Z{p} = Ztmp;
    end
end
%%
%%-----------------------------------------
%% recover complex solution
%%-----------------------------------------
%%
if (iscmp)
    for p = 1:numblk
        pblk = blk(p,:);
        n = sum(pblk{2})/2;
        if strcmp(pblk{1},'s');
            X{p} = X{p}(1:n,1:n) + sqrt(-1)*X{p}(n+1:2*n,1:n);
            Z{p} = Z{p}(1:n,1:n) + sqrt(-1)*Z{p}(n+1:2*n,1:n);
            X{p} = 0.5*(X{p}+X{p}');
            Z{p} = 0.5*(Z{p}+Z{p}');
        end
    end
end
if (isemptyAtb)
    X = X(1:end-1); Z = Z(1:end-1);
end
%%*****************************************************************************


function img = computeColor(u,v)

middlebury = 1;

%   computeColor color codes flow field U, V

%   According to the c++ source code of Daniel Scharstein
%   Contact: schar@middlebury.edu

%   Author: Deqing Sun, Department of Computer Science, Brown University
%   Contact: dqsun@cs.brown.edu
%   $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $

% Copyright 2007, Deqing Sun.
%
%                         All Rights Reserved
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for any purpose other than its incorporation into a
% commercial product is hereby granted without fee, provided that the
% above copyright notice appear in all copies and that both that
% copyright notice and this permission notice appear in supporting
% documentation, and that the name of the author and Brown University not be used in
% advertising or publicity pertaining to distribution of the software
% without specific, written prior permission.
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
% INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY
% PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR
% ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

nanIdx = isnan(u) | isnan(v);
u(nanIdx) = 0;
v(nanIdx) = 0;

colorwheel = makeColorwheel();

if middlebury == 0
  [M N] = size(u);
  r = zeros(M,N);
  g = zeros(M,N);
  b = zeros(M,N);
  img = zeros(M,N,3);

  magnitude = sqrt(u.*u + v.*v);
  mm = max(magnitude(:));
  magnitude = magnitude/mm;

  ncols = size(colorwheel, 1);
  a = atan2(u,v)/pi; % in [-1, 1]
  fk = (a+1) /2 * (ncols-1) + 1; % in [1 ncols]

  idx = floor(fk);

  for i=1:ncols
    tmp = idx == i;
    r(tmp) = magnitude(tmp).*colorwheel(i,1);
    g(tmp) = magnitude(tmp).*colorwheel(i,2);
    b(tmp) = magnitude(tmp).*colorwheel(i,3);
  end
  img(:,:,1) = r;
  img(:,:,2) = g;
  img(:,:,3) = b;
else

  ncols = size(colorwheel, 1);

  rad = sqrt(u.^2+v.^2);

  a = atan2(-v, -u)/pi;

  fk = (a+1) /2 * (ncols-1) + 1;  % -1~1 maped to 1~ncols

  k0 = floor(fk);                 % 1, 2, ..., ncols

  k1 = k0+1;
  k1(k1==ncols+1) = 1;

  f = fk - k0;

  for i = 1:size(colorwheel,2)
    tmp = colorwheel(:,i);
    col0 = tmp(k0)/255;
    col1 = tmp(k1)/255;
    col = (1-f).*col0 + f.*col1;

    idx = rad <= 1;
    col(idx) = 1-rad(idx).*(1-col(idx));    % increase saturation with radius

    col(~idx) = col(~idx)*0.75;             % out of range

    img(:,:, i) = uint8(floor(255*col.*(1-nanIdx)));
  end;
end

%%
function colorwheel = makeColorwheel()

%   color encoding scheme

%   adapted from the color circle idea described at
%   http://members.shaw.ca/quadibloc/other/colint.htm

RY = 15;
YG = 6;
GC = 4;
CB = 11;
BM = 13;
MR = 6;

ncols = RY + YG + GC + CB + BM + MR;

colorwheel = zeros(ncols, 3); % r g b

col = 0;
%RY
colorwheel(1:RY, 1) = 255;
colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)';
col = col+RY;

%YG
colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)';
colorwheel(col+(1:YG), 2) = 255;
col = col+YG;

%GC
colorwheel(col+(1:GC), 2) = 255;
colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)';
col = col+GC;

%CB
colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)';
colorwheel(col+(1:CB), 3) = 255;
col = col+CB;

%BM
colorwheel(col+(1:BM), 3) = 255;
colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)';
col = col+BM;

%MR
colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)';
colorwheel(col+(1:MR), 1) = 255;


%  Figure 9.54      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
function y = fas(u)
if u < 0.0606,
   y = 0.1 ;
elseif u < 0.0741,
   y = 0.1 + (u-0.0606)*20;
else y = 0.9;
end


% BOOKKEEPING - Updates the status of example indss and modifies the corresponding
%               coefficient a(indss) in certain cases to avoid numerical errors.
%
% Syntax: [indco,i] = bookkeeping(indss,cstatus,nstatus)
%
%     indco: matrix row/col to remove from Rs and Q if removing a margin vector
%         i: when i > 0, the i-th element was removed from ind{RESERVE}
%     indss: the example changing status
%   cstatus: current status of the example
%   nstatus: new status of the example
%
%            example status values:
%            1: margin vector
%            2: error vector
%            3: reserve vector
%            4: unlearned vector
%
% Version 3.22 -- Comments to diehl@alumni.cmu.edu
%

function [indco,i] = bookkeeping(indss,cstatus,nstatus)

indco = -1;
i = 0;
if (cstatus ~= nstatus)

	% flags for example state
	MARGIN    = 1;
	ERROR     = 2;
	RESERVE   = 3;
    UNLEARNED = 4;

	% define global variables
	global a;     % the alpha coefficients
	global C;     % regularization parameters
	global ind;   % cell array containing indices of margin, error, reserve and unlearned vectors

	% adjust coefficient to avoid numerical errors if necessary
	switch nstatus
	case RESERVE
	   a(indss) = 0;
	case ERROR
	   a(indss) = C(indss);
	end;

	% if the example is currently a margin vector, determine the row
	% in the extended kernel matrix inverse that needs to be removed
	if (cstatus == MARGIN)
   	indco = find(indss == ind{MARGIN}) + 1;
	end;

	% change the status of the example
	switch nstatus
	case RESERVE
   	[ind{cstatus},i] = move_indr(ind{cstatus},indss);
	otherwise
	   [ind{cstatus},ind{nstatus}] = move_ind(ind{cstatus},ind{nstatus},indss);
	end;

end;


function D = COPAR_updateD(Y, Y_range, D, X, opts) % and DCp1
% function D = COPAR_updateD(Y, Y_range, D, X, opts)
% update D in COPAR, including both PARTICULAR dictionaries and the
% COMMON dictionary.
% The algorithm used here is the efficient algorithm presented in LRSDL paper
% -----------------------------------------------
% Author: Tiep Vu, thv102@psu.edu, 5/11/2016
%         (http://www.personal.psu.edu/thv102/)
% -----------------------------------------------
    if nargin == 0
        clc;
        addpath(fullfile('..', 'utils'));
        addpath(fullfile('..', 'DLSI'));
        C = 10;    N = 7;    d = 300;
        k = 7;
        opts.k0          = 10;
        opts.lambda      = 0.01;
        opts.eta         = 0.1;
        opts.D_range     = k* (0:C);
        opts.D_range_ext = [opts.D_range opts.D_range(end)+opts.k0];
        opts.max_iter    = 10;
        opts.verbose      = true;

%         Y       = normc(rand(d, C*N));
%         Y_range = N * (0:C);
%         D       = normc(rand(d, opts.D_range_ext(end)));
%         X       = 0.01*rand(size(D,2), size(Y,2));
%         save('tmp2.mat', 'Y', 'Y_range', 'D', 'X');

        load('tmp2.mat', 'Y', 'Y_range', 'D', 'X');
    end

    %%
    C              = numel(Y_range) - 1;
    D_range_ext    = opts.D_range_ext;
    DCp1           = get_block_col(D, C+1, D_range_ext);
    optsD          = opts;
    optsD.verbose   = false;
    optsD.max_iter = 100;
    Yhat           = zeros(size(Y));
    %% ========= update Dc ==============================
    for c = 1: C
        %Dc = arg\min_Dc \|Ychat - Dc*Xcc\|_F^2 + \|Ycbar - Dc*Xcc\| + 2*eta\|A*Dc\|_F^2
        % = \arg\min_Dc \| [Ychat Ycbar] - Dc*[Xcc Xcc]\|_F^2 + 2*eta\|A*Dc\|_F^2
        % and solved using DLSI_updateD
        Dc_range = D_range_ext(c)+1: D_range_ext(c+1);
        Yc_range = Y_range(c)+1: Y_range(c+1);
        Yc       = Y(:, Yc_range);
        Dc       = D(:, Dc_range);
        Xc       = X(:, Yc_range);
        Xcc      = get_block_row(Xc, c, D_range_ext);
        XCp1c    = get_block_row(Xc, C+1, D_range_ext);
        Ychat    = Yc - D*Xc + Dc*Xcc;
        Ycbar    = Yc - DCp1*XCp1c;
        E        = (Ychat + Ycbar)*Xcc';
        F        = 2*Xcc*Xcc';
        A        = D;
        A(:,Dc_range)     = [];
        D(:, Dc_range)    = DLSI_updateD(Dc, E, F, A', opts.eta, optsD);
        Yhat(:, Yc_range) = Yc - D(:, Dc_range)*Xcc;
    end
    %% ========= DCp1 ==============================
    XCp1       = X(D_range_ext(C+1) + 1 : D_range_ext(C+2), :);
    Ybar       = Y - D(:, 1: D_range_ext(end-1))*X(1: D_range_ext(end-1), :);
    E          = (Ybar + Yhat)*XCp1';
    F          = 2*XCp1*XCp1';
    A          = D(:, 1: D_range_ext(C+1));
    DCp1_range = D_range_ext(C+1) + 1: D_range_ext(C+2);
    D(:, DCp1_range) = DLSI_updateD(D(:, DCp1_range), E, F, A', opts.eta,  optsD);
    %%
    if nargin == 0
        D = [];
    end
end


% Test file for chebtech/isreal.m

function pass = test_isreal(pref)

if ( nargin < 1 )
    pref = chebtech.techPref();
end

for n = 1:2
    if ( n == 1 )
        testclass = chebtech1();
    else
        testclass = chebtech2();
    end

    % Test a scalar-valued function:
    f = testclass.make(@(x) sin(x) + 1i*cos(x), [], pref);
    pass(n, 1) = ~isreal(f);

    f = testclass.make(@(x) 1i*cos(x), [], pref);
    pass(n, 2) = ~isreal(f);

    f = testclass.make(@(x) sin(x), [], pref);
    pass(n, 3) = isreal(f);

    % Test an array-valued function:
    f = testclass.make(@(x) [sin(x) + 1i*cos(x), exp(x)], [], pref);
    pass(n, 4) = ~isreal(f);

    f = testclass.make(@(x) [1i*cos(x), exp(x)], [], pref);
    pass(n, 5) = ~isreal(f);

    f = testclass.make(@(x) [sin(x), exp(x)], [], pref);
    pass(n, 6) = isreal(f);
end

end