%% Собственная схема IMPES на базе MRST
% Две несжимаемые фазы, без гравитации и капиллярности.
% Давление: incompTPFA. Перенос: собственный upwind + явный Euler.
clear; close all; clc;
assert(exist('mrstModule','file')==2,'Сначала выполните MRST startup.m.');
mrstModule add incomp
gravity off
lessonTag = 'impes';
G = computeGeometry(cartGrid([60,1,1],[100,1,1]));
rock = makeRock(G,100*milli*darcy(),0.20);
PV = poreVolume(G,rock);
mu = [1,5]*centi*poise();
fluid = initSimpleFluid('mu',mu,'rho',[1000,800],'n',[2,2]);
qIn = 1/day();
bc = fluxside([],G,'LEFT',qIn,'sat',[1,0]);
bc = pside(bc,G,'RIGHT',100*barsa(),'sat',[0,1]);
T = computeTrans(G,rock);
state = initResSol(G,100*barsa(),[0,1]); reference = state;
N = G.faces.neighbors;
fw = @(s) (s.^2/mu(1))./(s.^2/mu(1)+(1-s).^2/mu(2));
% Гарантированная консервативная оценка |fw'| для данных Corey-кривых.
Lfw = 2*max(mu)/min(mu); CFL = 0.8;
tEnd = 0.5*sum(PV)/qIn; t=0; step=0;
waterInitial = sum(PV.*state.s(:,1));
cumulativeIn=0; cumulativeOut=0; history=[];
while t < tEnd
    %% A. Неявное давление при подвижностях из S^n
    state = incompTPFA(state,G,T,fluid,'bc',bc);
    reference = incompTPFA(reference,G,T,fluid,'bc',bc);
    q = state.flux;                  % от N(:,1) к N(:,2)

    %% B. Ограничение CFL по выходящему полному расходу
    a=N(:,1)>0; b=N(:,2)>0;
    outgoing = accumarray(N(a,1),max(q(a),0),[G.cells.num,1]) ...
             + accumarray(N(b,2),max(-q(b),0),[G.cells.num,1]);
    active=outgoing>0;
    dtCfl = CFL*min(PV(active)./(Lfw*outgoing(active)));
    % Согласуем конец интервала с округлением dt, избегая почти нулевого шага.
    remaining=tEnd-t;
    if remaining<=dtCfl*(1+1e-8); dt=remaining; else; dt=dtCfl; end
    assert(isfinite(dt) && dt>0);

    %% C. Выбор донора против направления потока
    donor=N(:,1); donor(q<0)=N(q<0,2);
    donorSw=zeros(G.faces.num,1);
    internalDonor=donor>0;
    donorSw(internalDonor)=state.s(donor(internalDonor),1);
    inflow=find(~internalDonor & abs(q)>1e-12*max(abs(q)));
    [found,ib]=ismember(inflow,bc.face);
    assert(all(found),'Для притока задайте граничную насыщенность.');
    donorSw(inflow)=bc.sat(ib,1);
    waterFlux=q.*fw(donorSw);

    %% D. СОБСТВЕННЫЙ явный баланс насыщенности
    netOut=accumarray(N(a,1),waterFlux(a),[G.cells.num,1]) ...
          -accumarray(N(b,2),waterFlux(b),[G.cells.num,1]);
    sw=state.s(:,1)-dt*netOut./PV;
    % Значения не обрезаем: выход за границы должен выявлять ошибку.
    assert(all(sw>=-1e-10 & sw<=1+1e-10),'Проверьте CFL и направления потоков.');
    state.s=[sw,1-sw];

    %% E. Независимый эталон MRST с ТЕМ ЖЕ dt, без внутренних подшагов
    reference=explicitTransport(reference,G,dt,rock,fluid, ...
        'bc',bc,'dt',dt,'verbose',false);

    %% F. Интегральный баланс воды на внешней границе
    boundary=any(N==0,2);
    outwardSign=ones(G.faces.num,1); outwardSign(N(:,1)==0)=-1;
    waterOut=outwardSign(boundary).*waterFlux(boundary);
    cumulativeIn=cumulativeIn+dt*sum(max(-waterOut,0));
    cumulativeOut=cumulativeOut+dt*sum(max(waterOut,0));
    residual=abs(sum(PV.*sw)-waterInitial-cumulativeIn+cumulativeOut)/sum(PV);
    difference=norm(state.s(:,1)-reference.s(:,1),inf);
    assert(residual<1e-9 && difference<1e-9);
    t=t+dt; step=step+1;
    history(end+1,:)=[t/day(),dt/day(),t*qIn/sum(PV),min(sw),max(sw),residual,difference]; %#ok<SAGROW>
end
state=incompTPFA(state,G,T,fluid,'bc',bc);
reference=incompTPFA(reference,G,T,fluid,'bc',bc);
historyTable=array2table(history,'VariableNames', ...
    {'Time_day','Dt_day','PVI','Sw_min','Sw_max','WaterBalance','DifferenceMRST'});
writetable(historyTable,'custom_impes_history.csv'); disp(historyTable(end,:));
fprintf('IMPES: %d шагов, t=%.6f сут, max|Sown-Smrst|=%.3e\n',step,t/day(),difference);
figure('Name','Собственный IMPES и MRST');
subplot(2,1,1); plot(G.cells.centroids(:,1),state.s(:,1),'-', ...
    G.cells.centroids(:,1),reference.s(:,1),'o'); grid on;
xlabel('x, м'); ylabel('Sw'); legend('Свой upwind + Euler','explicitTransport','Location','best');
subplot(2,1,2); plot(history(:,3),history(:,6)); grid on;
xlabel('PVI'); ylabel('Относительный баланс воды');
save('custom_impes_result.mat','G','state','reference','historyTable','CFL','Lfw');
