classdef tools_test < meq_test
  % tests for generic meq tools
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  methods(Test, TestTags = {'Unit'})
    
    function test_slicers(testCase)
      % test data slicer/insertion functions
      % get data to user
      [~,~,LY] = fge('ana',1,0:1e-4:1e-3);
      
      % test meqxk (slice extractor) - compare using indices or logical mask
      kk = false(size(LY.t));
      k=kk; k(1)=true;   LY1=meqxk(LY,k);
      k=kk; k(end)=true; LYn=meqxk(LY,k);
      k=kk; k(2:3)=true; LYi=meqxk(LY,k);
      
      testCase.verifyEqual(LY1,meqxk(LY,1),'should match')
      testCase.verifyEqual(LYn,meqxk(LY,'last'),'should match')
      testCase.verifyEqual(LYi,meqxk(LY,[2:3]),'should match')
      
      % test meqsk (time slice inserter)
      testCase.verifyEqual(LY,meqsk(LY,true(size(kk)),LY),...
        'should be identity operation')
      testCase.verifyEqual(meqxk(LY,2),  meqxk(meqsk(LY,1  ,meqxk(LY,2)),  1  ),...
        'should have replaced first index');
      testCase.verifyEqual(meqxk(LY,2:3),meqxk(meqsk(LY,1:2,meqxk(LY,2:3)),1:2),...
        '`should have replaced first two indices');
    end
    
    function test_meqagconc(testCase)
      % sample inputs
      in1={'Ip','bp','qA'}; % simple
      in2={{'Ip','bp','qA'},{'Ip','bp','qA'},{'ag','ag','ag'}}; % complex
      
      % nondoublet
      L = fge('ana',1,0,'idoublet',0,'agcon',in1);
      testCase.verifyWarningFree(@() meqagconc(L))
      
      % doublet
      L = fge('ana',1,0,'idoublet',1,'agcon',in1);
      testCase.verifyWarningFree(@() meqagconc(L))
      L = fge('ana',1,0,'idoublet',1,'agcon',in2);
      testCase.verifyWarningFree(@() meqagconc(L))
      % direct pass
    end

    function test_meqxconvert(testCase)
      %% Test meqxconvert accuracy and iterq
      [L,~,LX]  = fbt('ana',1,0,'bfct',@bf3pmex,'bfp',[]   ,'nr',32,'nz',16,'iterq',0);
      [L2]      = fbt('ana',1,0,'bfct',@bfabmex,'bfp',[1 2],'nr',16,'nz',8, 'iterq',1);
      
      LX2 = meqxconvert(L,LX,L2);
      
      equalfields = {'PQ','PpQ','TQ','TTpQ','PpQg','TTpQg','Iv','Ia','Iu','Ip'};
      for ii=equalfields
        testCase.verifyEqual(LX.(ii{:}),LX2.(ii{:}),'RelTol',sqrt(eps),sprintf('Error in field %s',ii{:}))
      end
      
      % Sum of current Iy should be equal
      testCase.verifyEqual(sum(LX2.Iy(:)),sum(LX.Iy(:)),'RelTol',10*eps,'Sum of Iy is not equal after conversion')
    end
  end
end
