classdef test_voltage_stray_traces < matlab.unittest.TestCase
  
  properties
    verbose = 0;
    dt = 1e-4;
  end
  
  properties(TestParameter)
    selu = {'','e','v','ex','vx'};
    nu   = {0,50,256,50,256};
  end
  
  methods (TestClassSetup)
    function setup_mds(testCase)
      testCase.addTeardown(@() mdsdisconnect);
      testCase.assertTrue(logical(mdsconnect('tcvdata.epfl.ch')));
      [~,s] = mdsopen(0);
      testCase.assertTrue(logical(rem(s,2)),'problem opening shot 0');
    end
  end
  
  methods (Test, TestTags={'Unit'}, ParameterCombination='sequential')
    function test_simulation(testCase,selu,nu)
      % Check that linear simulation of coils-only system with Va input
      % retrieves original Ia input
      [Ia,Va,t,G] = voltage_stray_traces('selu',selu,'nu',nu);
      
      %% State-space model for coil system
      % xdot = -inv(Maa)*diag(Ra) + inv(Maa)*Va
      MM = [G.Maa,G.Mau;G.Mau',G.Muu]; RR=diag([G.Ra;G.Ru]);
      
      dt = testCase.dt; %#ok<*PROPLC,*PROP>
      tsim = t(1):dt:(t(end)/5);
      
      nu = G.nu; na=G.na; ne = na+nu;
      A = -MM\RR; B=MM\eye(ne,na);
      C = eye(na,ne); D=zeros(na);
      
      % interpolate to tiny time grid
      sys = ss(A,B,C,D);
      Vain = interp1(t,Va',tsim)';
      Iain = interp1(t,Ia',tsim)';
      [Iasim,Tsim] = lsim(sys,Vain,tsim); Iasim=Iasim';
      
      if testCase.verbose
        %%
        clf; clear hs
        hs(1) = subplot(311);
        plot(Tsim,Iasim,'-');
        hold on
        plot(t,Ia,'k--');
        
        hs(2) = subplot(312);
        plot(Tsim,Iain-Iasim,'r');
        title('Ia'); ylabel('[A]');
        
        hs(3) = subplot(313);
        plot(t,Va)
        title('Va'); ylabel('[V]');
        linkaxes(hs,'x');
      end
      
      testCase.assertEqual(Iasim,Iain,'AbsTol',40)
    end
  end
end
