% Wrapper class for the PARDISO MEX files.
% In particular, ensures that there is no memory leak, thanks to the destructor.

% Copyright © 2025 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare.  If not, see <https://www.gnu.org/licenses/>.

classdef pardiso < handle

properties
    pt
    iparm
    dparm
end

methods
    function obj = pardiso(number_of_threads)
        [obj.pt, obj.iparm, obj.dparm] = pardiso_init(number_of_threads);
    end

    function delete(obj)
        if ~isempty(obj.pt)
            pardiso_free(obj.pt, obj.iparm, obj.dparm)
            obj.pt = [];
        end
    end

    % Use standard solver
    function x = solve(obj, A, b)
        obj.iparm(4) = 0;
        [x, obj.pt, obj.iparm, obj.dparm] = pardiso_solve(A, b, obj.pt, obj.iparm, obj.dparm);
    end

    % Use CGS solver. Assumes that the standard solver has already been called on similar matrices.
    function x = solve_cgs(obj, A, b, iter_tol)
        obj.iparm(4) = -10*floor(log10(iter_tol)) + 1;
        [x, obj.pt, obj.iparm, obj.dparm] = pardiso_solve(A, b, obj.pt, obj.iparm, obj.dparm, 33);
    end
end

end
