function [ data, g, data0 ] = monotoneTest(which_approx, stencil_size,accuracy)
% monotoneTest: demonstrate the dangers of non-monotone approximations.
%
%   [ data, g, data0 ] = monotoneTest(which_approx, stencil_size, accuracy)
%
% Demonstrates that non-monotone approximations may do the wrong thing.
% Essentially the example discussed in section 1.3 of:
%
%    Adam M. Oberman, "A Convergent Monotone Difference Scheme for Motion of
%    Level Sets by Mean Curvature," Numerische Mathematik, 99: 365-379
%    (2004), DOI: 10.1007/s00211-004-0566-1.
%
% The initial conditions are phi = sin(2*pi*(x - y)).  With periodic BC, the
% function phi should be a steady state solution of the mean curvature flow.
% The centered difference approximation is non-monotone and causes the
% solution to decay away.  The median-based approximation does not.
%
% In practice, the results are not quite what is predicted.  There is a
% small but nonzero change in the median-based approach along the maxima and
% minima of the initial conditions of width proportional to the stencil
% size.  The centered difference approximation shows error everywhere, but
% the error does not grow nearly as fast as Oberman reports.  I have not yet
% investigated whether this behavior is a bug in the Toolbox code or in
% Oberman's paper.
%
% This function was originally designed as a script file, so most of the
% options can only be modified in the file.
%
% For example, edit the file to change the grid dimension, boundary conditions,
% flow field parameters, etc.
%
% Input Parameters:
%
%   which_approx: String.  Specifies method by which the mean curvature
%   term (one-Laplacian) is approximated.  Choices are:
%
%     'median': Use Oberman's approach.  Default.
%     'centered': Use a typical centered difference approximation.
%
%   stencil_size: Positive integer.  Controls the size of the stencil
%   when the median curvature approximation is chosen.  Ignored for the
%   centered curvature approximation.  Default is 3.
%
%   accuracy: String.  Controls the order of temporal approximations.  Note
%   that the spatial approximation is always second order. Choices are:
%  
%     'low': Use odeCFL1 (Forward Euler).  Default.
%     'medium': Use odeCFL2.
%     'high': Use odeCFL3.
%
% Output Parameters:
%
%   data: Implicit surface function at t_max.
%
%   g: Grid structure on which data was computed.
%
%   data0: Implicit surface function at t_0.

% Copyright 2007 Ian M. Mitchell (mitchell@cs.ubc.ca).
% This software is used, copied and distributed under the licensing 
%   agreement contained in the file LICENSE in the top directory of 
%   the distribution.
%
% Ian Mitchell, 1/21/07

%---------------------------------------------------------------------------
% You will see many executable lines that are commented out.
%   These are included to show some of the options available; modify
%   the commenting to modify the behavior.
  
%---------------------------------------------------------------------------
% Make sure we can see the kernel m-files.
run('../../addPathToKernel');

%---------------------------------------------------------------------------
% Curvature speed parameter.
bValue = 1;

% Handle default input arguments.
if(nargin < 1)
  which_approx = 'median';
end

if(nargin < 2)
  stencil_size = 3;
end

if(nargin < 3)
  accuracy = 'low';
end

%---------------------------------------------------------------------------
% Integration parameters.
tMax = 0.1;                  % End time.
plotSteps = 9;               % How many intermediate plots to produce?
t0 = 0;                      % Start time.
singleStep = 0;              % Plot at each timestep (overrides tPlot).

% Period at which intermediate plots should be produced.
tPlot = (tMax - t0) / (plotSteps - 1);

% How close (relative) do we need to get to tMax to be considered finished?
small = 100 * eps;

%---------------------------------------------------------------------------
% How to view the intermediate plots?
displayType = 'surf';    

% What level set should we view?
level = [ -0.02; +0.02 ];

% Pause after each plot?
pauseAfterPlot = 0;

% Delete previous plot before showing next?
deleteLastPlot = 0;

% Plot in separate subplots (set deleteLastPlot = 0 in this case)?
useSubplots = 1;

%---------------------------------------------------------------------------
% Create the grid.
g.dim = 2;
g.dx = 1 / 32;
g.min = -1;
g.max = (1 - g.dx);
g.bdry = @addGhostPeriodic;
g = processGrid(g);

%---------------------------------------------------------------------------
% Create initial conditions.
data = sin(2*pi*(g.xs{1} - g.xs{2}));
data0 = data;

%---------------------------------------------------------------------------
% Set up motion by mean curvature with constant coefficient.

% Some components of the schemeData structure are the same for either
% approximation.
schemeData.grid = g;
schemeData.b = bValue;

switch(which_approx)
 case 'median'
  schemeFunc = @termCurvatureByMedian;
  schemeData.stencil_size = stencil_size;
  schemeData.stencil_shape = 'circle';
  
 case 'centered'
  schemeFunc = @termCurvature;
  schemeData.curvatureFunc = @curvatureSecond;

 otherwise
  error('Unknown which_approx: %s', which_approx);
end
  
%---------------------------------------------------------------------------
% Set up time approximation scheme.
integratorOptions = odeCFLset('factorCFL', 0.75, 'stats', 'on');

% Choose approximations at appropriate level of accuracy.
switch(accuracy)
 case 'low'
  integratorFunc = @odeCFL1;
 case 'medium'
  integratorFunc = @odeCFL2;
 case 'high'
  integratorFunc = @odeCFL3;
 otherwise
  error('Unknown accuracy level %s', accuracy);
end

if(singleStep)
  integratorOptions = odeCFLset(integratorOptions, 'singleStep', 'on');
end

%---------------------------------------------------------------------------
% Initialize Display
f = figure;

% Set up subplot parameters if necessary.
if(useSubplots)
  rows = ceil(sqrt(plotSteps));
  cols = ceil(plotSteps / rows);
  plotNum = 1;
  subplot(rows, cols, plotNum);
end

h = visualizeLevelSet(g, data, displayType, level, [ 't = ' num2str(t0) ]);

hold on;
if(g.dim > 1)
  axis(g.axis);
  %daspect([ 1 1 1 ]);
end

%---------------------------------------------------------------------------
% Loop until tMax (subject to a little roundoff).
tNow = t0;
startTime = cputime;
while(tMax - tNow > small * tMax)

  % Reshape data array into column vector for ode solver call.
  y0 = data(:);

  % How far to step?
  tSpan = [ tNow, min(tMax, tNow + tPlot) ];
  
  % Take a timestep.
  [ t y ] = feval(integratorFunc, schemeFunc, tSpan, y0,...
                  integratorOptions, schemeData);
  tNow = t(end);

  % Get back the correctly shaped data array
  data = reshape(y, g.shape);

  if(pauseAfterPlot)
    % Wait for last plot to be digested.
    pause;
  end

  % Get correct figure, and remember its current view.
  figure(f);
  figureView = view;

  % Delete last visualization if necessary.
  if(deleteLastPlot)
    delete(h);
  end

  % Move to next subplot if necessary.
  if(useSubplots)
    plotNum = plotNum + 1;
    subplot(rows, cols, plotNum);
  end

  % Create new visualization.
  h = visualizeLevelSet(g, data - data0, displayType, level, [ 't = ' num2str(tNow) ]);

  % Restore view.
  view(figureView);
  
end

endTime = cputime;
fprintf('Total execution time %g seconds', endTime - startTime);
