classdef fgs_test < meq_test
  % Tests Static Forward-Grad-Shafranov solver FGS
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  properties
    fname
    tok = 'ana'
    dosave = false;
    verbosity = 0;
    insrc
  end
  
  properties(TestParameter)
    shot = {'1','2','3','4','5','6','11','82'}
    method = {'all-nl','Picard'};
  end
  
  methods(Test,TestTags={'fgs'})
    
    function test_algoNL_methods(testCase,shot)
      myshot = str2double(shot);
      testCase.assumeFalse(str2double(shot)==82,...
        'Picard method does not yet work for doublets, skipping test')
      % run for both methods and compare result
      for ii=1:numel(testCase.method)
        mymethod = testCase.method{ii};
        [L,~,LY(ii)] = fgs('ana',myshot,0,'algoNL',mymethod,...
          'usepreconditioner',~isequal(mymethod,'Picard'),...
          'iterq',50); %#ok<AGROW>
        if ii>1
          Ip0 = L.P.b0/L.P.r0/(4e-7*pi);
          testCase.verifyEqual(LY(1).Fx,LY(ii).Fx,'AbsTol',100*L.P.tolF)
          testCase.verifyEqual(LY(1).Iy,LY(ii).Iy,'AbsTol',Ip0*L.P.tolF)
          testCase.verifyEqual(LY(1).bp,LY(ii).bp,'AbsTol',100*L.P.tolF)
          testCase.verifyEqual(LY(1).li,LY(ii).li,'AbsTol',100*L.P.tolF)
          testCase.verifyEqual(LY(1).Ip,LY(ii).Ip,'AbsTol',10*Ip0*L.P.tolF)
        end
      end
    end
    
    function test_fgs(testCase,shot,method)
      testCase.assumeFalse(isequal(method,'Picard') && str2double(shot)==82,...
        'Picard method does not yet work for doublets, skipping test')
      
      if testCase.verbosity
        fprintf('Testing %s %s, %s\n',testCase.tok,shot,method)
      end
      
      t = 0:5e-3:1e-2; % test retrieving multiple slices for anamak too
      [~,LX,LY] = fgs(testCase.tok,str2double(shot),t,...
            'debug',testCase.verbosity,'algoNL',method,'tol',1e-8);

      testCase.verifyEqual(LX.t,t,sprintf('incorrect LX.t for shot %s',shot))
      testCase.verifyEqual(LY.t,t,sprintf('incorrect LY.t for shot %s',shot))
      testCase.verifyTrue(all(LY.isconverged),sprintf('shot %s did not converge',shot));
    end
    
  end
end
