%% Calcification Rate Correction
% 
% Method: Calculate the calcification rate by back-calculating the dissolution 
%         kinetics of whole-shell biogenic carbonates.
%
% Requirements: CO2SYS v3.2.1 or a compatible version must be installed.
%               GSW Oceanographic Toolbox (Gibbs SeaWater) must be installed. 
%
% Reference: Ries, J. B., Ghazaleh, M. N., Connolly, B., Westfield, I., and 
%            Castillo, K. D. (2016). Impacts of seawater saturation state 
%            (ΩA = 0.4–4.6) and temperature (10, 25 °C) on the dissolution 
%            kinetics of whole-shell biogenic carbonates. Geochimica et 
%            Cosmochimica Acta. 192: 318–337.

clear; clc; close all;

%% 1. Input Parameters
Volume_Water           = 3.3594;                     % Water Volume (L)
Soft_Tissue_Dry_Weight = 1.79;                       % Soft Tissue Dry Weight (g)
Shell_Dry_Weight       = 165.24;                     % Shell Dry Weight (g)
Temperature            = 30;                         % Temperature (°C)
Salinity               = 16;                         % Salinity (psu)
Duration               = 2.73;                       % Corrected Culture Duration (h)
SA = gsw_SA_from_SP(Salinity, 0, 0, 0);              % Absolute Salinity (g/kg)
CT = gsw_CT_from_t(SA, Temperature, 0);              % Conservative Temperature (°C)
rho_sw = gsw_rho(SA, CT, 0) / 1000;                  % Seawater Density (kg/L)

% Water chemistry parameters (μmol/L)
DO_ini  = 175;       DIC_ini = 960.42000;    TA_ini  = 967.25;     % Initial
DO_fin  = 103.125;   DIC_fin = 1128.47388;   TA_fin  = 1106.1;     % Final

% CO2SYS constant options (based on the selections supported by the toolbox)
K1K2CONST = 14;       % Carbonic acid dissociation constants:
                      %    1 = Roy et al. (1993)
                      %        (T: 0-45   S: 5-45   Total scale)
                      %    2 = Goyet & Poisson (1989)
                      %        (T: -1-40   S: 10-50   Seawater scale)
                      %    3 = Hansson (1973) refit by Dickson & Millero (1987)
                      %        (T: 2-35   S: 20-40   Seawater scale)
                      %    4 = Mehrbach refit by Dickson & Millero (1987)
                      %        (T: 2-35   S: 20-40   Seawater scale)
                      %    5 = Hansson & Mehrbach refit by Dickson & Millero (1987)
                      %        (T: 2-35   S: 20-40   Seawater scale)
                      %    6 = GEOSECS (original Mehrbach)
                      %        (T: 2-35   S: 19-43   NBS scale)
                      %    7 = Peng (original Mehrbach without pressure correction)
                      %        (T: 2-35   S: 19-43   NBS scale)
                      %    8 = Millero (1979) Freshwater only
                      %        (T: 0-50   S: 0)
                      %    9 = Cai & Wang (1998)
                      %        (T: 2-35   S: 0-49   NBS scale)
                      %    10 = Lueker et al. (2000)
                      %        (T: 2-35   S: 19-43   Total scale)
                      %    11 = Mojica Prieto & Millero (2002)
                      %        (T: 0-45   S: 5-42   Seawater scale)
                      %    12 = Millero et al. (2002)
                      %        (T: -1.6-35   S: 34-37   Seawater scale)
                      %    13 = Millero et al. (2006)
                      %        (T: 0-50   S: 1-50   Seawater scale)
                      %    14 = Millero (2010)
                      %        (T: 0-50   S: 1-50   Seawater scale)
                      %    15 = Waters, Millero & Woosley (2014)
                      %        (T: 0-50   S: 1-50   Seawater scale)
                      %    16 = Sulpis et al. (2020)
                      %        (T: -1.7-32   S: 31-38   Total scale)
                      %    17 = Schockman & Byrne (2021)
                      %        (T: 15-35   S: 19-41   Total scale)
KSO4CONST = 1;        % Bisulfate dissociation constant:
                      %    1 = Dickson (1990)
                      %    2 = Khoo et al. (1977)
                      %    3 = Waters & Millero (2013)
KFCONST   = 2;        % Hydrogen fluoride dissociation constant:
                      %    1 = Dickson & Riley (1979)
                      %    2 = Perez & Fraga (1987)
BORON     = 1;        % Total boron concentration formulation:
                      %    1 = Uppström (1974)
                      %    2 = Lee (2010)

% Numerical Integration options
dt         = 0.01;    % Time Step (h)
ode_solver = 'rk4';   % Integration method: 'euler' or 'rk4'

%% 2. Unit Conversion and Preprocessing
% Convert the units of DIC and TA from μmol/L to μmol/kg
DIC_ini_kg = DIC_ini / rho_sw;
TA_ini_kg  = TA_ini  / rho_sw;
DIC_fin_kg = DIC_fin / rho_sw;
TA_fin_kg  = TA_fin  / rho_sw;

% Convert changes in dissolved oxygen to the oxygen consumption rate (μmol/h)
R_O2 = (DO_ini - DO_fin) * Volume_Water / Duration;   % Oxygen Consumption Rate (μmol/h)

% Convert changes in total alkalinity to uncorrected calcification rate (μmol/h)
G_net_abs = (TA_ini - TA_fin) * Volume_Water / (2 * Duration);   % Uncorrected Calcification Rate (μmol/h)

% Convert changes in dissolved inorganic carbon and total alkalinity to carbon dioxide release rate (μmol/h)
Delta_DIC = (DIC_fin - DIC_ini) * Volume_Water;   % Dissolved Inorganic Carbon Change (μmol)
R_CO2 = G_net_abs + Delta_DIC / Duration;   % Carbon Dioxide Release Rate (μmol/h)

% Normalize to Soft Tissue Dry Weight (μmol/h/g DW)
R_O2_per_g  = R_O2  / Soft_Tissue_Dry_Weight;
R_CO2_per_g = R_CO2 / Soft_Tissue_Dry_Weight;
G_net_per_g = G_net_abs / Soft_Tissue_Dry_Weight;

fprintf('Calcification Rate_Uncorrected = %.4f μmol/h/g DW\n', G_net_per_g);
fprintf('Respiration Rate_O2            = %.4f μmol/h/g DW\n', R_O2_per_g);
fprintf('Respiration Rate_CO2           = %.4f μmol/h/g DW\n', R_CO2_per_g);
fprintf('Respiratory Quotient           = %.4f\n\n', R_CO2 / R_O2);

%% 3. Oyster Shell Dissolution Rate Equation
% y = 0.0015 - 0.0012 * T - 0.6379 * exp(-6.6214 * ΩA + 0.0816 * T * ΩA)
% y: % weight loss per day (Negative values indicate dissolution).
% Return the absolute dissolution rate (μmol CaCO3/h).
M_CaCO3 = 100.0869;   % Molar Mass (g/mol)
dissolution_rate = @(T, OmegaA) ...
    max(0, -(0.0015 - 0.0012 * T - 0.6379 * exp(-6.6214 * OmegaA + 0.0816 * T * OmegaA))) ...
    / 100 * Shell_Dry_Weight / M_CaCO3 * 1e6 / 24;   % Dissolution Rate (μmol/h)

%% 4. Forward Simulation Function
% Simulate the given corrected calcification rate G_guess (μmol/h)
simulate_incubation = @(G_guess) forward_model(G_guess, ...
    TA_ini_kg, DIC_ini_kg, Volume_Water, rho_sw, ...
    Soft_Tissue_Dry_Weight, R_CO2, ...
    Temperature, Salinity, Duration, dt, ...
    dissolution_rate, K1K2CONST, KSO4CONST, KFCONST, BORON, ode_solver);

% The function is defined at the end of the file; only a function handle is declared here.

%% 5. Back-Calculate the Corrected Calcification Rate
% Starting from G = 0, search for roots in both directions.

% Evaluation function: Given G (μmol/h), return (simulated TA − measured TA)
fval = @(G) simulate_incubation(G) - TA_fin_kg;

% Evaluate function value at G = 0
f0 = fval(0);
options = optimset('Display','iter','TolX',1e-9);

if abs(f0) < 1e-9
    G_opt_abs = 0;
    exitflag = 1;

elseif f0 > 0
    % f0 > 0: simulated TA > measured TA at G = 0 → increase G (positive) to consume total alkalinity
    G_high = 1;
    max_iter = 50;
    for iter = 1:max_iter
        if fval(G_high) < 0
            break;
        end
        G_high = G_high * 2;
    end
    if fval(G_high) >= 0
        error('Cannot find an upper bound on G that makes the simulated TA lower than the measured TA.');
    end
    [G_opt_abs, ~, exitflag] = fzero(fval, [0, G_high], options);

else % f0 < 0
    % f0 < 0: simulated TA < measured TA at G = 0 → decrease G (negative) to add total alkalinity
    warning('When G = 0, the simulated TA is already lower than the measured TA; attempting to search for negative G.');
    G_low = -1;   % Starting point (μmol/h) for negative-direction search
    max_iter = 50;
    for iter = 1:max_iter
        if fval(G_low) > 0
            break;
        end
        G_low = G_low * 2;
    end
    if fval(G_low) <= 0
        error('Cannot find a lower bound on G that makes the simulated TA higher than the measured TA.');
    end
    [G_opt_abs, ~, exitflag] = fzero(fval, [G_low, 0], options);
end

% Normalize the final optimization result
G_opt_per_g = G_opt_abs / Soft_Tissue_Dry_Weight;

fprintf('\n=====================================================\n');
fprintf('Back-Calculation Result: \n');
fprintf('Calcification Rate_Corrected   = %.4f μmol/h/g DW\n', G_opt_per_g);
fprintf('Calcification Rate_Uncorrected = %.4f μmol/h/g DW\n', G_net_per_g);
fprintf('Average Dissolution Rate       = %.4f μmol/h/g DW\n', G_opt_per_g - G_net_per_g);
fprintf('=====================================================\n');

%% 6. Forward Model Subfunction
function TA_sim_end = forward_model(G_abs, TA0_kg, DIC0_kg, V, rho, ...
    DW_soft, R_CO2_abs, T, S, t_end, dt, diss_rate_func, ...
    K1K2, KSO4, KF, BORON, solver)

    % State variable: TA (μmol/kg), DIC (μmol/kg)
    TA = TA0_kg;
    DIC = DIC0_kg;
    t = 0;

    while t < t_end
        % Adaptive step size; truncate the last step
        step = min(dt, t_end - t);
        
        % Call CO2SYS to calculate the current ΩA
        [Result, ~, ~] = CO2SYS(TA, DIC, 1, 2, ...
            S, T, T, 0, 0, ...   % Salinity, Temperature (in), Temperature (out), Pressure (in), Pressure (out)
            0, 0, 0, 0, 1, ...   % SI, PO4, NH4, H2S, pH scale
            K1K2, KSO4, KF, BORON);
        OmegaA = Result(18);   % Aragonite saturation state
        
        % Calculate instantaneous dissolution rate (μmol/h)
        R_diss = diss_rate_func(T, OmegaA);
        
        % Calculate contribution of calcification and respiration to TA and DIC (μmol/kg/h)
        conv = 1 / (V * rho);   % Convert the units from μmol/h to μmol/kg/h
        
        dTA_dt  = (-2 * G_abs + 2 * R_diss) * conv;
        dDIC_dt = (-G_abs + R_diss + R_CO2_abs) * conv;
        
        % Euler or RK4 integration
        switch lower(solver)
            case 'euler'
                TA  = TA  + dTA_dt * step;
                DIC = DIC + dDIC_dt * step;
            case 'rk4'
                % Simple RK4 implementation
                f_TA  = @(ta,dic) (-2 * G_abs + 2 * diss_rate_func(T, OmegaA_from_CO2SYS(ta,dic, S,T,K1K2,KSO4,KF,BORON))) * conv;
                f_DIC = @(ta,dic) (-G_abs + diss_rate_func(T, OmegaA_from_CO2SYS(ta,dic, S,T,K1K2,KSO4,KF,BORON)) + R_CO2_abs) * conv;
                [TA, DIC] = rk4_step(f_TA, f_DIC, TA, DIC, step);
            otherwise
                error('Unknown integration method: %s', solver);
        end
        
        t = t + step;
    end
    
    TA_sim_end = TA;   % Return final TA concentration (μmol/kg)
end

function [TA_new, DIC_new] = rk4_step(f_TA, f_DIC, TA, DIC, h)
    % Fourth-order Runge-Kutta step
    k1_TA = f_TA(TA, DIC);
    k1_DIC = f_DIC(TA, DIC);
    
    k2_TA = f_TA(TA + 0.5 * h * k1_TA, DIC + 0.5 * h * k1_DIC);
    k2_DIC = f_DIC(TA + 0.5 * h * k1_TA, DIC + 0.5 * h * k1_DIC);
    
    k3_TA = f_TA(TA + 0.5 * h * k2_TA, DIC + 0.5 * h * k2_DIC);
    k3_DIC = f_DIC(TA + 0.5 * h * k2_TA, DIC + 0.5 * h * k2_DIC);
    
    k4_TA = f_TA(TA + h * k3_TA, DIC + h * k3_DIC);
    k4_DIC = f_DIC(TA + h*k3_TA, DIC + h*k3_DIC);
    
    TA_new = TA + (h/6)*(k1_TA + 2*k2_TA + 2*k3_TA + k4_TA);
    DIC_new = DIC + (h/6)*(k1_DIC + 2*k2_DIC + 2*k3_DIC + k4_DIC);
end

function OmegaA = OmegaA_from_CO2SYS(TA, DIC, S, T, K1K2, KSO4, KF, BORON)
    % Return OmegaA
    Result = CO2SYS(TA, DIC, 1, 2, S, T, T, 0, 0, ...
        0, 0, 0, 0, 1, K1K2, KSO4, KF, BORON);
    OmegaA = Result(18);
end
