classdef RungekuttaRvInstage < time.Timestepper
    properties
        F       % RHS of the ODE
        k       % Time step
        t       % Time point
        v       % Solution vector
        n       % Time level
        coeffs  % The coefficents used for the RK time integration
        RV      % Residual Viscosity
        DvDt    % Function for computing the time deriative used for the RV evaluation
    end

    methods
        function obj = RungekuttaRvInstage(F, k, t0, v0, RV, DvDt, order)
            obj.F = F;
            obj.k = k;
            obj.t = t0;
            obj.v = v0;
            obj.n = 0;
            % Extract the coefficients for the specified order
            % used for the RK updates from the Butcher tableua.
            [s,a,b,c] = time.rk.butcherTableau(order);
            obj.coeffs = struct('s',s,'a',a,'b',b,'c',c);
            obj.RV = RV;
            obj.DvDt = DvDt;
        end

        function [v, t] = getV(obj)
            v = obj.v;
            t = obj.t;
        end

        function state = getState(obj)
            dvdt = obj.DvDt(obj.v);
            [viscosity,  Df, firstOrderViscosity, residualViscosity] = obj.RV.evaluate(obj.v, dvdt);
            state = struct('v', obj.v, 'dvdt', dvdt, 'Df', Df, 'viscosity', viscosity, 'residualViscosity', residualViscosity, 'firstOrderViscosity', firstOrderViscosity, 't', obj.t);
        end

        % Advances the solution vector one time step using the Runge-Kutta method given by
        % obj.coeffs, updating the Residual Viscosity in each Runge-Kutta stage
        function obj = step(obj)
            obj.v = rv.time.rungekuttaRV(obj.v, obj.t, obj.k, obj.F, obj.RV, obj.DvDt, obj.coeffs);
            obj.t = obj.t + obj.k;
            obj.n = obj.n + 1;
        end
    end

    % Takes one time step of size dt using the rungekutta method
    % starting from v and where the function F(v,t,RV) gives the
    % time derivatives. coeffs is a struct holding the RK coefficients
    % for the specific method. RV is the residual viscosity which is updated
    % in between the stages and after the updated solution is computed.
    methods (Static)
    function v = rungekuttaRV(v, t , dt, F, RV, DvDt, coeffs)
        % Move one stage outside to avoid branching for updating the
        % residual inside the loop.
        k = zeros(length(v), coeffs.s);
        k(:,1) = F(v,t,RV.evaluateViscosity(v,DvDt(v)));

        % Compute the intermediate stages k
        for i = 2:coeffs.s
            u = v;
            for j = 1:i-1
                u = u + dt*coeffs.a(i,j)*k(:,j);
            end
            k(:,i) = F(u,t+coeffs.c(i)*dt, RV.evaluateViscosity(u,DvDt(u)));
        end

        % Compute the updated solution as a linear combination
        % of the intermediate stages.
        u = v;
        for i = 1:coeffs.s
            u = u + dt*coeffs.b(i)*k(:,i);
        end
        v = u;
    end


end