classdef create_test < meq_test
  % Tests of CREATE file interfaces
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  properties
    rel_tol = 1e-1; % dz error tolerance w.r.t. L.dzx
    snapshotPath = '~/testdata/meq/Equil_00001_CL4E.mat';
    snapshotGeoPath = '~/testdata/meq/Equil_00001_CL4E.mat'; % old files have geometry and data mixed
%     segmentPath  = '~/testdata/meq/ITER_create_X.mat';
%     segmentGeoPath = '~/testdata/meq/ITER_create_G.mat';
    segmentPath = '~/testdata/meq/Case001_bellshape_curdriv_t625d000_t629d140_CNL4LIUQE.mat';
    segmentGeoPath = '~/testdata/meq/Case001_bellshape_curdriv_t625d000_t629d140_CNL4LIUQE.mat';
    verbose = 0;
  end
  
  methods(Test, TestTags={'CREATE'})
    function testCreateSnapshot(testCase)
      [~,~,cnl] = createf(testCase.snapshotPath,0);
      [L,~,LY] = liu('create',{testCase.snapshotGeoPath,testCase.snapshotPath},cnl,'iterq',100,'psichco',1e-4,'itera',50,...
        'Iaerr',1e3,'idml',0,'Iperr',1e4,'selfm','55\.A[ABDEL].*',...
        'bfct',@bf3pmex,'bfp',false,'wreg',0,...
        'pql',0.2,'iqR',1./[1 3/2 2 3 4],... % rational q surfaces to find
        'zfct',@liudz,'stab',1,'stabint',.1,'debug',0);
      
%       testCase.verifyLessThan(LY.chi,1e-1,'chi result failure');
      testCase.verifyNotEmpty(LY,'liu returned empty LY');
      testCase.verifyLessThan(LY.dz,L.dzx*testCase.rel_tol,'dz test result failure');
      
      %% plot rational surfaces
      if testCase.verbose
        iok = (LY.raR~=-1); % requested rational surfaces found
        plot(LY.raQ,1./LY.iqQ,'-',LY.raqmin,LY.qmin,'x',LY.raR(iok),L.P.qR(iok),'ok');
        hold on;
        plot(LY.raqmin,LY.qmin,'sk');
        drawnow;
      end
    end
    
    
    function testCreateStreaming(testCase)
      [~,~,cnl] = createf(testCase.segmentPath,[]);
      nt = min(length(cnl),1000); % run for max 1000 samples for brevity
      [L,~,LY] = liu('create',{testCase.segmentGeoPath,testCase.segmentPath},cnl(1:nt),'itert',1,...
        'Iaerr',1e3,'Iperr',1e4,'iterh',10,'tolh',1e-2,...
        'bfct',@bfef,'bfp',[3 3],'wreg',8e-6,...
        'debug',0,'selfm','55\.A[ABDEL].*');
      
      testCase.verifyLessThan(max(abs(LY.dz)),L.dzx*testCase.rel_tol,'dz test result failure');
    end
    
  end
  
  
end

