%% Сравнение физических моделей: одна фаза и вытеснение нефти водой
% Дополнительный пример, не входит в обязательные 90 минут.
% MRST startup.m должен быть выполнен заранее.
clear; close all; clc;
assert(exist('mrstModule', 'file') == 2, 'Сначала выполните MRST startup.m.');
mrstModule add incomp
gravity off
G = computeGeometry(cartGrid([40, 20, 1], [1000, 500, 20]));
rock = makeRock(G, 100*milli*darcy(), 0.20);
T = computeTrans(G, rock);
qIn = 200/day(); PV = sum(poreVolume(G, rock));
% Одинаковые геометрия, порода, координаты, радиусы и режимы скважин.
W1 = verticalWell([], G, rock, 2, 10, 1, ...
    'Type', 'rate', 'Val', qIn, 'Radius', 0.1, ...
    'Comp_i', 1, 'InnerProduct', 'ip_tpf', 'Name', 'I-1');
W1 = verticalWell(W1, G, rock, 39, 10, 1, ...
    'Type', 'bhp', 'Val', 150*barsa(), 'Radius', 0.1, ...
    'Comp_i', 1, 'InnerProduct', 'ip_tpf', 'Name', 'P-1');

%% Модель 1: одна несжимаемая фаза с вязкостью воды
fluid1 = initSingleFluid('mu', 1*centi*poise(), 'rho', 1000);
s1 = incompTPFA(initState(G, W1, 200*barsa(), 1), G, T, ...
    fluid1, 'wells', W1);
% У этой модели нет переменной Sw и понятия обводнённости смеси.

%% Модель 2: две несмешивающиеся несжимаемые фазы
% Порядок фаз [вода, нефть]. Начальная Sw=0.2; остаточные насыщенности = 0.
% krw=Sw^2, kro=(1-Sw)^2; mu_w=1 сП, mu_o=5 сП.
% Капиллярного давления и гравитации нет. Это не black-oil модель.
fluid2 = initSimpleFluid('mu', [1, 5]*centi*poise(), ...
    'rho', [1000, 800], 'n', [2, 2]);
W2 = W1;
for w = 1:numel(W2)
    W2(w).compi = [1, 0];             % при притоке в пласт — чистая вода
end
s2 = initState(G, W2, 200*barsa(), [0.2, 0.8]);
nSteps = 40;
tEnd = 0.5*PV/qIn;                    % 0.5 закачанного порового объёма
dt = tEnd/nSteps;
time_day = (0:nSteps)'*dt/day();
pvi = (0:nSteps)'/nSteps*0.5;
injector_bhp_bar = zeros(nSteps + 1, 1);
watercut = zeros(nSteps + 1, 1);
balance = zeros(nSteps + 1, 1);
for step = 0:nSteps
    % После транспорта пересчитываем давление при текущей насыщенности.
    s2 = incompTPFA(s2, G, T, fluid2, 'wells', W2);
    q = arrayfun(@(ws) sum(ws.flux), s2.wellSol);
    balance(step + 1) = abs(sum(q))/qIn;
    assert(balance(step + 1) < 1e-7);
    injector_bhp_bar(step + 1) = s2.wellSol(1).pressure/barsa();
    swProd = s2.s(W2(2).cells, 1);
    mobW = swProd.^2/(1*centi*poise());
    mobO = (1 - swProd).^2/(5*centi*poise());
    fw = mobW./(mobW + mobO);
    perfOutflow = -s2.wellSol(2).flux;
    assert(all(perfOutflow > 0), 'Ожидается отбор на всех перфорациях P-1.');
    watercut(step + 1) = sum(perfOutflow.*fw)/sum(perfOutflow);
    if step < nSteps
        s2 = implicitTransport(s2, G, dt, rock, fluid2, 'wells', W2);
    end
end
assert(all(s2.s(:) >= -1e-6 & s2.s(:) <= 1 + 1e-6));
history = table(time_day, pvi, injector_bhp_bar, watercut, balance);
disp(history([1, end], :));
writetable(history, 'physics_models_history.csv');
fprintf('Однофазная модель: BHP I-1 = %.6f бар\n', s1.wellSol(1).pressure/barsa());
fprintf('Двухфазная: начальная fw = %.6f (вода изначально подвижна)\n', watercut(1));
figure('Name', 'Сравнение физических моделей');
subplot(2, 2, 1);
plotCellData(G, s1.pressure/barsa(), 'EdgeColor', 'none');
view(2); axis equal tight; colorbar; title('Одна фаза: p, бар');
pLimits = [min([s1.pressure; s2.pressure]), max([s1.pressure; s2.pressure])]/barsa();
caxis(pLimits);
subplot(2, 2, 2);
plotCellData(G, s2.pressure/barsa(), 'EdgeColor', 'none');
view(2); axis equal tight; colorbar; caxis(pLimits); title('Две фазы: p, бар, PVI=0.5');
subplot(2, 2, 3);
plotCellData(G, s2.s(:, 1), 'EdgeColor', 'none');
view(2); axis equal tight; colorbar; caxis([0, 1]); title('Две фазы: Sw, PVI=0.5');
subplot(2, 2, 4);
plot(pvi, watercut, '-o'); grid on; ylim([0, 1]);
xlabel('Закачанный поровый объём, PVI'); ylabel('Обводнённость P-1');
% Независимая оценка временной погрешности: повторите с nSteps=80.
