dynare/matlab/utilities/estimation/check_varobs_are_endo_and_d...

114 lines
2.9 KiB
Matlab

function check_varobs_are_endo_and_declared_once(varobs, endo_names)
% Check that each declared observed variable is an endogenous variable and is declared only once
%
% INPUTS
% - varobs [cell] list of observed variables
% - endo_names [cell] list of endogenous variables
%
% OUTPUTS
% None, display an error message something is wrong with VAROBS
% Copyright © 2023-2024 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/>.
cut = @(x) x(1:end-2); % Remove the last two elements of an array.
% Throw an error if an observed variable is not declared as an endogenous variable.
unknown_varobs = setdiff(varobs, endo_names);
if ~isempty(unknown_varobs)
error('Estimation:varobs:unknown', 'VAROBS: Unknown endogenous variables (%s)\n', cut(sprintf('%s, ', unknown_varobs{:})))
end
% Check that a variable is not declared as observed more than once.
[varobs_, vi, vj] = unique(varobs);
if ~isequal(vi, vj)
duplicates = {}; j=0;
for i=2:length(vi)
if vi(i)>vi(i-1)+1
j = j+1;
duplicates{j} = varobs{vi(i-1)};
end
end
if sum(length(vi)==vj)
duplicates{j+1} = varobs{vi(end)};
end
error('Estimation:varobs:duplicate', 'VAROBS: A variable cannot be declared as observed more than once (%s)\n', cut(sprintf('%s, ', duplicates{:})))
end
return % --*-- Unit tests --*--
%@test:1
endovar={'A1','A2','A3','A4','A5'};
obsvar={'A1','A1','A3','A4','A4','A4','A5'};
% Call the tested routine.
try
check_varobs_are_endo_and_declared_once(obsvar, endovar)
t(1) = false;
catch ME
t(1) = true;
end
if t(1)
t(2) = strcmp(ME.identifier, 'Estimation:varobs:duplicate');
end
T = all(t);
%@eof:1
%@test:2
endovar={'A1','A2','A3','A4','A5'};
obsvar={'A1','A3','A4','A5','A5'};
% Call the tested routine.
try
check_varobs_are_endo_and_declared_once(obsvar, endovar)
t(1) = false;
catch ME
t(1) = true;
end
if t(1)
t(2) = strcmp(ME.identifier, 'Estimation:varobs:duplicate');
end
T = all(t);
%@eof:2
%@test:3
endovar={'A1','A2','A3','A4','A5'};
obsvar={'A1','A3','A4','B1','A5'};
% Call the tested routine.
try
check_varobs_are_endo_and_declared_once(obsvar, endovar)
t(1) = false;
catch ME
t(1) = true;
end
if t(1)
t(2) = strcmp(ME.identifier, 'Estimation:varobs:unknown');
end
T = all(t);
%@eof:3