classdef tests_mga < matlab.unittest.TestCase
  % abstract class for mga tests
  % tests results of re-running mga vs stored data in PCS tree
  
  properties
    verbosity = 0;
  end
  
  properties(Abstract)
    RelTol % relative error tolerance allowed
    RelTolV % relative error tolerance allowed for power supply voltages
    fort_equiv
  end

  properties(TestParameter,Abstract)
    shots % cell array of strings with shots to test
  end
  
  methods(TestClassSetup)
    function check_matlab_version(testCase)
      testCase.assumeFalse(verLessThan('matlab','9.6'),...
        'Golden shots test skipped for matlab versions lower than 9.6');
    end
    
    function working_folder_fixture(testCase)
      testCase.applyFixture(matlab.unittest.fixtures.WorkingFolderFixture);
    end
  end
  
  methods(Test, TestTags={'golden_shots'})
    function test_mga_vs_mds(testCase,shots)
      shot = str2double(shots);
      % Initial checks
      testCase.assertTrue(xor(testCase.fort_equiv,ismgam(shot)),sprintf('Shot %d has fort_equiv=%d and ismgam=%d',shot,testCase.fort_equiv,ismgam(shot)));
      
      % Get stored values
      MGAref = mgaget(shot);
      
      % Check no numerical instability was present in reference shot
      testCase.assumeTrue(all(abs(MGAref.EFCUR(:)) < 1e5),sprintf('Unphysical values found in reference EFCUR traces, skipping shot %d with fort_equiv=%d',shot,testCase.fort_equiv));
            
      % Re-run mga.m for this shot
      try
        [~,~,MGA] = mga(shot,testCase.fort_equiv);
        MGA = struct2single(MGA);
      catch ME
        if strcmp(ME.identifier,'TCVCS:MGA:InvalidInputData')
          testCase.assumeFail(sprintf('MGAMS parameters invalid: %s\n\tskipping shot %d with fort_equiv=%d',ME.message,shot,testCase.fort_equiv));
        else
          rethrow(ME);
        end
      end
      
      % Run comparision
      check = mgacmp(MGA,MGAref,'all',testCase.RelTol,testCase.RelTolV,testCase.verbosity);
      if ~check, mgacmp(MGA,MGAref,'all',testCase.RelTol,testCase.RelTolV,true); end % Repeat with verbose=true to display the offending traces
      testCase.verifyTrue(check,sprintf('Difference between MGA results and stored results exceed tolerance for shot %d with fort_equiv=%d',shot,testCase.fort_equiv));
    end
  end
end
