function fire_serial ( forest_size, prob_spread )

%*****************************************************************************80
%
%% MAIN is the main program for FIRE_SERIAL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013.
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, specifies the forest as a square of
%    FOREST_SIZE by FOREST_SIZE trees.  Default is 20.
%
%    Input, real PROB_SPREAD, the probability that fire will spread from
%    a burning tree to its neighbor.  Default is 0.5.
%
  if ( nargin < 1 )
    forest_size = 20;
  elseif ( ischar ( forest_size ) )
    forest_size = str2num ( forest_size );
  end

  if ( nargin < 2 )
    prob_spread = 0.5;
  elseif ( ischar ( prob_spread ) )
    prob_spread = str2num ( prob_spread );
  end

  SMOLDERING = 1;

  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FIRE_SERIAL\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  A probabilistic simulation of a forest fire.\n' );
  fprintf ( 1, '  The forest size is %d\n', forest_size );
  fprintf ( 1, '  The probability of tree-to-tree spread is %g\n', prob_spread );
%
%  Initialize the random number generator.
%
  seed = get_seed ( );
  fprintf ( 1, '  The random number generator is seeded by %d\n', seed );
%
%  Initialize the values in the forest.
%
  forest = forest_initialize ( forest_size );
%
%  Choose a tree at random where the fire will start.
%
  [ i_ignite, seed ] = i4_uniform_ab ( 1, forest_size, seed );
  [ j_ignite, seed ] = i4_uniform_ab ( 1, forest_size, seed );
  forest(i_ignite,j_ignite) = SMOLDERING;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Fire starts at tree(%d,%d)\n', i_ignite, j_ignite );
%
%  Let time run until nothing is burning any more.
%
  while ( forest_is_burning ( forest_size, forest ) )
    [ forest, seed ] = forest_burns ( forest_size, forest, seed, prob_spread );
  end
%
%  Display the final forest state.
%
  forest_print ( forest_size, forest, i_ignite, j_ignite );
%
%  Report the percentage of forest burned.
%
  percent = get_percent_burned ( forest_size, forest );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Percentage of forest burned = %g\n', percent );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FIRE_SERIAL:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function [ value, seed ] = fire_spreads ( seed, prob_spread )

%*****************************************************************************80
%
%% FIRE_SPREADS determines whether the fire spreads.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input/output, integer SEED, a seed for the random
%    number generator.
%
%    Input, real PROB_SPREAD, the probability of spreading.
%
%    Output, logical VALUE, is TRUE if the fire spreads.
%
  [ u, seed ] = r8_uniform_01 ( seed );

  if ( u < prob_spread )
    value = 1;
  else
    value = 0;
  end

  return
end
function [ forest, seed ] = forest_burns ( forest_size, forest, seed, ...
  prob_spread )

%*****************************************************************************80
%
%% FOREST_BURNS models a single time step of the burning forest.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, the linear dimension of the forest.
%
%    Input/output, integer FOREST(FOREST_SIZE,FOREST_SIZE), an
%    array with an entry for each tree in the forest.
%
%    Input/output, integer SEED, a seed for the random
%    number generator.
%
%    Input, real PROB_SPREAD, the probability that the fire will
%    spread from a burning tree to an unburnt one.
%
  BURNING = 2;
  BURNT = 3;
  SMOLDERING = 1;
  UNBURNT = 0;
%
%  Burning trees burn down;
%  Smoldering trees ignite;
%
  for j = 1 : forest_size
    for i = 1 : forest_size
      if ( forest(i,j) == BURNING )
        forest(i,j) = BURNT;
      elseif ( forest(i,j) == SMOLDERING )
        forest(i,j) = BURNING;
      end
    end
  end
%
%  Unburnt trees might catch fire.
%
  for j = 1 : forest_size
    for i = 1 : forest_size

      if ( forest(i,j) == BURNING )
%
%  North.
%
        if ( 1 < i )
          if ( forest(i-1,j) == UNBURNT )
            [ value, seed ] = fire_spreads ( seed, prob_spread );
            if ( value )
              forest(i-1,j) = SMOLDERING;
            end
          end
        end
%
%  South.
%
        if ( i < forest_size )
          if ( forest(i+1,j) == UNBURNT )
            [ value, seed ] = fire_spreads ( seed, prob_spread );
            if ( value )
              forest(i+1,j) = SMOLDERING;
            end
          end
        end
%
%  West.
%
        if ( 1 < j )
          if ( forest(i,j-1) == UNBURNT )
            [ value, seed ] = fire_spreads ( seed, prob_spread );
            if ( value )
              forest(i,j-1) = SMOLDERING;
            end
          end
        end
%
%  East.
%
        if ( j < forest_size )
          if ( forest(i,j+1) == UNBURNT )
            [ value, seed ] = fire_spreads ( seed, prob_spread );
            if ( value )
              forest(i,j+1) = SMOLDERING;
            end
          end
        end

      end

    end
  end

  return
end
function forest = forest_initialize ( forest_size )

%*****************************************************************************80
%
%% FOREST_INITIALIZE initializes the forest values.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, the linear dimension of the forest.
%
%    Output, integer FOREST(FOREST_SIZE,FOREST_SIZE), an array
%    with an entry for each tree in the forest.
%
  UNBURNT = 0;

  forest(1:forest_size,1:forest_size) = UNBURNT;

  return
end
function value = forest_is_burning ( forest_size, forest )

%*****************************************************************************80
%
%% FOREST_IS_BURNING reports whether any trees in the forest are burning.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, the linear dimension of the forest.
%
%    Input, integer FOREST(FOREST_SIZE,FOREST_SIZE), an array
%    with an entry for each tree in the forest.
%
%    Output, logical FOREST_IS_BURNING, is TRUE if any tree in the forest
%    is in the SMOLDERING or BURNING state.
%
  BURNING = 2;
  SMOLDERING = 1;

  value = 0;

  for j = 1 : forest_size
    for i = 1 : forest_size
      if ( forest(i,j) == SMOLDERING || forest(i,j) == BURNING )
        value = 1;
      end
    end
  end

  return
end
function forest_print ( forest_size, forest, i_ignite, j_ignite )

%*****************************************************************************80
%
%% FOREST_PRINT prints the state of the trees in the forest.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, the linear dimension of the forest.
%
%    Input, integer FOREST(FOREST_SIZE,FOREST_SIZE), an array
%    with an entry for each tree in the forest.
%
%    Input, integer I_IGNITE, J_IGNITE, the location of the start
%    of the fire.
%
  BURNT = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Map of fire damage.\n' );
  fprintf ( 1, '  Fire started at "*".\n' );
  fprintf ( 1, '  Burned trees are indicated by ".".\n' );
  fprintf ( 1, '  Unburned trees are indicated by "X".\n' );
  fprintf ( 1, '\n' );

  for i = 1 : forest_size
    fprintf ( 1, '  ' );
    for j = 1 : forest_size
      if ( i == i_ignite && j == j_ignite )
        fprintf ( 1, '*' );
      elseif ( forest(i,j) == BURNT )
        fprintf ( 1, '.' );
      else
        fprintf ( 1, 'X' );
      end
    end
    fprintf ( 1, '\n' );
  end

  return
end
function percent = get_percent_burned ( forest_size, forest )

%*****************************************************************************80
%
%% GET_PERCENT_BURNED computes the percentage of the forest that burned.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2013
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer FOREST_SIZE, the linear dimension of the forest.
%
%   Input, integer FOREST(FOREST_SIZE,FOREST_SIZE), an array
%    with an entry for each tree in the forest.
%
%    Output, real PERCENT, the percentage of the forest
%    that burned.
%
  BURNT = 3;

  total = 0;
  for j = 1 : forest_size
    for i = 1 : forest_size
      if ( forest(i,j) == BURNT )
        total = total + 1;
      end
    end
  end

  percent = total / forest_size / forest_size;

  return
end
function seed = get_seed ( )

%*****************************************************************************80
%
%% GET_SEED returns a seed for the random number generator.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 November 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer SEED, a random seed value.
%
  I_MAX = 2147483647;

  time_array = clock;

  hour = time_array(4);
  minute = time_array(5);
  second = time_array(6);

  temp = ( second + 60 * ( minute + 60 * hour ) ) / ( 60.0 * 60.0 * 24.0 );

  if ( temp <= 0.0 )
    temp = temp + 1.0;
  end

  if ( 1.0 < temp )
    temp = temp - 1.0;
  end

  seed = 1 + floor ( I_MAX * temp );

  return
end
function [ c, seed ] = i4_uniform_ab ( a, b, seed )

%*****************************************************************************80
%
%% I4_UNIFORM_AB returns a scaled pseudorandom I4.
%
%  Discussion:
%
%    The pseudorandom number will be scaled to be uniformly distributed
%    between A and B.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 November 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Bratley, Bennett Fox, Linus Schrage,
%    A Guide to Simulation,
%    Second Edition,
%    Springer, 1987,
%    ISBN: 0387964673,
%    LC: QA76.9.C65.B73.
%
%    Bennett Fox,
%    Algorithm 647:
%    Implementation and Relative Efficiency of Quasirandom
%    Sequence Generators,
%    ACM Transactions on Mathematical Software,
%    Volume 12, Number 4, December 1986, pages 362-376.
%
%    Pierre L'Ecuyer,
%    Random Number Generation,
%    in Handbook of Simulation,
%    edited by Jerry Banks,
%    Wiley, 1998,
%    ISBN: 0471134031,
%    LC: T57.62.H37.
%
%    Peter Lewis, Allen Goodman, James Miller,
%    A Pseudo-Random Number Generator for the System/360,
%    IBM Systems Journal,
%    Volume 8, Number 2, 1969, pages 136-143.
%
%  Parameters:
%
%    Input, integer A, B, the minimum and maximum acceptable values.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, integer C, the randomly chosen integer.
%
%    Output, integer SEED, the updated seed.
%
  i4_huge = 2147483647;

  if ( seed == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4_UNIFORM_AB - Fatal error!\n' );
    fprintf ( 1, '  Input SEED = 0!\n' );
    error ( 'I4_UNIFORM_AB - Fatal error!' );
  end

  seed = floor ( seed );
  a = round ( a );
  b = round ( b );

  seed = mod ( seed, i4_huge );

  if ( seed < 0 )
    seed = seed + i4_huge;
  end

  k = floor ( seed / 127773 );

  seed = 16807 * ( seed - k * 127773 ) - k * 2836;

  if ( seed < 0 )
    seed = seed + i4_huge;
  end

  r = seed * 4.656612875E-10;
%
%  Scale R to lie between A-0.5 and B+0.5.
%
  r = ( 1.0 - r ) * ( min ( a, b ) - 0.5 ) ...
    +         r   * ( max ( a, b ) + 0.5 );
%
%  Use rounding to convert R to an integer between A and B.
%
  value = round ( r );

  value = max ( value, min ( a, b ) );
  value = min ( value, max ( a, b ) );

  c = value;

  return
end
function [ r, seed ] = r8_uniform_01 ( seed )

%*****************************************************************************80
%
%% R8_UNIFORM_01 returns a unit pseudorandom R8.
%
%  Discussion:
%
%    This routine implements the recursion
%
%      seed = 16807 * seed mod ( 2^31 - 1 )
%      r8_uniform_01 = seed / ( 2^31 - 1 )
%
%    The integer arithmetic never requires more than 32 bits,
%    including a sign bit.
%
%    If the initial seed is 12345, then the first three computations are
%
%      Input     Output      R8_UNIFORM_01
%      SEED      SEED
%
%         12345   207482415  0.096616
%     207482415  1790989824  0.833995
%    1790989824  2035175616  0.947702
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Bratley, Bennett Fox, Linus Schrage,
%    A Guide to Simulation,
%    Springer Verlag, pages 201-202, 1983.
%
%    Pierre L'Ecuyer,
%    Random Number Generation,
%    in Handbook of Simulation,
%    edited by Jerry Banks,
%    Wiley Interscience, page 95, 1998.
%
%    Bennett Fox,
%    Algorithm 647:
%    Implementation and Relative Efficiency of Quasirandom
%    Sequence Generators,
%    ACM Transactions on Mathematical Software,
%    Volume 12, Number 4, pages 362-376, 1986.
%
%    Peter Lewis, Allen Goodman, James Miller,
%    A Pseudo-Random Number Generator for the System/360,
%    IBM Systems Journal,
%    Volume 8, pages 136-143, 1969.
%
%  Parameters:
%
%    Input, integer SEED, the integer "seed" used to generate
%    the output random number.  SEED should not be 0.
%
%    Output, real R, a random value between 0 and 1.
%
%    Output, integer SEED, the updated seed.  This would
%    normally be used as the input seed on the next call.
%
  if ( seed == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8_UNIFORM_01 - Fatal error!\n' );
    fprintf ( 1, '  Input SEED = 0!\n' );
    error ( 'R8_UNIFORM_01 - Fatal error!' );
  end

  seed = floor ( seed );

  seed = mod ( seed, 2147483647 );

  if ( seed < 0 )
    seed = seed + 2147483647;
  end

  k = floor ( seed / 127773 );

  seed = 16807 * ( seed - k * 127773 ) - k * 2836;

  if ( seed < 0 )
    seed = seed + 2147483647;
  end

  r = seed * 4.656612875E-10;

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function inds = fernsInds( data, fids, thrs )
% Compute indices for each input by each fern.
%
% USAGE
%  inds = fernsInds( data, fids, thrs )
%
% INPUTS
%  data     - [NxF] N length F binary feature vectors
%  fids     - [MxS] feature ids for each fern for each depth
%  thrs     - [MxS] threshold corresponding to each fid
%
% OUTPUTS
%  inds     - [NxM] computed indices for each input by each fern
%
% EXAMPLE
%
% See also fernsClfTrain, fernsClfApply
%
% Piotr's Image&Video Toolbox      Version 2.50
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

inds = fernsInds1( data, fids, thrs );

%%% OLD MATLAB CODE -- NOW IN MEX
% [M,S]=size(fids); N=size(data,1);
% inds = zeros(N,M,'uint32');
% for n=1:N
%   for m=1:M
%     for s=1:S
%       inds(n,m)=inds(n,m)*2;
%       if( data(n,fids(m,s))<thrs(m,s) )
%         inds(n,m)=inds(n,m)+1;
%       end
%     end
%   end
% end
% inds=inds+1;
% end


function element_node = grid_element ( code, element_order, nelemx, nelemy )

%*****************************************************************************80
%
%% GRID_ELEMENT returns the grid associated with any available element.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character CODE(*), identifies the element desired.
%    Legal values include 'Q4', 'Q8', 'Q9', 'Q12', 'Q16', 'QL', 'T3',
%    'T6' and 'T10'.
%
%    Input, integer ELEMENT_ORDER, the order of the element.
%
%    Input, integer NELEMX, NELEMY, the number of quadrilaterals along the
%    X and Y directions.  The number of elements generated will be
%    NELEMX * NELEMY for quadrilaterals, or 2 * NELEMX * NELEMY for
%    triangles.
%
%    Output, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM), the nodes
%    that form each element.
%
  if ( s_eqi ( code, 'Q4' ) )
    element_node = grid_q4_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'Q8' ) )
    element_node = grid_q8_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'Q9' ) )
    element_node = grid_q9_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'Q12' ) )
    element_node = grid_q12_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'Q16' ) )
    element_node = grid_q16_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'QL' ) )
    element_node = grid_ql_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'T3' ) )
    element_node = grid_t3_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'T4' ) )
    element_node = grid_t4_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'T6' ) )
    element_node = grid_t6_element ( nelemx, nelemy );
  elseif ( s_eqi ( code, 'T10' ) )
    element_node = grid_t10_element ( nelemx, nelemy );

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'GRID_ELEMENT - Fatal error!\n' );
    fprintf ( 1, '  Illegal value of CODE = %s\n', code );
    error ( 'GRID_ELEMENT - Fatal error!' );

  end

  return
end


function results = PTKComputeVentilatedVolume(ventilation_mask, region_mask)
    % PTKComputeVentilatedVolume. Computes the percentage of a region showing
    %     ventilation in gas MRI images
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2014.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.

    ventilation_mask_raw = ventilation_mask.RawImage > 0;
    ventilation_mask_raw = ventilation_mask_raw & region_mask.RawImage > 0;

    sum_ventilated_voxels = sum(ventilation_mask_raw(:));
    sum_region_voxels = sum(region_mask.RawImage(:));

    percentage_ventilated = 100*sum_ventilated_voxels/sum_region_voxels;

    ventilated_volume_mm3 = sum_ventilated_voxels*prod(ventilation_mask.VoxelSize);

    results = PTKMetrics;
    results.AddMetric('VentilatedVolumePercent', percentage_ventilated, 'Ventilated volume (%)');
    results.AddMetric('VentilatedVolume', ventilated_volume_mm3/1000, 'ventilated Volume (cm^3)');
end


function Y=diff(varargin)
%DIFF (overloaded)

X = varargin{1};
n = X.dim(1);
m = X.dim(2);

Y = X;
x_lmi_variables = X.lmi_variables;
lmi_variables = [];

% Fast diff of large matrices. Convert to optmized case
switch nargin
    case 1
        if (min([n m]) > 1)
            Y = diff(X',1,2)';
            return
        end

    case 2
        if varargin{2} == 1 & (min([n m]) > 1)
            Y = diff(X',1,2)';
            return
        end
    case 3
        if varargin{2}==1 & varargin{3} == 2 & (min([n m]) > 1)
            shift = [-speye(m-1) spalloc(m-1,1,0)] + [spalloc(m-1,1,0) speye(m-1)];
            %            shift = shift(1:m-1,1:m);
            shift = kron(shift,speye(n));
            Y.basis = shift*X.basis;
            Y.dim(1) = n;
            Y.dim(2) = m - 1;
            % Reset info about conic terms
            Y.conicinfo = [0 0];
            Y = clean(Y);
            return
        elseif varargin{2}==1 & varargin{3} == 1  & (min([n m]) > 1)
            Y = diff(X',1,2)';
            return
        end

    otherwise
        error('To many input arguments.')
end

% Slow but safe case. Used for higher order diff
try
    j = 1;
    diffX = diff(reshape(X.basis(:,1),n,m),varargin{2:end});
    Y.basis=diffX(:);
    for i = 1:length(x_lmi_variables)
        diffX = diff(reshape(X.basis(:,i+1),n,m),varargin{2:end});
        if (norm(diffX,inf)>0)
            Y.basis(:,j+1) = diffX(:);
            lmi_variables = [lmi_variables x_lmi_variables(i)];
            j = j+1;
        end
    end
    if j~=1
        Y.lmi_variables = lmi_variables;
    else
        Y = full(reshape(Y.basis(:,1),size(diffX,1),size(diffX,2)));
        return
    end
catch
    error(lasterr)
end
Y.dim(1) = size(diffX,1);
Y.dim(2) = size(diffX,2);
% Reset info about conic terms
Y.conicinfo = [0 0];


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

% parameters
dataset = 'thun';
granularity = 60;
houses = [5];
appliance_name = 'microwave';
dates = ['2012-07-11'];
start_date = '2012-07-11';
end_date = '2012-07-11';
consumptionArray = zeros((24*60*60)/granularity,5);

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

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


function [XS,XF,O,H,L,C,V] = filterdata_lookback(XS,XF,D,O,H,L,C,V)

ndays = length(D);

% Take out the days that are NaN
index_nonNaN_linear = find(~isnan(O));
index_nonNaN_sub = zeros(size(O));
index_nonNaN_sub(index_nonNaN_linear(:)) = 1; % matrix of values with non-NaN
ndays_valid = sum(index_nonNaN_sub,1);

% Now we filter by stocks, then by days
ndays_filter = mode(ndays_valid); % use the charts with the modal number of days
%index_stocks_valid = find(ndays_valid == ndays_filter); % filter out stocks with not many days
index_stocks_invalid = find(ndays_valid ~= ndays_filter); % filter out stocks with not many days

% Filter out stocks that don't have modal number of available days
%ntickers = size(XS(:,1),1);
O(:,index_stocks_invalid)=[]; H(:,index_stocks_invalid)=[]; L(:,index_stocks_invalid)=[];
C(:,index_stocks_invalid)=[]; V(:,index_stocks_invalid)=[];
XS(index_stocks_invalid,:)=[]; XF(index_stocks_invalid,:)=[];

fprintf('Filtering modal days... [%d days, %d stocks]\n',size(O,1),size(O,2))

% Now take out all rows with nans (corresponds to holidays and weekends)
[rows, columns] = find(isnan(O)); % finds the rows and columns of elements that have nan
index_weekendsholidays = unique(rows); % find the unique rows
O(index_weekendsholidays,:)=[]; H(index_weekendsholidays,:)=[]; L(index_weekendsholidays,:)=[];
C(index_weekendsholidays,:)=[]; V(index_weekendsholidays,:)=[];
fprintf('Filtering NaN days... [%d days, %d stocks]\n',size(O,1),size(O,2));

% Make sure there are no more NaNs
if( length(find(isnan(O)))>0 )
  error('NaNs are still in the data. Remove them!')
end
end


function [pvec, pstruct] = tapas_softmax_binary_transp(r, ptrans)
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

pvec    = NaN(1,length(ptrans));
pstruct = struct;

pvec(1)    = exp(ptrans(1));         % be
pstruct.be = pvec(1);

return;


function CompareClassifierWithLabels(clfile,ncomparisons,explist)
% Compares the classifier's predictions with a classifier trained with the current labels.

if nargin <2
  ncomparisons = 3;
end

if nargin<3,
  explist = {};
end

Q = load(clfile);
configfile = Q.configfilename;

data = JLabelData(configfile,'openmovie',false);

if isempty(explist),
  data.SetClassifierFileName(clfile);
  allOrig = getCurrentScores(data);

else
  data.SetClassifierFileNameWoExp(clfile);
  for ndx = 1:numel(explist)
    [success,msg] = data.AddExpDir(explist{ndx});
    if ~success,
      warning(msg);
      continue;
    end
  end

  scores = [];
  for endx = 1:data.nexps
    sfn = data.GetFile('scores',endx);
    Q = load(sfn);
    allScores = Q.allScores;

    for ndx = 1:numel(allScores.scores);
      ts = allScores.tStart(ndx);
      te = allScores.tEnd(ndx);
      scores = [scores allScores.scores{ndx}(ts:te)];
    end
  end
  allOrig = scores;

end

allNew = {};
for ndx = 1:ncomparisons
  data.Train();
  allNew{ndx} = getCurrentScores(data);
end

origdiff = [];
newdiff = [];
origdiffpos = [];
newdiffpos = [];
origdiffneg = [];
newdiffneg = [];
sn = data.windowdata.scoreNorm;
bins = linspace(-sn,sn,20);
origmat = zeros(2,2,ncomparisons);
newmat = zeros(2,2,ncomparisons);
for ndx = 1:ncomparisons
  t = histc(allOrig - allNew{ndx},[-inf bins inf]);
  t(1) = []; t(end) = [];
  origdiff(end+1,:) = t;

  origmat(1,1,ndx) = nnz(allOrig>0 & allNew{ndx}>0);
  origmat(1,2,ndx) = nnz(allOrig>0 & allNew{ndx}<0);
  origmat(2,1,ndx) = nnz(allOrig<0 & allNew{ndx}>0);
  origmat(2,2,ndx) = nnz(allOrig<0 & allNew{ndx}<0);

  popul = setdiff(1:ncomparisons,ndx);
  if isempty(popul),
    ndx1 = 1;
  else
    ndx1 = randsample(setdiff(1:ncomparisons,ndx),1);
  end
  t = histc(allNew{ndx1} - allNew{ndx},[-inf bins inf]);
  t(1) = []; t(end) = [];
  newdiff(end+1,:) = t;

  newmat(1,1,ndx) = nnz(allNew{ndx1}>0 & allNew{ndx}>0);
  newmat(1,2,ndx) = nnz(allNew{ndx1}>0 & allNew{ndx}<0);
  newmat(2,1,ndx) = nnz(allNew{ndx1}<0 & allNew{ndx}>0);
  newmat(2,2,ndx) = nnz(allNew{ndx1}<0 & allNew{ndx}<0);

  pos = allOrig>0;
  t = histc(allOrig(pos) - allNew{ndx}(pos),[-inf bins inf]);
  t(1) = []; t(end) = [];
  origdiffpos(end+1,:) = t;

  t = histc(allNew{ndx1}(pos) - allNew{ndx}(pos),[-inf bins inf]);
  t(1) = []; t(end) = [];
  newdiffpos(end+1,:) = t;

  pos = allOrig<0;
  t = histc(allOrig(pos) - allNew{ndx}(pos),[-inf bins inf]);
  t(1) = []; t(end) = [];
  origdiffneg(end+1,:) = t;

  t = histc(allNew{ndx1}(pos) - allNew{ndx}(pos),[-inf bins inf]);
  t(1) = []; t(end) = [];
  newdiffneg(end+1,:) = t;

end

origmat = round(mean(origmat,3));
newmat = round(mean(newmat,3));

figure;
subplot(2,2,[1 2]); hold on;
for ndx = 1:ncomparisons
  plot(bins/sn,origdiff(ndx,:),'r');
  plot(bins/sn,newdiff(ndx,:),'b');
end

numPosOrig = nnz(allOrig>0);
numNegOrig = nnz(allOrig<0);
numPosNew = 0; numNegNew = 0;
for ndx = 1:numel(allNew)
  numPosNew = numPosNew + nnz(allNew{ndx}>0);
  numNegNew = numNegNew + nnz(allNew{ndx}<0);

end
numPosNew = numPosNew/numel(allNew);
numNegNew = numNegNew/numel(allNew);

title({'Red: Orig - new, Blue: new - new'});
msg = {...
 sprintf('Frames predicted by the orig, pos :%d neg:%d',numPosOrig,numNegOrig),...
 sprintf('Frames predicted by the new (avg), pos :%d neg:%d',round(numPosNew),round(numNegNew)),...
 sprintf('Orig Vs New'),...
 sprintf('           New Pos          New Neg     '),...
 sprintf('Orig Pos     %d          %d     ',origmat(1,1),origmat(1,2)),...
 sprintf('Orig Neg     %d          %d     ',origmat(2,1),origmat(2,2)),...
 sprintf('New Vs New'),...
 sprintf('           New Pos          New Neg     '),...
 sprintf('New Pos     %d          %d     ',newmat(1,1),newmat(1,2)),...
 sprintf('New Neg     %d          %d     ',newmat(2,1),newmat(2,2)),...
};
warndlg(msg);

subplot(2,2,3); hold on;
for ndx = 1:ncomparisons
  plot(bins/sn,origdiffpos(ndx,:),'r');
  plot(bins/sn,newdiffpos(ndx,:),'b');
end
title('On frames predicted positive by orig');

subplot(2,2,4); hold on;
for ndx = 1:ncomparisons
  plot(bins/sn,origdiffneg(ndx,:),'r');
  plot(bins/sn,newdiffneg(ndx,:),'b');
end
title('On frames predicted negative by orig');

function scores = getCurrentScores(data)
scores = [];
for expi = 1:data.nexps
  allScores = data.PredictWholeMovie(expi);
  for ndx = 1:numel(allScores.scores);
    ts = allScores.tStart(ndx);
    te = allScores.tEnd(ndx);
    scores = [scores allScores.scores{ndx}(ts:te)];
  end
end


function x = emailFeatures(word_indices)
    %% EMAILFEATURES takes in a word_indices vector and produces a feature vector
    %from the word indices
    %   x = EMAILFEATURES(word_indices) takes in a word_indices vector and
    %   produces a feature vector from the word indices.

    % Total number of words in the dictionary
    n = 1899;

    % You need to return the following variables correctly.
    x = zeros(n, 1);

    % ====================== YOUR CODE HERE ======================
    % Instructions: Fill in this function to return a feature vector for the
    %               given email (word_indices). To help make it easier to
    %               process the emails, we have have already pre-processed each
    %               email and converted each word in the email into an index in
    %               a fixed dictionary (of 1899 words). The variable
    %               word_indices contains the list of indices of the words
    %               which occur in one email.
    %
    %               Concretely, if an email has the text:
    %
    %                  The quick brown fox jumped over the lazy dog.
    %
    %               Then, the word_indices vector for this text might look
    %               like:
    %
    %                   60  100   33   44   10     53  60  58   5
    %
    %               where, we have mapped each word onto a number, for example:
    %
    %                   the   -- 60
    %                   quick -- 100
    %                   ...
    %
    %              (note: the above numbers are just an example and are not the
    %               actual mappings).
    %
    %              Your task is take one such word_indices vector and construct
    %              a binary feature vector that indicates whether a particular
    %              word occurs in the email. That is, x(i) = 1 when word i
    %              is present in the email. Concretely, if the word 'the' (say,
    %              index 60) appears in the email, then x(60) = 1. The feature
    %              vector should look like:
    %
    %              x = [ 0 0 0 0 1 0 0 0 ... 0 0 0 0 1 ... 0 0 0 1 0 ..];
    %
    x(word_indices) = 1;
end


 function I_sr = superresolve_bvsr(slidingWindow, magFactor)

    vid_l_bic = slidingWindow.frames;

    % Reshape input images from 3-D array to cell array.
    if ~iscell(vid_l_bic)
        if ndims(vid_l_bic) == 3
            for j = 1:size(vid_l_bic,3)
                I{j}(:,:,1) = vid_l_bic(:,:,j);
                I{j}(:,:,2) = vid_l_bic(:,:,j);
                I{j}(:,:,3) = vid_l_bic(:,:,j);
            end
            vid_l_bic = I;
        end
    end

    % Set parameters
    param.LINUX = 1;
    param.MOTION_ESTIMATION = 1;
    param.OPTICAL_FLOW = 1;
    param.BLUR_ESTIMATION = 1;
    param.NOISE_ESTIMATION = 1;
    param.SHOW_IMAGE = 0;
    param.SAVE_RESULT = 1;
    param.MAKE_VIDEO = 0;

    opt(1).nref = round((length(vid_l_bic) - 1) / 2); % num of reference frames (one-side)
    opt(1).res = magFactor; % for scale factor
    opt(1).maxit = 5; % maximum iteration number
    opt(1).eps = 0.0005;         % iteration stop criteria
    opt(1).eps_out = 0.0001;    % iteration stop criteria
    opt(1).eps_blur = 0.0001;    % iteration stop criteria
    opt(1).eta = 20; % for derivative of image
    opt(1).xi = 0.7; % for derivative of kernel
    opt(1).alpha = 1;  % for noise
    opt(1).beta = 0.1; % for noise
    opt(1).degrad = 0; % 0:imresize, 1:LPF+downsampling
    opt(1).hsigma = 0.4*magFactor; % for degradation (blur kernel)
    opt(1).hsize = round(6*magFactor*0.4); % for degradation (blur kernel)
    if mod(opt(1).hsize, 2) == 0
        opt(1).hsize = opt(1).hsize + 1;
    end
    opt(1).noisesd = 0; % for degradation (noise st.dev.) 0,0.01,0.03,0.05
    if param.BLUR_ESTIMATION % Initialization of estimated blur kernel (h_2d)
        opt(1).hmode_init = 1; % 1:gaussian, 2:uniform
        opt(1).hsigma_init = 0.4*magFactor;
    end

    for l = 1:length(opt)

        opt(l).nFrames = length(vid_l_bic);
        opt(l).maxnbf = min(opt(l).nFrames, opt(l).nref); % maximum frame numbers for reference

        [opt(l).M,opt(l).N] = size(vid_l_bic{1}(:,:,1)); % height and width of high-res image
        opt(l).M = opt(1).res * opt(l).M;
        opt(l).N = opt(1).res * opt(l).N;
        [opt(l).m,opt(l).n] = size(vid_l_bic{1}(:,:,1)); % height and widht of low-res image
        M = opt(l).M;
        N = opt(l).N;

        h_2d_sim = fspecial('gaussian', [opt(l).hsize opt(l).hsize], opt(l).hsigma); % blur kernel
        if param.BLUR_ESTIMATION
            [h_1d,h_2d_init] = create_h1(opt(l));
            h_2d = h_2d_init;
        else
            h_2d = h_2d_sim;
        end

        J = extract_y(vid_l_bic);
        I_init = create_initial_I(J,opt(l).res, h_2d);

        % Initialize the variables
        W0 = zeros(opt(l).m,opt(l).n); % for weight matrix for high-res img
        Ws = zeros(M,N); % for weight matrix for derivative
        Wk = zeros(M,N); % for weight matrix for kernel
        Wi = []; % for weight matrix for high-res img (neighboring frames)
        I_sr = I_init; % initialization for super-resolved image

        % Loop for each frame
        for j = round((opt(l).nFrames + 1) / 2)

            n_back = min(opt(l).maxnbf, j-1);
            n_for = min(opt(l).maxnbf, opt(l).nFrames-j);
            th = ones(n_for+n_back+1, 1); % for noise estimation

            % Coordinate descent algorithm
            I = I_init{j}; % current frame (high-res)
            J0 = J{j}; % current frame (low-res)
            for i = -n_back:n_for
                FI{j+i} = I_init{j+i};
            end

            %  Outer iteration
            for k = 1:opt(l).maxit % Loop for each sweep of the algorithm

                I_old_out = I;

                % (1) Estimate motion
                % IRLS
                % motion estimation with optical flow algorithm
                if param.MOTION_ESTIMATION && param.OPTICAL_FLOW
                    for i = -n_back:n_for
                        if i == 0
                            u{j+i} = zeros(size(I));
                            v{j+i} = zeros(size(I));
                            ut{j+i} = zeros(size(I));
                            vt{j+i} = zeros(size(I));
                        else
                            %[u{j+i},v{j+i}] = opticalFlow_CLG_TV(I,I_sr{j+i}); % I->Ii(J_bic)
                            oflParams = [0.025, ...  % Regularization weight
                                0.5, ...    % Downsample ratio
                                20, ...     % Width of image pyramid coarsest level
                                7, ...      % Number of outer fixed point iterations
                                1, ...      % Number of inner fixed point iterations
                                20];        % Number of SOR iterations
                            [u{j+i},v{j+i}] = Coarse2FineTwoFrames(I, I_sr{j+i}, oflParams);
                            %[ut{j+i},vt{j+i}] = Coarse2FineTwoFrames(I_sr{j+i}, I, oflParams);
                            ut{j+i} = -u{j+i};
                            vt{j+i} = -v{j+i};
                            FI{j+i} = warped_img(I,u{j+i},v{j+i});
                        end
                    end
                end

                % (2) Estimate noise
                Nq = opt(l).m*opt(l).n;
                if k == 1
                    for i = -n_back:n_for
                        th(j+i) = max(1,max(n_back,n_for)) / (abs(i)+1);
                    end
                else
                    for i = -n_back:n_for
                        if i == 0
                            KI = cconv2d(h_2d,I);
                            SKI = down_sample(KI,opt(l).res);
                            x_tmp = sum(sum(abs(J{j+i}-SKI))) / Nq;
                            th(j+i) = (opt(l).alpha+Nq-1)/(opt(l).beta+Nq*x_tmp);
                        else
                            KFI = cconv2d(h_2d,FI{j+i});
                            SKFI = down_sample(KFI,opt(l).res);
                            x_tmp = sum(sum(abs(J{j+i}-SKFI)))/Nq;
                            th(j+i) = (opt(l).alpha+Nq-1)/(opt(l).beta+Nq*x_tmp);
                        end
                    end
                end

                % (3) Estimate high-res img
                % IRLS
                for m = 1:opt(l).maxit
                    I_old_in = I;
                    % compute W0,Ws,Wi
                    W0 = compute_W0(I,J0,h_2d,opt(l).res);
                    Ws = compute_Ws(I);
                    if param.MOTION_ESTIMATION
                        for i = -n_back:n_for
                            if i ~= 0
                                FI{j+i} = warped_img(I,u{j+i},v{j+i});
                                Wi{j+i} = compute_Wi(FI{j+i},J{j+i},h_2d,opt(l).res);
                            end
                        end
                    end

                    % estimat I
                    AI = zeros(M,N);
                    b = zeros(M,N);
                    if param.MOTION_ESTIMATION
                        AI = compute_Ax_h(I,W0,Ws,th,h_2d,opt(l),j,n_back,n_for,FI,Wi,ut,vt,param);
                        b = compute_b_h(J,W0,th,h_2d,opt(l),j,n_back,n_for,Wi,ut,vt,param);
                        I = conj_gradient_himg(AI,I,b,W0,Ws,th,h_2d,opt(l),j,n_back,n_for,FI,Wi,ut,vt,param);
                    else
                        AI = compute_Ax(I,W0,Ws,th(j),h_2d,opt(l));
                        b = compute_b1(J0,W0,th(j),h_2d,opt(l));
                        I = conj_gradient_himg_0(AI,I,b,W0,Ws,th(j),h_2d,opt(l),param);
                    end

                    % stop criteria
                    diff_in = norm(I-I_old_in)/norm(I_old_in);
                    if diff_in < opt(l).eps
                        break;
                    end
                end

                % (4) Estimate kernel
                % IRLS
                if param.BLUR_ESTIMATION
                    K = otf2psf(psf2otf(h_2d,size(I))); % 2d kernel (Kx x Ky)
                    for m = 1:opt(l).maxit-2
                        K_old = K;
                        % compute W0,Ws,Wi
                        Wk = compute_Wk(K,I,J0,opt(l).res);
                        Ws = compute_Ws(K);
                        % estimat Kx
                        AK = compute_Ax_k(K,Wk,Ws,th(j),I,opt(l));
                        b = compute_b1_k(J0,Wk,th(j),I,opt(l));
                        K = conj_gradient_kernel(AK,K,b,Wk,Ws,th(j),I,opt(l),param);
                        % stop criteria
                        diff_K = norm(K-K_old)/norm(K_old);
                        if diff_K < opt(l).eps_blur
                            break;
                        end
                    end
                    half = floor(opt(l).hsize/2);
                    h_2d = K(M/2-half+1:M/2+half+1,N/2-half+1:N/2+half+1);
                    h_2d = h_2d / sum(sum(h_2d));
                end

                % (5) Check convergence
                diff_out = norm(I-I_old_out)/norm(I_old_out);
                if diff_out < opt(l).eps_out
                    break;
                end

            end

            I_sr{j} = I;

        end

        % Correct offset
        if opt(l).degrad == 0
            I_sr = shift_adjust(I_sr,opt(l).res,-1);
        end
        I_sr = I_sr{round((opt(l).nFrames + 1) / 2)}(:,:,1);

    end

    clear W0 Ws Wk Wi;


function k = ratquadKernDiagCompute(kern, x)

% RATQUADKERNDIAGCOMPUTE Compute diagonal of RATQUAD kernel.
% FORMAT
% DESC computes the diagonal of the kernel matrix for the rational quadratic kernel given a design matrix of inputs.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG x : input data matrix in the form of a design matrix.
% RETURN k : a vector containing the diagonal of the kernel matrix
% computed at the given points.
%
% SEEALSO : ratquadKernParamInit, kernDiagCompute, kernCreate, ratquadKernCompute
%
% COPYRIGHT : Neil D. Lawrence, 2006

% KERN

k = repmat(kern.variance, size(x, 1), 1);


function out=mplog2(precision)

if nargin==0
 mp_defaults
 precision=default_precision;
end

out_rval=mpfr_const_log2(precision);

out=class(struct('rval',out_rval,...
                  'ival','0',...
                  'precision',precision),'mp');


function label_mat  = convert_labelvec_to_mat(label_vec, num, class_num)
    label_mat = zeros(class_num, num);
    for i=1:num
        label_mat(label_vec(i),i) = 1;
    end
end


function [command] = generate_command(drone_type, autopilot_version, time)
% GENERATE_COMMAND - function that generates commands for a fixed_wing or a
% quadcopter drone. This function is used to test the autopilots of the
% drones, the commanded values here are hard-coded.

if drone_type == "fixed_wing"
        % command set
        command = [0 100 0.26 0]';
elseif drone_type == "quadcopter" || drone_type == "point_mass"
        flag = mod(floor(time/3),2);

        switch autopilot_version
            case 1 % attitude control
                if flag == 0
                    command = [0 0 0 0.5]';
                else
                    command = [0 0 0 -0.5]';
                end
            case 2 % velocity controller
                if flag == 0
                    command = [0 0 6 0]';
                else
                    command = [0 0 -6 0]';
                end
            case 3 % acceleration controller
                command = [0.5 0 0 0]';
        end

end

end


clc;
pzstat = input('enter a puzzle in 3 x 3 form (use 0 for space) ..........:   ');
pzrstat = [1 2 3;4 5 6;7 8 0];
intv000 = size(pzstat);
if not(all(intv000 == [3 3]))
    msgbox('Input is not in correct format.............. The format must be 3 x 3 matrix. The blank space should be replaced by 0.','8-Puzzle suresh Kumar Gadi');
else
    pzinl = [];
    pzhis = [];
    pzrhis = [];
    intv00g = 0;
    [intv0h1,intv0h2] = gskcostastar(pzstat,pzrstat);
    intv00h = intv0h1 + intv0h2;
    intv00f = intv00h + intv00g;
    pzinl = gskpzjoin(pzinl,pzstat,intv00f,intv00g,intv00h);
    pzhis = gskpzjoin(pzhis,pzstat,intv00f,intv00g,intv00h);
    pzhis(:,13)=0;
    pzhis(1,14)=0;
    pzhis(1,15)=1;
    intv001 = 1;
    intv0ct = 0;
    intv0nd = 1;
    intv1nd = 1;
    while intv001 == 1;
        intv0ct = intv0ct + 1;
        [pzout, intv00f, intv00g, intv00h] =  gskpzget(pzinl,1);
        [intv002, intv003] = find(pzout==0);
        pzinl = [];
        if intv00h ~= 0
% % % % % % left
            if intv003 > 1
                pzout1 = pzout;
                pzout1(intv002,intv003) = pzout(intv002,intv003 - 1);
                pzout1(intv002,intv003 - 1) = 0;
                [intv0h1,intv0h2] = gskcostastar(pzout1,pzrstat);
                intv00h = intv0h1 + intv0h2;
                intv0g1 = intv00g + 1;
                intv00f = intv0g1 + intv00h;
                [pzinl] =  gskpzjoin(pzinl,pzout1,intv00f,intv0g1,intv00h);
            end
% % % % % % top
            if intv002 > 1
                pzout1 = pzout;
                pzout1(intv002,intv003) = pzout(intv002-1,intv003);
                pzout1(intv002-1,intv003) = 0;
                [intv0h1,intv0h2] = gskcostastar(pzout1,pzrstat);
                intv00h = intv0h1 + intv0h2;
                intv0g1 = intv00g + 1;
                intv00f = intv0g1 + intv00h;
                [pzinl] =  gskpzjoin(pzinl,pzout1,intv00f,intv0g1,intv00h);
            end
% % % % % % right
            if intv003 < 3
                pzout1 = pzout;
                pzout1(intv002,intv003) = pzout(intv002,intv003 + 1);
                pzout1(intv002,intv003 + 1) = 0;
                [intv0h1,intv0h2] = gskcostastar(pzout1,pzrstat);
                intv00h = intv0h1 + intv0h2;
                intv0g1 = intv00g + 1;
                intv00f = intv0g1 + intv00h;
                [pzinl] =  gskpzjoin(pzinl,pzout1,intv00f,intv0g1,intv00h);
            end
% % % % % % down
            if intv002 < 3
                pzout1 = pzout;
                pzout1(intv002,intv003) = pzout(intv002 + 1,intv003);
                pzout1(intv002 + 1,intv003) = 0;
                [intv0h1,intv0h2] = gskcostastar(pzout1,pzrstat);
                intv00h = intv0h1 + intv0h2;
                intv0g1 = intv00g + 1;
                intv00f = intv0g1 + intv00h;
                [pzinl] =  gskpzjoin(pzinl,pzout1,intv00f,intv0g1,intv00h);
            end
% % % % % % compare with history
            [intv003, intv004] = size(pzinl);
            for intv004 = 1 : intv003
                intv005 = gsksearch(pzhis,pzinl(intv004,:));
                if ~isempty(intv005)
%                     pzhis(intv005,13) = 1;
                else
                    [intv007 , intv008] = size(pzhis);
                    intv008 = pzinl(intv004,1:12);
                    intv008(13) = 0;
                    intv008(14) = intv0nd;
                    intv1nd = intv1nd + 1;
                    intv008(15) = intv1nd;
                    pzhis(intv007+1,:)=intv008;
                end
            end
% % % % % % selecting new node
            intv005 = find(pzhis(:,13) == 1);
            intv006 = length(intv005);
            pzrhis = pzhis;
            for intv007 = 1:intv006
                pzrhis(intv005(intv007)-(intv007-1),:)=[];
            end
            intv003 = min(pzrhis,[],1);
            [pzout, intv00f, intv00g, intv00h] =  gskpzget(intv003,1);
            [intv002, intv003] = find((pzrhis(:,10)==intv00f) & (pzrhis(:,13) == 0));
%             intv002 = intv002(1,1);
            [pzout, intv00f, intv00g, intv00h] =  gskpzget(pzrhis,intv002(1,1));
            intv0nd = pzrhis(intv002(1,1),15);
            pzinl = [];
            [pzinl] =  gskpzjoin(pzinl,pzout,intv00f,intv00g,intv00h);
            intv005 = gsksearch(pzhis,pzinl);
            pzhis(intv005,13) = 1;
            intv001 = 1;
        else
            intv001 = 2;
        end
    end
% % Display of steps
    [intv000, intv001] = size(pzhis);
    intv002 = 1;
    pzshow = [];
    intvcnt = 0;
    while intv002 ==1
        intvcnt = intvcnt + 1;
        pzshow(intvcnt) = intv000;
        intv000 = pzhis(intv000,14);
        if intv000 == 0
            intv002 = 2;
        else
            intv002 = 1;
        end
    end
    for intv000 = 1 : intvcnt
        [pzout, intv00f, intv00g, intv00h] =  gskpzget(pzhis,pzshow(intvcnt-intv000+1));
        intv000
        pzout
    end
end


function [z,e]=oneoutnn(x,iil)

[m,n]=size(x);
d=zeros(m,m);
v=double(x)*double(x');
for i=1:m;
    for j=1:m;
        d(i,j)=sqrt(v(i,i)+v(j,j)-2*v(i,j));
    end;
    d(i,i)=10000000000000;
end;
[a,b]=min(d);
e=iil(b');
c=iil-e;
e(:,2)=iil;
z=0;
for i=1:m;
    if c(i)~=0;
        z=z+1;
    end;
end;


%io_writepta.m
%Jamie Near, McGill University 2014.
%
% USAGE:
% RF=io_writepta(rf,outfile);
%
% DESCRIPTION:
% Write a matlab RF pulse structure (containing N x 3 waveform array field
% with rf.waveform(:,1)= phase, rf.waveform(:,2)=amplitude, and rf.waveform(:,3)=timestep),
% to a siemens format .pta file.
%
% INPUTS:
% rf         = matlab RF pulse.
% outfile    = name of the output .pta file to be written.
%
% OUTPUTS:
% RF            = Same as input.  Not used.  The primary output of this
%                   function is a text file in Siemens .pta format.

function RF=io_writepta(rf,outfile);

B1INT=sum(rf.waveform(:,2));

l=length(rf.waveform(:,2));
RF.waveform=zeros(3,l);
RF.waveform(1,:)=rf.waveform(:,2)/max(rf.waveform(:,2));
RF.waveform(2,:)=mod(rf.waveform(:,1)*pi/180,2*pi);
RF.waveform(3,:)=[0:l-1];

%For simplicity:  Make a complex valued version of the RF pulse
RF_complex=RF.waveform(1,:).*exp(1i*RF.waveform(2,:));

%Calculate the POWER INTEGRAL (POWERINT).  This is used for calculating the
%SAR:
POWERINT=sum((real(RF_complex).^2)+(imag(RF_complex).^2));

%Calculate the MAGNITUDE/ABSOLUTE INTEGRAL (ABSINT):
ABSINT=sum(abs(RF_complex));

%AMPLITUDE INTEGRAL (AMPINT)...  This is the parameter that is used to
%calculate the transmitter voltage at runtime, and therefore it determines
%the flip angle that will be realied.  It must be calculated properly to
%ensure that the flip angle will be correct.  In addition, the calculation
%of AMPINT depends on the type of pulse that you are dealing with.  For a
%straigt plain wave (That is, the phase of each data point is either a
%constant ph, or ph+180 or ph-180)  the AMPINT is simply the sum of the
%waveform points when the maximum value is scaled to 1.  For example, for a
%three point pulse with point values of -1, 3 and -1, the AMPINT would be
%1.  This will be the method used for automatic calculation of AMPINT.  If
%the pulse is not a plane pulse, do not use this method to calculate
%AMPINT.

AIcalc=input('Would you like to perform an automatic Amplitude Inegral Calculation?(y or n)  ', 's');

if AIcalc=='y' || AIcalc=='Y'
    AMPINT=sqrt((sum(real(RF_complex)).^2)+(sum(imag(RF_complex)).^2));
elseif AIcalc=='n' || AIcalc=='N'
    % If the pulse is not a plane wave (Adiabatic pulses, off resonance pulses,
    % or dual Band Pulses), you should calculate the Amplitude integral
    % yourself and input it manually.  For methods of calculating AMPINT in this
    % case, see the document entitled
    % "RF_amplitude_integral_in_pulse_sequences.pdf', which can be found in
    % /Users/jnear/Documents/RF pulses/
    AMPINT=input('Now you must input the Amplitude Integral Manually.  Lets have it?  ');
else
    error('ERROR!  You must input a value for AMPINT!  ABORTING!');
end

%Reference gradient is only used in slice selective pulses.  This refers to
%the gradient required to excite a 10mm slice if the pulse duration is
%5.12ms  Given that the Time-bandwidth product is included in the rf
%structure, the refgrad value can be calculated here, but the option is
%provided to enter it manually, in case a different refgrad value is
%desired.

refgrad=1;
refg=input('Would you like to input a reference gradient (REFGRAD)? ','s');
if refg=='y' || refg=='Y'
    disp('INFORMATION:  REFGRAD is the gradient amplitude in [mT/m] required ');
    disp('to excite a 10mm slice with a pulse duration of 5.12 ms. ');
    man=input('Calculate refgrad automatically (y or n) ? ','s');
    if man=='y' || man=='Y'
        %refgrad [mT/m] = (1000 [mT]/[1T]) * tbw [unitless] ) / ( (0.00512 [s]) * (42577000 [Hz]/[T]) * (0.01 [m]) );
        refgrad = 1000 * rf.tbw/(0.00512 * 42577000 * 0.01);
    elseif man=='n' || man=='N'
        refgrad=input('Manually enter the reference gradient (mT/m):  ');
    else
        error('ERROR:  Response not recognized!!');
    end
end

%write to pta file for siemens
fid=fopen(outfile,'w+');
fprintf(fid,['PULSENAME: \t' outfile]);
fprintf(fid,'\nCOMMENT:  \tRF pulse generated using the FID-A toolkit (github.com/CIC-methods/FID-A).');
fprintf(fid,'\nREFGRAD:  \t%5.6f' ,refgrad);
fprintf(fid,'\nMINSLICE: \t1.00000000');
fprintf(fid,'\nMAXSLICE: \t200.00000000');
fprintf(fid,'\nAMPINT: \t%5.6f',AMPINT);
fprintf(fid,'\nPOWERINT: \t%5.6f',POWERINT);
fprintf(fid,'\nABSINT: \t%5.6f',ABSINT);
fprintf(fid,'\n\n');
n=0;
fprintf(fid,'%1.9f %1.9f ; (%1.0f)\n',RF.waveform);
fclose(fid);


function [rc] = calc_ratechangeF(mycat,time,timef,bootloops,maepi)
    % function [rc] = calc_ratechangeF(mycat,time,timef,bootloops,maepi);
    % ----------------------------------------------------------------
    % Determines ratechanges within aftershock sequences for defined time window
    %
    % Input parameters:
    %   mycat       earthquake catalog
    %   time_as     delay times (days)
    %   step        number of quakes to determine forecast period
    %   time        learning period
    %   timeF       forecast period
    %   bootloops   Number of bootstraps
    %   ZG.maepi       Mainsock values
    %
    % Output parameters:
    %   rc      Matrix containing: time, absdiff, sigma, numreal, nummod,
    %           pval, pvalstd, cval, cvalstd, kval, kvalstd, t_forecast, fMc
    %
    % Info: Version for ZMAP, original function by ratechange.m by S. Neukomm May 27, 2002
    % J. Woessner
    % last update: 09.07.03

    % if min(time_as) >= 1
    %     rc = [];
    %     return
    % end

    % Initialize
    rc = [];
    % fMc0 = mcwithtime(mycat,time_as,7);
    %
    % %time = mintime;
    %
    % % determination of magnitude of completeness
    % if time < 7
    %     fMc = mcwithtime(mycat,time_as,time);
    % else
    %     fMc = fMc0;
    % end
report_this_filefun(mfilename('fullpath'));
    date_matlab = datenum(mycat.Date);
    date_main = datenum(ZG.maepi.Date);
    time_aftershock = date_matlab-date_main;

    l = time_aftershock(:) > 0;
    tas = time_aftershock(l);
    eqcatalogue = mycat.subset(l);

    % Estimation of Omori parameters from learning period
    l = tas <= time;% & mycat.Magnitude >= fMc;
    time_as=tas(l);
    % [pval, pvalstd, cval, cvalstd, kval, kvalstd, loopout] = brutebootF(time_as, bootloops);
    % Calculate uncertainties and mean values of p,c,and k
    [pval, pvalstd, cval, cvalstd, kval, kvalstd, loopout] = brutebootloglike(time_as,bootloops);
    % Calculate p,c,k for real dataset
    [pval, cval, kval] = bruteforceloglike(sort(time_as));
    pval = round(100*pval)/100;
    cval = round(100*cval)/100;
    kval = round(10*kval)/10;

    [H,P,KSSTAT,fRMS] = calc_llkstest(time_as, pval, cval, kval);
    if H==1
        rc = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
        return
    end

    if isnan(pval) == 0
        lf = tas <= time+timef ;
        time_asf= [tas(lf) ];
        %     nummod = length(time_asf); % forecasted number of aftershocks in time window
        if pval == 1
            pv = 1-10^(-6);
        else
            pv = pval;
        end

        cumnrf = (1:length(time_asf))';
        cumnr_modelf = [];
        for i=1:length(time_asf)
            if pval ~= 1
                cm = kval/(pval-1)*(cval^(1-pval)-(time_asf(i)+cval)^(1-pval));
            else
                cm = kval*log(time_asf(i)/cval+1);
            end
            cumnr_modelf = [cumnr_modelf; cm];
        end
        %     t_forecast = (-nummod*(pv-1)/kval+(time+cval)^(1-pv))^(1/(1-pv))-cval; % forecast interval
        %     if isreal(t_forecast) == 1 & t_forecast > time
        %         if t_forecast > max(time_as)
        %             return
        %         end
        %l = time_as <= t_forecast & mycat.Magnitude >= fMc & time_as >= time;
        %l = tas <= time+timef;
        % Find amount of events in forecast period for modeled data
        nummod = max(cumnr_modelf)-cumnr_modelf(length(time_as));
        % Find amount of  events in forecast period for observed data
        l = time_asf <=time+timef & time_asf > time;
        numreal = sum(l); % observed number of aftershocks
        absdiff = numreal-nummod;

        % calculate uncertainty sigma in forecasted number of aftershocks by Fehlerfortpflanzungsgesetz
        %time1 = t_forecast;
        time1 = time+timef;
        mpm1 = 1-pv;
        t1c = time1+cval;
        t0c = time+cval;
        sigma = (((-t1c^mpm1+t0c^mpm1)/(pv-1)*kvalstd)^2+...
            (kval/(pv-1)*(-t1c^mpm1*mpm1/t1c+t0c^mpm1*mpm1/t0c)*cvalstd)^2+...
            (kval/(pv-1)*(t1c^mpm1*log(t1c)+t1c^mpm1/(pv-1)-t0c^mpm1*log(t0c)-t0c^mpm1/(pv-1))*pvalstd)^2)^0.5;

        %rc = [rc; time absdiff sigma numreal nummod pval pvalstd cval cvalstd kval kvalstd t_forecast fMc];

        % Compute 2nd moment of forecasted number of events at time
        for j = 1:length(loopout(:,1))
            cumnr = (1:length(time_asf))';
            cumnr_model = [];
            pvalb = loopout(j,1);
            cvalb = loopout(j,2);
            kvalb = loopout(j,3);
            for i=1:length(time_asf)
                if pval ~= 1
                    cm = kvalb/(pvalb-1)*(cvalb^(1-pvalb)-(time_asf(i)+cvalb)^(1-pvalb));
                else
                    cm = kvalb*log(time_asf(i)/cvalb+1);
                end
                cumnr_model = [cumnr_model; cm];
            end
            loopout(j,4) = max(cumnr_model);
        end
        fStdBst = calc_StdDev(loopout(:,4));
        rc = [time absdiff sigma numreal nummod pval pvalstd cval cvalstd kval kvalstd fStdBst];
    else
        rc = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
    end


function obj = configureDynamics(obj, varargin)
    % Set the symbolic expressions of the dynamics of the rigid body system
    %
    % Parameters:
    % varargin: extra options @type varargin

    opts = struct(varargin{:});
    if isfield(opts, 'DelayCoriolisSet')
        delay_set = opts.DelayCoriolisSet;
    else
        delay_set = false;
    end

    if isfield(opts, 'OmitCoriolisSet')
        omit_set = opts.OmitCoriolisSet;
    else
        omit_set = false;
    end

    n_link = length(obj.Links);
    links = getTwists(obj.Links);
    for i=1:n_link
        links{i}.Mass = obj.Links(i).Mass;
        links{i}.Inertia = obj.Links(i).Inertia;
    end

    % set the inertia matrix
    tic
    %     De = eval_math_fun('InertiaMatrix',[links,{obj.numState}]);
    n_link = length(links);
    De = cell(n_link,1);
    m = 100;
    fprintf('Evaluating the inertia matrix D(q): \t');
    bs = '\b';
    sp = ' ';
    msg = '%d percents completed.\n'; % carriage return included in case error interrupts loop
    msglen = length(msg)-3; % compensate for conversion character and carriage return
    fprintf(1,sp(ones(1,ceil(log10(m+1))+msglen)));

    for i=1:n_link
        k = floor(i*100/n_link);
        fprintf(1,[bs(mod(0:2*(ceil(log10(k+1))+msglen)-1,2)+1) msg],k);
        De{i} = eval_math_fun('InertiaMatrixByLink',[links(i),{obj.numState}]);
    end

    De_motor = zeros(obj.numState);
    for i=1:obj.numState
        if ~isempty(obj.Joints(i).Actuator)
            actuator = obj.Joints(i).Actuator;

            if ~isempty(actuator.Inertia) && ~isempty(actuator.Ratio)
                % reflected motor inertia: I*r^2
                De_motor(i,i) = actuator.Inertia * actuator.Ratio^2;
            end
        end
    end

    %     fprintf(1,sp(ones(1,40)));
    Mmat_full = [De; {De_motor}];
    obj.setMassMatrix(Mmat_full);

    toc

    Qe = obj.States.x;
    dQe = obj.States.dx;

    %|@note !!! The minus sign !!!
    % Fvec appears at the right hand side (typically -C(q,dq)dq - G(q)
    % appears at the left hand side of the Euler-Lagrangian Equation)
    if omit_set
        tic
        fprintf('Evaluating the gravity vector G(q): \t');
        Ge = SymFunction(['Ge_vec_',obj.Name],-eval_math_fun('GravityVector',[links,{Qe}]),{Qe,dQe});
        toc
        vf = {Ge};
    else
        tic
        n_mass_mat = numel(obj.Mmat);
        n_dof      = obj.numState;
        Ce1 = cell(n_mass_mat*n_dof,1);
        Ce2 = cell(n_mass_mat*n_dof,1);
        Ce3 = cell(n_mass_mat*n_dof,1);
        m = 100;
        fprintf('Evaluating the coriolis term C(q,dq)dq: \t');
        bs = '\b';
        sp = ' ';
        msg = '%d percents completed.\n'; % carriage return included in case error interrupts loop
        msglen = length(msg)-3; % compensate for conversion character and carriage return
        fprintf(1,sp(ones(1,ceil(log10(m+1))+msglen)));
        for i=1:n_mass_mat
            for j=1:n_dof
                k = floor(((i-1)*3+(j-1)+1)*100/(3*n_mass_mat*n_dof));
                fprintf(1,[bs(mod(0:2*(ceil(log10(k+1))+msglen)-1,2)+1) msg],k);
                Ce1{(i-1)*n_dof+j} = SymFunction(...
                    ['Ce1_vec_L',num2str(i),'_J',num2str(j),'_', obj.Name],...
                    eval_math_fun('InertiaToCoriolisPart1New',{Mmat_full{i},Qe,dQe,j},[],'DelayedSet',delay_set),...
                    {Qe,dQe});
                k = floor(((i-1)*3+(j-1)+2)*100/(3*n_mass_mat*n_dof));
                fprintf(1,[bs(mod(0:2*(ceil(log10(k+1))+msglen)-1,2)+1) msg],k);
                Ce2{(i-1)*n_dof+j} = SymFunction(...
                    ['Ce2_vec_L',num2str(i),'_J',num2str(j),'_', obj.Name],...
                    eval_math_fun('InertiaToCoriolisPart2New',{Mmat_full{i},Qe,dQe,j},[],'DelayedSet',delay_set),...
                    {Qe,dQe});
                k = floor(((i-1)*3+(j-1)+3)*100/(3*n_mass_mat*n_dof));
                fprintf(1,[bs(mod(0:2*(ceil(log10(k+1))+msglen)-1,2)+1) msg],k);
                Ce3{(i-1)*n_dof+j} = SymFunction(...
                    ['Ce3_vec_L',num2str(i),'_J',num2str(j),'_', obj.Name],...
                    eval_math_fun('InertiaToCoriolisPart3New',{Mmat_full{i},Qe,dQe,j},[],'DelayedSet',delay_set),...
                    {Qe,dQe});
            end
        end
        fprintf(1,sp(ones(1,40)));
        toc
        % We add dQe as dependent variables to the gravity vector in order to have a same structure
        % as the corilios forces
        tic
        fprintf('Evaluating the gravity vector G(q): \t');
        Ge = SymFunction(['Ge_vec_',obj.Name],-eval_math_fun('GravityVector',[links,{Qe}]),{Qe,dQe});
        toc
        vf = [Ce1;Ce2;Ce3;{Ge}];
    end

    obj.setDriftVector(vf);

end


% =========================================================================
% This code is part of the Matlab-based toolbox
% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and
%                        Intensity-Preserving Diffeomorphic Image Registration
%
% For details and license info see
% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM
%
% 3D Hyperelastic registration of NIREP data to compare with LDDMM
% as described in Sec. 4 of the paper:
%
% @article{MangRuthotto2017,
%   Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},
%   Year = {2017},
%   Journal = {SIAM Journal on Scientific Computing},
%   Author = {A. Mang, L. Ruthotto},
% }
%
% =========================================================================

close all; clc; clear all;

setupNIREPDataNA02;
%setupNIREPDataNA03;
%setupNIREPDataNA04;
%setupNIREPDataNA05;

imgModel('reset','imgModel','linearInterMex');
trafo('reset','trafo','rigid3D');
distance('reset','distance','SSD');
viewImage('reset','viewImage','viewOrthoSlices2D');

% example specific parameters
switch example
    case ['3D-nirep-',dataset]
        alpha(1) = 100;
        alpha(2) = 1;
        alpha(3) = .1;
        alpha(4) = 1;
        pad = 0;
        minLevel = 5;
        maxLevel = 7;
        maxIterNPIR = 50;
    otherwise
        error('MP-LDDMM example %s - nyi');
end

Dshow = @(T,R,omega,m) viewIP(abs(T-R),omega,m,'colormap',gray(256));
FAIRplots('set','Dshow',Dshow);

solve = true;
postproc = true;

% 2) setup regularizer
regularizer('reset','regularizer','mfHyperElastic','alpha',alpha(1),...
    'alphaLength',alpha(2),'alphaArea',alpha(3),'alphaVolume',alpha(4));

filename = ['HyperElastic-',example,'-',regularizer,'-alpha-',num2str(alpha(1)),'-',num2str(alpha(2)),'-',num2str(alpha(3)),'-',num2str(alpha(4))];

if (solve)
    diary(fullfile('results',[filename,'.log']));
    % finally: run the MultiLevel Non-Parametric Image Registration
    [yc,wc,his] = MLIR(ML,'parametric',0,'NPIRLS',@ArmijoBacktrack,'minLevel',minLevel,'maxLevel',maxLevel,'maxIterNPIR',maxIterNPIR);
    diary('off')
    [~,interOpts] = inter;
    [~,distOpts ] = distance;
    [~,regOpts  ] = regularizer;

    save(fullfile('results',[filename,'.mat']),'yc','wc','his','m','minLevel','maxLevel','interOpts','distOpts','regOpts')
end

if postproc
    % generate figures
    close all;
    load(fullfile('results',[filename,'.mat']));

    computeOverlap;

    % generate figures
    figDir = ['results/',filename];
    if ~exist(figDir,'dir'), mkdir(figDir); end;
    dim  = numel(omega)/2;

    viewImage('reset','viewImage','viewOrthoSlices2D','colormap','gray');
    fig = figure(1); clf;
    fig.Name = 'dataR';
    viewImage(dataR,omega,m);
    cax = caxis;

    fig = figure(2); clf;
    fig.Name = 'dataT';
    viewImage(dataT,omega,m);
    caxis(cax);

    fig = figure(3); clf;
    fig.Name = 'res0';
    % viewImage(abs(dataR-dataT),omega,m)
    viewOrthoSlices2D(abs(dataR-dataT),omega,m,'color1',[0 0 0],'color2',[0 0 0]);
    colormap gray;
    colormap(flipud(colormap));
    % caxd = caxis;
    caxd = cax;

    Topt = imgModel(dataT,omega,center(yc,m));
    fig = figure(4); clf;
    fig.Name = 'Topt';
    viewImage(Topt,omega,m);
    % colormap gray
    caxis(cax);

    fig = figure(5); clf;
    fig.Name = 'resOpt';
    % viewImage(abs(dataR(:)-Topt),omega,m)
    viewOrthoSlices2D(abs(dataR(:)-Topt),omega,m,'color1',[0 0 0],'color2',[0 0 0]);
    caxis(caxd);
    colormap gray;
    colormap(flipud(colormap));

    fig = figure(6); clf;
    fig.Name = 'vol';
    Jac = geometry(yc,m,'Jac','matrixFree',1,'omega',omega);
    viewOrthoSlices2D(Jac,omega,m,'color1',[0 0 0],'color2',[0 0 0]);
    colormap jet;
    cb = colorbar('East');
    cpos = cb.Position;
    cb.Position(4) = cpos(4)*.4;
    cb.Position(2) = .56;
    cb.Ticks = [min(Jac) max(Jac)];
    caxis([min(Jac) max(Jac)]);
    cb.TickLabels = {sprintf('%1.2f',min(Jac)), sprintf('%1.2f',max(Jac))};
    cb.FontSize = 50;
    cb.Color = 'k';

    %str = {'dataR','dataT','res0','Topt','resOpt','yOpt','yInv','vol','T+yc'};
    str = {'dataR','dataT','res0','Topt','resOpt','vol'};
    for k=1:6
        figure(k);
        axis off;
        title([]);
        printFigure(gcf,fullfile(figDir,['LDDMM-' str{k} '_' regularizer '.png']),...
            'printOpts','-dbmp','printFormat','.bmp');
    end
end


function sqi = rsqi(qrs,fs,CI,debug)
% compute smoothness of hrv or of hr time series given a confidence interval (CI).
% The underlying assumption for using this function is that the more smooth
% the qrs time series is the most likely it is to be a meaningful qrs time series.
%SMI = length(find(abs(hrv_CI)>30));

% inputs
%   qrs:    qrs fiducials (required, in data points number)
%   secDer: use second derivative? (i.e. HRV instead of HR to
%           compute SMI, default: 1)
%   fs:     sampling frequency (default: 1kHz)
%   CI:     confidence interval (default: 0.96)
%   segL:   length of the ecg segment in seconds (default: 60sec)
%
% outputs
%   sqi     percentage of intervals inside CI
%
% References:
% [1] Johnson, A. E. W., Behar, J., Andreotti, F., Clifford, G. D. and Oster, J. (2015).
% Multimodal heart beat detection using signal quality indices, Physiological Measurement
% 36 (2015): 1665-1677.
%
%
%
% Multimodal peak detection using ECG, ABP, PPG or SV
% Johnson, A. E. W., Behar, J., Andreotti, F., Clifford, G. D. and Oster, J.
%
%
% 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.

if size(qrs,2) > size(qrs,1); qrs = qrs';end

if length(qrs) < 3, sqi = 0; return; end;

% == manage inputs
if nargin<1; error('rsqi: wrong number of input arguments \n'); end;
if nargin<2; fs = 1000; end;
if nargin<3; CI = 1; end;
if nargin<4; debug = 0; end;
if length(qrs) < 5;
    sqi = 0;
    disp('rSQI: too few qrs detection points')
    return
end

% == core function
%try
% == compute variability
hr = 60./(diff(qrs)/fs);

% rather than looking at the distribution of hr this option is looking at
% the distribution of hrv. This makes more sense because this way
% we are looking into high variation in deltaHR from a measure to the
% following one rather than the variability of absolute value of HR (which
% might be high if the foetus HR is changing significantly)

% now taking the derivative of smoothed hear rate. This will give the
% hrv
hrv = sort(diff(hr));
hrv_N = length(hrv);
% plot(hr); hold on, plot(yi,'r');
% we tolerate some mistakes using a confidence interval
if CI~=1
    CI_sup = ceil(hrv_N*(CI+(1-CI)/2));
    CI_inf = ceil(hrv_N*((1-CI)/2));
    hrv_CI = hrv(CI_inf:CI_sup);
else
    hrv_CI = hrv;
end
% output the std of the hrv
% SMI = std(hrv_CI); % OLD version

% new version (25-08-2013)
SMI = length(find(abs(hrv_CI)>20));
% this looks at the absolute number of outliers in hrv_CI with >
% 30bpm drop or increase from a point to the next.

sqi = 1 - SMI/hrv_N;
if sqi <0
    disp('What')
end

% == plots
if debug
    hist(hrv_CI,40); xlabel('hr or hrv histogram');
    title(['assess regularity in term of hr or hrv, REGULARITY:' SMI]);
    set(findall(gcf,'type','text'),'fontSize',14,'fontWeight','bold');
end

end


function D = driving_function_mono_nfchoa(x0,xs,src,f,conf)
%DRIVING_FUNCTION_MONO_NFCHOA driving signal for NFC-HOA
%
%   Usage: D = driving_function_mono_nfchoa(x0,xs,src,f,conf)
%
%   Input parameters:
%       x0          - position and direction of the secondary source / m [nx7]
%       xs          - position of virtual source or direction of plane
%                     wave / m [1x3] or [1x6]
%                     OR position and orientation of a line source [1x6]
%       src         - source type of the virtual source
%                         'pw' - plane wave (xs is the direction of the
%                                plane wave in this case)
%                         'ls' - line source
%                         'ps' - point source
%                         'fs' - focused source
%       f           - frequency of the monochromatic source / Hz
%       conf        - configuration struct (see SFS_config)
%
%   Output parameters:
%       D           - driving function signal [nx1]
%
%   See also: plot_sound_field, sound_field_mono_nfchoa,
%             driving_function_imp_nfchoa

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

%% ===== Checking of input  parameters ==================================
nargmin = 5;
nargmax = 5;
narginchk(nargmin,nargmax);
isargsecondarysource(x0);
isargxs(xs);
isargpositivescalar(f);
isargchar(src);
isargstruct(conf);

%% ===== Computation ====================================================

% Secondary source positions
x0 = x0(:,1:3);

% Get maximum order of spherical harmonics
N = nfchoa_order(size(x0,1),conf);

% Source position/direction/orientation
xs = repmat(xs,[size(x0,1) 1]);

% Get driving signals
if strcmp('pw',src)
    % === Plane wave =====================================================
    % Direction of plane wave
    nk = bsxfun(@rdivide,xs,vector_norm(xs,2));
    % Driving signal
    D = driving_function_mono_nfchoa_pw(x0,nk,f,N,conf);

elseif strcmp('ps',src)
    % === Point source ===================================================
    % Driving Signal
    D = driving_function_mono_nfchoa_ps(x0,xs,f,N,conf);

elseif strcmp('ls',src)
    % === Line source ====================================================
    % Driving signal
    D = driving_function_mono_nfchoa_ls(x0,xs,f,N,conf);

elseif strcmp('fs',src)
    % === Focused source =================================================
    % Driving Signal
    D = driving_function_mono_nfchoa_fs(x0,xs,f,N,conf);

else
    error('%s: %s is not a known source type.',upper(mfilename),src);
end


function itc_ds=cosmo_phase_itc(ds,varargin)
% compute phase inter trial coherence
%
% itc_ds=cosmo_phase_itc(ds,varargin)
%
% Inputs:
%   ds                      dataset struct with fields:
%       .samples            PxQ complex matrix for P samples (trials,
%                           observations) and Q features (e.g. combinations
%                           of time points, frequencies and channels)
%       .sa.targets         Px1 array with trial conditions. Each condition
%                           must occur equally often; that is, the
%                           samples must be balanced.
%                           In the typical case of two conditions,
%                           .sa.targets must have exactly two unique
%                           values.
%       .sa.chunks          Px1 array indicating which samples can be
%                           considered to be independent. It is required
%                           that all samples are independent, therefore
%                           all values in .sa.chunks must be different from
%                           each other
%       .fa                 } optional feature attributes
%       .a                  } optional sample attributes
%  'samples_are_unit_length',u  (optional, default=false)
%                           If u==true, then all elements in ds.samples
%                           are assumed to be already of unit length. If
%                           this is indeed true, this can speed up the
%                           computation of the output.
%  'check_dataset',c        (optional, default=true)
%                           if c==false, there is no check for consistency
%                           of the ds input.
%
% Output:
%   itc_ds                  dataset struct with fields:
%       .samples            (N+1)xQ array with inter-trial coherence
%                           measure, where U=unique(ds.sa.targets) and
%                           N=numel(U). The first N rows correspond to the
%                           inter trial coherence for each condition. The
%                           last row is the inter trial coherence for all
%                           samples together.
%       .sa.targets         (N+1)x1 vector containing the values
%                           [U(:);NaN]' with trial conditions
%       .a                  } if present in the input, then the output
%       .fa                 } contains these fields as well
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    defaults=struct();
    defaults.samples_are_unit_length=false;
    defaults.check_dataset=true;

    opt=cosmo_structjoin(defaults,varargin{:});

    check_input(ds,opt);

    samples=ds.samples;
    if opt.samples_are_unit_length
        quick_check_some_samples_being_unit_length(samples);
    else
        % normalize
        samples=samples./abs(samples);
    end

    % split based on .sa.targets
    [idxs,classes]=cosmo_index_unique(ds.sa.targets);
    nclasses=numel(classes);
    nfeatures=size(samples,2);

    % allocate space for output
    itc=zeros(nclasses+1,nfeatures);

    % ITC for each class
    for k=1:nclasses
        samples_k=samples(idxs{k},:);
        itc(k,:)=itc_on_unit_length_elements(samples_k);
    end

    % overall ITC
    itc(nclasses+1,:)=itc_on_unit_length_elements(samples);

    % set output
    itc_ds=set_output(itc,ds,classes);

function itc_ds=set_output(itc,ds,classes)
    % store results
    itc_ds=struct();
    itc_ds.samples=itc;
    itc_ds.sa.targets=[classes(:); NaN];

    % copy .a and .fa fields, if present
    if isfield(ds,'a')
        itc_ds.a=ds.a;

        if isfield(ds.a,'sdim')
            % remove sample dimensions if present
            itc_ds.a=rmfield(itc_ds.a,'sdim');
        end
    end

    if isfield(ds,'fa')
        itc_ds.fa=ds.fa;
    end

function itc=itc_on_unit_length_elements(samples)
    % computes inter-trial coherence for each column seperately
    itc=abs(sum(samples,1)/size(samples,1));

function quick_check_some_samples_being_unit_length(samples)
    % instead of checking all values, only verify for a subset of values.
    % This should prevent most use cases where the user accidentally
    % uses non-normalized data, whereas checking all values would be
    % equivalent to actually computing their length for each of them.
    count_to_check=10;

    % generate random positions to check for unit length
    nelem=numel(samples);
    pos=ceil(rand(1,count_to_check)*nelem);

    samples_subset=samples(pos);
    lengths=abs(samples_subset);

    % safety margin
    delta=10*eps('single');
    if any(lengths+delta<1 | lengths-delta>1)
        error('.samples input is not of unit length');
    end

function check_input(ds,opt)
    % must be a proper dataset
    if opt.check_dataset
        raise_exception=true;
        cosmo_check_dataset(ds,raise_exception);

        % must have targets and chunks
        cosmo_isfield(ds,{'sa.targets','sa.chunks'},raise_exception);
    end

    % all chunks must be unique
    if ~isequal(sort(ds.sa.chunks),unique(ds.sa.chunks))
        error(['All values in .sa.chunks must be different '...
                    'from each other']);
    end

    % trial counts must be balanced
    [idxs,classes]=cosmo_index_unique(ds.sa.targets);
    class_count=cellfun(@numel,idxs);
    unequal_pos=find(class_count~=class_count(1),1);
    if ~isempty(unequal_pos)
        error(['.sa.targets indicates unbalanced targets, with '...
                        '.sa.targets==%d occuring %d times, and '...
                        '.sa.targets==%d occuring %d times.\n'...
                        'To obtain balanced targets, consider '...
                        'using cosmo_balance_dataset.'],...
                    classes(1),class_count(1),...
                    classes(unequal_pos),class_count(unequal_pos));
    end

    % input must be complex
    if isreal(ds.samples)
        error('.samples must be complex');
    end

    v=opt.samples_are_unit_length;
    if ~(islogical(v) ...
            && isscalar(v))
        error('option ''samples_are_unit_length'' must be logical scalar');
    end


function addnoise_asl(cleanfile, noisefile, outfile, snr)
% ----------------------------------------------------------------------
%   This function adds noise to a file at a specified SNR level. It uses
%   the active speech level to compute the speech energy. The
%   active speech level is computed as per ITU-T P.56 standard [1].
%
%   Usage:  addnoise_asl(cleanFile.wav, noiseFile.wav, noisyFile.wav, SNR)
%
%         cleanFile.wav  - clean input file in .wav format
%         noiseFile.wav  - file containing the noise signal in .wav format
%         noisyFile.wav  - resulting noisy file
%         SNR            - desired SNR in dB
%
%   Note that if the variable IRS below (line 38) is set to 1, then it applies the IRS
%   filter to bandlimit the signal to 300 Hz - 3.2 kHz. The default IRS
%   value is 0, ie, no IRS filtering is applied.
%
%  Example call:
%       addnoise_asl('sp04.wav','white_noise.wav','sp04_white_5db.wav',5);
%
%
%  References:
%   [1] ITU-T (1993). Objective measurement of active speech level. ITU-T
%       Recommendation P. 56
%
%   Author: Yi Hu and Philipos C. Loizou
%
% Copyright (c) 2006 by Philipos C. Loizou
% $Revision: 0.0 $  $Date: 10/09/2006 $
% ----------------------------------------------------------------------

if nargin ~=4
    fprintf('USAGE: addnoise_asl(cleanFile.wav, noiseFile.wav, noisyFile.wav, SNR) \n');
    fprintf('For more help, type: help addnoise_asl\n\n');
    return;
end

IRS=0;  % if 1 apply IRS filter simulating telephone handset bandwidth (300 Hz -3.2 kHz)

% wavread gives floating point column data
[clean, srate, nbits]= wavread(cleanfile);
% filter clean speech with irs filter
if IRS==1, clean= apply_IRS( clean, srate, nbits); end;

[Px, asl, c0]= asl_P56 ( clean, srate, nbits);
% Px is the active speech level ms energy, asl is the active factor, and c0
% is the active speech level threshold.

x=clean;
x_len= length( x); % length of speech signal

[noise, srate1, nbits1]= wavread( noisefile);
if (srate1~= srate)| (nbits1~= nbits)
    error( 'the formats of the two files dont match!');
end
noise_len= length( noise);
if (noise_len<= x_len)
    error( 'the noise length has to be greater than speech length!');
end

rand_start_limit= noise_len- x_len+ 1;
% the start of the noise segment can vary between [1 rand_start_limit]
rand_start= round( (rand_start_limit- 1)* rand( 1)+ 1);
% random start of the noise segment
noise_segment= noise( rand_start: rand_start+ x_len- 1);

if IRS==1, noise_segment= apply_IRS( noise_segment, srate, nbits); end;

% this is the randomly selected noise segment that will be added to the
% clean speech x
Pn= noise_segment'* noise_segment/ x_len;
% we need to scale the noise segment samples to obtain the desired snr= 10*
% log10( Px/ (sf^2 * Pn))
sf= sqrt( Px/Pn/ (10^ (snr/ 10))); % scale factor for noise segment data
noise_segment= noise_segment * sf;

noisy = x+ noise_segment;

if ( (max( noisy)>= 1) | (min( noisy)< -1))
    error( 'Overflow occurred!\n');
end;

wavwrite( noisy, srate, nbits, outfile);

fprintf( 1, '\n NOTE: For comparison, the SNR based on long-term RMS level is %4.2f dB.\n\n', 10*log10((x'*x)/ ...
     (noise_segment'*noise_segment)));

%------------------------------------------------------------------------
function data_filtered= apply_IRS( data, Fs, nbits);

n= length( data);

% now find the next power of 2 which is greater or equal to n
pow_of_2= 2^ (ceil( log2( n)));

align_filter_dB= [0, -200; 50, -40; 100, -20; 125, -12; 160, -6; 200, 0;...
    250, 4; 300, 6; 350, 8; 400, 10; 500, 11; 600, 12; 700, 12; 800, 12;...
    1000, 12; 1300, 12; 1600, 12; 2000, 12; 2500, 12; 3000, 12; 3250, 12;...
    3500, 4; 4000, -200; 5000, -200; 6300, -200; 8000, -200];

[number_of_points, trivial]= size( align_filter_dB);
overallGainFilter= interp1( align_filter_dB( :, 1), align_filter_dB( :, 2), ...
    1000);

x= zeros( 1, pow_of_2);
x( 1: n)= data;

x_fft= fft( x, pow_of_2);

freq_resolution= Fs/ pow_of_2;

factorDb( 1: pow_of_2/2+ 1)= interp1( align_filter_dB( :, 1), ...
    align_filter_dB( :, 2), (0: pow_of_2/2)* freq_resolution)- ...
    overallGainFilter;
factor= 10.^ (factorDb/ 20);

factor= [factor, fliplr( factor( 2: pow_of_2/2))];
x_fft= x_fft.* factor;

y= ifft( x_fft, pow_of_2);

data_filtered= y( 1: n)';

function [asl_ms, asl, c0]= asl_P56 ( x, fs, nbits)
% this implements ITU P.56 method B.
% 'speechfile' is the speech file to calculate active speech level for,
% 'asl' is the active speech level (between 0 and 1),
% 'asl_rms' is the active speech level mean square energy.

% x is the column vector of floating point speech data

x= x(:); % make sure x is column vector
T= 0.03; % time constant of smoothing, in seconds
H= 0.2; % hangover time in seconds
M= 15.9;
% margin in dB of the difference between threshold and active speech level
thres_no= nbits- 1; % number of thresholds, for 16 bit, it's 15

I= ceil( fs* H); % hangover in samples
g= exp( -1/( fs* T)); % smoothing factor in envelop detection
c( 1: thres_no)= 2.^ (-15: thres_no- 16);
% vector with thresholds from one quantizing level up to half the maximum
% code, at a step of 2, in the case of 16bit samples, from 2^-15 to 0.5;
a( 1: thres_no)= 0; % activity counter for each level threshold
hang( 1: thres_no)= I; % hangover counter for each level threshold

sq= x'* x; % long-term level square energy of x
x_len= length( x); % length of x

% use a 2nd order IIR filter to detect the envelope q
x_abs= abs( x);
p= filter( 1-g, [1 -g], x_abs);
q= filter( 1-g, [1 -g], p);

for k= 1: x_len
    for j= 1: thres_no
        if (q(k)>= c(j))
            a(j)= a(j)+ 1;
            hang(j)= 0;
        elseif (hang(j)< I)
            a(j)= a(j)+ 1;
            hang(j)= hang(j)+ 1;
        else
            break;
        end
    end
end

asl= 0;
asl_rms= 0;
if (a(1)== 0)
    return;
else
    AdB1= 10* log10( sq/ a(1)+ eps);
end

CdB1= 20* log10( c(1)+ eps);
if (AdB1- CdB1< M)
    return;
end

AdB(1)= AdB1;
CdB(1)= CdB1;
Delta(1)= AdB1- CdB1;

for j= 2: thres_no
    AdB(j)= 10* log10( sq/ (a(j)+ eps)+ eps);
    CdB(j)= 20* log10( c(j)+ eps);
end

for j= 2: thres_no
    if (a(j) ~= 0)
        Delta(j)= AdB(j)- CdB(j);
        if (Delta(j)<= M)
            % interpolate to find the asl
            [asl_ms_log, cl0]= bin_interp( AdB(j), ...
                AdB(j-1), CdB(j), CdB(j-1), M, 0.5);
            asl_ms= 10^ (asl_ms_log/ 10);
            asl= (sq/ x_len)/ asl_ms;
            c0= 10^( cl0/ 20);
            break;
        end
    end
end

function [asl_ms_log, cc]= bin_interp(upcount, lwcount, ...
    upthr, lwthr, Margin, tol)

if (tol < 0)
    tol = -tol;
end

% Check if extreme counts are not already the true active value
iterno = 1;
if (abs(upcount - upthr - Margin) < tol)
    asl_ms_log= upcount;
    cc= upthr;
    return;
end
if (abs(lwcount - lwthr - Margin) < tol)
    asl_ms_log= lwcount;
    cc= lwthr;
    return;
end

% Initialize first middle for given (initial) bounds
midcount = (upcount + lwcount) / 2.0;
midthr = (upthr + lwthr) / 2.0;

% Repeats loop until `diff' falls inside the tolerance (-tol<=diff<=tol)
while ( 1)

    diff= midcount- midthr- Margin;
    if (abs(diff)<= tol)
        break;
    end

    % if tolerance is not met up to 20 iteractions, then relax the
    % tolerance by 10%

    iterno= iterno+ 1;

    if (iterno>20)
      tol = tol* 1.1;
    end

    if (diff> tol)   % then new bounds are ...
        midcount = (upcount + midcount) / 2.0;
        % upper and middle activities
        midthr = (upthr + midthr) / 2.0;
        % ... and thresholds
    elseif (diff< -tol)	% then new bounds are ...
        midcount = (midcount + lwcount) / 2.0;
        % middle and lower activities
        midthr = (midthr + lwthr) / 2.0;
        % ... and thresholds
    end

end
%   Since the tolerance has been satisfied, midcount is selected
%   as the interpolated value with a tol [dB] tolerance.

asl_ms_log= midcount;
cc= midthr;


function calpak_test018 ( )

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

  i = 0;

  while ( 1 )

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

    if ( jed1 < 0.0 )
      break
    end

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

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

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

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

  end

  return
end


classdef billiard

    % this are the dimensions of the table
    properties(Constant = true)
        XMAX = 100;
        XMIN = 0;
        YMAX = 50;
        YMIN = 0;
    end

    methods
        function whatever = billiard()
            % step 1. Draw the billiard table
            whatever.drawtable();

            % step 2. Draw the balls
          % ===========================
          % draw a single ball
          x = 10;   % Initial x-position
          y = 25;   % Initial y-position
          u = 1;    % Initial x-velocity (moves in x # pixels per iteration)
          v = 1;    % Initial y-velcotiy (moves in y # pixels per iteration)
          d = 5;    % Diameter of the ball
          m = 1;    % The mass of the ball

          ball = rectangle('position',[x,y,d,d],...
                    'FaceColor','b',...
                    'curvature',1.0 ...
                    );
          % ===========================
            % Update position
          % ===========================
           % the initial position
           x_new = x;
           y_new = y;

           % Update position

           dt = 1; % the time step is constant

           for iteration = 1:950;

               disp(x_new)

               if (abs(x_new-whatever.XMAX+d)<eps) || (abs(x_new-whatever.XMIN)<eps)
                   u = -u;
               end

               if (abs(y_new-whatever.YMAX+d)<eps) || (abs(y_new-whatever.YMIN)<eps)
                   v = -v;
               end

           x_new = x_new + u*dt;
           y_new = y_new + v*dt;

           ball.Position = [x_new,y_new,d,d];

           drawnow

           end

           % ===========================
        end

        function drawtable(whatever)
            % properties of the table
            w = whatever.XMAX-whatever.XMIN;
            h = whatever.YMAX-whatever.YMIN;
            x0 = whatever.XMIN;
            y0 = whatever.YMIN;
            % draw the table
            figure( 'name'   ,'TheCrazyBilliard2000',...
                    'menubar','none',...
                    'units'  ,'pixels'...
                    );
            rectangle('position',[x0,y0,w,h],...
                      'FaceColor','w',...
                      'curvature',0.1...
                      );
            axis('equal','off');
        end

    end
end


function F = asec(F, varargin)
%ASEC   Inverse secant of a CHEBFUN.
%   ASEC(F) computes the inverse secant of the CHEBFUN F.
%
%   ASEC(F, PREF) does the same but uses the CHEBFUNPREF object PREF when
%   computing the composition.
%
% See also SEC, ASECD.

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

% Call the compose method:
F = compose(F, @asec, varargin{:});

end


function [volume, permutevec] = volumepermute(volume, permutevec)

% VOLUMEPERMUTE
%
% See also VOLUMEFLIP

% do a low-level check on the input data
if ~isfield(volume, 'transform'), ft_error('the input volume needs a transformation matrix'); end
if ~isfield(volume, 'dim'),       ft_error('the input volume needs a dim field');             end

% define some variable locally
T   = volume.transform;
dim = volume.dim;

% determine which fields can be permuted
fnames = fieldnames(volume);
sel    = false(1,numel(fnames));
for k = 1:numel(fnames)
  tmp = volume.(fnames{k});
  if isnumeric(tmp) && numel(tmp)==prod(dim) && ndims(tmp)==3
    sel(k) = true;
  end
end
fnames = fnames(sel);

if nargin<2
  permutevec = 'auto';
end

if isequal(permutevec, 'auto')
  % determine the order of permutation to make the transformatiom matrix approximately diagonal
  [dum, m1]  = max(abs(T(1,1:3)));
  [dum, m2]  = max(abs(T(2,1:3)));
  % [dum, m3]  = max(abs(T(3,1:3)));
  [dum, m3]  = setdiff(1:3, [m1 m2]); % whichever dimension remains
  permutevec = [m1 m2 m3];
end

if ~all(permutevec==[1 2 3])
  % do the permutation on the numeric data
  for k = 1:numel(fnames)
    volume = setsubfield(volume, fnames{k}, permute(getsubfield(volume, fnames{k}), permutevec));
  end

  % do the permutation on the transformation matrix and dim
  volume.transform = volume.transform(:,[permutevec 4]);
  volume.dim       = volume.dim(permutevec);
else
  % do nothing
end


%FEATSELF Trainable mapping for forward feature selection
%
%   [W,R] = FEATSELF(A,CRIT,K,T)
%   [W,R] = A*FEATSELF([],CRIT,K,T)
%   [W,R] = A*FEATSELF(CRIT,K,T)
%   [W,R] = FEATSELF(A,CRIT,K,N)
%   [W,R] = A*FEATSELF([],CRIT,K,N)
%   [W,R] = A*FEATSELF(CRIT,K,N)
%
% INPUT
%   A    Training dataset
%   CRIT Name of the criterion or untrained mapping
%        (default: 'NN', i.e. the LOO 1-Nearest Neighbor error)
%   K    Number of features to select (default: K = 0, return optimal set)
%   T    Tuning dataset (optional)
%   N    Number of cross-validations (optional)
%
% OUTPUT
%   W    Output feature selection mapping
%   R    Matrix with step-by-step results
%
% DESCRIPTION
% Forward selection of K features using the dataset A. CRIT sets the
% criterion used by the feature evaluation routine FEATEVAL. If the
% dataset T is given, it is used as test set for FEATEVAL. Alternatvely a
% a number of cross-validation N may be supplied. For K = 0, the optimal
% feature set (corresponding to the maximum value of FEATEVAL) is returned.
% The result W can be used for selecting features using B*W.
% The selected features are stored in W.DATA and can be found by +W.
% In R, the search is reported step by step as:
%
% 	R(:,1) : number of features
% 	R(:,2) : criterion value
% 	R(:,3) : added / deleted feature
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, DATASETS, FEATEVAL, FEATSELLR, FEATSEL,
% FEATSELO, FEATSELB, FEATSELI, FEATSELP, FEATSELM

% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands

% $Id: featself.m,v 1.3 2007/04/21 23:06:46 duin Exp $

function [w,r] = featself(varargin)

  varargin = shiftargin(varargin,{'char','prmapping'});
  argin = setdefaults(varargin,[],'NN',0,[],[]);
  if mapping_task(argin,'definition')
    w = define_mapping(argin,'untrained','Forward FeatSel');
    return
  end

  [a,crit,ksel,t,fid] = deal(argin{:});
  [w,r] = featsellr(a,crit,ksel,1,0,t);

return