classdef meqgsave_test < meq_test
  % tests for meq geometry saving functions
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  properties
    verbosity = 0;
    fname = 'meqG.mat'; % file name for storing
    list = {'Muu','Mau','Maa','Bzxu','Brxu','dzMux','dzMax','Mbou','Mxia','Brbou','drBrxa'};   % list of G objects
    L,G; % L, Geometry to be populated
  end
  
  properties(TestParameter)
    opts = {'auxzmf','wvxzmf'} % object identifiers to save
  end
  
  properties(ClassSetupParameter)
    tok = {'ana','tcv'}
    selu = {'v','e'}
  end
  
  
  methods(TestClassSetup)
    function compute_geom(testCase,tok,selu)
      switch tok
        case 'ana', shot = 1;
        case 'tcv', shot = 61400;
      end
      
      [ok,msg] = meq_test.check_tok(tok,shot);
      testCase.assumeTrue(ok,msg);
      
      vprintf(testCase.verbosity,'\ntok: %s, vessel mode: %s\n',tok,selu);
      
      L = fbt(tok,shot,[],'selu',selu,'debug',testCase.verbosity>1,'izgrid',true); %#ok<*PROPLC>
      t=tic;
      testCase.G = meqg(L.G,L.P,testCase.list{:}); % generate G with these objects
      vprintf(testCase.verbosity,'gemetry generated in %fs\n',toc(t))
      
      testCase.L=L;
    end
  end
  
  methods(TestClassTeardown)
    function cleanup(testCase)
      % delete trailing geometry file
      if ~isempty(which(testCase.fname)); delete(testCase.fname); end
    end
  end
  
  methods(TestMethodSetup)
    function delete_previous_file(testCase)
      % delete existing geometry file
      if ~isempty(which(testCase.fname)); delete(testCase.fname); end
    end
  end
  
  methods(Test,TestTags={'Unit'})
    function test_equality(testCase,opts)
      % Check that computing geometry from scratch, or loading it, gives
      % same result.
      
      vprintf(testCase.verbosity,'\nmeqgsave saving options: %s\n',opts);
      L = testCase.L;
      t=tic;
      meqgsave(L.G,L.P,opts,testCase.fname,testCase.verbosity); % save geometry to file
      vprintf(testCase.verbosity,'geometry    saved in %fs\n',toc(t));
      
      t=tic;
      L.P.gfile = testCase.fname;
      Gload = meqg(L.G,L.P,testCase.list{:}); % retrieve it using file
      vprintf(testCase.verbosity,'geometry   loaded in %fs\n',toc(t));
      
      % remove fields in G1 that are not in G
      % since meqgload may have added further fields that were not in the
      % original desired list
      Gload = rmfield(Gload,setdiff(fieldnames(Gload),fieldnames(testCase.G)));
      
      % Check equality
      ok = structcmp(Gload,testCase.G);
      
      %%
      testCase.assertTrue(ok,'computed vs loaded geometries are not equal');
    end
  end
end

function vprintf(v,varargin)
if v, fprintf(varargin{:}); end
end
