%kkblend 'Output = (Input 1 * Constant) + (Input 2 (1 - Constant))'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kblend.pane file
%
% Parameters:
% InputFile: i1 'Input 1 ', required: 'first input data object'
% InputFile: i2 'Input 2 ', required: 'second input file object'
% OutputFile: o 'Output', required: 'resulting output data object'
% InputFile: iratio 'Blending file', optional: 'Input object for providing blending ratios'
%
% Example: o = kkblend({i1, i2, iratio}, {'i1','';'i2','';'o','';'iratio',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kblend - Output = (Input 1 * Constant) + (Input 2 (1 - Constant))
%
%  DESCRIPTION
% The "Blend" operator (kblend) forms a blend of two objects by
% adding X*(object1)+(1-X)*(object2).
%
% Instead of specifying a constant for the blending ratio, an object can be
% supplied for the blending values. The value segment of the ratio object
% is used to determine the proportion in which the two objects are blended.
% It must take on values between 0 and 1, otherwise an error is generated.
%
%
%  "Data Type" 5
% .cI $DATAMANIP/repos/shared/man/sections/value_type_2input
%
%  "Map Data" 5
% .cI $DATAMANIP/repos/shared/man/sections/map_2input
%
%  "Validity Mask" 5
% If there is a validity mask associated with any of the input objects, the
% resulting output object will have a mask.  The output object mask is the
% logical AND of the input object masks.  If only one input object has a mask,
% then the other input object's mask is assumed to be "all valid" (mask
% value = 1).  If a mask is resized for the operation, the mask padding value
% will be 1.
%
%  "Input Objects of Different Sizes" 5
% .cI $DATAMANIP/repos/shared/man/sections/resize_2input
%
%  "Explicit Location and Time Data" 5
% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_2input
%
%  "Failure Modes - Two Input Objects"
% .cI $DATAMANIP/repos/shared/man/sections/fail_2input
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% The blend operator has not been updated to be fully polymorphic.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkblend(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kkblend(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i1', '__input';'i2', '__input';'o', '__output';'iratio', '__input'};
maxval={0,0,0,1};
minval={0,0,0,1};
istoggle=[0,0,0,1];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','OutputFile','InputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'kblend"  '],Inputs,narglist);


%% ellipseCoord
% Below is a demonstration of the features of the |ellipseCoord| function

%%
clear; close all; clc;

%% Syntax
% |[V]=ellipseCoord(A,t);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*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 [x,y,K]=postprocessSDP(newx,newy,prepinfo,newK)
% [x,y,K]=postprocessSDP(newx,newy,prepinfo,newK)
% postprocessSDP: Postprocesses an SDP solution using the info from
% preprocessing (preprocessSDP)
%
% **********  INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi, preprocessSDP

% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

if issparse(newx)
    x=sparse([]);
else
    x=[];
end
y=newy;
K=newK;

for j=length(prepinfo):-1:1
    op=prepinfo{j};
    switch op(1)
        case 0
            %Do nothing
            x=[newx(end-op(2)+1:end);x];
            newx=newx(1:end-op(2));
        case 1
            %Diagonal matrix
            x=[reshape(diag(newx(1:op(2))),op(2)^2,1);x];
            newx=newx(op(2)+1:end);
            K.l=K.l-op(2);
            K.s(end+1)=op(2);
            K.rsdpN=K.rsdpN+1;
    end
end


function test_bug2639
% DEPENDENCY ft_checkdata

% MEM 2gb
% WALLTIME 00:10:00

shufflechan = [1 3 2]';

channelcmb = {
  '1' '2'
  '1' '3'
  '2' '3'
  };

%%
freq1o           = [];
freq1o.freq      = 1;
freq1o.label     = {'1', '2', '3'}';
freq1o.dimord    = 'chan_freq';
freq1o.powspctrm = reshape([1 2 3], [3 1]);

freq1r           = freq1o;
freq1r.label     = freq1o.label(shufflechan);
freq1r.powspctrm = freq1o.powspctrm(shufflechan,:);

freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(selo,:), freq2r.powspctrm(selr,:)));

%%
freq1o           = [];
freq1o.freq      = 1;
freq1o.cumtapcnt = 1;
freq1o.label     = {'1', '2', '3'}';
freq1o.dimord    = 'rpt_chan_freq';
freq1o.fourierspctrm = reshape([1 2 3], [1 3 1]);

freq1r           = freq1o;
freq1r.label     = freq1o.label(shufflechan);
freq1r.fourierspctrm = freq1o.fourierspctrm(:,shufflechan,:);

freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.fourierspctrm(:,selo,:), freq2r.fourierspctrm(:,selr,:)));

%% full, sparse, fourier, sparsewithpow, fullfast

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'fourier');
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'fourier');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.fourierspctrm(:,selo,:), freq2r.fourierspctrm(:,selr,:)));

assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'full');
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'full');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));

assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'fullfast');
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'fullfast');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));

assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'sparse', 'channelcmb', channelcmb);
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'sparse', 'channelcmb', channelcmb);
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));

assert( isequal(freq2o.labelcmb,freq2r.labelcmb));

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'sparsewithpow', 'channelcmb', channelcmb);
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'sparsewithpow', 'channelcmb', channelcmb);
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(selo,:), freq2r.powspctrm(selr,:)));

assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));
assert( isequal(freq2o.labelcmb,freq2r.labelcmb));

%%
freq1o           = [];
freq1o.freq      = 1;
freq1o.cumtapcnt = 1;
freq1o.dimord    = 'chancmb_freq';
freq1o.label     = {'1', '2', '3'}';
freq1o.powspctrm = [1 2 3]';
freq1o.labelcmb  = {
  '1' '2'
  '1' '3'
  '2' '3'
  };
freq1o.crsspctrm = [
  2
  3
  6
  ];

freq1r           = freq1o;
freq1r.label     = freq1o.label(shufflechan);
freq1r.labelcmb  = freq1o.labelcmb(shufflechan,:);
freq1r.powspctrm = freq1o.powspctrm(shufflechan,:);
freq1r.crsspctrm = freq1o.crsspctrm(shufflechan,:);

freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(selo,:), freq2r.powspctrm(selr,:)));
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'full');
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'full');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));

% assert( isequal(freq1r.label,freq2r.label)); % this is where the channel reordering becomes clear
% assert(~isequal(freq2o.label,freq2r.label)); % this is where the channel reordering becomes clear

freq2o = ft_checkdata(freq1o, 'cmbstyle', 'fullfast');
freq2r = ft_checkdata(freq1r, 'cmbstyle', 'fullfast');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr))); % this is where another problem appears

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [sel1, sel2] = match_strcmb(chancmb1, chancmb2)
for i=1:size(chancmb1,1)
  chan1{i} = sprintf('%s_%s', chancmb1{i,:});
end
for i=1:size(chancmb2,1)
  chan2{i} = sprintf('%s_%s', chancmb2{i,:});
end
[sel1, sel2] = match_str(chan1, chan2);


function objectiveAbbr = checkObjective(model)
warning('checkObjective will be depreciated because the function name is a misnomer, please use printObjective instead')
% Prints out the Stoichiometric Coefficients for each
% Metabolite, with the name of the objective
%
% USAGE:
%
%    objectiveAbbr = checkObjective(model)
%
% INPUT:
%    model:            COBRA model structure
%
% OUTPUT:
%    objectiveAbbr:    Objective reaction abbreviation
%
% .. Authors:
%       - Ronan Fleming 22/10/2008
%       - Thomas Pfau 15/12/2015 - Made the function compatible with sparse S matrices
%       - Laurent Heirendt March 2017 - Compatibility with large models and conversion to table

objRxnInd = find(model.c ~= 0);
objectiveAbbr = model.rxns(objRxnInd);
T = cell(length(objRxnInd), 1);

if isempty(objRxnInd)
    warning('There is no objective!');
else
    objMetVect = {};
    objRxnVect = {};
    objCoeffVect = {};
    for k = 1:length(objRxnInd)
        objMetInd = find(model.S(:, objRxnInd(k)));
        objMetVect{k} = model.mets(objMetInd);
        rxnName = model.rxns(objRxnInd(k));
        objCoeffVect{k} = full(model.S(objMetInd, objRxnInd(k)));

        objRxnVect = {};
        objRxnIDVect = {};
        % fill the list with the reaction name and ID
        for m = 1:length(objMetInd)
            objRxnVect{m} = char(rxnName);
            objRxnIDVect{m} = objRxnInd(k);
        end

        % save the table for reaction k
        T{k} = table(objCoeffVect{k}, categorical(objMetVect{k}), objMetInd, categorical(objRxnVect'), cell2mat(objRxnIDVect'), ...
                     'VariableNames', {'Coefficient', 'Metabolite', 'metID', 'Reaction', 'RxnID'});

        % concatenate the tables
        if k == 1
            summaryT = T{1};
        else
            summaryT = vertcat(summaryT, T{k});
        end
    end

    % display a summary
    display(summaryT);
end


function turn_imagesc()
%TURN_IMAGES corrects the Y axis for imagesc plots

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

%% ===== Main ============================================================
set(gca,'YDir','normal');


function y = bin2polar(x)
y = 2*x-1;


function [] = LoadNetworkWeights(n_layers)
    %Load the shared NN-based denoisers network
    if ~exist('vl_setupnn','file')
        error('vl_setupnn not found. Make sure matconvnet is in your path');
    end
    vl_setupnn
    global net_0to10
    global net_10to20
    global net_20to40
    global net_40to60
    global net_60to80
    global net_80to100
    global net_100to150
    global net_150to300
    global net_300to500
    global net_500to1000
    if nargin~=0
        if n_layers==17
            %Load 17 layer network weights
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma0to10-best');%loads net
            net.layers = net.layers(1:end-1);
            net_0to10 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma10to20-best');%loads net
            net.layers = net.layers(1:end-1);
            net_10to20 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma20to40-best');%loads net
            net.layers = net.layers(1:end-1);
            net_20to40 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma40to60-best');%loads net
            net.layers = net.layers(1:end-1);
            net_40to60 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma60to80-best');%loads net
            net.layers = net.layers(1:end-1);
            net_60to80 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma80to100-best');%loads net
            net.layers = net.layers(1:end-1);
            net_80to100 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma100to150-best');%loads net
            net.layers = net.layers(1:end-1);
            net_100to150 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma150to300-best');%loads net
            net.layers = net.layers(1:end-1);
            net_150to300 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma300to500-best');%loads net
            net.layers = net.layers(1:end-1);
            net_300to500 = vl_simplenn_move(net, 'gpu') ;
            load('./../Packages/DnCNN/BestNets_17/DnCNN_17Layer_sigma500to1000-best');%loads net
            net.layers = net.layers(1:end-1);
            net_500to1000 = vl_simplenn_move(net, 'gpu') ;
        else
            LoadNetworkWeights();
        end
    else
        %Load 20 layer network weights
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma0to10-best');%loads net
        net.layers = net.layers(1:end-1);
        net_0to10 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma10to20-best');%loads net
        net.layers = net.layers(1:end-1);
        net_10to20 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma20to40-best');%loads net
        net.layers = net.layers(1:end-1);
        net_20to40 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma40to60-best');%loads net
        net.layers = net.layers(1:end-1);
        net_40to60 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma60to80-best');%loads net
        net.layers = net.layers(1:end-1);
        net_60to80 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma80to100-best');%loads net
        net.layers = net.layers(1:end-1);
        net_80to100 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma100to150-best');%loads net
        net.layers = net.layers(1:end-1);
        net_100to150 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma150to300-best');%loads net
        net.layers = net.layers(1:end-1);
        net_150to300 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma300to500-best');%loads net
        net.layers = net.layers(1:end-1);
        net_300to500 = vl_simplenn_move(net, 'gpu') ;
        load('./../Packages/DnCNN/BestNets_20/DnCNN_20Layer_sigma500to1000-best');%loads net
        net.layers = net.layers(1:end-1);
        net_500to1000 = vl_simplenn_move(net, 'gpu') ;
    end
end


function seg = segCreate(name, classPath,  grayPath, anatFile);
% Create an empty segmentation object. Includes a description of
% the segmentation format.
%
% seg = segCreate(<name>, <classPath>, <grayPath>, <anatFile>);
%
% If any of the input arguments are omitted, prompts for them.
%
% returns a struct with the following fields:
%   name: name of the segmentation. E.g., 'Right', 'Left', 'Both'.
%   subject: subject info.
%   class: path to classification file, or loaded class struct (see
%           readClassFile for description).
%   nodes: 8xN list of gray nodes (see segGet for a description).
%   edges: set of gray edges.
%   mesh: cell array of meshes which may be loaded/built from this
%   segmentation.
%   anatFile: name or path to anat file that was segmented.
%   created: date stamp, set in this function, when it was first created.
%   modified: date stamp, describing the time when it was last modified.
%
% Note that the segmentation struct, in itself, doesn't contain info on the
% anatomy that was segmented. Rather, it simply points to the original
% segmented file. This is because I am intending for segmentations to be
% attached to an mr struct, rather than the other way around (e.g., left,
% right, and both segmentations on the anatomy).
%
%
% ras, 04/06.
if notDefined('name')
    name = inputdlg('Name of Segmentation?', mfilename, 1, {'Right'});
    if isempty(name), return; else, name = name{1}; end
end

if notDefined('classPath')
    classPath = mrvSelectFile('r', '*lass', 'Select Class File');
end

[p f ext] = fileparts(classPath);

if notDefined('grayPath') & ~strfind(ext, 'nii')
	% (don't need a gray graph for NIFTI classifications...)
    grayPath = mrvSelectFile('r', '*ray', 'Select Gray File', p);
end

if notDefined('anatFile')
	ttl = 'Select the anatomy file that was segmented';
    anatFile = mrvSelectFile('r', '*', ttl, fileparts(p));
end

seg.name = name;
seg.subject = [];
seg.anatFile = anatFile;
seg.class = classPath;
seg.gray = grayPath;
seg.nodes = [];
seg.edges = [];
seg.mesh = {};
seg.settings.mesh = 0; % currently selected mesh
seg.params.numLayers = 3;
seg.params.layer0 = 0;
seg.params.meshDir = '';
seg.created = datestr(clock);
seg.modified = datestr(clock);
if isempty('grayPath')
	[seg.nodes seg.edges] = mrgGrowGray(classPath, seg.params.numLayers, ...
                                    seg.params.layer0);
else
	[seg.nodes seg.edges] = readGrayGraph(grayPath);
end

try
	hdr = mrLoadHeader(anatFile);
	seg.subject = hdr.info;
	seg.voxelSize = hdr.voxelSize(1:3);
catch
	disp('Couldn''t load subject header info. Guessing 1x1x1 voxel size')
	seg.voxelSize = [1 1 1];
end

if exist(fullfile(fileparts(seg.class), '3DMeshes'), 'dir')
    seg.params.meshDir = fullfile(fileparts(seg.class), '3DMeshes');
end

return


classdef AdaptiveChol < handle
   properties (Constant)
      mex = AdaptiveChol.mexSelector();
   end

   methods (Static)
      function func = mexSelector()
         if isarm()
            func = @AdaptiveCholArmMex;
         else
            func = @AdaptiveCholMex;
         end
      end
   end

   properties
      % the constraint matrix
      A
      w = NaN
      cholTol = 1e-4

      % private
      uid
      lastChol = 0; % 1 = double, 2 = ddouble, 3 = qdouble
   end

   methods (Static)
      function o = loadobj(s)
         s.uid = AdaptiveChol.mex('new', uint64(randi(2^32-1,'uint32')), s.A);
         if ~any(isnan(s.w))
            w = s.w; s.w = NaN;
            s.factorize(w);
         end
         o = s;
      end
   end

   methods
      function o = AdaptiveChol(A, cholTol)
         if nargin <= 1, cholTol = 1e-4; end;

         o.A = A;
         o.cholTol = cholTol;
         if isobject(A), A = A.x; end
         o.uid = AdaptiveChol.mex('new', uint64(randi(2^32-1,'uint32')), A);
      end

      function b = saveobj(a)
         b = a;
         b.uid = [];
      end

      function delete(o)
         if ~isempty(o.uid)
            AdaptiveChol.mex('delete', o.uid);
         end
      end

      function err = factorize(o, w, offset)
         if nargin <= 2, offset = 0.0; end
         if isvector(w), w = diag(sparse(w)); end

         o.w = w;
         err = +Inf;

         okay = AdaptiveChol.mex('factorize', o.uid, double(w), offset);
         o.lastChol = 1;
         if okay, err = o.cholAccuracy(); end
         if err < o.cholTol, return; end

         okay = AdaptiveChol.mex('factorize', o.uid, ddouble.toMex(w), offset);
         o.lastChol = 2;
         if okay, err = o.cholAccuracy(); end
         if err < o.cholTol, return; end

         okay = AdaptiveChol.mex('factorize', o.uid, qdouble.toMex(w), offset);
         o.lastChol = 3;
         if okay
            err = o.cholAccuracy();
         else
            err = +Inf;
         end
      end

      function ls = leverageScore(o, JLDim)
         % Warning: This compute (W A' (AWA')^-1 A)_ii
         % This is not exactly leverageScore unless W is diagonal.

         % tau = A' L^{-1} zeta
         tau = AdaptiveChol.mex('halfProj', o.uid, JLDim);
         if (o.lastChol == 2)
            tau = ddouble(tau);
         elseif (o.lastChol == 3)
            tau = qdouble(tau);
         end

         % ls = avg_j (W tau_j)_i (tau_j)_i
         ls = sum((o.w * tau) .* tau,2) / JLDim;
      end

      function err = cholAccuracy(o)
         err = abs(sum(o.leverageScore(1)) - size(o.A, 1));
      end

      function r = diagonal(o)
         assert(o.lastChol, 'factorize must be called before diagonal.');

         r = AdaptiveChol.mex('diagonal', o.uid);

         if (o.lastChol == 2)
            r = ddouble(r);
         elseif (o.lastChol == 3)
            r = qdouble(r);
         end
      end

      function y = solve(o, b, w, iter)
         assert(logical(o.lastChol), 'factorize must be called before solve.');
         assert(nargin >= 2);
         if nargin <= 2 || isempty(w), w = o.w; end
         if nargin <= 3, iter = 3; end

         className = class(b);
         if issparse(b), b = full(b); end
         if isobject(b), b = b.x; end
         if isobject(w), w = w.x; end

         y = AdaptiveChol.mex('solve', o.uid, b, w, iter);

         if (strcmp(className, 'ddouble')) %#ok<*STISA>
            y = ddouble(y);
         elseif (strcmp(className, 'qdouble'))
            y = qdouble(y);
         end
      end

   end
end


function [flag,feedBack]=nonBlockingCheck_WithFeedback(t_Kuka, param)
% This functions is used with nonBlocking motion functions to check whether
% the non-blcokking motion is finished execution, in addition this function
% returns a feedback about the state of the robot.

%% Syntax:
% [flag]=nonBlockingCheck_WithFeedback(t_Kuka, param)

%% Arguments
% t_Kuka: is the TCP/IP connection object
% param: an integer value used to specify the feedback required from the
% robot (EEF force, EEF moment, joints torques, joint angles), please check
% the "feedBack" variable in the "return value" section-below for more info
% about the supported values of (param).

%% return value
% flag is a numerical value:
% flag=1: signifies the goal is reached
% flag=0: signifies the goal is not reached
% flag=-1: signifies an error
% feedBack: a cell array representing the feedback from the robot, the
% dimention of the array and the information in its cells depend
% on the value of the "param" argument as in the following table:
%-------------------------------------------------
% param | feedback
%   1   | force at EEF described in frame of EEF
%   2   | external torques at the joints
%   3   | measured torques at the joints
%   4   | joints positions from internal encoders
%--------------------------------------------------
% Copyright: Mohammad SAFEEA 12th-May-2019

global paramName;
global paramVal;
paramArg_CarLevel={'DcSeCarEEfFrelEEF_','DcSeCarExT_','DcSeCarMT_','DcSeCarJP_'};
sleeping_time=0.005;
x='eefpos';
%% if motion at EEF level
if(strcmp(x,paramName))
    % check size of array
    if(max(size(paramVal))==6)
    else
        flag=-1;
        return;
    end
% check if parameters are equal
    paramArg=paramArg_CarLevel{param};
    [feedBack,tempFlag]=GetFeedback( t_Kuka,paramArg );
    if tempFlag==false
        flag=1;
        pause(sleeping_time);
    else
        flag=0;
        pause(sleeping_time);
    end
    return;
end
%% if motion at joint space level
x='jpos';
if(strcmp(x,paramName))
    % check size of array
    if(max(size(paramVal))==7)
    else
        flag=-1;
        return;
    end
    % check if parameters are equal
    paramArg=paramArg_CarLevel{param};
    [feedBack,tempFlag]=GetFeedback( t_Kuka,paramArg );
    if tempFlag==false
        flag=1;
        pause(sleeping_time);
    else
        flag=0;
        pause(sleeping_time);
    end
    return;
end
% otherwise
flag=-1;
end

function [ feeadback,flag ] = GetFeedback( t_Kuka, paramArg )
EEEFpos={0,0,0,0,0,0};
theCommand=paramArg;

for i=1:6
    x=EEEFpos{i};
    theCommand=[theCommand,sprintf('%0.5f',x),'_'];
end
% send the message through network
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);
[feeadback,N]=getDoubleFromString(message);
if(N==0) % when motion is finished, server returns "done+stopCharacter", raising this case
    flag=false; % segnifies motion is done
    message=fgets(t_Kuka);
    [feeadback,N]=getDoubleFromString(message);
    pause(0.1); % wait for sometime
else
    flag=true;
end
end

function [jPos,j]=getDoubleFromString(message)
n=max(max(size(message)));
j=0;
numString=[];
for i=1:n
    if message(i)=='_'
        j=j+1;
        jPos{j}=str2num(numString);
        numString=[];
    else
        numString=[numString,message(i)];
    end
end
if j==0
    jPos={0};
end
end


%% plane_fit
% Below is a demonstration of the features of the |plane_fit| function

%%
clear; close all; clc;

%% Syntax
% |[A,B,C]=plane_fit(x,y,z);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*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 segNum = get_segNum
%Get the previously highest value of segNum for all displayed active contours
%LM:  18 April 02, JOD.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Get handles to all the existing plotted segments
hSegsV = findobj('tag','newSegment');

segNum = 0;
for i = 1 : length(hSegsV)
  segS = get(hSegsV(i),'userdata');
  if segS.segNum > segNum
    segNum = segS.segNum;
  end
end


function [message,result,solverTime] = runcontest(flagVisualize,charFlag,whichBoards)
%RUNCONTEST Test an entry.
%   [MESSAGE,RESULTS,TIME] = RUNCONTEST runs the file solver.m against all
%   the problems defined in testsuite_sample.mat. MESSAGE returns a summary
%   of the testing, RESULTS measures how well the entry solved the problem,
%   and TIME measures the time the entry took to compute the answer.
%
%   RUNCONTEST(true) graphically visualize the results.
%
%   RUNCONTEST(true/false, true) displays numbers as their ASCII
%   equivalents
%
%   RUNCONTEST(true/false, true/false, DOBOARDS) runs the file solver.m
%   against the problems enumerated in the vector DOBOARDS as defined in
%   the testsuite.

% Copyright 2011 The MathWorks, Inc.

% The MATLAB Contest Team
% April 2011

testSuiteFile = 'testsuite_sample.mat';
tests = load(testSuiteFile,'testsuite');

% Argument parsing.
if nargin < 3
    whichBoards = 1:numel(tests.testsuite); % do all boards in test suite
end
if nargin < 2
    charFlag = false;  % display numbers as numbers
end
if nargin < 1
    flagVisualize = false;  % no visualization
end

numBoards = numel(whichBoards);
solverTime = zeros(numBoards,1);
solverScore = zeros(numBoards,1);

if flagVisualize
    fh = figure('Color', [1 1 1]);
end

for n = 1:numBoards
    [words, weights, boardSize, penalty] = getboard(tests.testsuite,whichBoards(n));

    time0 = cputime;
    board = solver(words, weights, boardSize, penalty);
    solverTime(n) = cputime-time0;

    [remainInDictionary, inPuzzle, bogus] = ...
        runSolution(board, boardSize, words, weights);

    solverScore(n) = scoresolution(remainInDictionary, bogus, penalty);

    % Print a report to the Command Window
    if flagVisualize
        visualizeSolution(board, boardSize, bogus, charFlag, fh);
        fprintf('\n  Puzzle: %d\n  Score: %d\n\n', n, solverScore(n));

        fprintf('Unused words remaining in dictionary\n------------------------------------\n');
        printWords(remainInDictionary.words, charFlag);

        fprintf('Valid words used in puzzle solution\n-----------------------------------\n');
        printWords(inPuzzle.words, charFlag);

        fprintf('Bogus words used in puzzle solution\n-----------------------------------\n');
        printWords(bogus.words, charFlag);

        if (n < numBoards) && mypause(fh)
            break; % stop
        end
    end
end

% Report results.
result = sum(solverScore);
resultTime = sum(solverTime);
message = sprintf('results: %.2f\ntime: %.2f', result, resultTime);

end

function printWords(words, charFlag)
%printWords: displays words in cell array to the Command Window

for n = 1:numel(words)
    if charFlag
        fprintf([char(words{n}),'\n']);
    else
        fprintf([num2str(words{n}),'\n']);
    end
end
fprintf('\n');
end

function [remainInDictionary, inPuzzle, bogus] = runSolution(board, boardSize, dictionary, weights)
%runSolution: parses the solution returned by the solver to determine the
% words it contains. Three structures are returned:
%
%  * remainInDictionary.words: words that remain in the dictionary
%  * remainInDictionary.points: points for each unused dictionary word
%  * remainInDictionary.hash: hash value used internally for searching
%
%  * inPuzzle.words: valid dictionary words used in the solution
%  * inPuzzle.points: points for each valid word
%
%  * bogus.words: words in the solution that aren't in the dictionary
%  * bogus.locations: linear indices of all letters in each word

% Initialize outputs
remainInDictionary = struct('words',{dictionary}, 'weights',{weights}, ...
    'hash', {cellfun(@applyHash, dictionary)});
inPuzzle = struct('words',{{}}, 'weights',{[]});
bogus = struct('words',{{}}, 'locations',{{}});

% Find words going across and down. dir = 1 for across, 2 for down.
for dir = 1:2
    for n = 1:boardSize
        % Get the current row / column to process
        if dir == 1
            curLine = board(n,:);
        else
            curLine = board(:,n).';
        end

        % Split current line of the board by locations of zeros
        zeroLoc = find(curLine == 0);
        idx1 = [1, zeroLoc+1];
        idx2 = [zeroLoc-1, boardSize];

        % Process the words on the current line
        for m = 1:numel(idx1)
            % Get the linear indices that make up the current word
            idxRange = idx1(m):idx2(m);
            idxConst = repmat(n, 1, numel(idxRange));
            if dir == 1
                linearWordIdx = sub2ind([boardSize, boardSize], idxConst, idxRange);
            else
                linearWordIdx = sub2ind([boardSize, boardSize], idxRange, idxConst);
            end

            % Current word to process
            curWord = board(linearWordIdx);

            if isscalar(curWord)
                % Get the indices of the adjacent squares - above,
                % below, left, and right.
                [r, c] = ind2sub([boardSize, boardSize], linearWordIdx);
                rows = [r-1, r+1, r,   r];
                cols = [c,   c,   c-1, c+1];
                outOfRange = (rows < 1) | (rows > boardSize) | ...
                    (cols < 1) | (cols > boardSize);
                rows(outOfRange) = [];
                cols(outOfRange) = [];
                adjacentIdx = sub2ind([boardSize, boardSize], rows, cols);

                % Treat a lone floating letter as invalid both across
                % and down. We assume that the dictionary never
                % contains any single letter words.
                if all(board(adjacentIdx) == 0)
                    bogus = addBogusWord(bogus, curWord, linearWordIdx);
                end
            elseif ~isempty(curWord) % Skip empty words - nothing to process
                % Determine if the word is in the dictionary
                dictionaryLoc = findWord(curWord, remainInDictionary.words, ...
                    remainInDictionary.hash);
                if isempty(dictionaryLoc)
                    % Bogus word - add to bogus word list
                    bogus = addBogusWord(bogus, curWord, linearWordIdx);
                else
                    % Legit word - move to inPuzzle list
                    [remainInDictionary, inPuzzle] = moveValidWord( ...
                        remainInDictionary, inPuzzle, dictionaryLoc);
                end
            end
        end
    end
end
end

function val = applyHash(word)
% applyHash: A rudimentary hashing function to speed up looking for words
% in the dictionary

n = min(5, ceil(numel(word)/2));
m1 = [1e10, 1e9, 1e8, 1e7, 1e6];
m2 = [1e4, 1e3, 1e2, 1e1, 1e0];

val = 1e12*sum(word) + sum(word(1:n).*m1(1:n)) + sum(word(end-n+1:end).*m2(1:n));
end

function idx = findWord(word, dictionary, dictionaryHash)
% findWord: Find word in dictionary using hash table. An empty matrix is
% return if the word does not exist in the dictionary

% Initialize output - assume word won't be found
idx = [];

% Find possible matches
possibleIdx = find(dictionaryHash == applyHash(word));

% Check all possible matches. If none is an actual match, we'll return empty
for n = 1:numel(possibleIdx)
    if isequal(dictionary{possibleIdx(n)},word)
        idx = possibleIdx(n);
        return;
    end
end

end

function bogus = addBogusWord(bogus, newWord, wordLoc)
%addBogusWord: add a word to the list of bogus words

bogus.words{end+1} = newWord;
bogus.locations{end+1} = wordLoc;
end

function [inDictionary, inPuzzle] = moveValidWord(inDictionary, inPuzzle, dictionaryLoc)
%moveValidWord: moves a word from the list of unused dictionary words to
% the list of words used in the puzzle solution

% Add word to list of words in the puzzle solution
inPuzzle.words{end+1} = inDictionary.words{dictionaryLoc};
inPuzzle.weights(end+1) = inDictionary.weights(dictionaryLoc);

% Remove word for list of unused dictionary words
inDictionary.words(dictionaryLoc) = [];
inDictionary.weights(dictionaryLoc) = [];
inDictionary.hash(dictionaryLoc) = [];
end

function score = scoresolution(remainInDictionary, bogus, penalty)
% SCORESOLUTION Calculates the score for the solution.

score = sum(remainInDictionary.weights) + penalty * numel(bogus.words);
end

function  [words, weights, n, penalty] = getboard(testsuite,k)
% GETBOARD Gets the k-th problem from the loaded testsuite

k = round(min(max(1,k),numel(testsuite)));
n = testsuite(k).n;
words = testsuite(k).words;
weights = testsuite(k).weights;
penalty = testsuite(k).penalty;
end

function visualizeSolution(board, boardSize, bogus, charFlag, fh)
% Display the resulting crossword puzzle solution

% Set the figure
figure(fh);
clf(fh);

% Set the axes
ax = axes('Parent',fh, 'Ydir','reverse', 'XLim',[0.5, boardSize+0.5], ...
    'YLim',[0.5, boardSize+0.5], 'Visible', 'off', ...
    'DataAspectRatio',[1, 1, 1], 'DataAspectRatioMode','manual');

% Draw the grid
for n = 0.5:boardSize+0.5
    line([n, n], [0.5, boardSize+0.5], 'Parent',ax, 'Color',[0, 0, 0]);
    line([0.5, boardSize+0.5], [n, n], 'Parent',ax, 'Color',[0, 0, 0]);
end

% Mark bogus word squares in red
for n = 1:numel(bogus.locations)
    for m = 1:numel(bogus.locations{n})
        [y, x] = ind2sub([boardSize, boardSize], bogus.locations{n}(m));
        patch([x-0.5, x+0.5, x+0.5, x-0.5],[y-0.5, y-0.5, y+0.5, y+0.5], [-1, -1, -1, -1], ...
            'Parent',ax, 'FaceColor',[1, 0, 0]);
    end
end

% Fill in each square - either a letter or black if unused
idx = 0;
for n = 1:boardSize
    for m = 1:boardSize
        if board(n,m) == 0
        patch([m-0.5, m+0.5, m+0.5, m-0.5],[n-0.5, n-0.5, n+0.5, n+0.5], [0, 0, 0, 0], ...
            'Parent',ax, 'FaceColor',[0, 0, 0]);
        else
            if charFlag
                letter = char(board(n,m));
            else
                letter = num2str(board(n,m));
            end

            idx = idx + 1;
            letterSize(idx) = 0.75/(boardSize*ceil(numel(letter)/2)); %#ok<AGROW>
            tx(idx) = text(m, n, letter, 'Parent',ax, 'FontUnits','normalized', ...
                'FontSize',letterSize(idx), 'VerticalAlignment','middle', ...
                'HorizontalAlignment','center', 'Clipping','on'); %#ok<AGROW>
        end
    end
end

% Set up zoom callback to resize text objects
h = zoom(fh);
set(h,'ActionPostCallback',@(o,e)zoomcb);

    function zoomcb
        zoom_ratio = boardSize / diff(get(ax,'XLim'));
        set(tx,{'FontSize'},num2cell(letterSize*zoom_ratio).');
    end
end

function flag = mypause(fh)
%mypause: provide navigation through puzzle board solutions

flag = false;
h1 = uicontrol('Parent',fh, 'Position',[20, 5, 100, 20], 'String','Next Problem', ...
    'Callback',@(o,e)uiresume(fh));
h2 = uicontrol('Parent',fh, 'Position',[140, 5, 100, 20], 'String','Stop', ...
    'Callback',@(o,e)stop_cb);
uiwait(fh);

% Remove uicontrols when we're done
if ishandle(h1)
    delete(h1);
end
if ishandle(h2)
    flag = ~isempty(get(h2,'UserData')); % stop?
    delete(h2);
end

    function stop_cb
        set(h2,'UserData',1);
        uiresume(fh);
    end
end


function rs = rang(s)

%tstoolbox/@signal/rang
%   Syntax:
%     * rs = rang(s)
%
%   Transform scalar time series to rang values.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

narginchk(1,1);

c = rang(s.core);
rs = signal(c, s);				% special constructor calling syntax for working routines

rs = setyunit(rs, unit);
rs = setyname(rs, 'Rang');
rs = addhistory(rs,  ['Transformed to rang values'] );
rs = addcommandlines(rs, 's = rang(s');


function test_pull2099

% WALLTIME 00:20:00
% MEM 3gb
% DEPENDENCY ft_multiplotER ft_singleplotER ft_topoplotER lineattributes_common ft_databrowser

%%
load(dccnpath('/home/common/matlab/fieldtrip/data/test/pull2099.mat'));

% try a bunch of visualizations
cfg = [];
cfg.layout = 'CTF275_helmet.mat';
ft_multiplotER(cfg, t);

cfg = [];
cfg.linecolor = 'spatial';
cfg.layout = 'butterfly';
ft_multiplotER(cfg, t); % ->monochrome because spatial information of the sensors is not known (grad missing)

cfg = [];
cfg.linecolor = 'spatial';
cfg.layout = 'CTF275_helmet.mat';
cfg.linewidth = 2;
ft_multiplotER(cfg, t);

cfg = [];
cfg.linecolor = 'spatial';
cfg.viewmode = 'butterfly';
cfg.layout = 'CTF275_helmet.mat';
ft_multiplotER(cfg, t);

cfg = [];
cfg.viewmode = 'butterfly';
cfg.layout = 'CTF275_helmet.mat';
cfg.colorgroups = 'labelchar3';
ft_multiplotER(cfg, t);

cfg = [];
cfg.channel = 'MRO';
cfg.showlocations = 'yes';
cfg.linecolor = [0.8 0.4 0.3];
cfg.layout = 'CTF275_helmet.mat';
ft_singleplotER(cfg, t);

cfg = [];
cfg.channel = 'MRO';
cfg.showlocations = 'yes';
cfg.layout = 'CTF275_helmet.mat';
ft_singleplotER(cfg, t1, t2, t3, t4);


classdef ObjectiveFunction < handle

    properties (Access = public)
        value
        gradient
    end

    properties (Access = protected)
        cost
        constraint
        dualVariable
    end

    properties (Access = private)
        valueOld
    end

    methods (Access = public, Static)

        function obj = create(cParams)
            f = ObjectiveFunctionFactory();
            obj = f.create(cParams);
        end

    end

    methods (Access = protected)

        function init(obj,cParams)
            obj.cost         = cParams.cost;
            obj.constraint   = cParams.constraint;
            obj.dualVariable = cParams.dualVariable;
        end

    end

    methods (Access = public)

        function incr = computeIncrement(obj)
            v  = obj.value;
            vI = obj.valueOld;
            incr = (v - vI)/abs(vI);
        end

        function updateOld(obj)
            obj.valueOld = obj.value;
        end

        function restart(obj)
            obj.value = obj.valueOld;
        end

    end

end


function Gnew = gsp_kron_reduction( G,ind )
%GSP_KRON_REDUCTION See gsp_kron_reduce

Gnew = gsp_kron_reduce(G,ind);

end


function board = lines(board)

% Add lines to your board by clicking the begin- and endcoordinates. Exit
% by right clicking.

ui = questdlg('Continuing will destroy all line-information that is already in your current board.', ...
              'Continue?', 'Continue', 'Stop');

if ~strcmp(ui, 'Continue')
    return;
end

for i = 1:numel(board)
    p = patch(board(i).xy(:,1), board(i).xy(:,2), [1 1 1]);
    set(p, 'EdgeColor', [0 0 0]);
end

set(gca, 'XTick', [], 'YTick', [], 'box', 'on')
xlim([0, 800])
ylim([0, 600])

eps = 5;

while true
    [x1,y1,button] = ginput(1);
    if button == 3
        break
    end

    [x2,y2,button] = ginput(1);
    if button == 3
        continue
    end

    % Try to make straight lines
    if abs(x1 - x2) < eps
        x1 = 1/2 * (x1 + x2);
        x2 = x1;
    end
    if abs(y1 - y2) < eps
        y1 = 1/2 * (y1 + y2);
        y2 = y1;
    end

    % No lines outside the borders (800x600)
    x = [x1, x2];
    x(x < 0) = 0;
    x(x > 800) = 800;
    y = [y1, y2];
    y(y < 0) = 0;
    y(y > 600) = 600;

    l = line(x, y, 'LineStyle', '--');
    ui = questdlg('OK?', 'OK?', 'Yes', 'No', 'Yes');
    switch ui
        case 'Yes'
            L(end + 1, :) = [x, y]; %#ok<AGROW>
        otherwise
            delete(l)
            continue
    end
end

close(gcf);


function size = calculateSize( fileName )
%CALCULATESIZE Calculates the size of a MATLAB file for use in the game Cody
%   CALCULATESIZE(FILENAME) determines the number of nodes in the parse tree
%   associated with the file FILENAME.
%
%   For more information, visit http://www.mathworks.com/matlabcentral/cody
%
%   Copyright 1984-2012 The MathWorks, Inc.

    % MTREE is an undocumented function. It will change in the future
    % versions of MATLAB.
    t = mtree(fileName,'-file');
    size = length(t.nodesize);
end


% STD_READSPEC - load spectrum measures for data channels or
%                  for all components of a specified cluster.
%                  Called by plotting functions
%                  STD_ENVTOPO, STD_ERPPLOT, STD_ERSPPLOT, ...
% Usage:
%         >> [STUDY, specdata, allfreqs, setinds, cinds] = ...
%                   std_readspec(STUDY, ALLEEG, varargin);
% Inputs:
%       STUDY - studyset structure containing some or all files in ALLEEG
%      ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
%  'design'    - [integer] read files from a specific STUDY design. Default
%                is empty (use current design in STUDY.currentdesign).
%  'channels'  - [cell] list of channels to import {default: none}
%  'clusters'  - [integer] list of clusters to import {[]|default: all but
%                the parent cluster (1) and any 'NotClust' clusters}
%  'singletrials' - ['on'|'off'] load single trials spectral data (if
%                available). Default is 'off'.
%  'subject'   - [string] select a specific subject {default:all}
%  'component' - [integer] select a specific component in a cluster
%                 {default:all}
%
% Spectrum specific inputs:
%  'freqrange' - [min max] frequency range {default: whole measure range}
%  'rmsubjmean' - ['on'|'off'] remove mean subject spectrum from every
%                 channel spectrum, making them easier to compare
%                 { default: 'off' }
% Output:
%  STUDY    - updated studyset structure
%  specdata - [cell array] spectral data (the cell array size is
%             condition x groups)
%  freqs    - [float array] array of frequencies
%  setinds  - [cell array] datasets indices
%  cinds    - [cell array] channel or component indices
%
% Example:
%  std_precomp(STUDY, ALLEEG, { ALLEEG(1).chanlocs.labels }, 'spec', 'on');
%  [spec freqs] = std_readspec(STUDY, ALLEEG, 'channels', { ALLEEG(1).chanlocs(1).labels });
%
% Author: Arnaud Delorme, CERCO, 2006-

% Copyright (C) Arnaud Delorme, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [STUDY, specdata, allfreqs] = std_readspec(STUDY, ALLEEG, varargin)

if nargin < 2
    help std_readspec;
    return;
end

[STUDY, specdata, allfreqs] = std_readerp(STUDY, ALLEEG, 'datatype', 'spec', varargin{:});


function c = solver(a)
%
% Copyright 2003 The MathWorks, Inc.

c = [1 1];


function Y = identityPhi(X)
    Y = X;


% Copyright (C) 1993-2019 Peter I. Corke
%
% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).
%
% 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.
%
% https://github.com/petercorke/spatial-math

function smtbcheck
    % display current versions of MATLAB
    year = version('-release');
    fprintf('You are using:\n - MATLAB release %s\n', year);

    % check how old it is
    today = datevec(now);
    age =  today(1) - str2num(year(1:4));
    if age >= 2
        fprintf('     ** this is at least %d years old, you may have issues\n', age);
    end

    %% display versions of toolboxes (use unique RTB and MVTB functions)

    %SMTB
    smtb = checktoolbox('RTBPose', 'SMTB');

    %% check for shadowed files

    shadows = {};

    shadows = checkshadow(shadows, 'rotx');
    shadows = checkshadow(shadows, 'roty');
    shadows = checkshadow(shadows, 'rotz');
    shadows = checkshadow(shadows, 'angdiff');

    if ~isempty(shadows)
        fprintf('\n*** Some Toolbox files are "shadowed" and will cause problems with the use of this toolbox ***\n');
        for s = shadows'
            fprintf(' - toolbox function "%s" is shadowed by the MathWorks file %s\n', s{1}, s{2} );
        end
        fprintf('Use the pathtool function to:\n 1. move the Toolbox containing the shadowed function to the top of the path\n 2. Delete the problematic MathWorks toolbox (do you really need it?)\n 3. Move the problematic MathWorks toolbox to the end of the path\n')
    end
end

function present = checktoolbox(funcname, tbname)

    present = true;

    p = which(funcname);
    if isempty(p)
        % toolbox not present
        present = false;
        return
    end

    % display versions of toolbox
    fprintf('%s (%s)\n', short2long(tbname), p);
    v = ver( p );

    where = [];
    if strcmp(tbname, 'SMTB')
        % special case for SMTB, is it standalone or part of RTB or MVTB?
        if contains(p, 'vision', 'IgnoreCase', true)
            where = 'included with MVTB';
        elseif contains(p, 'robot', 'IgnoreCase', true)
            where = 'included with RTB';
        end
    end
    if isempty(where)
        if findstr(p, 'Add-Ons')
            where = 'Add-Ons (installed from mltbx file or Add-On Explorer)';
        else
            if exist( fullfile(p, '.git'), 'dir' )
                where = 'local (git clone)';
            else
                where = 'local (zip install)';
            end
        end
    end

    if ~isempty(v)
        fprintf(' - %s%s, %s\n', tbname, v.Version, v.Date);
    end
    fprintf(' - %s\n', where);
end

function out = checkshadow(shadows, funcname)
    % add to the list if function lives below MATLAB root
    funcpath = which(funcname); % find first instance in path
    out = shadows;
    if startsWith(funcpath, matlabroot) || startsWith(funcpath, 'built-in')
        out = [out; {funcname, which(funcname)}];
    end
end

function fullname = short2long(shortname)
    switch shortname
        case 'RTB'
            fullname = 'Robotics Toolbox for MATLAB';
        case 'MVTB'
            fullname = 'Machine Vision Toolbox for MATLAB';
        case 'SMTB'
            fullname = 'Spatial Math Toolbox for MATLAB';
    end
end

function p = getpath(funcname)
    funcpath = which(funcname);
    k = strfind( funcpath, [filesep funcname]);
    p = funcpath(1:k-1);
end


clear;
clc;

root1 = './Train_argu/shadow/';
image_path1 = dir(fullfile(root1,'*.jpg'));
root3 = './Train_argu/shadow_free/';
image_path3 = dir(fullfile(root3,'*.jpg'));

save_root1 = './Train_argu/shadow_lab/';
save_root3 = './Train_argu/shadow_free_lab/';

colorTransform = makecform('srgb2lab');

for i=1: length(image_path1)
    i

    image1 = imread([root1 image_path1(i).name]);
    image3 = imread([root3 image_path3(i).name]);

    image1_lab = applycform(image1, colorTransform);
    image3_lab = applycform(image3, colorTransform);

    imwrite(image1_lab,[save_root1  image_path1(i).name]);
    imwrite(image3_lab,[save_root3  image_path1(i).name]);
end


%%  RDT testing for VISTASOFT
%
% Some examples and testing of the download of vistadata from the
% RemoteDataToolbox (RDT) site.

%% Create an RDT client object

rd = RdtClient('vistasoft');

% Here is a look at the general repository
rd.openBrowser('fancy',true)

%% Download examples

% First some examples from the AFQ remote path.
rd.crp('/AFQ/templates');

% This is a list of the artifacts and we print it
a = rd.listArtifacts('print',true);

% Notice they have a variety of types.  We automatically handle matlab file
% types by loading them.  Other types may need special handling.

%% For Matlab files, the handling is simpler

% Here are just the matlab types
a = rd.listArtifacts('print',true,'type','mat');

% In this case, the returned variable (data) is a struct with each of the
% variables in the Remote Matlab file
data = rd.readArtifact(a(1))

%% Downloading a text file

% Here is a text file, the outcome is putting the text file in a default
% location with a lousy, default name.
a = rd.listArtifacts('print',true,'type','txt');

fname = rd.readArtifact(a(1),'type','txt');

% This is the file that was downloaded by default.  It is ugly and includes
% terms thare are used by the database.  Readable, but ugly.  The advantage
% of doing it this way is the server will know that you downloaded it and
% if you request it again, it will just use the cached, local copy.
disp(fname)

% An alternative is that you can control the file destination. Used in this way,
% the file name is better and you control the destination folder precisely.
dFolder = fullfile(vistaRootPath,'local');
fname = rd.readArtifact(a(1),'destinationFolder',dFolder);
dir(dFolder)

% Notice that the file name is correct here, without all the annoying
% database formatting.  It is yours.  The server doesn't know about it.
disp(fname)

%% nii.gz files are stored as type 'gz'.  Sorry about that

% Here they are.  Vistasoft has a lot of nii.gz files in general
a = rd.listArtifacts('print',true,'type','gz');

% Here is the download with the destination specified
fname = rd.readArtifact(a(1),'destinationFolder',dFolder);

% But the file that is written out is good
disp(fname)

% And niftiRead works on the downloaded fname.
ni = niftiRead(fname)

%% Recursive listing

rd.crp('/vistadata/anatomy');

a = rd.listArtifacts('print',true,'recursive',true);

%% To upload vista data files requires a credential.

% See the files rdtPublishFunctional and rdtPublishAFQ for the methods used
% to move AFQ data and vistadata up to the RemoteDataToolbox site.

% cd(vistadata)
rd = RdtClient('vistasoft');
rd.credentialsDialog;

%%


function [status, fieldsUsed] = spm_matlab_version_chk(chk,tbx)
% Check a version number against a Toolbox version.
%    FORMAT [STATUS FIELDSUSED] = SPM_MATLAB_VERSION(CHK,TBX)
%
%    This function checks if a user supplied version number is less than,
%    equal to or greater than the version number of specified toolbox. If no
%    toolbox is specified the function checks the version of Matlab. User
%    defined toolboxes can be checked but the Contents.m file must conform
%    to the specification defined in ver.m
%
%    This function assumes that the version number is really a text string
%    with fields major.minor.revision.build. Other formats are not supported.
%    Checking is done to the level specified by the input version. Thus an
%    input of '7' will be rated as the same version as 7.1, but 7.0 would be
%    rated as earlier than 7.1.
%
%    INPUTS
%       chk         Version number to be checked [string].
%       tbx         Name of toolbox to check. Defaults to 'Matlab'.
%
%    OUPUTS
%       This is based on the fields the user supplies in the input.
%
%       status      Defines the outcome of the comparison
%            -1       Toolbox version is earlier than the user supplied version.
%             0       Toolbox and user versions are the same
%             1       Toolbox version is later than the user supplied version.
%                   Think of it this way, the sign of status is determined by
%                   MATLAB_TOOLBOX_VERSION - USER_VERSION (i.e., THE VERSION YOU
%                   INPUT).
%       fieldsUsed  Returns the version fields that were actually compared.
%
%    EXAMPLES
%       If the Matlab version is 7.1.0.83, and the user supplied version is '7':
%       status = spm_matlab_version_chk('7');
%       returns status == 0   : major revision numbers are the same.
%
%       If the Matlab version is 7.1.0.0, and the user supplied version is '7.1':
%       status = spm_matlab_version_chk('7');
%       returns status == 0   : major and minor revision numbers are the same.
%
%       If the Matlab version is 7.1.0.83, and the user supplied version is '7.2':
%       status = spm_matlab_version_chk('7.2');
%       returns status == -1   : major + minor revision is earlier for Matlab.
%
%       If the Matlab version is 6.5.1, and the user supplied version is '6.5.0'.
%       status = spm_matlab_version_chk('6.5.0');
%       returns status == 1     : major + minor + release revision is later
%                                 for matlab
%       The statement ( spm_matlab_version_chk('6.5.0') > 0 ) is true for
%       all Matlab Toolbox versions after 6.5.0.
%
%    See also  VERSION, VER.

%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Darren Gitelman
% $Id$

% output variable
%--------------------------------------------------------------------------
status = [];
fieldsUsed = [];

%  Check inputs
%--------------------------------------------------------------------------
% If no inputs then error; if 1 then set tbx to Matlab
%-------------------------------------------------------
switch nargin
    case 0
        error('Please provide a version number to be checked.');
    case 1
        tbx = 'Matlab';
end

% If a number is supplied then convert to text
%-------------------------------------------------------
if isnumeric(chk)
    chk = num2str(chk);
end

% If too many fields in input then error
%-------------------------------------------------------
if numel(findstr(chk,'.')) > 3
    error('Input string has too many fields. Only major.minor.release.build fields are supported.');
end

% parse the input string into a cell array of strings
%--------------------------------------------------------------------------
vCHK = textscan(chk,'%s %s %s %s','delimiter','.');

% find empty cells. These will be set to 0 in both cell arrays so that the
% same revision fields are compared
%--------------------------------------------------------------------------
emptyCHK = cellfun('isempty',vCHK);

% Get the requested toolbox version
%--------------------------------------------------------------------------
if strcmpi(tbx,'Matlab')
    % Matlab is a special case. The ver command does not report the
    % entire version string.
    [ tbxVer tmp ] = strtok(version);
else
    tbxStruct = ver(tbx);
    if numel(tbxStruct) >1
        error('Too many toolboxes found for given toolbox name.')
    end
    tbxVer = tbxStruct.Version;
end

% parse the requested toolbox version string into a cell array of strings.
%--------------------------------------------------------------------------
vTBX = textscan(tbxVer,'%s %s %s %s','delimiter','.');

% find empty cells. These will be removed from the cell array so that the
% same revision fields are compared
%--------------------------------------------------------------------------
emptyTBX = cellfun('isempty',vTBX);

% combine empty cell indices. notEmptyCells tell us which version
% fields are compared.
%--------------------------------------------------------------------------
emptyCellLogical = emptyCHK | emptyTBX;
emptyCells       = find(emptyCellLogical);
notEmptyCells    = find(~emptyCellLogical);

% and remove them.
%--------------------------------------------------------------------------
 vCHK(emptyCells) = [];
 vTBX(emptyCells) = [];

% final version fields to compare are converted to numbers
%--------------------------------------------------------------------------
vCHKMat = str2num(strvcat([vCHK{:}]))';
vTBXMat = str2num(strvcat([vTBX{:}]))';

% compare versions
%--------------------------------------------------------------------------
% This array will be used to decide which version is the later one. The
% differences between versions are computed on each element of the version
% number: major.minor.release.build and then multiplied by the base2array
% and summed. This is equivalent to logically combining the base 2 place
% values and ensures that the fields are evaluated by their significance.
% The sign of the summed values gives the result. Positive values mean the
% toolbox version is later, negative values mean the user supplied version,
% is later, and 0 means they are equal.
%--------------------------------------------------------------------------
base2array             = [8 4 2 1];
base2array(emptyCells) = [];

% take the difference between version elements.
%--------------------------------------------------------------------------
vDiff = vTBXMat - vCHKMat;

% get the sign of the differences
%--------------------------------------------------------------------------
signDiff = sign(vDiff);

% multiply by the base2array
%--------------------------------------------------------------------------
vVal = signDiff.*base2array;

% If the sign of the sum is positive then toolbox version is later; if 0
% they are the same, and if negative the user supplied version is later.
% Think of it this way: MATLAB_TOOLBOX_VERSION - USER_VERSION.
% Remember the comparison is made with respect to the FIELDS SUPPLED IN THE
% INPUT
%--------------------------------------------------------------------------
switch sign(sum(vVal))
    case -1     % MATLB_TOOLBOX_VERSION is EARLIER than USER_VERSION
        status = -1;
    case 0      % MATLB_TOOLBOX_VERSION = EQUALS = USER_VERSION
        status =  0;
    case 1      % MATLB_TOOLBOX_VERSION is LATER than USER_VERSION
        status =  1;
end

% also return the fields that were compared.
%--------------------------------------------------------------------------
fieldsUsed             = {'major','minor','revision','build'}';
fieldsUsed(emptyCells) = [];
return


function plotx2north
% set the default plot direction of the x-axis

setMTEXpref('xAxisDirection','north');


%{
Authors:
Jonatas Lopes de Paiva
Claudio Fabiano Motta Toledo
Helio Pedrini

%}

function pop = restartPop(pop, sizePop, denoisedImages, img, beta, lambda)

popTemp(sizePop).fitness = 0;
popTemp(sizePop).cromo = [];
popTemp(sizePop).id = '';
popTemp(1) = pop(1);

mut1 = denoisedImages(1).img;
mut2 = denoisedImages(2).img;
mut3 = denoisedImages(3).img;

fit1 = calcFitness(mut1, img, beta, lambda);
fit2 = calcFitness(mut2, img, beta, lambda);
fit3 = calcFitness(mut3, img, beta, lambda);

popTemp(2).fitness = fit1;
popTemp(2).cromo = mut1;
popTemp(2).id = char(java.util.UUID.randomUUID.toString);

popTemp(3).fitness = fit2;
popTemp(3).cromo = mut2;
popTemp(3).id = char(java.util.UUID.randomUUID.toString);

popTemp(4).fitness = fit3;
popTemp(4).cromo = mut3;
popTemp(4).id = char(java.util.UUID.randomUUID.toString);

for i = 5:sizePop
    tmp = denoisedImages(randi(3)).img;
    popTemp(i).cromo = mutation(tmp);
    popTemp(i).fitness = calcFitness(popTemp(i).cromo, img, beta, lambda);
    popTemp(i).id = char(java.util.UUID.randomUUID.toString);
end

pop = arrangePop(popTemp);

end


% This file should be run before running the HOWTO scripts
function startup

current_directory = fileparts(mfilename('fullpath'));
entries = strsplit(genpath(current_directory), pathsep);

% helper function to find matching entries
entry_matcher = @(entries, pattern) ~cellfun(@isempty, strfind(entries, pattern));

% Remove all .git and .svn entries from the path
entries(entry_matcher(entries, '.git') | entry_matcher(entries, '.svn')) = [];

% as well as the documentation folder
entries(entry_matcher(entries, strcat(filesep, 'documentation'))) = [];

if ~exist('OCTAVE_VERSION', 'builtin')
    % Matlab is running
    % Thus remove also the octave helper functions
    octave_path = strcat(filesep, 'external', filesep, 'octave_only');
    entries(entry_matcher(entries, octave_path)) = [];
else
    % Octave is running
    more off;
    pkg load tsa;
    pkg load signal;
end

% remove backward compatible functions
MATLABVERSION=version('-release');
MATLABVERSION=MATLABVERSION(1:end-1);
if str2double(MATLABVERSION)>=2015
    entries(entry_matcher(entries, 'backcompatibility_2015')) = [];
end

% addpaths
addpath(strjoin(entries, pathsep));
end


function verifyVarsEqual(testCase, name, varargin)
%verifyVarsEqual  Verify the equality of demo results within tolerance.
%
%  Description
%    verifyVarsEqual(testCase, name, vars, funcs, OPTIONS)
%    compares the elements in the results of a demo into the expected ones
%    using relative tolerance to each element individually and/or to the
%    range of the expected array and/or using absolute tolerance. The data
%    is loaded from the 'realValues' and 'testValues' folders. Used by the
%    gpstuff tests. Can be used with xUnit Test Framework package by Steve
%    Eddins or with the Matlab's built-in Unit Testing Framework (as of
%    version 2013b).
%
%    Parameters:
%      testCase
%        The testCase object, if using the integrated unit test framework,
%        or empty array, if using the xUnit package.
%      name
%        The name of the demo.
%      vars (optional)
%        Cell array of strings defining the numerical array variables that
%        are compared. Giving string 'same' (default) looks the names of
%        the saved variables in the file 'realValues/<nameOfTheDemo>.mat'
%        and compares them.
%      funcs (optional)
%        Cell array of function handles that are applied into the
%        corresponding actual and expected arrays before comparison. Cell
%        containing an empty array indicates that no function is used for
%        that variable. Empty array in general indicates that no function
%        is applied for any variable. Providing a single function handle
%        applies the function to all variables.
%
%    OPTIONS is optional parameter-value pair
%      RelTolElement - tolerance relative to the magnitude of each element
%                      (default 0.05)
%      RelTolRange   - tolerance relative to the range of the elements
%                      (default 0.01)
%      AbsTol        - absolute tolerance (default 0)
%
%   See also
%     TEST_*
%
% Copyright (c) 2014 Tuomas Sivula

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

% Parse inputs
ip = inputParser;
ip.FunctionName = 'verifyVarsEqual';
ip.addRequired('testCase',@(x) isempty(x) ...
    || isa(testCase, 'matlab.unittest.FunctionTestCase'))
ip.addRequired('name', @ischar)
ip.addOptional('vars', 'same', @(x) iscellstr(x) ...
    || (ischar(x) && strcmp(x,'same')))
ip.addOptional('funcs', [], @(x) isempty(x) || ...
    isa(x,'function_handle') || (iscell(x) && all( ...
    cellfun(@(y)isa(y,'function_handle')||isempty(y),x) )))
ip.addParamValue('RelTolElement', 0, ...
  @(x) isnumeric(x) && isscalar(x) && isreal(x) && x >= 0)
ip.addParamValue('RelTolRange', 0, ...
  @(x) isnumeric(x) && isscalar(x) && isreal(x) && x >= 0)
ip.addParamValue('AbsTol', 0, ...
  @(x) isnumeric(x) && isscalar(x) && isreal(x) && x >= 0)
ip.parse(testCase,name,varargin{:});
testCase = ip.Results.testCase;
name = ip.Results.name;
vars = ip.Results.vars;
funcs = ip.Results.funcs;
tol_el = ip.Results.RelTolElement;
tol_range = ip.Results.RelTolRange;
tol_abs = ip.Results.AbsTol;

% Handle parameter vars
if ischar(vars) && strcmp(vars, 'same')
  % Check the variable names from 'realValues/<nameOfTheDemo>.mat'
  vars = whos(matfile(['realValues/' name '.mat']));
  vars = {vars.name};
end

% Validate parameter funcs
if ~isempty(funcs) && iscell(funcs) && length(funcs) ~= length(vars)
  error('Parameter funcs size mismatch')
end

% Find the path to the test folder
path = mfilename('fullpath');
path = path(1:end-length(mfilename));

% For every variable in vars
for i = 1:length(vars)

  % Load the variables
  if isempty(testCase)
    % xUnit package
    Sw = warning('off','MATLAB:load:variableNotFound')
    try
      actual = load([path, 'testValues/' name '.mat'], vars{i});
      if ~isfield(actual, vars{i})
        error(['Variable ' vars{i} ' not found in testValues/' name '.mat'])
      end
      expected = load([path, 'realValues/' name '.mat'], vars{i});
      if ~isfield(expected, vars{i})
        error(['Variable ' vars{i} ' not found in realValues/' name '.mat'])
      end
    catch err
      warning(Sw)
      rethrow(err)
    end
    warning(Sw)
  else
    % Built-in test framework
    actual = assertWarningFree(testCase, ...
      @() load([path, 'testValues/' name '.mat'], vars{i}));
    expected = assertWarningFree(testCase, ...
      @() load([path, 'realValues/' name '.mat'], vars{i}));
  end

  % Error message (if the variable should fail the validation)
  msg = ['The variable ' vars{i} ' failed the verification.'];

  % Apply funcs
  if isa(funcs,'function_handle')
    actual = funcs(actual.(vars{i}));
    expected = funcs(expected.(vars{i}));
    %Add info to the error message
    msg = sprintf('%s\nFunction applied:\n%s', msg, func2str(funcs));
  elseif ~isempty(funcs) && ~isempty(funcs{i})
    actual = funcs{i}(actual.(vars{i}));
    expected = funcs{i}(expected.(vars{i}));
    %Add info to the error message
    msg = sprintf('%s\nFunction applied:\n%s', msg, func2str(funcs{i}));
  else
    actual = actual.(vars{i});
    expected = expected.(vars{i});
  end

  if isempty(testCase)

    % xUnit package (N.B. using assertions instead of verifications)
    if tol_el == 0 && tol_range == 0 && tol_abs == 0
      % No tolerance
      assertEqual(actual, expected, msg)
    else
      % Manual assertion

      % Compare
      diff = abs(actual(:) - expected(:));
      viol_el = 1;
      viol_range = 1;
      viol_abs = 1;
      if tol_el > 0
        viol_el = diff > tol_el*abs(expected(:));
      end
      if tol_range > 0
        viol_range = diff > tol_range ...
          *( max(expected(:)) - min(expected(:)) );
      end
      if tol_abs > 0
        viol_abs = diff > tol_abs;
      end

      if any( viol_el & viol_range & viol_abs )

        % Compose the message
        msg = sprintf( ...
          ['%s\nInput elements are not all equal within tolerances\n' ...
           '(RelTolElement=%g, RelTolRange=%g, AbsTol=%g)\n\n'], ...
          msg, tol_el, tol_range, tol_abs);
        if tol_el > 0 && any(viol_el)
          msg = sprintf( ...
            ['%sThe following indexes fail the elementwise relative ' ...
             'tolerance:\n%s\n\n'], ...
            msg, xunit.utils.arrayToString(find(viol_el)'));
        end
        if tol_range > 0 && any(viol_range)
          msg = sprintf( ...
            ['%sThe following indexes fail the range relative ' ...
             'tolerance:\n%s\n\n'], ...
            msg, xunit.utils.arrayToString(find(viol_range)'));
        end
        if tol_abs > 0 && any(viol_abs)
          msg = sprintf( ...
            ['%sThe following indexes fail the absolute ' ...
             'tolerance:\n%s\n\n'], ...
            msg, xunit.utils.arrayToString(find(viol_abs)'));
        end
        msg = sprintf( ...
          ['%sThe following indexes fail the comparison(s):\n%s\n\n' ...
           'First input:\n%s\n\nSecond input:\n%s'], ...
          msg, ...
          xunit.utils.arrayToString(find(viol_el & viol_range & viol_abs)'), ...
          xunit.utils.arrayToString(actual), ...
          xunit.utils.arrayToString(expected) );

        % Raise error
        throwAsCaller(MException('assertVars:tolExceeded', msg));

      end
    end

  else

    if tol_el == 0 && tol_range == 0 && tol_abs == 0
      % No tolerance
      verifyEqual(testCase, actual, expected, msg)
    else
      % Construct tolerance object
      if tol_el > 0
        tolObj = matlab.unittest.constraints.RelativeTolerance(tol_el);
      end
      if tol_range > 0
        if exist('tolObj', 'var')
          tolObj = tolObj | matlab.unittest.constraints.AbsoluteTolerance( ...
            tol_range*( max(expected(:)) - min(expected(:)) ));
        else
          tolObj = matlab.unittest.constraints.AbsoluteTolerance( ...
            tol_range*( max(expected(:)) - min(expected(:)) ));
        end
      end
      if tol_abs > 0
        if exist('tolObj', 'var')
          tolObj = tolObj | matlab.unittest.constraints.AbsoluteTolerance( ...
            tol_abs);
        else
          tolObj = matlab.unittest.constraints.AbsoluteTolerance(tol_abs);
        end
      end

      % Perform the verification
      testCase.verifyThat(actual, matlab.unittest.constraints.IsEqualTo( ...
        expected, 'Within', tolObj), msg);

    end

  end

  % Clear variables
  clear actual expected tolObj

end


function title = p04_title ( )

%*****************************************************************************80
%
%% P04_TITLE returns the title of problem 4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'The jump data, 0 0 0 0 0 1/2 1 1 1 1 1';

  return
end


function s = json2struct(j)

j = j(2:end-1); % remove the { and }
t = tokenize(j, ',');

s = struct();
for i=1:numel(t)
  kv = tokenize(t{i}, ':');
  key = kv{1}(2:end-1); % remove the " and "
  val = kv{2};
  if any(val(1)=='0123456789') && ~isnan(str2double(val))
    val = str2double(val);
  elseif isequal(val, 'true')
    val = true;
  elseif isequal(val, 'false')
    val = false;
  else
    val = val(2:end-1); % remove the " and "
  end
  key = fixname(key);
  s.(key) = val;
end


function [hdr] = read_wdq_header(filename)

% READ_WDQ_HEADER reads header information from wdq files
%
% Use as
%  [hdr] = read_wdq_header(filename)
%

% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% information about how to interpret the file are taken from the document
% 'CODAS data storage format'

fid = fopen_or_error(filename, 'r');
%tmp = fread(fid, 110); % the first 110 bytes are always interpretable equally
hdr = [];
hdr.nchan         = fread(fid, 1, 'uint16=>uint16');
% hdr.nchan         = hdr.nchan - bitand(hdr.nchan, 32);
hdr.nchan         = double(bitand(hdr.nchan, 255)); % only the lowest bits seem to be coding the number of channels
i2                = fread(fid, 1, 'uint16');
hdr.offset        = fread(fid, 1, 'uint8');
hdr.nbyteschanhdr = fread(fid, 1, 'uint8');
hdr.nbyteshdr     = fread(fid, 1, 'int16');
hdr.nbytesdat     = fread(fid, 1, 'uint32'); %FIXME only for unpacked files
hdr.nbytestrailer1 = fread(fid, 1, 'uint32');
hdr.nbytestrailer2 = fread(fid, 1, 'uint16');
i9  = fread(fid, 1, 'uint16'); % not used
i10 = fread(fid, 1, 'uint16'); % not used
i11 = fread(fid, 1, 'int16');
i12 = fread(fid, 4, 'int8');
i13 = fread(fid, 1, 'double');

% FIXME there seems to be a discrepancy here, according to the
% documentation it should be the next (commented) line. according to the
% file I have at hand it should be the uncommented line.
%hdr.fsample        = double(hdr.nchan)./i13;
hdr.fsample = 1./i13;
i14 = fread(fid, 1, 'uint32');
i15 = fread(fid, 1, 'uint32');
i16 = fread(fid, 1, 'uint32');
i17 = fread(fid, 1, 'uint32');
i18 = fread(fid, 1, 'uint32');
i19 = fread(fid, 2, 'uint16');
i20 = fread(fid, 1, 'int16');
i21 = fread(fid, 1, 'int16');
i22 = fread(fid, 1, 'int8');
i23 = fread(fid, 1, 'int8');
i24 = fread(fid, 1, 'int8');
i25 = fread(fid, 1, 'int8');
i26 = fread(fid, 32, 'int8');
i27 = fread(fid, 1, 'uint16');
i28 = fread(fid, 1, 'uint8');
empty = fread(fid, 1, 'uint8');
i29 = fread(fid, 1, 'int8');
i30 = fread(fid, 1, 'int8');
i31 = fread(fid, 1, 'int8');
empty = fread(fid, 1, 'uint8');
i32 = fread(fid, 1, 'int8');
i33 = fread(fid, 1, 'int8');

% interpret relevant stuff from i27
% other stuff may or may not be relevant
hdr.ispacked  = bitand(i27, 2^15)>0;
hdr.lowchan   = bitand(i27, 2^9) >0;

% get channel info
for k = 1:(hdr.nbyteshdr-hdr.offset-2)/hdr.nbyteschanhdr
  fseek(fid, hdr.offset + (k-1)*hdr.nbyteschanhdr, 'bof');
  chanhdr(k).scalingslope     = fread(fid, 1, 'float');
  chanhdr(k).scalingintercept = fread(fid, 1, 'float');
  chanhdr(k).scale            = fread(fid, 1, 'double');
  chanhdr(k).intercept        = fread(fid, 1, 'double');
  chanhdr(k).unit             = fread(fid, 1, 'uint8=>char');
  fread(fid, 1, 'uint8');
  fread(fid, 1, 'uint8'); % may be relevant for packed files
  chanhdr(k).channr = fread(fid, 1, 'uint8');
  chanhdr(k).label  = num2str(k);
end
hdr.chanhdr = chanhdr;

fseek(fid, hdr.nbyteshdr + hdr.nbytesdat, 'bof');
x = fread(fid, hdr.nbytestrailer1, 'uint8');
hdr.x = x; % what shall we do with this?

fseek(fid, hdr.nbyteshdr + hdr.nbytesdat + hdr.nbytestrailer1, 'bof');
annot = fread(fid, hdr.nbytestrailer2, 'uint8');
sel   = find(annot==0);
indx  = find(annot>0, 1, 'first');
sel   = [0;sel];
for k = 1:numel(sel)-1
  hdr.chanhdr(k).annot = char(annot(sel(k)+1:sel(k+1)-1))';
end

fclose(fid);


function OutputFile = db_add(iTarget, InputFile, isReload)
% DB_ADD: Create a new file in a given study.
%
% USAGE:  db_add(iStudy/iSubject, InputFile, isReload)
%         db_add(iStudy/iSubject, sNew     , isReload)
%         db_add(iStudy/iSubject)             : Read a variable from Matlab workspace

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2011-2022

%% ===== GET INPUT FILE =====
if (nargin < 3) || isempty(isReload)
    isReload = 1;
end
% USAGE:  db_add(iTarget)
if (nargin < 2) || isempty(InputFile)
    % Get variable from workspace
    [InputFile, varname] = in_matlab_var([], 'struct');
    if isempty(InputFile)
        OutputFile = [];
        return
    end
end
% USAGE:  db_add(iTarget, sMat)
if isstruct(InputFile)
    % Get structure
    sMat = InputFile;
    InputFile = [];
    % Detect file type
    fileType = file_gettype(sMat);
    % Add sub-category for timefreq files
    fileSubType = '';
    if ismember(fileType, {'timefreq', 'ptimefreq'})
        if ismember(lower(sMat.Method), {'corr', 'cohere', 'granger', 'spgranger', 'plv', 'plvt', 'aec', 'pte','henv'})
            if (length(sMat.RefRowNames) > 1) && (isequal(sMat.RowNames, sMat.RefRowNames) || isequal(sMat.RowNames, sMat.RefRowNames'))
                fileSubType = ['connectn_', lower(sMat.Method), '_'];
                if (size(sMat.TF,1) == length(sMat.RefRowNames)*length(sMat.RowNames))
                    sMat.Options.isSymmetric = 0;
                else
                    sMat.Options.isSymmetric = 1;
                end
            else
                fileSubType = ['connect1_', lower(sMat.Method), '_'];
                sMat.Options.isSymmetric = 0;
            end
        elseif ismember(lower(sMat.Method), {'pac', 'dpac', 'tpac'}) && isfield(sMat,'sPAC')
            if isfield(sMat.sPAC, 'DirectPAC') && ~isempty(sMat.sPAC.DirectPAC)
                fileSubType = 'pac_fullmaps_';
            else
                fileSubType = 'dpac_fullmaps_';
            end
        else
            fileSubType = [lower(sMat.Method), '_'];
        end
    end
    % Add stat thresholding method
    if ismember(fileType, {'pdata', 'presults', 'ptimefreq', 'pmatrix'})
        if isfield(sMat, 'Correction') && ~isempty(sMat.Correction)
            fileSubType = [fileSubType, lower(sMat.Correction), '_'];
        end
    end
    % Add zscore tag
    if isfield(sMat, 'ZScore') && ~isempty(sMat.ZScore)
        if isfield(sMat.ZScore, 'abs') && isequal(sMat.ZScore.abs, 1)
            fileSubType = [fileSubType 'abs_zscore_'];
        else
            fileSubType = [fileSubType 'zscore_'];
        end
    end
    % Some files cannot be imported
    if ismember(fileType, {'brainstormsubject', 'brainstormstudy', 'unknown'})
        bst_error('This structure cannot be imported in the database.', 'Add file to database', 0);
        return;
    end
    % Surfaces subtypes
    if ismember(fileType, {'fibers', 'fem'})
        fileType = 'tess';
        fileSubType = [fileType, '_'];
    end
    isAnatomy = ismember(fileType, {'subjectimage', 'tess'});
    % Spikes: file tag is data
    if strcmp(fileType, 'spike')
        fileType = 'data';
        fileSubType = '0ephys_';
    end
    % Create a new output filename
    c = clock;
    strTime = sprintf('%02.0f%02.0f%02.0f_%02.0f%02.0f', c(1)-2000, c(2:5));
    OutputFile = [fileType '_' fileSubType strTime '.mat'];

% USAGE:  db_add(iTarget, InputFile)
else
    % Get full file path and type
    [InputFileFull, fileType, isAnatomy] = file_fullpath(InputFile);
    % Output filename
    [fPath, fBase] = bst_fileparts(InputFile);
    OutputFile = [fBase, '.mat'];
    % Read file
    sMat = load(InputFileFull);
end

%% ===== OUTPUT FILENAME =====
% Get protocol folders
ProtocolInfo = bst_get('ProtocolInfo');
% Full output filename
if isAnatomy
    % Get destination study
    sSubject = bst_get('Subject', iTarget);
    % Build full filename
    OutputFileFull = file_unique(bst_fullfile(ProtocolInfo.SUBJECTS, bst_fileparts(sSubject.FileName), OutputFile));
    OutputFile = file_short(OutputFileFull);
else
    % Get destination study
    sStudy = bst_get('Study', iTarget);
    % Build full filename
    OutputFileFull = file_unique(bst_fullfile(ProtocolInfo.STUDIES, bst_fileparts(sStudy.FileName), OutputFile));
    OutputFile = file_short(OutputFileFull);
end

%% ===== REPLACE EXISTING FILES =====
% Check for files that can exist in only one version
if ismember(fileType, {'subjectimage', 'channel', 'noisecov', 'ndatacov'})
    % Get file to replace
    delfile = '';
    switch(fileType)
        case 'subjectimage'
%             if ~isempty(sSubject.Anatomy)
%                 delfile = bst_fullfile(ProtocolInfo.SUBJECTS, sSubject.Anatomy(1).FileName);
%             end
        case 'channel'
            if ~isempty(sStudy.Channel)
                delfile = bst_fullfile(ProtocolInfo.STUDIES, sStudy.Channel(1).FileName);
            end
        case 'noisecov'
            if ~isempty(sStudy.NoiseCov) && ~isempty(sStudy.NoiseCov(1).FileName)
                delfile = bst_fullfile(ProtocolInfo.STUDIES, sStudy.NoiseCov(1).FileName);
            end
        case 'ndatacov'
            if ~isempty(sStudy.NoiseCov) && (length(sStudy.NoiseCov) >= 2) && ~isempty(sStudy.NoiseCov(2).FileName)
                delfile = bst_fullfile(ProtocolInfo.STUDIES, sStudy.NoiseCov(2).FileName);
            end
    end
    % Replace file
    if ~isempty(delfile)
        % Ask for user confirmation
        isdel = java_dialog('confirm', ['Replace existing ' fileType ' file?'], 'Add file to database');
        if ~isdel
            OutputFile = [];
            return
        end
        % Delete existing file
        file_delete(delfile, 1);
    end
end

%% ===== ADD COMMENT TAG =====
matVer = 'v7';
if isAnatomy
    % Get subject structure
    sSubject = bst_get('Subject', iTarget);
    % Update comment with a file tag, to make it unique
    switch (fileType)
        case 'subjectimage'
            % Nothing to do: file is replaced anyway
        case {'tess', 'cortex', 'scalp', 'outerskull', 'innerskull', 'fibers', 'fem'}
            sMat.Comment = file_unique(sMat.Comment, {sSubject.Surface.Comment});
    end
else
    % Add comment if missing
    if isempty(sMat.Comment)
        [tmp__, sMat.Comment] = bst_fileparts(InputFile);
    end
    % Get study structure
    sStudy = bst_get('Study', iTarget);
    % Update comment with a file tag, to make it unique
    switch (fileType)
        case 'data'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.Data.Comment});
            matVer = 'v6';
        case 'headmodel'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.HeadModel.Comment});
        case 'results'
            if ~isempty(sMat.DataFile)
                iRes = find(file_compare(sMat.DataFile, {sStudy.Result.DataFile}));
                if isempty(iRes)
                    iRes = find(cellfun(@isempty, {sStudy.Result.DataFile}));
                end
                if ~isempty(iRes)
                    sMat.Comment = file_unique(sMat.Comment, {sStudy.Result(iRes).Comment});
                end
            else
                sMat.Comment = file_unique(sMat.Comment, {sStudy.Result.Comment});
            end
            matVer = 'v6';
        case 'stat'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.Stat.Comment});
            matVer = 'v6';
        case 'dipoles'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.Dipoles.Comment});
        case 'timefreq'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.Timefreq.Comment});
            matVer = 'v6';
        case 'matrix'
            sMat.Comment = file_unique(sMat.Comment, {sStudy.Matrix.Comment});
            matVer = 'v6';
    end
end

%% ===== ADD NEW FILE TO DATABASE =====
% Progress bar
isProgress = bst_progress('isVisible');
if ~isProgress
    bst_progress('start', 'Add file to database', 'Saving new file...');
else
    bst_progress('text', 'Saving new file...');
end
% Save new file
bst_save(OutputFileFull, sMat, matVer);
% Close progress bar
if ~isProgress
    bst_progress('stop');
end
% Reload output study
if isReload
    if isAnatomy
        db_reload_subjects(iTarget);
    else
        db_reload_studies(iTarget);
    end
    panel_protocols('UpdateTree');
    panel_protocols('SelectNode', [], OutputFileFull);
end


classdef TestWarpAffine
    %TestWarpAffine

    properties (Constant)
        img = fullfile(mexopencv.root(),'test','img001.jpg');
    end

    methods (Static)
        function test_1
            im = imread(TestWarpAffine.img);
            M = eye(2,3);  % identity transform
            dst = cv.warpAffine(im, M);
            validateattributes(dst, {class(im)}, {'size',size(im)});
            assert(isequal(im, dst));
        end

        function test_2
            im = cv.imread(TestWarpAffine.img, 'Grayscale',true);
            M = eye(2,3);  % identity transform
            dst = cv.warpAffine(im, M, 'DSize',[256 256], ...
                'Interpolation','Linear', 'WarpInverse',false, ...
                'BorderType','Constant', 'BorderValue',0);
            validateattributes(dst, {class(im)}, {'size',[256 256]});
        end

        function test_3
            im = imread(TestWarpAffine.img);
            [h,w,~] = size(im);
            M = cv.getRotationMatrix2D([w h]./2, 30, 0.7);
            dst = cv.warpAffine(im, M, 'Dst',im, 'BorderType','Transparent');
            validateattributes(dst, {class(im)}, {'size',size(im)});
        end

        function test_error_argnum
            try
                cv.warpAffine();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end