## Copyright (C) 2009 Carlo de Falco <carlo DOT defalco AT gmail DOT com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn {Function File} {@var{data} =} osc_steady_state_init (@var{data})  
## Prepare the non linear solver kernel to run a steady state simulation.
##
## @end deftypefn

## Author: Carlo de Falco <carlo DOT defalco AT gmail DOT com>

function data = osc_steady_state_init(data)

  switch data.nls
    case "fsolve"
      Nx = data.Nx;
      ## FIXME: initial guess could be set in a more clever way..
      data.a0 = data.b0 = data.c0 = zeros(Nx,1);
      data.a0 += 1e9; data.b0 += 1e9;
      
      ## FIXME: this is for consistency with tst as apparently daspk chokes on
      ## negative potential???
      data.d0 = data.V * (data.x - data.x(1)) / data.L / data.sc(4);
      data.d0 -= min(data.d0); 
      data.x0 = [data.a0; data.b0; data.c0; data.d0(2:end-1)];
      data.xdot0 = 0*data.x0;

      ## FIXME: user should be able to override default settings
      fun{1} = @(y) ...
	  __osc_residual_tpl__ ( data, y, zeros(size(y)), data.tslot(2) );

      fun{2} = @(y) ...
          __osc_jacobian_tpl__ (data, y, zeros(size(y)), data.tslot(2) );

      data.t   = data.tslot(2);

      data.fun = @(y) thefun (y, fun);

    otherwise
      error("unsupported solver")
  endswitch

endfunction

function [res, jac] = thefun (y, fun)
  res = fun{1}(y);
  if nargout > 1
    jac = fun{2}(y);
  endif
endfunction

  
