classdef bsp2deval_test < genlib_test
  % Testclass for bsp2deval (2D spline basis functions)
  %
  % [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
 
  properties
    tol_ = 1e-8;
  end

  methods (Test)
    function test_bsp2deval(testCase)
      % Test bsp2eval using cubic function of 2 variables

      % 1. Define analytical function and its derivatives
      fh    = @(x,y)    x.^3 - 3.*x.^2.*y +  6.*x.*y.^3 -    y.^3;
      dxfh  = @(x,y) 3.*x.^2 - 6.*x   .*y +  6.*   y.^3          ;
      dyfh  = @(x,y)         - 3.*x.^2    + 18.*x.*y.^2 - 3.*y.^2;
      dx2fh = @(x,y) 6.*x    - 6      .*y                        ;
      dy2fh = @(x,y)                      + 36.*x.*y    - 6.*y   ;
      dxyfh = @(x,y)         - 6.*x       + 18.*   y.^2          ;

      % 2. Construct 2D spline interpolant
      x = linspace(0,1,11).';
      y = linspace(0,1,21).';
      [Mx,taux] = csdec(x,x,'a');
      [My,tauy] = csdec(y,y,'a');

      [yy,xx] = meshgrid(y,x);

      % Spline coeffcients
      F = fh(xx,yy);
      c = Mx*F*My.';

      % 3. Comparison using evaluation on random values
      n0 = 1001;
      x0 = rand(n0,1);
      y0 = rand(n0,1);

      tol = testCase.tol_;

      [f,dxf,dyf,dx2f,dxyf,dy2f] = bsp2deval(taux,tauy,c,x0,y0,[0,1,2],1);

      % Check values
      testCase.verifyEqual(   f,   fh(x0,y0),'AbsTol',tol,'Verification failed for values of function');
      testCase.verifyEqual( dxf, dxfh(x0,y0),'AbsTol',tol,'Verification failed for values of x-derivative');
      testCase.verifyEqual( dyf, dyfh(x0,y0),'AbsTol',tol,'Verification failed for values of y-derivative');
      testCase.verifyEqual(dx2f,dx2fh(x0,y0),'AbsTol',tol,'Verification failed for values of xx-derivative');
      testCase.verifyEqual(dy2f,dy2fh(x0,y0),'AbsTol',tol,'Verification failed for values of yy-derivative');
      testCase.verifyEqual(dxyf,dxyfh(x0,y0),'AbsTol',tol,'Verification failed for values of xy-derivative');
    end
  end 
end
