=5 && ~isempty(gsa0),
- for j=1:np,
+if nargin >=5 && ~isempty(gsa0)
+ for j=1:np
nvr2(j) = var(diff(gsa2.fs(:,j),2));
nvr0(j) = var(diff(gsa0.fs(:,j),2));
end
@@ -702,7 +702,7 @@ if nargin >=5 && ~isempty(gsa0),
gsa1 = ss_anova(y, x, 1, 0, 2, gsa1.nvr);
gsa2 = log2level_map(gsa1, isig, lam);
end
-if nargin==6,
+if nargin==6
gsax = ss_anova(gsa2.y-gsa2.fit, x, 1, 0, 2, nvrs(:,2));
else
gsax = ss_anova(gsa2.y-gsa2.fit, x, 1);
@@ -713,7 +713,7 @@ gsa22.f0 = mean(gsa22.fit);
gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2);
gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest);
gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2);
-for j=1:np,
+for j=1:np
gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j);
gsa22.fses(:,j) = gsax.fses(:,j);
gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j);
@@ -730,7 +730,7 @@ hfig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title);
density] = posterior_moments(y0,1,0.9);
post_deciles = [-inf; post_deciles; inf];
-for jt=1:10,
+for jt=1:10
indy{jt}=find( (y0>post_deciles(jt)) & (y0<=post_deciles(jt+1)));
leg{jt}=[int2str(jt) '-dec'];
end
@@ -741,18 +741,18 @@ indmcf = indmcf(jtmp);
nbr_par = length(indmcf);
nrow=ceil(sqrt(nbr_par+1));
ncol=nrow;
-if nrow*(nrow-1)>nbr_par,
+if nrow*(nrow-1)>nbr_par
ncol=nrow-1;
end
cmap = colormap(jet(10));
-for jx=1:nbr_par,
+for jx=1:nbr_par
subplot(nrow,ncol,jx)
hold off
- for jt=1:10,
+ for jt=1:10
h=cumplot(x0(indy{jt},indmcf(jx)));
set(h,'color', cmap(jt,:), 'linewidth', 2)
- hold all,
+ hold all
end
title(options_mcf.param_names(indmcf(jx),:),'interpreter','none')
end
diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m
index fd09d9cac..d4c007174 100644
--- a/matlab/gsa/redform_screen.m
+++ b/matlab/gsa/redform_screen.m
@@ -8,7 +8,7 @@ function redform_screen(dirname, options_gsa_)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2012-2016 European Commission
% Copyright (C) 2012-2017 Dynare Team
@@ -39,7 +39,7 @@ iload = options_gsa_.load_redform;
nliv = options_gsa_.morris_nliv;
pnames = M_.param_names(estim_params_.param_vals(:,1),:);
-if nargin==0,
+if nargin==0
dirname='';
end
@@ -53,7 +53,7 @@ nshock = length(bayestopt_.pshape)-np;
nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:)));
js=0;
-for j=1:size(anamendo,1),
+for j=1:size(anamendo,1)
namendo=deblank(anamendo(j,:));
iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact');
@@ -63,10 +63,10 @@ for j=1:size(anamendo,1),
namexo=deblank(anamexo(jx,:));
iexo=strmatch(namexo,M_.exo_names,'exact');
- if ~isempty(iexo),
+ if ~isempty(iexo)
y0=teff(T(iendo,iexo+nspred,:),kn,istable);
- if ~isempty(y0),
- if mod(iplo,9)==0,
+ if ~isempty(y0)
+ if mod(iplo,9)==0
ifig=ifig+1;
hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. shocks ',int2str(ifig)]);
iplo=0;
@@ -82,11 +82,11 @@ for j=1:size(anamendo,1),
%set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
set(gca,'xticklabel',' ','fontsize',10)
set(gca,'xlim',[0.5 10.5])
- for ip=1:min(np,10),
+ for ip=1:min(np,10)
text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
title([namendo,' vs. ',namexo],'interpreter','none')
- if iplo==9,
+ if iplo==9
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1)
end
@@ -94,7 +94,7 @@ for j=1:size(anamendo,1),
end
end
end
- if iplo<9 && iplo>0 && ifig,
+ if iplo<9 && iplo>0 && ifig
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3))
end
@@ -105,10 +105,10 @@ for j=1:size(anamendo,1),
namlagendo=deblank(anamlagendo(je,:));
ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
- if ~isempty(ilagendo),
+ if ~isempty(ilagendo)
y0=teff(T(iendo,ilagendo,:),kn,istable);
- if ~isempty(y0),
- if mod(iplo,9)==0,
+ if ~isempty(y0)
+ if mod(iplo,9)==0
ifig=ifig+1;
hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
iplo=0;
@@ -124,25 +124,25 @@ for j=1:size(anamendo,1),
%set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
set(gca,'xticklabel',' ','fontsize',10)
set(gca,'xlim',[0.5 10.5])
- for ip=1:min(np,10),
+ for ip=1:min(np,10)
text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
- if iplo==9,
+ if iplo==9
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1)
end
end
end
end
- if iplo<9 && iplo>0 && ifig,
+ if iplo<9 && iplo>0 && ifig
dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3))
end
end
-hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening');
+hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening');
%bar(SA)
% boxplot(SA','whis',10,'symbol','r.')
myboxplot(SA',[],'.',[],10)
@@ -150,7 +150,7 @@ set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
set(gca,'xlim',[0.5 np+0.5])
set(gca,'ylim',[0 1])
set(gca,'position',[0.13 0.2 0.775 0.7])
-for ip=1:np,
+for ip=1:np
text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
xlabel(' ')
@@ -177,4 +177,3 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
-
diff --git a/matlab/gsa/scatter_analysis.m b/matlab/gsa/scatter_analysis.m
index ddd4fec3a..d526b3f0e 100644
--- a/matlab/gsa/scatter_analysis.m
+++ b/matlab/gsa/scatter_analysis.m
@@ -37,12 +37,12 @@ amcf_title = options_scatter.amcf_title;
title = options_scatter.title;
fname_ = options_scatter.fname_;
xparam1=[];
-if isfield(options_scatter,'xparam1'),
+if isfield(options_scatter,'xparam1')
xparam1=options_scatter.xparam1;
-end
+end
OutputDirectoryName = options_scatter.OutputDirectoryName;
-if ~DynareOptions.nograph,
+if ~DynareOptions.nograph
skipline()
xx=[];
if ~isempty(xparam1)
diff --git a/matlab/gsa/scatter_callback.m b/matlab/gsa/scatter_callback.m
index afba86225..61345107c 100644
--- a/matlab/gsa/scatter_callback.m
+++ b/matlab/gsa/scatter_callback.m
@@ -34,7 +34,7 @@ xparam1=x(K,:)';
switch type
case 'save'
save(['my_params_' int2str(K)],'xparam1')
-
+
case 'eval'
disp('Evaluating smoother ...')
[oo_, M_]=evaluate_smoother(xparam1,M_.endo_names,M_,oo_,options_,bayestopt_,estim_params_);
diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m
index 3718b23ed..211b2e74b 100644
--- a/matlab/gsa/scatter_mcf.m
+++ b/matlab/gsa/scatter_mcf.m
@@ -2,7 +2,7 @@ function scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, D
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2014-2016 European Commission
% Copyright (C) 2014-2017 Dynare Team
@@ -49,7 +49,7 @@ clear Z;
nflag = 0;
if nargin >=3
nflag = 1;
-end;
+end
if nargin<4 || isempty(plotsymbol)
if n*p<100, plotsymbol = 'o';
@@ -60,37 +60,37 @@ end
if nargin<5
fnam='';
end
-if nargin<6,
+if nargin<6
dirname='';
nograph=1;
else
- nograph=0;
+ nograph=0;
end
-if nargin<7,
+if nargin<7
figtitle=fnam;
end
-if nargin<8,
+if nargin<8
xparam1=[];
end
-if nargin<10,
+if nargin<10
beha_name = 'BEHAVIOUR';
non_beha_name = 'NON-BEHAVIOUR';
end
-if nargin==10,
+if nargin==10
non_beha_name = ['NON-' beha_name];
end
figtitle_tex=strrep(figtitle,'_','\_');
fig_nam_=[fnam];
-if ~nograph,
+if ~nograph
hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
end
bf = 0.1;
ffs = 0.05/(p-1);
ffl = (1-2*bf-0.05)/p;
-if p>1,
+if p>1
fL = linspace(bf,1-bf+ffs,p+1);
else
fL = bf;
@@ -129,7 +129,7 @@ for i = 1:p
end
hold off;
% axis([-0.1 1.1 -0.1 1.1])
- if i=3
nflag = 1;
-end;
+end
if nargin<4 || isempty(plotsymbol)
if n*p<100, plotsymbol = 'o';
@@ -55,17 +55,17 @@ end
if nargin<5 || isempty(fnam)
fnam='scatter_plot';
end
-if nargin<6 || isempty(dirname),
+if nargin<6 || isempty(dirname)
dirname='';
nograph=1;
DynareOptions.nodisplay=0;
else
- nograph=0;
+ nograph=0;
end
-if nargin<7 || isempty(figtitle),
+if nargin<7 || isempty(figtitle)
figtitle=fnam;
end
-if nargin<8,
+if nargin<8
xparam1=[];
end
@@ -79,7 +79,7 @@ set(hh,'userdata',{X,xp})
bf = 0.1;
ffs = 0.05/(p-1);
ffl = (1-2*bf-0.05)/p;
-if p>1,
+if p>1
fL = linspace(bf,1-bf+ffs,p+1);
else
fL = bf;
@@ -135,7 +135,7 @@ for i = 1:p
end
hold off;
% axis([-0.1 1.1 -0.1 1.1])
- if i
0,
+ if np<52 && ilptau>0
[lpmat] = qmc_sequence(np, int64(1), 0, Nsam)';
- if np>30 || ilptau==2, % scrambled lptau
- for j=1:np,
+ if np>30 || ilptau==2 % scrambled lptau
+ for j=1:np
lpmat(:,j)=lpmat(randperm(Nsam),j);
end
end
else %ilptau==0
[lpmat] = NaN(Nsam,np);
- for j=1:np,
+ for j=1:np
lpmat(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
end
@@ -188,9 +188,9 @@ if fload==0,
% end
%
% end
- if pprior,
- for j=1:nshock,
- if opt_gsa.morris~=1,
+ if pprior
+ for j=1:nshock
+ if opt_gsa.morris~=1
lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
end
if opt_gsa.prior_range
@@ -204,7 +204,7 @@ if fload==0,
% xdelt(:,:,j)=prior_draw_gsa(0,[lpmat0 lpmat]+deltx);
% end
% end
- for j=1:np,
+ for j=1:np
lpmat(:,j)=lpmat(:,j).*(bounds.ub(j+nshock)-bounds.lb(j+nshock))+bounds.lb(j+nshock);
end
else
@@ -254,13 +254,13 @@ if fload==0,
% end
% end
%load([fname_,'_mode'])
- if neighborhood_width>0 && isempty(options_.mode_file),
+ if neighborhood_width>0 && isempty(options_.mode_file)
xparam1 = get_all_parameters(estim_params_,M_);
else
eval(['load ' options_.mode_file '.mat;']);
end
- if neighborhood_width>0,
- for j=1:nshock,
+ if neighborhood_width>0
+ for j=1:nshock
if opt_gsa.morris ~= 1
lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
end
@@ -268,10 +268,10 @@ if fload==0,
lb=max([bounds.lb(j) xparam1(j)*(1-neighborhood_width)]);
lpmat0(:,j)=lpmat0(:,j).*(ub-lb)+lb;
end
- for j=1:np,
+ for j=1:np
ub=xparam1(j+nshock)*(1+sign(xparam1(j+nshock))*neighborhood_width);
lb=xparam1(j+nshock)*(1-sign(xparam1(j+nshock))*neighborhood_width);
- if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock),
+ if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock)
ub=min([bounds.ub(j+nshock) ub]);
lb=max([bounds.lb(j+nshock) lb]);
else
@@ -283,7 +283,7 @@ if fload==0,
d = chol(inv(hh));
lp=randn(Nsam*2,nshock+np)*d+kron(ones(Nsam*2,1),xparam1');
lnprior=zeros(1,Nsam*2);
- for j=1:Nsam*2,
+ for j=1:Nsam*2
lnprior(j) = any(lp(j,:)'<=bounds.lb | lp(j,:)'>=bounds.ub);
end
ireal=[1:2*Nsam];
@@ -305,7 +305,7 @@ if fload==0,
inorestriction=zeros(1,Nsam);
irestriction=zeros(1,Nsam);
infox=zeros(Nsam,1);
- for j=1:Nsam,
+ for j=1:Nsam
M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_);
%try stoch_simul([]);
try
@@ -315,14 +315,14 @@ if fload==0,
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
end
infox(j,1)=info(1);
- if infox(j,1)==0 && ~exist('T','var'),
+ if infox(j,1)==0 && ~exist('T','var')
dr_=oo_.dr;
- if prepSA,
+ if prepSA
try
T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam);
catch
ME = lasterror();
- if strcmp('MATLAB:nomem',ME.identifier),
+ if strcmp('MATLAB:nomem',ME.identifier)
prepSA=0;
disp('The model is too large for storing state space matrices ...')
disp('for mapping reduced form or for identification')
@@ -334,26 +334,26 @@ if fload==0,
end
egg=zeros(length(dr_.eigval),Nsam);
end
- if infox(j,1),
+ if infox(j,1)
% disp('no solution'),
- if isfield(oo_.dr,'ghx'),
+ if isfield(oo_.dr,'ghx')
oo_.dr=rmfield(oo_.dr,'ghx');
end
- if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval'),
+ if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval')
oo_.dr=rmfield(oo_.dr,'eigval');
end
end
catch ME
- if isfield(oo_.dr,'eigval'),
+ if isfield(oo_.dr,'eigval')
oo_.dr=rmfield(oo_.dr,'eigval');
end
- if isfield(oo_.dr,'ghx'),
+ if isfield(oo_.dr,'ghx')
oo_.dr=rmfield(oo_.dr,'ghx');
end
- disp('No solution could be found'),
+ disp('No solution could be found')
end
dr_ = oo_.dr;
- if isfield(dr_,'ghx'),
+ if isfield(dr_,'ghx')
egg(:,j) = sort(dr_.eigval);
if prepSA
jstab=jstab+1;
@@ -363,14 +363,14 @@ if fload==0,
% bayestopt_.restrict_columns, ...
% bayestopt_.restrict_aux);
end
- if ~exist('nspred','var'),
+ if ~exist('nspred','var')
nspred = dr_.nspred; %size(dr_.ghx,2);
nboth = dr_.nboth;
nfwrd = dr_.nfwrd;
end
info=endogenous_prior_restrictions(Tt,Rr,M_,options_,oo_);
infox(j,1)=info(1);
- if info(1),
+ if info(1)
inorestriction(j)=j;
else
iunstable(j)=0;
@@ -384,13 +384,13 @@ if fload==0,
if any(isnan(egg(1:nspred,j)))
iwrong(j)=j;
else
- if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium,
+ if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium
iindeterm(j)=j;
end
end
end
else
- if exist('egg','var'),
+ if exist('egg','var')
egg(:,j)=ones(size(egg,1),1).*NaN;
end
iwrong(j)=j;
@@ -402,7 +402,7 @@ if fload==0,
dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
end
dyn_waitbar_close(h);
- if prepSA && jstab,
+ if prepSA && jstab
T=T(:,:,1:jstab);
else
T=[];
@@ -454,7 +454,7 @@ if fload==0,
bkpprior.p2=bayestopt_.p2;
bkpprior.p3=bayestopt_.p3;
bkpprior.p4=bayestopt_.p4;
- if pprior,
+ if pprior
if ~prepSA
save([OutputDirectoryName filesep fname_ '_prior.mat'], ...
'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
@@ -477,19 +477,19 @@ if fload==0,
end
end
else
- if pprior,
+ if pprior
filetoload=[OutputDirectoryName filesep fname_ '_prior.mat'];
else
filetoload=[OutputDirectoryName filesep fname_ '_mc.mat'];
end
load(filetoload,'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun','egg','yys','nspred','nboth','nfwrd','infox')
Nsam = size(lpmat,1);
- if pprior==0 && ~isempty(options_.mode_file),
+ if pprior==0 && ~isempty(options_.mode_file)
eval(['load ' options_.mode_file '.mat;']);
end
- if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact')),
+ if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact'))
h = dyn_waitbar(0,'Please wait...');
options_.periods=0;
options_.nomoments=1;
@@ -499,7 +499,7 @@ else
%T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),length(istable));
ntrans=length(istable);
yys=NaN(length(ys_),ntrans);
- for j=1:ntrans,
+ for j=1:ntrans
M_.params(estim_params_.param_vals(:,1)) = lpmat(istable(j),:)';
%stoch_simul([]);
[Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
@@ -548,51 +548,51 @@ delete([OutputDirectoryName,filesep,fname_,'_',aindname,'.*']);
delete([OutputDirectoryName,filesep,fname_,'_',aunstname,'.*']);
delete([OutputDirectoryName,filesep,fname_,'_',awrongname,'.*']);
-if length(iunstable)>0 || length(iwrong)>0,
+if length(iunstable)>0 || length(iwrong)>0
fprintf(['%4.1f%% of the prior support gives unique saddle-path solution.\n'],length(istable)/Nsam*100)
fprintf(['%4.1f%% of the prior support gives explosive dynamics.\n'],(length(ixun) )/Nsam*100)
- if ~isempty(iindeterm),
+ if ~isempty(iindeterm)
fprintf(['%4.1f%% of the prior support gives indeterminacy.\n'],length(iindeterm)/Nsam*100)
end
inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions
- if ~isempty(iwrong) || ~isempty(inorestriction),
+ if ~isempty(iwrong) || ~isempty(inorestriction)
skipline()
- if any(infox==49),
+ if any(infox==49)
fprintf(['%4.1f%% of the prior support violates prior restrictions.\n'],(length(inorestriction) )/Nsam*100)
end
- if ~isempty(iwrong),
+ if ~isempty(iwrong)
skipline()
disp(['For ',num2str(length(iwrong)/Nsam*100,'%4.1f'),'% of the prior support dynare could not find a solution.'])
skipline()
end
- if any(infox==1),
+ if any(infox==1)
disp([' For ',num2str(length(find(infox==1))/Nsam*100,'%4.1f'),'% The model doesn''t determine the current variables uniquely.'])
end
- if any(infox==2),
+ if any(infox==2)
disp([' For ',num2str(length(find(infox==2))/Nsam*100,'%4.1f'),'% MJDGGES returned an error code.'])
end
- if any(infox==6),
+ if any(infox==6)
disp([' For ',num2str(length(find(infox==6))/Nsam*100,'%4.1f'),'% The jacobian evaluated at the deterministic steady state is complex.'])
end
- if any(infox==19),
+ if any(infox==19)
disp([' For ',num2str(length(find(infox==19))/Nsam*100,'%4.1f'),'% The steadystate routine thrown an exception (inconsistent deep parameters).'])
end
- if any(infox==20),
+ if any(infox==20)
disp([' For ',num2str(length(find(infox==20))/Nsam*100,'%4.1f'),'% Cannot find the steady state.'])
end
- if any(infox==21),
+ if any(infox==21)
disp([' For ',num2str(length(find(infox==21))/Nsam*100,'%4.1f'),'% The steady state is complex.'])
end
- if any(infox==22),
+ if any(infox==22)
disp([' For ',num2str(length(find(infox==22))/Nsam*100,'%4.1f'),'% The steady has NaNs.'])
end
- if any(infox==23),
+ if any(infox==23)
disp([' For ',num2str(length(find(infox==23))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has complex valued scalars.'])
end
- if any(infox==24),
+ if any(infox==24)
disp([' For ',num2str(length(find(infox==24))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has some NaNs.'])
end
- if any(infox==30),
+ if any(infox==30)
disp([' For ',num2str(length(find(infox==30))/Nsam*100,'%4.1f'),'% Ergodic variance can''t be computed.'])
end
@@ -602,7 +602,7 @@ if length(iunstable)>0 || length(iwrong)>0,
itot = [1:Nsam];
isolve = itot(find(~ismember(itot,iwrong))); % dynare could find a solution
% Blanchard Kahn
- if neighborhood_width,
+ if neighborhood_width
options_mcf.xparam1 = xparam1(nshock+1:end);
end
itmp = itot(find(~ismember(itot,istable)));
@@ -613,7 +613,7 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.title = 'unique solution';
mcf_analysis(lpmat, istable, itmp, options_mcf, options_);
- if ~isempty(iindeterm),
+ if ~isempty(iindeterm)
itmp = isolve(find(~ismember(isolve,iindeterm)));
options_mcf.amcf_name = aindname;
options_mcf.amcf_title = aindtitle;
@@ -622,8 +622,8 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.title = 'indeterminacy';
mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_);
end
-
- if ~isempty(ixun),
+
+ if ~isempty(ixun)
itmp = isolve(find(~ismember(isolve,ixun)));
options_mcf.amcf_name = aunstname;
options_mcf.amcf_title = aunsttitle;
@@ -632,10 +632,10 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.title = 'instability';
mcf_analysis(lpmat, itmp, ixun, options_mcf, options_);
end
-
+
inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions
iwrong = iwrong(find(~ismember(iwrong,inorestriction))); % what went wrong beyond prior restrictions
- if ~isempty(iwrong),
+ if ~isempty(iwrong)
itmp = itot(find(~ismember(itot,iwrong)));
options_mcf.amcf_name = awrongname;
options_mcf.amcf_title = awrongtitle;
@@ -644,9 +644,9 @@ if length(iunstable)>0 || length(iwrong)>0,
options_mcf.title = 'inability to find a solution';
mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_);
end
-
- if ~isempty(irestriction),
- if neighborhood_width,
+
+ if ~isempty(irestriction)
+ if neighborhood_width
options_mcf.xparam1 = xparam1;
end
np=size(bayestopt_.name,1);
@@ -679,7 +679,7 @@ if length(iunstable)>0 || length(iwrong)>0,
x0=0.5.*(bounds.ub(1:nshock)-bounds.lb(1:nshock))+bounds.lb(1:nshock);
x0 = [x0; lpmat(iok,:)'];
end
-
+
M_ = set_all_parameters(x0,estim_params_,M_);
[oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
% stoch_simul([]);
@@ -699,12 +699,8 @@ xparam1=x0;
save prior_ok.mat xparam1;
options_.periods=opt.periods;
-if isfield(opt,'nomoments'),
+if isfield(opt,'nomoments')
options_.nomoments=opt.nomoments;
end
options_.irf=opt.irf;
options_.noprint=opt.noprint;
-
-
-
-
diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m
index 6a23fe63d..092b50daa 100644
--- a/matlab/gsa/stab_map_1.m
+++ b/matlab/gsa/stab_map_1.m
@@ -8,7 +8,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
% iplot = 1 plot cumulative distributions (default)
% iplot = 0 no plots
% ipar = index array of parameters to plot
-% dirname = (OPTIONAL) path of the directory where to save
+% dirname = (OPTIONAL) path of the directory where to save
% (default: current directory)
% pcrit = (OPTIONAL) critical value of the pvalue below which show the plots
%
@@ -18,7 +18,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2012-2016 European Commission
% Copyright (C) 2012-2017 Dynare Team
@@ -40,11 +40,11 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
global estim_params_ bayestopt_ M_ options_
-if nargin<5,
+if nargin<5
iplot=1;
end
fname_ = M_.fname;
-if nargin<7,
+if nargin<7
dirname='';
end
if nargin<9,
@@ -59,20 +59,20 @@ nshock = nshock + estim_params_.ncn;
npar=size(lpmat,2);
ishock= npar>estim_params_.np;
-if nargin<6,
+if nargin<6
ipar=[];
end
-if nargin<8 || isempty(pcrit),
+if nargin<8 || isempty(pcrit)
pcrit=1;
end
-% Smirnov test for Blanchard;
-for j=1:npar,
+% Smirnov test for Blanchard;
+for j=1:npar
[H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j));
proba(j)=P;
dproba(j)=KSSTAT;
end
-if isempty(ipar),
+if isempty(ipar)
% ipar=find(dproba>dcrit);
ipar=find(proba12,
+ if nparplot>12
dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA_',int2str(i) '.tex'],'w');
diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m
index 80d140e15..f4b958355 100644
--- a/matlab/gsa/stab_map_2.m
+++ b/matlab/gsa/stab_map_2.m
@@ -3,7 +3,7 @@ function indcorr = stab_map_2(x,alpha2, pvalue_crit, fnam, dirname,xparam1,figti
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2011-2016 European Commission
% Copyright (C) 2011-2017 Dynare Team
@@ -29,17 +29,17 @@ npar=size(x,2);
nsam=size(x,1);
ishock= npar>estim_params_.np;
nograph = options_.nograph;
-if nargin<4,
+if nargin<4
fnam='';
end
-if nargin<5,
+if nargin<5
dirname='';
nograph=1;
end
-if nargin<6,
+if nargin<6
xparam1=[];
end
-if nargin<7,
+if nargin<7
figtitle=fnam;
end
@@ -61,7 +61,7 @@ ifig=0;
j2=0;
if ishock==0
npar=estim_params_.np;
- if ~isempty(xparam1),
+ if ~isempty(xparam1)
xparam1=xparam1(nshock+1:end);
end
else
@@ -73,14 +73,14 @@ title_string_tex=['Correlation analysis for ',strrep(fnam,'_','\\_')];
indcorr = [];
entry_iter=1;
-for j=1:npar,
+for j=1:npar
i2=find(abs(c00(:,j))>alpha2);
- if length(i2)>0,
- for jx=1:length(i2),
- if pvalue(j,i2(jx))0
+ for jx=1:length(i2)
+ if pvalue(j,i2(jx))0,
+ if (mod(j2,12)==0) && j2>0
dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
@@ -159,10 +159,10 @@ for j=1:npar,
end
end
end
-
+
end
end
- if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0),
+ if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0)
dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
@@ -177,10 +177,10 @@ for j=1:npar,
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
- end
+ end
end
-if j2==0,
+if j2==0
disp(['No correlation term with pvalue <', num2str(pvalue_crit),' and |corr. coef.| >',num2str(alpha2),' found for ',fnam])
else
headers=strvcat('Parameters','corrcoef');
diff --git a/matlab/gsa/stand_.m b/matlab/gsa/stand_.m
index f1547c3c6..0a53f1a3b 100644
--- a/matlab/gsa/stand_.m
+++ b/matlab/gsa/stand_.m
@@ -11,10 +11,10 @@ function [y, meany, stdy] = stand_(x)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2012 European Commission
-% Copyright (C) 2012 Dynare Team%
+% Copyright (C) 2012-2017 Dynare Team%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
@@ -30,11 +30,11 @@ function [y, meany, stdy] = stand_(x)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin==0,
- return;
+if nargin==0
+ return
end
-for j=1:size(x,2);
+for j=1:size(x,2)
meany(j)=mean(x(find(~isnan(x(:,j))),j));
stdy(j)=std(x(find(~isnan(x(:,j))),j));
y(:,j)=(x(:,j)-meany(j))./stdy(j);
diff --git a/matlab/gsa/tcrit.m b/matlab/gsa/tcrit.m
index 560d90175..d65b97a39 100644
--- a/matlab/gsa/tcrit.m
+++ b/matlab/gsa/tcrit.m
@@ -1,15 +1,15 @@
function t_crit = tcrit(n,pval0)
% function t_crit = tcrit(n,pval0)
%
-% given the p-value pval0, the function givese the
-% critical value t_crit of the t-distribution with n degress of freedom
+% given the p-value pval0, the function givese the
+% critical value t_crit of the t-distribution with n degress of freedom
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
% Copyright (C) 2011-2012 European Commission
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -27,16 +27,16 @@ function t_crit = tcrit(n,pval0)
% along with Dynare. If not, see .
-if nargin==1 || isempty(pval0),
+if nargin==1 || isempty(pval0)
pval0=0.05;
end
-if pval0==1,
+if pval0==1
t_crit=0;
- return,
+ return
end
-if pval0==0,
+if pval0==0
t_crit=inf;
- return,
+ return
end
pval = [ 0.10 0.05 0.025 0.01 0.005 0.001];
pval0=max(pval0,min(pval));
@@ -146,7 +146,7 @@ t_crit=[
inf 1.282 1.645 1.960 2.326 2.576 3.090
];
-if n<=100,
+if n<=100
t_crit=t_crit(n,ncol);
else
t_crit=t_crit(end,ncol);
diff --git a/matlab/gsa/teff.m b/matlab/gsa/teff.m
index 622abca94..8ebea8d1c 100644
--- a/matlab/gsa/teff.m
+++ b/matlab/gsa/teff.m
@@ -3,13 +3,13 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable)
%
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
-% marco.ratto@ec.europa.eu
+% marco.ratto@ec.europa.eu
%
% Reference:
% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
% Copyright (C) 2012 European Commission
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -27,8 +27,8 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable)
% along with Dynare. If not, see .
ndim = (length(size(T)));
-if ndim==3,
- if nargin==1,
+if ndim==3
+ if nargin==1
Nsam=size(T,3);
istable = [1:Nsam]';
end
@@ -38,7 +38,7 @@ if ndim==3,
j0 = length(ir);
yt=zeros(Nsam, j0);
- for j=1:j0,
+ for j=1:j0
y0=squeeze(T(ir(j),ic(j),:));
%y1=ones(size(lpmat,1),1)*NaN;
y1=ones(Nsam,1)*NaN;
@@ -54,6 +54,6 @@ else
yt=NaN(Nsam, j0);
yt(istable,:)=T(ir,:)';
-
+
end
%clear y0 y1;
diff --git a/matlab/gsa/th_moments.m b/matlab/gsa/th_moments.m
index 5616b4045..9b886e851 100644
--- a/matlab/gsa/th_moments.m
+++ b/matlab/gsa/th_moments.m
@@ -1,7 +1,7 @@
function [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
% [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -56,13 +56,13 @@ var = gamma_y{1};
z;
%'VARIANCE DECOMPOSITION (in percent)';
-if M_.exo_nbr>1,
+if M_.exo_nbr>1
vdec = 100*gamma_y{options_.ar+2}(i1,:);
else
vdec = 100*ones(size(gamma_y{1}(i1,1)));
end
%'MATRIX OF CORRELATIONS';
-if options_.opt_gsa.useautocorr,
+if options_.opt_gsa.useautocorr
corr = gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
corr = corr-diag(diag(corr))+diag(diag(gamma_y{1}(i1,i1)));
else
@@ -71,7 +71,7 @@ end
if options_.ar > 0
%'COEFFICIENTS OF AUTOCORRELATION';
for i=1:options_.ar
- if options_.opt_gsa.useautocorr,
+ if options_.opt_gsa.useautocorr
autocorr{i} = gamma_y{i+1}(i1,i1);
else
autocorr{i} = gamma_y{i+1}(i1,i1).*(sd(i1)*sd(i1)');
@@ -79,5 +79,3 @@ if options_.ar > 0
zz(:,i) = diag(gamma_y{i+1}(i1,i1));
end
end
-
-
diff --git a/matlab/gsa/trank.m b/matlab/gsa/trank.m
index a47c91262..eb39f1647 100644
--- a/matlab/gsa/trank.m
+++ b/matlab/gsa/trank.m
@@ -1,4 +1,4 @@
-function yr = trank(y);
+function yr = trank(y)
% yr = trank(y);
% yr is the rank transformation of y
%
@@ -10,7 +10,7 @@ function yr = trank(y);
% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
% Copyright (C) 2012 European Commission
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -28,7 +28,7 @@ function yr = trank(y);
% along with Dynare. If not, see .
[nr, nc] = size(y);
-for j=1:nc,
+for j=1:nc
[dum, is]=sort(y(:,j));
yr(is,j)=[1:nr]'./nr;
end
diff --git a/matlab/hessian.m b/matlab/hessian.m
index cf2f549bd..844251f7c 100644
--- a/matlab/hessian.m
+++ b/matlab/hessian.m
@@ -12,19 +12,19 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests --
% hessian_mat [double] Hessian matrix
%
% ALGORITHM
-% Uses Abramowitz and Stegun (1965) formulas 25.3.23
+% Uses Abramowitz and Stegun (1965) formulas 25.3.23
% \[
% \frac{\partial^2 f_{0,0}}{\partial {x^2}} = \frac{1}{h^2}\left( f_{1,0} - 2f_{0,0} + f_{ - 1,0} \right)
% \]
% and 25.3.27 p. 884
-%
+%
% \[
% \frac{\partial ^2f_{0,0}}{\partial x\partial y} = \frac{-1}{2h^2}\left(f_{1,0} + f_{-1,0} + f_{0,1} + f_{0,-1} - 2f_{0,0} - f_{1,1} - f_{-1,-1} \right)
% \]
%
% SPECIAL REQUIREMENTS
% none
-%
+%
% Copyright (C) 2001-2017 Dynare Team
%
@@ -43,7 +43,7 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests --
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if ~isa(func, 'function_handle')
+if ~isa(func, 'function_handle')
func = str2func(func);
end
@@ -67,7 +67,7 @@ for i=1:n
xh1(i) = x(i)-h_1(i);
f_1(:,i) = feval(func, xh1, varargin{:});
%reset parameter
- xh1(i) = x(i);
+ xh1(i) = x(i);
end
xh_1 = xh1;
@@ -75,14 +75,14 @@ temp = f1+f_1-f0*ones(1, n); %term f_(1,0)+f_(-1,0)-f_(0,0) used later
hessian_mat = zeros(size(f0,1), n*n);
-for i=1:n
- if i > 1
- %fill symmetric part of Hessian based on previously computed results
+for i=1:n
+ if i > 1
+ %fill symmetric part of Hessian based on previously computed results
k = [i:n:n*(i-1)];
hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1) = hessian_mat(:,k);
- end
+ end
hessian_mat(:,(i-1)*n+i) = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); %formula 25.3.23
- for j=i+1:n
+ for j=i+1:n
%step in up direction
xh1(i) = x(i)+h1(i);
xh1(j) = x(j)+h_1(j);
@@ -95,7 +95,7 @@ for i=1:n
xh1(j) = x(j);
xh_1(i) = x(i);
xh_1(j) = x(j);
- end
+ end
end
diff --git a/matlab/hessian_sparse.m b/matlab/hessian_sparse.m
index d63534e79..1d7a75dbe 100644
--- a/matlab/hessian_sparse.m
+++ b/matlab/hessian_sparse.m
@@ -16,9 +16,9 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin)
%
% SPECIAL REQUIREMENTS
% none
-%
+%
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -35,7 +35,7 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if ~isa(func, 'function_handle')
+if ~isa(func, 'function_handle')
func = str2func(func);
end
n=size(x,1);
@@ -49,7 +49,7 @@ xh1=x;
f0=feval(func,x,varargin{:});
f1=zeros(size(f0,1),n);
f_1=f1;
-for i=1:n
+for i=1:n
xh1(i)=x(i)+h1(i);
f1(:,i)=feval(func,xh1,varargin{:});
xh1(i)=x(i)-h_1(i);
@@ -59,15 +59,15 @@ end
xh_1=xh1;
hessian_mat = sparse(size(f0,1),n*n);
-for i=1:n
- % if i > 1
+for i=1:n
+ % if i > 1
% k=[i:n:n*(i-1)];
% hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
% hessian_mat(:,k)=0;
- % end
+ % end
hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
temp=f1+f_1-f0*ones(1,n);
- for j=1:i-1
+ for j=1:i-1
xh1(i)=x(i)+h1(i);
xh1(j)=x(j)+h_1(j);
xh_1(i)=x(i)-h1(i);
@@ -77,5 +77,5 @@ for i=1:n
xh1(j)=x(j);
xh_1(i)=x(i);
xh_1(j)=x(j);
- end
+ end
end
\ No newline at end of file
diff --git a/matlab/histvalf.m b/matlab/histvalf.m
index e2c144554..580c9be92 100644
--- a/matlab/histvalf.m
+++ b/matlab/histvalf.m
@@ -1,6 +1,6 @@
function histvalf(fname)
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -86,4 +86,3 @@ for i = 1:length(outvars)
end
M_.endo_histval(j, :) = getfield(S, ov_);
end
-
diff --git a/matlab/homotopy1.m b/matlab/homotopy1.m
index e7de1f16a..e849fceca 100644
--- a/matlab/homotopy1.m
+++ b/matlab/homotopy1.m
@@ -30,7 +30,7 @@ function [M,oo,info,ip,ix,ixd] = homotopy1(values, step_nbr, M, options, oo)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -90,7 +90,7 @@ for i=1:step_nbr+1
% if homotopy step is not successful, current values of steady
% state are not modified
oo.steady_state = steady_state;
- else
+ else
M.params = old_params;
oo.exo_steady_state = old_exo;
oo.exo_det_steady_state = old_exo_det;
diff --git a/matlab/homotopy2.m b/matlab/homotopy2.m
index 8e1318a86..7ec87258d 100644
--- a/matlab/homotopy2.m
+++ b/matlab/homotopy2.m
@@ -25,7 +25,7 @@ function homotopy2(values, step_nbr)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -99,7 +99,7 @@ for i = 1:nv
end
disp([ 'HOMOTOPY mode 2: lauching solver with ' deblank(varname) ' = ' num2str(v) ' ...'])
-
+
oo_.steady_state = steady_(M_,options_,oo_);
end
end
diff --git a/matlab/homotopy3.m b/matlab/homotopy3.m
index a506bb6b6..b4b46d6f2 100644
--- a/matlab/homotopy3.m
+++ b/matlab/homotopy3.m
@@ -33,7 +33,7 @@ function [M,oo,info,ip,ix,ixd]=homotopy3(values, step_nbr, M, options, oo)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -91,11 +91,11 @@ disp('HOMOTOPY mode 3: launching solver at initial point...')
iter = 1;
while iter <= step_nbr
-
+
M.params(values(ip,2)) = curvalues(ip);
oo.exo_steady_state(values(ix,2)) = curvalues(ix);
oo.exo_det_steady_state(values(ixd,2)) = curvalues(ixd);
-
+
old_ss = oo.steady_state;
[steady_state,params,info] = steady_(M,options,oo);
@@ -121,8 +121,8 @@ while iter <= step_nbr
disp('HOMOTOPY mode 3: failed step, now dividing increment by 2...')
inc = inc/2;
oo.steady_state = old_ss;
- end
-
+ end
+
curvalues = last_values + inc;
kplus = find(curvalues(iplus) >= targetvalues(iplus));
curvalues(iplus(kplus)) = targetvalues(iplus(kplus));
@@ -136,7 +136,7 @@ while iter <= step_nbr
oo.exo_det_steady_state = old_exo_det_steady_state;
return
end
-
+
iter = iter + 1;
end
disp('HOMOTOPY mode 3: failed, maximum iterations reached')
diff --git a/matlab/ident_bruteforce.m b/matlab/ident_bruteforce.m
index ea68deaea..34725ade4 100644
--- a/matlab/ident_bruteforce.m
+++ b/matlab/ident_bruteforce.m
@@ -12,12 +12,12 @@ function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX,tittxt)
% pnames_TeX [char] list of tex names
% tittxt [string] string indicating the title text for
% graphs and figures
-%
+%
% OUTPUTS
% pars : cell array with groupf of params for each column of J for 1 to n
% cosnJ : the cosn of each column with the selected group of columns
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -52,7 +52,7 @@ tittxt1=strrep(tittxt1, '.', '');
cosnJ=zeros(k,n);
pars{k,n}=[];
-for ll = 1:n,
+for ll = 1:n
h = dyn_waitbar(0,['Brute force collinearity for ' int2str(ll) ' parameters.']);
for ii = 1:k
tmp = find([1:k]~=ii);
@@ -63,8 +63,8 @@ for ll = 1:n,
[cosnJ2(jj,1), b(:,jj)] = cosn([J(:,ii),J(:,tmp2(jj,:))]);
end
cosnJ(ii,ll) = max(cosnJ2(:,1));
- if cosnJ(ii,ll)>1.e-8,
- if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8),
+ if cosnJ(ii,ll)>1.e-8
+ if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8)
pars{ii,ll} = [pars{ii,ll-1} NaN];
cosnJ(ii,ll) = cosnJ(ii,ll-1);
else
@@ -85,7 +85,7 @@ for ll = 1:n,
fprintf(fidTeX,['%% ' datestr(now,0)]);
fprintf(fidTeX,' \n');
fprintf(fidTeX,' \n');
-
+
fprintf(fidTeX,'{\\tiny \n');
fprintf(fidTeX,'\\begin{longtable}{llc} \n');
fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s): ',tittxt,'}\n ']);
@@ -101,10 +101,10 @@ for ll = 1:n,
fprintf(fidTeX,'\\midrule \\endhead \n');
fprintf(fidTeX,'\\bottomrule \\multicolumn{3}{r}{(Continued on next page)}\\endfoot \n');
fprintf(fidTeX,'\\bottomrule\\endlastfoot \n');
- for i=1:k,
+ for i=1:k
plist='';
- for ii=1:ll,
- if ~isnan(pars{i,ll}(ii)),
+ for ii=1:ll
+ if ~isnan(pars{i,ll}(ii))
plist = [plist ' $' pnames_TeX(pars{i,ll}(ii),:) '\;\; $ '];
else
plist = [plist ' ---- '];
diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m
index f83bcf1a6..c59e08ec6 100644
--- a/matlab/identification_analysis.m
+++ b/matlab/identification_analysis.m
@@ -9,14 +9,14 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
% o options_ident [structure] identification options
% o dataset_ [structure] the dataset after required transformation
% o dataset_info [structure] Various informations about the dataset (descriptive statistics and missing observations) info for Kalman Filter
-% o prior_exist [integer]
+% o prior_exist [integer]
% =1 when prior exists and indentification is checked only for estimated params and shocks
% =0 when prior is not defined and indentification is checked for all params and shocks
% o name_tex [char] list of tex names
% o init [integer] flag for initialization of persistent vars
% o tittxt [string] string indicating the title text for
% graphs and figures
-%
+%
% OUTPUTS
% o ide_hess [structure] identification results using Asymptotic Hessian
% o ide_moments [structure] identification results using theoretical moments
@@ -24,11 +24,11 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
% o ide_lre [structure] identification results using LRE model
% o derivatives_info [structure] info about analytic derivs
% o info output from dynare resolve
-%
+%
% SPECIAL REQUIREMENTS
% None
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -42,7 +42,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
% 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
+% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
global oo_ M_ options_ bayestopt_ estim_params_
@@ -51,7 +51,7 @@ persistent indH indJJ indLRE
nparam=length(params);
np=length(indx);
offset=nparam-np;
-if ~isempty(estim_params_),
+if ~isempty(estim_params_)
M_ = set_all_parameters(params,estim_params_,M_);
end
@@ -73,7 +73,7 @@ ide_lre = struct();
derivatives_info = struct();
[A,B,ys,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
-if info(1)==0,
+if info(1)==0
oo0=oo_;
tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); dyn_vech(B*M_.Sigma_e*B')];
yy0=oo_.dr.ys(I);
@@ -86,16 +86,16 @@ if info(1)==0,
derivatives_info.DT=dA;
derivatives_info.DOm=dOm;
derivatives_info.DYss=dYss;
- if init,
+ if init
indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
if isempty(indJJ) && any(any(isnan(JJ)))
error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set diffuse_filter=1.' )
elseif any(any(isnan(gam)))
error('There are NaN''s in the theoretical moments: make sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification. [TIP: use first differences].')
end
- while length(indJJ)1.e-8));
end
- if length(indJJ)1.e-8));
@@ -117,50 +117,50 @@ if info(1)==0,
LRE(:,1)=vg1(indLRE);
GAM(:,1)=gam(indJJ);
siJ = (JJ(indJJ,:));
- siH = (H(indH,:));
+ siH = (H(indH,:));
siLRE = (gp(indLRE,:));
ide_strength_J=NaN(1,nparam);
ide_strength_J_prior=NaN(1,nparam);
- if init, %~isempty(indok),
+ if init
normaliz = NaN(1,nparam);
- if prior_exist,
- if ~isempty(estim_params_.var_exo),
+ if prior_exist
+ if ~isempty(estim_params_.var_exo)
normaliz1 = estim_params_.var_exo(:,7)'; % normalize with prior standard deviation
else
normaliz1=[];
end
- if ~isempty(estim_params_.corrx),
+ if ~isempty(estim_params_.corrx)
normaliz1 = [normaliz1 estim_params_.corrx(:,8)']; % normalize with prior standard deviation
end
- if ~isempty(estim_params_.param_vals),
+ if ~isempty(estim_params_.param_vals)
normaliz1 = [normaliz1 estim_params_.param_vals(:,7)']; % normalize with prior standard deviation
end
% normaliz = max([normaliz; normaliz1]);
normaliz1(isinf(normaliz1)) = 1;
-
+
else
normaliz1 = NaN(1,nparam);
end
- try,
+ try
options_.irf = 0;
options_.noprint = 1;
options_.order = 1;
options_.SpectralDensity.trigger = 0;
options_.periods = periods+100;
- if options_.kalman_algo > 2,
+ if options_.kalman_algo > 2
options_.kalman_algo = 1;
end
analytic_derivation = options_.analytic_derivation;
options_.analytic_derivation = -2;
info = stoch_simul(char(options_.varobs));
- dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);
+ dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);
derivatives_info.no_DLIK=1;
%bounds = prior_bounds(bayestopt_, options_.prior_trunc);
- [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info);
+ [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info);
% fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
options_.analytic_derivation = analytic_derivation;
AHess=-AHess;
- if min(eig(AHess))<-1.e-10,
+ if min(eig(AHess))<-1.e-10
error('identification_analysis: Analytic Hessian is not positive semi-definite!')
end
% chol(AHess);
@@ -168,7 +168,7 @@ if info(1)==0,
deltaM = sqrt(diag(AHess));
iflag=any((deltaM.*deltaM)==0);
tildaM = AHess./((deltaM)*(deltaM'));
- if iflag || rank(AHess)>rank(tildaM),
+ if iflag || rank(AHess)>rank(tildaM)
[ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(AHess, 1);
else
[ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1);
@@ -187,7 +187,7 @@ if info(1)==0,
rhoM=sqrt(1./diag(inv(tildaM(indok,indok))));
% deltaM = deltaM.*abs(params');
flag_score=1;
- catch,
+ catch
% replic = max([replic, nparam*(nparam+1)/2*10]);
replic = max([replic, length(indJJ)*3]);
cmm = simulated_moment_uncertainty(indJJ, periods, replic,options_,M_,oo_);
@@ -197,7 +197,7 @@ if info(1)==0,
if isoctave || matlab_ver_less_than('8.3')
[V,D]=eig(cc);
%fix for older Matlab versions that do not support computing left eigenvalues, see http://mathworks.com/help/releases/R2012b/matlab/ref/eig.html
- [W,junk] = eig(cc.');
+ [W,junk] = eig(cc.');
W = conj(W);
else
[V,D,W]=eig(cc);
@@ -225,7 +225,7 @@ if info(1)==0,
deltaM = sqrt(diag(MIM));
iflag=any((deltaM.*deltaM)==0);
tildaM = MIM./((deltaM)*(deltaM'));
- if iflag || rank(MIM)>rank(tildaM),
+ if iflag || rank(MIM)>rank(tildaM)
[ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(MIM, 1);
else
[ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1);
@@ -239,7 +239,7 @@ if info(1)==0,
% chh = siH(:,ind1)*((MIM(ind1,ind1))\siH(:,ind1)');
ind1=ind1(ind1>offset);
clre = siLRE(:,ind1-offset)*((MIM(ind1,ind1))\siLRE(:,ind1-offset)');
- if ~isempty(indok),
+ if ~isempty(indok)
rhoM(indok)=sqrt(1./diag(inv(tildaM(indok,indok))));
normaliz(indok) = (sqrt(diag(inv(tildaM(indok,indok))))./deltaM(indok))'; %sqrt(diag(inv(MIM(indok,indok))))';
end
@@ -253,7 +253,7 @@ if info(1)==0,
deltaM = deltaM.*abs(params');
deltaM(params==0)=deltaM_prior(params==0);
quant = siJ./repmat(sqrt(diag(cmm)),1,nparam);
- if size(quant,1)==1,
+ if size(quant,1)==1
siJnorm = abs(quant).*normaliz1;
else
siJnorm = vnorm(quant).*normaliz1;
@@ -268,9 +268,9 @@ if info(1)==0,
iy = find(diag_chh);
indH=indH(iy);
siH=siH(iy,:);
- if ~isempty(iy),
+ if ~isempty(iy)
quant = siH./repmat(sqrt(diag_chh(iy)),1,nparam);
- if size(quant,1)==1,
+ if size(quant,1)==1
siHnorm = abs(quant).*normaliz1;
else
siHnorm = vnorm(quant).*normaliz1;
@@ -288,9 +288,9 @@ if info(1)==0,
iy = find(diag_clre);
indLRE=indLRE(iy);
siLRE=siLRE(iy,:);
- if ~isempty(iy),
+ if ~isempty(iy)
quant = siLRE./repmat(sqrt(diag_clre(iy)),1,np);
- if size(quant,1)==1,
+ if size(quant,1)==1
siLREnorm = abs(quant).*normaliz1(offset+1:end);
else
siLREnorm = vnorm(quant).*normaliz1(offset+1:end);
@@ -299,16 +299,16 @@ if info(1)==0,
siLREnorm=[];
end
% siLREnorm = vnorm(siLRE./repmat(LRE,1,nparam-offset)).*normaliz(offset+1:end);
- ide_hess.ide_strength_J=ide_strength_J;
- ide_hess.ide_strength_J_prior=ide_strength_J_prior;
- ide_hess.deltaM=deltaM;
- ide_hess.deltaM_prior=deltaM_prior;
- ide_moments.siJnorm=siJnorm;
- ide_model.siHnorm=siHnorm;
- ide_lre.siLREnorm=siLREnorm;
- ide_hess.flag_score=flag_score;
- end,
- if normalize_jacobians,
+ ide_hess.ide_strength_J=ide_strength_J;
+ ide_hess.ide_strength_J_prior=ide_strength_J_prior;
+ ide_hess.deltaM=deltaM;
+ ide_hess.deltaM_prior=deltaM_prior;
+ ide_moments.siJnorm=siJnorm;
+ ide_model.siHnorm=siHnorm;
+ ide_lre.siLREnorm=siLREnorm;
+ ide_hess.flag_score=flag_score;
+ end
+ if normalize_jacobians
normH = max(abs(siH)')';
normH = normH(:,ones(nparam,1));
normJ = max(abs(siJ)')';
@@ -354,9 +354,8 @@ if info(1)==0,
ide_moments.S = S;
ide_moments.V = V;
end
-
indok = find(max(ide_moments.indno,[],1)==0);
- if advanced,
+ if advanced
[ide_moments.pars, ide_moments.cosnJ] = ident_bruteforce(JJ(indJJ,:)./normJ,max_dim_cova_group,options_.TeX,name_tex,tittxt);
end
-end
+end
diff --git a/matlab/identification_checks.m b/matlab/identification_checks.m
index 735682ec7..e52fa960d 100644
--- a/matlab/identification_checks.m
+++ b/matlab/identification_checks.m
@@ -7,21 +7,21 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific
% derivatives of output w.r.t. parameters and shocks
% o JJ [matrix] [nparams x nparams] IF hess_flag==1
% information matrix
-%
+%
% OUTPUTS
% o cond condition number of JJ
% o ind0 [array] binary indicator for non-zero columns of H
-% o indnoJ [matrix] index of non-identified params
+% o indnoJ [matrix] index of non-identified params
% o ixnoJ number of rows in indnoJ
% o Mco [array] multicollinearity coefficients
-% o Pco [matrix] pairwise correlations
+% o Pco [matrix] pairwise correlations
% o jweak [binary array] gives 1 if the parameter has Mco=1(with tolerance 1.e-10)
% o jweak_pair [binary matrix] gives 1 if a couple parameters has Pco=1(with tolerance 1.e-10)
-%
+%
% SPECIAL REQUIREMENTS
% None
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -45,23 +45,23 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific
npar = size(JJ,2);
indnoJ = zeros(1,npar);
-if size(JJ,1)>1,
+if size(JJ,1)>1
ind1 = find(vnorm(JJ)>=eps); % take non-zero columns
else
ind1 = find(abs(JJ)>=eps); % take non-zero columns
-end
+end
JJ1 = JJ(:,ind1);
[eu,ee2,ee1] = svd( JJ1, 0 );
condJ= cond(JJ1);
rankJ = rank(JJ);
rankJJ = rankJ;
icheck=0;
-if npar>0 && (rankJ0 && (rankJ 1.e-3))==1,
+ for j=1:length(ee0)
+ if length(find(abs(ee1(:,ee0(j))) > 1.e-3))==1
icheck=1;
ind11 = ind11.*(abs(ee1(:,ee0(j))) <= 1.e-3); % take non-zero columns
end
@@ -69,26 +69,26 @@ if npar>0 && (rankJ0 && (rankJ 1.e-3)';
end
-else %rank(J)==length(theta) =>
- % disp('All parameters are identified at theta by the moments included in J')
end
% here there is no exact linear dependence, but there are several
@@ -134,19 +132,19 @@ jweak_pair=zeros(npar,npar);
if hess_flag==0,
PcoJ = NaN(npar,npar);
- for ii = 1:size(JJ1,2);
+ for ii = 1:size(JJ1,2)
PcoJ(ind1(ii),ind1(ii)) = 1;
- for jj = ii+1:size(JJ1,2);
+ for jj = ii+1:size(JJ1,2)
PcoJ(ind1(ii),ind1(jj)) = cosn([JJ1(:,ii),JJ1(:,jj)]);
PcoJ(ind1(jj),ind1(ii)) = PcoJ(ind1(ii),ind1(jj));
end
end
- for j=1:npar,
- if McoJ(j)>(1-1.e-10),
+ for j=1:npar
+ if McoJ(j)>(1-1.e-10)
jweak(j)=1;
[ipair, jpair] = find(PcoJ(j,j+1:end)>(1-1.e-10));
- for jx=1:length(jpair),
+ for jx=1:length(jpair)
jweak_pair(j, jpair(jx)+j)=1;
jweak_pair(jpair(jx)+j, j)=1;
end
@@ -155,4 +153,3 @@ if hess_flag==0,
end
jweak_pair=dyn_vech(jweak_pair)';
-
diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m
index 9f7bdc480..66841319a 100644
--- a/matlab/imcforecast.m
+++ b/matlab/imcforecast.m
@@ -2,31 +2,31 @@ function imcforecast(constrained_paths, constrained_vars, options_cond_fcst)
% Computes conditional forecasts.
%
% INPUTS
-% o constrained_paths [double] m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods.
-% o constrained_vars [char] m*x array holding the names of the controlled endogenous variables.
+% o constrained_paths [double] m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods.
+% o constrained_vars [char] m*x array holding the names of the controlled endogenous variables.
% o options_cond_fcst [structure] containing the options. The fields are:
% + replic [integer] scalar, number of monte carlo simulations.
% + parameter_set [char] values of the estimated parameters:
-% "posterior_mode",
-% "posterior_mean",
-% "posterior_median",
-% "prior_mode" or
-% "prior mean".
+% "posterior_mode",
+% "posterior_mean",
+% "posterior_median",
+% "prior_mode" or
+% "prior mean".
% [double] np*1 array, values of the estimated parameters.
% + controlled_varexo [char] m*x array, list of controlled exogenous variables.
-% + conf_sig [double] scalar in [0,1], probability mass covered by the confidence bands.
+% + conf_sig [double] scalar in [0,1], probability mass covered by the confidence bands.
%
% OUTPUTS
% None.
-%
+%
% SPECIAL REQUIREMENTS
% This routine has to be called after an estimation statement or an estimated_params block.
%
% REMARKS
% [1] Results are stored in a structure which is saved in a mat file called conditional_forecasts.mat.
-% [2] Use the function plot_icforecast to plot the results.
+% [2] Use the function plot_icforecast to plot the results.
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -119,7 +119,7 @@ if estimated_model
data_index = dataset_info.missing.aindex;
gend = dataset_.nobs;
missing_value = dataset_info.missing.state;
-
+
%store qz_criterium
qz_criterium_old=options_.qz_criterium;
options_=select_qz_criterium_value(options_);
@@ -147,7 +147,7 @@ if estimated_model
% add trend to constant
for obs_iter=1:length(options_.varobs)
j = strmatch(options_.varobs{obs_iter},M_.endo_names,'exact');
- constant(j,:) = constant(j,:)+trend_addition(obs_iter,:);
+ constant(j,:) = constant(j,:)+trend_addition(obs_iter,:);
end
trend = constant(oo_.dr.order_var,:);
InitState(:,1) = atT(:,end);
diff --git a/matlab/indnv.m b/matlab/indnv.m
index 1df707786..0cc88ab5b 100644
--- a/matlab/indnv.m
+++ b/matlab/indnv.m
@@ -13,7 +13,7 @@ function a=indnv(x,y)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -40,6 +40,3 @@ for i = 1:size(x,1)
a(i) = j;
end
end
-
-
-
diff --git a/matlab/init_plan.m b/matlab/init_plan.m
index 24bd3ea65..3e22f6998 100644
--- a/matlab/init_plan.m
+++ b/matlab/init_plan.m
@@ -1,4 +1,4 @@
-function plan = init_plan(date)
+function plan = init_plan(date)
% Creates and initializes a new forecast scenario
%
% INPUTS
@@ -9,7 +9,7 @@ function plan = init_plan(date)
% plan [structure] Returns a structure containing a new forecast scenario
%
%
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -36,17 +36,16 @@ plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr
plan.constrained_vars_ = [];
plan.constrained_paths_ = [];
plan.constrained_date_ = [];
-plan.constrained_int_date_ = [];
+plan.constrained_int_date_ = [];
plan.constrained_str_date_ = [];
plan.constrained_perfect_foresight_ = [];
plan.shock_vars_ = [];
plan.shock_paths_ = [];
plan.shock_date_ = [];
-plan.shock_int_date_ = [];
+plan.shock_int_date_ = [];
plan.shock_str_date_ = [];
plan.shock_perfect_foresight_ = [];
plan.options_cond_fcst_ = struct();
plan.options_cond_fcst_.parameter_set = 'calibration';
plan.options_cond_fcst_.simulation_type = 'deterministic';
-plan.options_cond_fcst_.controlled_varexo = [];
-
+plan.options_cond_fcst_.controlled_varexo = [];
\ No newline at end of file
diff --git a/matlab/initial_condition_decomposition.m b/matlab/initial_condition_decomposition.m
index f99bcd622..cee5335a8 100644
--- a/matlab/initial_condition_decomposition.m
+++ b/matlab/initial_condition_decomposition.m
@@ -4,7 +4,7 @@ function oo_ = initial_condition_decomposition(M_,oo_,options_,varlist,bayestopt
% oo_.initval_decomposition. It is a n_var by n_var+2 by nperiods array. The
% first n_var columns store the respective endogenous initval contribution, column n+1
% stores the role of the shocks, while column n+2 stores the
-% value of the smoothed variables. Variables are stored
+% value of the smoothed variables. Variables are stored
% in the order of declaration, i.e. M_.endo_names.
%
% INPUTS
@@ -50,7 +50,8 @@ if size(varlist,1) == 0
varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
end
-[i_var,nvar] = varlist_indices(varlist,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
% number of variables
endo_nbr = M_.endo_nbr;
@@ -60,9 +61,9 @@ parameter_set = options_.parameter_set;
if isempty(parameter_set)
if isfield(oo_,'posterior_mean')
parameter_set = 'posterior_mean';
- elseif isfield(oo_,'mle_mode')
+ elseif isfield(oo_,'mle_mode')
parameter_set = 'mle_mode';
- elseif isfield(oo_,'posterior')
+ elseif isfield(oo_,'posterior')
parameter_set = 'posterior_mode';
else
error(['shock_decomposition: option parameter_set is not specified ' ...
@@ -92,7 +93,7 @@ if ~isfield(oo_,'initval_decomposition')
z = zeros(endo_nbr,endo_nbr+2,gend);
z(:,end,:) = Smoothed_Variables_deviation_from_mean;
- for i=1:endo_nbr,
+ for i=1:endo_nbr
z(i,i,1) = Smoothed_Variables_deviation_from_mean(i,1);
end
@@ -104,7 +105,7 @@ if ~isfield(oo_,'initval_decomposition')
if i > 1 && i <= maximum_lag+1
lags = min(i-1,maximum_lag):-1:1;
end
-
+
if i > 1
tempx = permute(z(:,1:endo_nbr,lags),[1 3 2]);
m = min(i-1,maximum_lag);
diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m
index 7155552a6..7dfc4d9a2 100644
--- a/matlab/initial_estimation_checks.m
+++ b/matlab/initial_estimation_checks.m
@@ -20,7 +20,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -54,7 +54,7 @@ if maximum_number_non_missing_observations>length(find(diag(Model.Sigma_e)))+Est
end
if (any(BayesInfo.pshape >0 ) && DynareOptions.mh_replic) && DynareOptions.mh_nblck<1
- error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.'])
+ error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.'])
end
old_steady_params=Model.params; %save initial parameters for check if steady state changes param values
@@ -75,29 +75,29 @@ if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.par
fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n')
disp(Model.param_names(EstimatedParameters.param_vals(changed_par_indices,1),:));
fprintf('This will override the parameter values drawn from the proposal density and may lead to wrong results.\n')
- fprintf('Check whether this is really intended.\n')
+ fprintf('Check whether this is really intended.\n')
warning('The steady state file internally changes the values of the estimated parameters.')
end
end
if any(BayesInfo.pshape) % if Bayesian estimation
nvx=EstimatedParameters.nvx;
- if nvx && any(BayesInfo.p3(1:nvx)<0)
+ if nvx && any(BayesInfo.p3(1:nvx)<0)
warning('Your prior allows for negative standard deviations for structural shocks. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.')
end
offset=nvx;
nvn=EstimatedParameters.nvn;
- if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0)
+ if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0)
warning('Your prior allows for negative standard deviations for measurement error. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.')
end
offset = nvx+nvn;
- ncx=EstimatedParameters.ncx;
- if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1))
+ ncx=EstimatedParameters.ncx;
+ if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1))
warning('Your prior allows for correlations between structural shocks larger than +-1 and will not integrate to 1 due to truncation. Please change your prior')
end
offset = nvx+nvn+ncx;
- ncn=EstimatedParameters.ncn;
- if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1))
+ ncn=EstimatedParameters.ncn;
+ if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1))
warning('Your prior allows for correlations between measurement errors larger than +-1 and will not integrate to 1 due to truncation. Please change your prior')
end
end
@@ -142,9 +142,9 @@ if ~isequal(DynareOptions.mode_compute,11) || ...
fprintf('initial_estimation_checks:: If you think the latter is the case, you should try with different initial values for the estimated parameters.\n')
error('initial_estimation_checks:: The forecast error variance in the multivariate Kalman filter became singular.')
end
- %reset options
+ %reset options
DynareOptions.use_univariate_filters_if_singularity_is_detected=use_univariate_filters_if_singularity_is_detected_old;
-else
+else
info=0;
fval = 0;
end
diff --git a/matlab/initialize_from_mode.m b/matlab/initialize_from_mode.m
index d7c11a9d0..4521ec255 100644
--- a/matlab/initialize_from_mode.m
+++ b/matlab/initialize_from_mode.m
@@ -1,20 +1,20 @@
function estim_params_ = initialize_from_mode(fname,M_,estim_params_)
% function estim_params_ = initialize_from_mode(fname,M_,estim_params_)
% initialize parameters and initial value of estimated parameters
-% from a *_mode.mat file
-%
+% from a *_mode.mat file
+%
% INPUTS
% fname: mode file name (*.mat file)
% M_: sructure of model characteristics
% estim_params_: structure of estimated parameters
-%
+%
% OUTPUTS
% estim_params: modified structure of estimated parameters
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -99,4 +99,3 @@ for i=1:length(parameter_names)
end
error([name 'doesn''t exist in this model'])
end
-
diff --git a/matlab/initvalf.m b/matlab/initvalf.m
index 28292ed61..afffede43 100644
--- a/matlab/initvalf.m
+++ b/matlab/initvalf.m
@@ -1,7 +1,7 @@
function initvalf(fname_)
% function initvalf(fname_)
%
-% Reads an initial path from the 'fname_' file for exogenous and endogenous variables
+% Reads an initial path from the 'fname_' file for exogenous and endogenous variables
%
% INPUTS
% fname_: name of the function or file containing the data
@@ -13,7 +13,7 @@ function initvalf(fname_)
% All variables local to this function have an underscore appended to
% their name, to minimize clashes with model variables loaded by this function.
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -79,7 +79,7 @@ for i_=1:size(M_.endo_names,1)
if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
oo_.endo_simul = [oo_.endo_simul; x_];
else %transpose if column vector
- oo_.endo_simul = [oo_.endo_simul; x_'];
+ oo_.endo_simul = [oo_.endo_simul; x_'];
end
else
k_ = strmatch(deblank(M_.endo_names(i_,:)),names_v_,'exact');
@@ -87,7 +87,7 @@ for i_=1:size(M_.endo_names,1)
error(['INITVAL_FILE: ' deblank(M_.endo_names(i_,:)) ' not found'])
end
x_ = data_(:,k_);
- oo_.endo_simul = [oo_.endo_simul; x_'];
+ oo_.endo_simul = [oo_.endo_simul; x_'];
end
end
@@ -97,7 +97,7 @@ for i_=1:size(M_.exo_names,1)
if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
oo_.exo_simul = [oo_.exo_simul x_'];
else %if column vector
- oo_.exo_simul = [oo_.exo_simul x_];
+ oo_.exo_simul = [oo_.exo_simul x_];
end
else
k_ = strmatch(deblank(M_.exo_names(i_,:)),names_v_,'exact');
@@ -105,6 +105,6 @@ for i_=1:size(M_.exo_names,1)
error(['INITVAL_FILE: ' deblank(M_.exo_names(i_,:)) ' not found'])
end
x_ = data_(:,k_);
- oo_.exo_simul = [oo_.exo_simul x_];
+ oo_.exo_simul = [oo_.exo_simul x_];
end
end
\ No newline at end of file
diff --git a/matlab/internals.m b/matlab/internals.m
index 4fc079ec2..a7b96a81f 100644
--- a/matlab/internals.m
+++ b/matlab/internals.m
@@ -56,7 +56,7 @@ function internals(flag, varargin)
%! @end deftypefn
%@eod:
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/interpret_resol_info.m b/matlab/interpret_resol_info.m
index a80a23f5d..45b3993ff 100644
--- a/matlab/interpret_resol_info.m
+++ b/matlab/interpret_resol_info.m
@@ -3,13 +3,13 @@ function message = interpret_resol_info(info)
% Returns a message describing problem encountered during the resolution of
% a model.
%
-% INPUTS
+% INPUTS
% - info [struct] Second output argument return by the resol routine
%
-% OUTPUTS
+% OUTPUTS
% - message [string] Description of the issue preventing model's resolution.
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/irf.m b/matlab/irf.m
index f4be40503..c80b65b1b 100644
--- a/matlab/irf.m
+++ b/matlab/irf.m
@@ -2,7 +2,7 @@ function y = irf(dr, e1, long, drop, replic, iorder)
% function y = irf(dr, e1, long, drop, replic, iorder)
% Computes impulse response functions
-%
+%
% INPUTS
% dr: structure of decisions rules for stochastic simulations
% e1: exogenous variables value in time 1 after one shock
@@ -13,11 +13,11 @@ function y = irf(dr, e1, long, drop, replic, iorder)
%
% OUTPUTS
% y: impulse response matrix
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -60,7 +60,7 @@ else
for j = 1: replic
ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S;
ex2 = ex1;
- ex2(drop+1,:) = ex2(drop+1,:)+e1';
+ ex2(drop+1,:) = ex2(drop+1,:)+e1';
y1 = simult_(temps,dr,ex1,iorder);
y2 = simult_(temps,dr,ex2,iorder);
y = y+(y2(:,M_.maximum_lag+drop+1:end)-y1(:,M_.maximum_lag+drop+1:end));
diff --git a/matlab/isoctave.m b/matlab/isoctave.m
index 15c6fb38d..22941ce9e 100644
--- a/matlab/isoctave.m
+++ b/matlab/isoctave.m
@@ -1,6 +1,6 @@
function A = isoctave()
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2016 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/isolder.m b/matlab/isolder.m
index 127393854..d364c5c62 100644
--- a/matlab/isolder.m
+++ b/matlab/isolder.m
@@ -2,14 +2,14 @@ function b = isolder(f, F) % --*-- Unitary tests --*--
% Returns true if f is older than any file in folder (and subfolders) F.
%
-% INPUTS
+% INPUTS
% - f [string] file name
% - F [string] folder name
%
-% OUTPUT
-% - b [logical]
+% OUTPUT
+% - b [logical]
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m
index 4c6917f5f..de982c8a1 100644
--- a/matlab/k_order_pert.m
+++ b/matlab/k_order_pert.m
@@ -1,7 +1,7 @@
function [dr,info] = k_order_pert(dr,M,options)
% Compute decision rules using the k-order DLL from Dynare++
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -27,8 +27,8 @@ endo_nbr = M.endo_nbr;
exo_nbr = M.exo_nbr;
nspred = M.nspred;
-if order>1 && options.loglinear
- error('The loglinear-option currently only works at order 1')
+if order>1 && options.loglinear
+ error('The loglinear-option currently only works at order 1')
end
if M.maximum_endo_lead == 0 && order>1
error(['2nd and 3rd order approximation not implemented for purely ' ...
@@ -40,32 +40,32 @@ switch(order)
[err, g_1] = k_order_perturbation(dr,M,options);
if err
info(1)=9;
- return;
+ return
end
dr.g_1 = g_1;
case 2
[err, g_0, g_1, g_2] = k_order_perturbation(dr,M,options);
if err
info(1)=9;
- return;
+ return
end
dr.g_0 = g_0;
dr.g_1 = g_1;
dr.g_2 = g_2;
case 3
- if options.pruning
+ if options.pruning
[err, g_0, g_1, g_2, g_3, derivs] = k_order_perturbation(dr, ...
M,options);
if err
info(1)=9;
- return;
+ return
end
else
[err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr, ...
M,options);
if err
info(1)=9;
- return;
+ return
end
end
dr.g_0 = g_0;
@@ -119,7 +119,7 @@ else
if s1 > s0
ghxx(:,s1*nspred+s0+1) = 2*g_2(:,i);
end
- elseif s0 < nspred && s1 < nspred+exo_nbr
+ elseif s0 < nspred && s1 < nspred+exo_nbr
ghxu(:,(s0*exo_nbr+s1-nspred+1)) = 2*g_2(:,i);
elseif s0 < nspred+exo_nbr && s1 < nspred+exo_nbr
ghuu(:,(s0-nspred)*exo_nbr+s1-nspred +1) = 2*g_2(:,i);
@@ -132,7 +132,7 @@ else
s1 = s1+1;
if s1 == nspred+exo_nbr
s0 = s0+1;
- s1 = s0;
+ s1 = s0;
end
end % for loop
dr.ghxx = ghxx;
@@ -186,7 +186,7 @@ for i=1:n1
m = m + 1;
end
end
-end
+end
function y = unfold12(x,n1,n2)
y = zeros(size(x,1),n1*n2*n2);
@@ -202,8 +202,4 @@ for i=1:n1
m = m + 1;
end
end
-end
-
-
-
-
+end
\ No newline at end of file
diff --git a/matlab/kalman/build_selection_matrix.m b/matlab/kalman/build_selection_matrix.m
index f78662ddb..e9899591c 100644
--- a/matlab/kalman/build_selection_matrix.m
+++ b/matlab/kalman/build_selection_matrix.m
@@ -2,7 +2,7 @@ function Z = build_selection_matrix(mf,m,p)
% Builds the selection matrix of the measurement equation from the vector
% of indices mf.
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -17,7 +17,7 @@ function Z = build_selection_matrix(mf,m,p)
% 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 .
+% along with Dynare. If not, see .
Z = zeros(p,m);
for i=1:p
Z(i,mf(i)) = 1;
diff --git a/matlab/kalman/likelihood/computeDLIK.m b/matlab/kalman/likelihood/computeDLIK.m
index eab34c3ba..0fc417220 100644
--- a/matlab/kalman/likelihood/computeDLIK.m
+++ b/matlab/kalman/likelihood/computeDLIK.m
@@ -1,6 +1,6 @@
function [Da,DP,DLIK,D2a,D2P,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P)
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -24,20 +24,20 @@ persistent DK DF D2K D2F
if notsteady
if Zflag
[DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K);
- if nargout>4,
+ if nargout>4
[D2K,D2F,D2P] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
end
else
[DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K);
- if nargout>4,
+ if nargout>4
[D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
end
end
DP=DP1;
- clear DP1,
+ clear DP1
else
DP=DP;
- if nargout>4,
+ if nargout>4
D2P=D2P;
end
end
@@ -71,8 +71,8 @@ for ii = 1:k
% dai = da(:,:,ii);
dKi = DK(:,:,ii);
dtmp(:,ii) = Da(:,ii)+dKi*v+K*Dv(:,ii);
-
- if nargout>4,
+
+ if nargout>4
diFi = -iF*DF(:,:,ii)*iF;
for jj = 1:ii
jcount=jcount+1;
@@ -83,7 +83,7 @@ for ii = 1:k
d2Fij = D2F(:,:,jj,ii);
d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
% dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
-
+
% d2vij = D2v(:,ii,jj);
if Zflag
d2vij = -Z*D2Yss(:,jj,ii) - Z*D2a(:,jj,ii);
@@ -93,28 +93,28 @@ for ii = 1:k
d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
D2a(:,jj,ii) = reshape(D2T(:,jcount),size(T))*tmp + DT(:,:,jj)*dtmp(:,ii) + DT(:,:,ii)*dtmp(:,jj) + T*d2tmpij;
D2a(:,ii,jj) = D2a(:,jj,ii);
-
- if nargout==6,
+
+ if nargout==6
Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
end
end
end
-
+
Da(:,ii) = DT(:,:,ii)*tmp + T*dtmp(:,ii);
DLIK(ii,1) = trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
end
-if nargout==4,
+if nargout==4
% Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),0,iF,diFi,diFj,0,dFj,0);
vecDPmf = reshape(DF,[],k);
D2a = 2*Dv'*iF*Dv + (vecDPmf' * kron(iF,iF) * vecDPmf);
% for ii = 1:k
- %
+ %
% diFi = -iF*DF(:,:,ii)*iF;
% for jj = 1:ii
% dFj = DF(:,:,jj);
% diFj = -iF*DF(:,:,jj)*iF;
- %
+ %
% Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0);
% end
% end
@@ -122,7 +122,7 @@ end
% end of computeDLIK
-function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij);
+function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij)
% computes (i,j) term in the Hessian
Hesst_ij = trace(diSi*dSj + iS*d2Sij) + e'*d2iSij*e + 2*(dei'*diSj*e + dei'*iS*dej + e'*diSi*dej + e'*iS*d2eij);
@@ -165,7 +165,7 @@ end
% end of computeDKalmanZ
-function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0);
+function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0)
% computes the second derivatives of the Kalman matrices
% note: A=T in main func.
@@ -189,7 +189,7 @@ for ii = 1:k
% d2Omi = d2Om(:,:,ii);
diFi = -iF*dFi*iF;
dKi = dK0(:,:,ii);
- for jj = 1:ii,
+ for jj = 1:ii
jcount=jcount+1;
dAj = dA(:,:,jj);
dFj = dP0(Z,Z,jj);
@@ -201,20 +201,20 @@ for ii = 1:k
d2Aij = reshape(d2A(:,jcount),[ns ns]);
d2Pij = dyn_unvech(d2P1(:,jcount));
d2Omij = dyn_unvech(d2Om(:,jcount));
-
+
% second order
-
+
d2Fij = d2Pij(Z,Z) ;
-
+
% d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
d2APC = d2Pij(:,Z);
-
+
d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-
+
d2Kij= d2Pij(:,Z)*iF + P0(:,Z)*d2iF + dP0(:,Z,jj)*diFi + dP0(:,Z,ii)*diFj;
-
+
d2KCP = d2Kij*P0(Z,:) + K0*d2Pij(Z,:) + dKi*dP0(Z,:,jj) + dKj*dP0(Z,:,ii) ;
-
+
dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*P0(Z,:) - K0*dP0(Z,:,ii);
dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*P0(Z,:) - K0*dP0(Z,:,jj);
d2tmp = d2Pij - d2KCP;
@@ -233,7 +233,7 @@ end
% end of computeD2Kalman
-function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0);
+function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0)
% computes the second derivatives of the Kalman matrices
% note: A=T in main func.
@@ -251,13 +251,13 @@ d2S = zeros(no,no,k,k);
% d2P1 = zeros(ns,ns,k,k);
jcount=0;
-for ii = 1:k,
+for ii = 1:k
dAi = dA(:,:,ii);
dFi = Z*dP0(:,:,ii)*Z;
% d2Omi = d2Om(:,:,ii);
diFi = -iF*dFi*iF;
dKi = dK0(:,:,ii);
- for jj = 1:ii,
+ for jj = 1:ii
jcount=jcount+1;
dAj = dA(:,:,jj);
dFj = Z*dP0(:,:,jj)*Z;
@@ -269,20 +269,20 @@ for ii = 1:k,
d2Aij = reshape(d2A(:,jcount),[ns ns]);
d2Pij = dyn_unvech(d2P1(:,jcount));
d2Omij = dyn_unvech(d2Om(:,jcount));
-
+
% second order
-
+
d2Fij = Z*d2Pij(:,:)*Z ;
-
+
% d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
d2APC = d2Pij(:,:)*Z;
-
+
d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-
+
d2Kij= d2Pij(:,:)*Z*iF + P0(:,:)*Z*d2iF + dP0(:,:,jj)*Z*diFi + dP0(:,:,ii)*Z*diFj;
-
+
d2KCP = d2Kij*Z*P0(:,:) + K0*Z*d2Pij(:,:) + dKi*Z*dP0(:,:,jj) + dKj*Z*dP0(:,:,ii) ;
-
+
dtmpi = dP0(:,:,ii) - dK0(:,:,ii)*Z*P0(:,:) - K0*Z*dP0(:,:,ii);
dtmpj = dP0(:,:,jj) - dK0(:,:,jj)*Z*P0(:,:) - K0*Z*dP0(:,:,jj);
d2tmp = d2Pij - d2KCP;
@@ -300,5 +300,3 @@ for ii = 1:k,
end
% end of computeD2KalmanZ
-
-
diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m
index e0dcafadc..441ee8525 100644
--- a/matlab/kalman/likelihood/kalman_filter.m
+++ b/matlab/kalman/likelihood/kalman_filter.m
@@ -71,7 +71,7 @@ function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_t
%! @end deftypefn
%@eod:
-% Copyright (C) 2004-2013 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -123,7 +123,7 @@ notsteady = 1;
F_singular = true;
asy_hess=0;
-if analytic_derivation == 0,
+if analytic_derivation == 0
DLIK=[];
Hess=[];
LIKK=[];
@@ -132,15 +132,15 @@ else
DLIK = zeros(k,1); % Initialization of the score.
Da = zeros(mm,k); % Derivative State vector.
dlikk = zeros(smpl,k);
-
- if Zflag==0,
+
+ if Zflag==0
C = zeros(pp,mm);
- for ii=1:pp; C(ii,Z(ii))=1;end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+ for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
else
C=Z;
end
dC = zeros(pp,mm,k); % either selection matrix or schur have zero derivatives
- if analytic_derivation==2,
+ if analytic_derivation==2
Hess = zeros(k,k); % Initialization of the Hessian
D2a = zeros(mm,k,k); % State vector.
d2C = zeros(pp,mm,k,k);
@@ -151,7 +151,7 @@ else
D2T=[];
D2Yss=[];
end
- if asy_hess,
+ if asy_hess
Hess = zeros(k,k); % Initialization of the Hessian
end
LIK={inf,DLIK,Hess};
@@ -188,7 +188,7 @@ while notsteady && t<=last
end
else
F_singular = false;
- if rescale_prediction_error_covariance,
+ if rescale_prediction_error_covariance
log_dF = log(det(F./(sig*sig')))+2*sum(log(sig));
iF = inv(F./(sig*sig'))./(sig*sig');
else
@@ -204,15 +204,15 @@ while notsteady && t<=last
Ptmp = T*(P-K*P(Z,:))*transpose(T)+QQ;
end
tmp = (a+K*v);
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,DP,DLIKt,D2a,D2P, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P);
else
[Da,DP,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady);
end
if t>presample
DLIK = DLIK + DLIKt;
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
Hess = Hess + Hesst;
end
end
@@ -232,11 +232,11 @@ end
% Add observation's densities constants and divide by two.
likk(1:s) = .5*(likk(1:s) + pp*log(2*pi));
-if analytic_derivation,
+if analytic_derivation
DLIK = DLIK/2;
dlikk = dlikk/2;
- if analytic_derivation==2 || asy_hess,
- if asy_hess==0,
+ if analytic_derivation==2 || asy_hess
+ if asy_hess==0
Hess = Hess + tril(Hess,-1)';
end
Hess = -Hess/2;
@@ -245,8 +245,8 @@ end
% Call steady state Kalman filter if needed.
if t <= last
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[tmp, tmp2] = kalman_filter_ss(Y, t, last, a, T, K, iF, dF, Z, pp, Zflag, analytic_derivation, Da, DT, DYss, D2a, D2T, D2Yss);
else
[tmp, tmp2] = kalman_filter_ss(Y, t, last, a, T, K, iF, dF, Z, pp, Zflag, analytic_derivation, Da, DT, DYss, asy_hess);
@@ -263,14 +263,14 @@ if t <= last
end
% Compute minus the log-likelihood.
-if presample>diffuse_periods,
+if presample>diffuse_periods
LIK = sum(likk(1+(presample-diffuse_periods):end));
else
LIK = sum(likk);
end
-if analytic_derivation,
- if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+ if analytic_derivation==2 || asy_hess
LIK={LIK, DLIK, Hess};
else
LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m
index 61c4b53fe..79b3607fb 100644
--- a/matlab/kalman/likelihood/kalman_filter_d.m
+++ b/matlab/kalman/likelihood/kalman_filter_d.m
@@ -1,7 +1,7 @@
function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
% Computes the diffuse likelihood of a state space model.
%
-% INPUTS
+% INPUTS
% Y [double] pp*smpl matrix of (detrended) data, where pp is the number of observed variables.
% start [integer] scalar, first observation.
% last [integer] scalar, last observation.
@@ -10,33 +10,33 @@ function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, k
% Pstar [double] mm*mm matrix used to initialize the covariance matrix of the state vector.
% kalman_tol [double] scalar, tolerance parameter (rcond) of F_star.
% diffuse_kalman_tol [double] scalar, tolerance parameter (rcond) of Pinf to signify end of diffuse filtering and Finf.
-% riccati_tol [double] scalar, tolerance parameter (riccati iteration);
+% riccati_tol [double] scalar, tolerance parameter (riccati iteration);
% not used in this filter as usually diffuse phase will be left before convergence of filter to steady state.
-% presample [integer] scalar, presampling if strictly positive.
+% presample [integer] scalar, presampling if strictly positive.
% T [double] mm*mm matrix, transition matrix in the state equations.
% R [double] mm*rr matrix relating the structural innovations to the state vector.
% Q [double] rr*rr covariance matrix of the structural innovations.
-% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
+% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
% Z [double] pp*mm matrix, selection matrix or pp linear independent combinations of the state vector.
% mm [integer] scalar, number of state variables.
% pp [integer] scalar, number of observed variables.
-% rr [integer] scalar, number of structural innovations.
-%
-% OUTPUTS
+% rr [integer] scalar, number of structural innovations.
+%
+% OUTPUTS
% LIK [double] scalar, minus loglikelihood
% lik [double] smpl*1 vector, log density of each vector of observations.
% a [double] mm*1 vector, current estimate of the state vector.
-% Pstar [double] mm*mm matrix, covariance matrix of the state vector.
-%
-% REFERENCES
+% Pstar [double] mm*mm matrix, covariance matrix of the state vector.
+%
+% REFERENCES
% See "Filtering and Smoothing of State Vector for Diffuse State Space
-% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
-% Analysis, vol. 24(1), pp. 85-98.
+% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+% Analysis, vol. 24(1), pp. 85-98.
% and
% Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 5 and 7.2
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -70,7 +70,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
v = Y(:,t)-Z*a; %get prediction error v^(0) in (5.13) DK (2012)
Finf = Z*Pinf*Z'; % (5.7) in DK (2012)
%do case distinction based on whether F_{\infty,t} has full rank or 0 rank
- if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0
+ if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0
if ~all(abs(Finf(:)) < diffuse_kalman_tol) %rank-deficient but not rank 0
% The univariate diffuse kalman filter should be used instead.
return
@@ -117,7 +117,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
end
if t>last
- warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
+ warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
dLIK = NaN;
return
end
diff --git a/matlab/kalman/likelihood/kalman_filter_fast.m b/matlab/kalman/likelihood/kalman_filter_fast.m
index cc8c3d1f9..db3dec3b7 100644
--- a/matlab/kalman/likelihood/kalman_filter_fast.m
+++ b/matlab/kalman/likelihood/kalman_filter_fast.m
@@ -74,7 +74,7 @@ function [LIK, LIKK, a, P] = kalman_filter_fast(Y,start,last,a,P,kalman_tol,ricc
%! @end deftypefn
%@eod:
-% Copyright (C) 2004-2013 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -152,7 +152,7 @@ while notsteady && t<=last
end
if rcond(F) < kalman_tol
if ~all(abs(F(:))diffuse_periods,
+if presample>diffuse_periods
LIK = sum(likk(1+(presample-diffuse_periods):end));
else
LIK = sum(likk);
end
-if analytic_derivation,
- if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+ if analytic_derivation==2 || asy_hess
LIK={LIK, DLIK, Hess};
else
LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/kalman_filter_ss.m b/matlab/kalman/likelihood/kalman_filter_ss.m
index 8e5f92733..5510de9f3 100644
--- a/matlab/kalman/likelihood/kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/kalman_filter_ss.m
@@ -54,7 +54,7 @@ function [LIK, likk, a] = kalman_filter_ss(Y,start,last,a,T,K,iF,log_dF,Z,pp,Zfl
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -86,18 +86,18 @@ if nargin<12
analytic_derivation = 0;
end
-if analytic_derivation == 0,
+if analytic_derivation == 0
DLIK=[];
Hess=[];
else
k = size(DT,3); % number of structural parameters
DLIK = zeros(k,1); % Initialization of the score.
dlikk = zeros(smpl,k);
- if analytic_derivation==2,
+ if analytic_derivation==2
Hess = zeros(k,k); % Initialization of the Hessian
else
asy_hess=D2a;
- if asy_hess,
+ if asy_hess
Hess = zeros(k,k); % Initialization of the Hessian
else
Hess=[];
@@ -112,14 +112,14 @@ while t <= last
v = Y(:,t)-a(Z);
end
tmp = (a+K*v);
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,junk,DLIKt,D2a,junk2, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady,D2a,D2Yss,D2T,[],[]);
else
[Da,junk,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady);
end
DLIK = DLIK + DLIKt;
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
Hess = Hess + Hesst;
end
dlikk(t-start+1,:)=DLIKt;
@@ -137,17 +137,17 @@ likk = .5*(likk + pp*log(2*pi));
% Sum the observation's densities (minus the likelihood)
LIK = sum(likk);
-if analytic_derivation,
+if analytic_derivation
dlikk = dlikk/2;
DLIK = DLIK/2;
likk = {likk, dlikk};
end
-if analytic_derivation==2 || asy_hess,
- if asy_hess==0,
+if analytic_derivation==2 || asy_hess
+ if asy_hess==0
Hess = Hess + tril(Hess,-1)';
end
Hess = -Hess/2;
LIK={LIK,DLIK,Hess};
-elseif analytic_derivation==1,
+elseif analytic_derivation==1
LIK={LIK,DLIK};
end
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
index 4d357cd29..f1bd40cb5 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
@@ -5,34 +5,34 @@ function [LIK, lik, a, P] = missing_observations_kalman_filter(data_index,numbe
% data_index [cell] 1*smpl cell of column vectors of indices.
% number_of_observations [integer] scalar.
% no_more_missing_observations [integer] scalar.
-% Y [double] pp*smpl matrix of data.
+% Y [double] pp*smpl matrix of data.
% start [integer] scalar, index of the first observation.
% last [integer] scalar, index of the last observation.
% a [double] pp*1 vector, initial level of the state vector.
% P [double] pp*pp matrix, covariance matrix of the initial state vector.
% kalman_tol [double] scalar, tolerance parameter (rcond).
-% riccati_tol [double] scalar, tolerance parameter (riccati iteration).
+% riccati_tol [double] scalar, tolerance parameter (riccati iteration).
% presample [integer] scalar, presampling if strictly positive.
% T [double] mm*mm transition matrix of the state equation.
-% Q [double] rr*rr covariance matrix of the structural innovations.
+% Q [double] rr*rr covariance matrix of the structural innovations.
% R [double] mm*rr matrix, mapping structural innovations to state variables.
-% H [double] pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors.
-% Z [integer] pp*1 vector of indices for the observed variables.
+% H [double] pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors.
+% Z [integer] pp*1 vector of indices for the observed variables.
% mm [integer] scalar, dimension of the state vector.
% pp [integer] scalar, number of observed variables.
-% rr [integer] scalar, number of structural innovations.
-%
-% OUTPUTS
+% rr [integer] scalar, number of structural innovations.
+%
+% OUTPUTS
% LIK [double] scalar, MINUS loglikelihood
% lik [double] vector, density of observations in each period.
% a [double] mm*1 vector, estimated level of the states.
-% P [double] mm*mm matrix, covariance matrix of the states.
-%
+% P [double] mm*mm matrix, covariance matrix of the states.
+%
%
% NOTES
-% The vector "lik" is used to evaluate the jacobian of the likelihood.
+% The vector "lik" is used to evaluate the jacobian of the likelihood.
-% Copyright (C) 2004-2012 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -123,7 +123,7 @@ while notsteady && t<=last
end
else
F_singular = false;
- if rescale_prediction_error_covariance,
+ if rescale_prediction_error_covariance
log_dF = log(det(F./(sig*sig')))+2*sum(log(sig));
iF = inv(F./(sig*sig'))./(sig*sig');
else
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
index 5334c301e..ec8c286a4 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
@@ -5,7 +5,7 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n
T, R, Q, H, Z, mm, pp, rr)
% Computes the diffuse likelihood of a state space model when some observations are missing.
%
-% INPUTS
+% INPUTS
% data_index [cell] 1*smpl cell of column vectors of indices.
% number_of_observations [integer] scalar.
% no_more_missing_observations [integer] scalar.
@@ -17,32 +17,32 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n
% Pstar [double] mm*mm matrix used to initialize the covariance matrix of the state vector.
% kalman_tol [double] scalar, tolerance parameter (rcond).
% riccati_tol [double] scalar, tolerance parameter (riccati iteration).
-% presample [integer] scalar, presampling if strictly positive.
+% presample [integer] scalar, presampling if strictly positive.
% T [double] mm*mm matrix, transition matrix in the state equations.
% R [double] mm*rr matrix relating the structural innovations to the state vector.
% Q [double] rr*rr covariance matrix of the structural innovations.
-% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
+% H [double] pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
% Z [double] pp*mm matrix, selection matrix or pp linear independant combinations of the state vector.
% mm [integer] scalar, number of state variables.
% pp [integer] scalar, number of observed variables.
-% rr [integer] scalar, number of structural innovations.
-%
-% OUTPUTS
+% rr [integer] scalar, number of structural innovations.
+%
+% OUTPUTS
% dLIK [double] scalar, MINUS loglikelihood
% dlik [double] vector, density of observations in each period.
% a [double] mm*1 vector, estimated level of the states.
-% Pstar [double] mm*mm matrix, covariance matrix of the states.
-%
+% Pstar [double] mm*mm matrix, covariance matrix of the states.
+%
% REFERENCES
% See "Filtering and Smoothing of State Vector for Diffuse State Space
-% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
-% Analysis, vol. 24(1), pp. 85-98.
+% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+% Analysis, vol. 24(1), pp. 85-98.
% and
% Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 5 and 7.2
-%
-% Copyright (C) 2004-2016 Dynare Team
+%
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -87,9 +87,9 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
Pinf = T*Pinf*transpose(T);
else
ZZ = Z(d_index,:); %span selector matrix
- v = Y(d_index,t)-ZZ*a; %get prediction error v^(0) in (5.13) DK (2012)
+ v = Y(d_index,t)-ZZ*a; %get prediction error v^(0) in (5.13) DK (2012)
Finf = ZZ*Pinf*ZZ'; % (5.7) in DK (2012)
- if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0
+ if rcond(Finf) < diffuse_kalman_tol %F_{\infty,t} = 0
if ~all(abs(Finf(:)) < diffuse_kalman_tol) %rank-deficient but not rank 0
% The univariate diffuse kalman filter should be used.
return
@@ -129,7 +129,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
end
if t==(last+1)
- warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
+ warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
dLIK = NaN;
return
end
diff --git a/matlab/kalman/likelihood/univariate_computeDLIK.m b/matlab/kalman/likelihood/univariate_computeDLIK.m
index 3601ba754..083fb12db 100644
--- a/matlab/kalman/likelihood/univariate_computeDLIK.m
+++ b/matlab/kalman/likelihood/univariate_computeDLIK.m
@@ -1,6 +1,6 @@
function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K,PZ,F,Da,DYss,DP,DH,notsteady,D2a,D2Yss,D2P)
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -21,12 +21,12 @@ function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K
persistent DDK DDF DD2K DD2F
-if notsteady,
+if notsteady
if Zflag
Dv = -Z*Da(:,:) - Z*DYss(:,:);
DF = zeros(k,1);
DK = zeros([rows(K),k]);
- for j=1:k,
+ for j=1:k
DF(j)=Z*DP(:,:,j)*Z'+DH;
DK(:,j) = (DP(:,:,j)*Z')/F-PZ*DF(j)/F^2;
end
@@ -35,9 +35,9 @@ if notsteady,
D2v = zeros(k,k);
D2K = zeros(rows(K),k,k);
jcount=0;
- for j=1:k,
+ for j=1:k
D2v(:,j) = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j);
- for i=1:j,
+ for i=1:j
jcount=jcount+1;
D2F(j,i)=Z*dyn_unvech(D2P(:,jcount))*Z';
D2F(i,j)=D2F(j,i);
@@ -47,7 +47,7 @@ if notsteady,
end
end
end
-
+
else
Dv = -Da(Z,:) - DYss(Z,:);
DF = squeeze(DP(Z,Z,:))+DH';
@@ -57,8 +57,8 @@ if notsteady,
D2K = zeros(rows(K),k,k);
D2v = squeeze(-D2a(Z,:,:) - D2Yss(Z,:,:));
jcount=0;
- for j=1:k,
- for i=1:j,
+ for j=1:k
+ for i=1:j
jcount=jcount+1;
tmp = dyn_unvech(D2P(:,jcount));
D2F(j,i) = tmp(Z,Z);
@@ -89,7 +89,7 @@ else
Dv = -Z*Da(:,:) - Z*DYss(:,:);
if nargout>4
D2v = zeros(k,k);
- for j=1:k,
+ for j=1:k
D2v(:,j) = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j);
end
end
@@ -105,7 +105,7 @@ DLIK = DF/F + 2*Dv'/F*v - v^2/F^2*DF;
if nargout==6
Hesst = D2F/F-1/F^2*(DF*DF') + 2*D2v/F*v + 2*(Dv'*Dv)/F - 2*(DF*Dv)*v/F^2 ...
- v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF');
-elseif nargout==4,
+elseif nargout==4
D2a = 1/F^2*(DF*DF') + 2*(Dv'*Dv)/F ;
% D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F + 2*v^2/F^3*(DF*DF') ...
% - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF');
@@ -114,34 +114,34 @@ end
Da = Da + DK*v+K*Dv;
if nargout>4
-
+
D2a = D2a + D2K*v;
- for j=1:k,
+ for j=1:k
% D2a(:,:,j) = D2a(:,:,j) + DK*Dv(j) + DK(:,j)*Dv + K*D2v(j,:);
- for i=1:j,
+ for i=1:j
D2a(:,j,i) = D2a(:,j,i) + DK(:,i)*Dv(j) + DK(:,j)*Dv(i) + K*D2v(j,i);
D2a(:,i,j) = D2a(:,j,i);
end
end
-
-
+
+
end
-if notsteady,
+if notsteady
DP1 = DP*0;
- if Zflag,
- for j=1:k,
+ if Zflag
+ for j=1:k
DP1(:,:,j)=DP(:,:,j) - (DP(:,:,j)*Z')*K'-PZ*DK(:,j)';
end
else
- for j=1:k,
+ for j=1:k
DP1(:,:,j)=DP(:,:,j) - (DP(:,Z,j))*K'-PZ*DK(:,j)';
end
end
- if nargout>4,
- if Zflag,
- for j=1:k,
- for i=1:j,
+ if nargout>4
+ if Zflag
+ for j=1:k
+ for i=1:j
jcount = jcount+1;
tmp = dyn_unvech(D2P(:,jcount));
tmp = tmp - (tmp*Z')*K' - (DP(:,:,j)*Z')*DK(:,i)' ...
@@ -153,8 +153,8 @@ if notsteady,
else
DPZ = squeeze(DP(:,Z,:));
jcount = 0;
- for j=1:k,
- for i=1:j,
+ for j=1:k
+ for i=1:j
jcount = jcount+1;
tmp = dyn_unvech(D2P(:,jcount));
D2PZ = tmp(:,Z);
@@ -163,11 +163,9 @@ if notsteady,
% D2P(:,:,i,j) = D2P(:,:,j,i);
end
end
-
+
end
end
else
DP1=DP;
end
-
-
diff --git a/matlab/kalman/likelihood/univariate_computeDstate.m b/matlab/kalman/likelihood/univariate_computeDstate.m
index 52e85c255..eecee428e 100644
--- a/matlab/kalman/likelihood/univariate_computeDstate.m
+++ b/matlab/kalman/likelihood/univariate_computeDstate.m
@@ -1,6 +1,6 @@
function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om)
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -22,25 +22,25 @@ function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notst
DP1=DP*0;
Da1=Da*0;
-for j=1:k,
+for j=1:k
Da1(:,j) = T*Da(:,j) + DT(:,:,j)*a;
- if notsteady,
+ if notsteady
DP1(:,:,j) = T*DP(:,:,j)*T'+DT(:,:,j)*P*T'+T*P*DT(:,:,j)';
else
DP1=DP;
end
end
-if notsteady,
+if notsteady
DP1 = DP1 + DOm;
end
-if nargout>2,
+if nargout>2
jcount=0;
- for j=1:k,
- for i=1:j,
+ for j=1:k
+ for i=1:j
jcount=jcount+1;
D2a(:,j,i) = DT(:,:,i)*Da(:,j) + DT(:,:,j)*Da(:,i) + T*D2a(:,j,i)+ reshape(D2T(:,jcount),size(T))*a;
D2a(:,i,j) = D2a(:,j,i);
- if notsteady,
+ if notsteady
tmp = dyn_unvech(D2P(:,jcount));
tmp = T*tmp*T' +DT(:,:,i)*DP(:,:,j)*T'+T*DP(:,:,j)*DT(:,:,i)' + ...
DT(:,:,j)*DP(:,:,i)*T'+T*DP(:,:,i)*DT(:,:,j)' + ...
@@ -52,5 +52,5 @@ if nargout>2,
end
end
end
-
+
end
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter.m b/matlab/kalman/likelihood/univariate_kalman_filter.m
index 9f9571a64..add638a54 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter.m
@@ -37,7 +37,7 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat
%! @item Q
%! Matrix (@var{rr}*@var{rr}) of doubles, covariance matrix of the structural innovations (noise in the state equation).
%! @item R
-%! Matrix (@var{mm}*@var{rr}) of doubles,
+%! Matrix (@var{mm}*@var{rr}) of doubles,
%! @item H
%! Vector (@var{pp}) of doubles, diagonal of covariance matrix of the measurement errors (corelation among measurement errors is handled by a model transformation).
%! @item Z
@@ -76,15 +76,15 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat
%! @ref{univariate_kalman_filter_ss}
%! @end deftypefn
%@eod:
-%
+%
% Algorithm:
-%
+%
% Uses the univariate filter as described in Durbin/Koopman (2012): "Time
% Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 6.4 + 7.2.5
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -128,7 +128,7 @@ oldK = Inf;
K = NaN(mm,pp);
asy_hess=0;
-if analytic_derivation == 0,
+if analytic_derivation == 0
DLIK=[];
Hess=[];
else
@@ -136,15 +136,15 @@ else
DLIK = zeros(k,1); % Initialization of the score.
Da = zeros(mm,k); % Derivative State vector.
dlik = zeros(smpl,k);
-
- if Zflag==0,
+
+ if Zflag==0
C = zeros(pp,mm);
- for ii=1:pp; C(ii,Z(ii))=1;end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+ for ii=1:pp, C(ii,Z(ii))=1; end % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
else
C=Z;
end
dC = zeros(pp,mm,k); % either selection matrix or schur have zero derivatives
- if analytic_derivation==2,
+ if analytic_derivation==2
Hess = zeros(k,k); % Initialization of the Hessian
D2a = zeros(mm,k,k); % State vector.
d2C = zeros(pp,mm,k,k);
@@ -155,7 +155,7 @@ else
D2T=[];
D2Yss=[];
end
- if asy_hess,
+ if asy_hess
Hess = zeros(k,k); % Initialization of the Hessian
end
LIK={inf,DLIK,Hess};
@@ -172,13 +172,13 @@ while notsteady && t<=last %loop over t
oldP = P(:);
for i=1:rows(z) %loop over i
if Zflag
- prediction_error = Y(d_index(i),t) - z(i,:)*a; % nu_{t,i} in 6.13 in DK (2012)
+ prediction_error = Y(d_index(i),t) - z(i,:)*a; % nu_{t,i} in 6.13 in DK (2012)
PZ = P*z(i,:)'; % Z_{t,i}*P_{t,i}*Z_{t,i}'
- Fi = z(i,:)*PZ + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
+ Fi = z(i,:)*PZ + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
else
- prediction_error = Y(d_index(i),t) - a(z(i)); % nu_{t,i} in 6.13 in DK (2012)
+ prediction_error = Y(d_index(i),t) - a(z(i)); % nu_{t,i} in 6.13 in DK (2012)
PZ = P(:,z(i)); % Z_{t,i}*P_{t,i}*Z_{t,i}'
- Fi = PZ(z(i)) + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
+ Fi = PZ(z(i)) + H(d_index(i)); % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
end
if Fi>kalman_tol
Ki = PZ/Fi; %K_{t,i} in 6.13 in DK (2012)
@@ -186,15 +186,15 @@ while notsteady && t<=last %loop over t
K(:,i) = Ki;
end
lik(s,i) = log(Fi) + (prediction_error*prediction_error)/Fi + l2pi; %Top equation p. 175 in DK (2012)
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,DP,DLIKt,D2a,D2P, Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady,D2a,D2Yss,D2P);
else
[Da,DP,DLIKt,Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady);
end
if t>presample
DLIK = DLIK + DLIKt;
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
Hess = Hess + Hesst;
end
end
@@ -207,14 +207,14 @@ while notsteady && t<=last %loop over t
% p. 157, DK (2012)
end
end
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,DP,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om);
else
[Da,DP] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady);
end
end
- a = T*a; %transition according to (6.14) in DK (2012)
+ a = T*a; %transition according to (6.14) in DK (2012)
P = T*P*T' + QQ; %transition according to (6.14) in DK (2012)
if t>=no_more_missing_observations
notsteady = max(abs(K(:)-oldK))>riccati_tol;
@@ -225,10 +225,10 @@ end
% Divide by two.
lik(1:s,:) = .5*lik(1:s,:);
-if analytic_derivation,
+if analytic_derivation
DLIK = DLIK/2;
dlik = dlik/2;
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
% Hess = (Hess + Hess')/2;
Hess = -Hess/2;
end
@@ -236,8 +236,8 @@ end
% Call steady state univariate kalman filter if needed.
if t <= last
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P);
else
@@ -247,7 +247,7 @@ if t <= last
lik(s+1:end,:)=tmp2{1};
dlik(s+1:end,:)=tmp2{2};
DLIK = DLIK + tmp{2};
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
Hess = Hess + tmp{3};
end
else
@@ -262,8 +262,8 @@ else
LIK = sum(sum(lik));
end
-if analytic_derivation,
- if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+ if analytic_derivation==2 || asy_hess
LIK={LIK, DLIK, Hess};
else
LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
index ac121ee33..ce78d2421 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
@@ -80,14 +80,14 @@ function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index,
%! @ref{univariate_kalman_filter_ss}
%! @end deftypefn
%@eod:
-%
+%
% Algorithm:
-%
+%
% Uses the diffuse univariate filter as described in Durbin/Koopman (2012): "Time
% Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 5, 6.4 + 7.2.5
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -125,15 +125,15 @@ while newRank && (t<=last)
d_index = data_index{t};
for i=1:length(d_index)
Zi = Z(d_index(i),:);
- prediction_error = Y(d_index(i),t) - Zi*a; % nu_{t,i} in 6.13 in DK (2012)
+ prediction_error = Y(d_index(i),t) - Zi*a; % nu_{t,i} in 6.13 in DK (2012)
Fstar = Zi*Pstar*Zi' + H(d_index(i)); % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal
- Finf = Zi*Pinf*Zi'; % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal
+ Finf = Zi*Pinf*Zi'; % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal
Kstar = Pstar*Zi';
% Conduct check of rank
- % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead,
+ % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead,
% depends on the actual values of std errors in the model and can be badly scaled.
- % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure
- % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf.
+ % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure
+ % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf.
% Also the test for singularity is better set coarser for Finf than for Fstar for the same reason
if Finf>diffuse_kalman_tol && newRank % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i}
Kinf = Pinf*Zi';
@@ -141,7 +141,7 @@ while newRank && (t<=last)
a = a + Kinf_Finf*prediction_error;
Pstar = Pstar + Kinf*(Kinf_Finf'*(Fstar/Finf)) - Kstar*Kinf_Finf' - Kinf_Finf*Kstar';
Pinf = Pinf - Kinf*Kinf_Finf';
- llik(s,d_index(i)) = log(Finf) + l2pi;
+ llik(s,d_index(i)) = log(Finf) + l2pi;
dlikk(s) = dlikk(s) + llik(s,d_index(i));
elseif Fstar>kalman_tol
llik(s,d_index(i)) = log(Fstar) + (prediction_error*prediction_error/Fstar) + l2pi;
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
index dd2623b8e..9d8cbff06 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
@@ -54,10 +54,10 @@ function [LIK,likk,a] = univariate_kalman_filter_ss(Y,start,last,a,P,kalman_tol,
%! @sp 1
%! @end deftypefn
%@eod:
-%
+%
% Algorithm: See univariate_kalman_filter.m
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -90,18 +90,18 @@ if nargin<12
analytic_derivation = 0;
end
-if analytic_derivation == 0,
+if analytic_derivation == 0
DLIK=[];
Hess=[];
else
k = size(DT,3); % number of structural parameters
DLIK = zeros(k,1); % Initialization of the score.
dlikk = zeros(smpl,k);
- if analytic_derivation==2,
+ if analytic_derivation==2
Hess = zeros(k,k); % Initialization of the Hessian
else
asy_hess=D2a;
- if asy_hess,
+ if asy_hess
Hess = zeros(k,k); % Initialization of the Hessian
else
Hess=[];
@@ -113,9 +113,9 @@ end
while t<=last
s = t-start+1;
PP = P;
- if analytic_derivation,
+ if analytic_derivation
DPP = DP;
- if analytic_derivation==2,
+ if analytic_derivation==2
D2PP = D2P;
end
end
@@ -134,14 +134,14 @@ while t<=last
a = a + Ki*prediction_error;
PP = PP - PPZ*Ki';
likk(s,i) = log(Fi) + prediction_error*prediction_error/Fi + l2pi;
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,DPP,DLIKt,D2a,D2PP, Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0,D2a,D2Yss,D2PP);
else
[Da,DPP,DLIKt,Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0);
end
DLIK = DLIK + DLIKt;
- if analytic_derivation==2 || asy_hess,
+ if analytic_derivation==2 || asy_hess
Hess = Hess + Hesst;
end
dlikk(s,:)=dlikk(s,:)+DLIKt';
@@ -151,8 +151,8 @@ while t<=last
% p. 157, DK (2012)
end
end
- if analytic_derivation,
- if analytic_derivation==2,
+ if analytic_derivation
+ if analytic_derivation==2
[Da,junk,D2a] = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0,D2a,D2P,D2T);
else
Da = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0);
@@ -165,15 +165,15 @@ end
likk = .5*likk;
LIK = sum(sum(likk));
-if analytic_derivation,
+if analytic_derivation
dlikk = dlikk/2;
DLIK = DLIK/2;
likk = {likk, dlikk};
end
-if analytic_derivation==2 || asy_hess,
+if analytic_derivation==2 || asy_hess
% Hess = (Hess + Hess')/2;
Hess = -Hess/2;
LIK={LIK,DLIK,Hess};
-elseif analytic_derivation==1,
+elseif analytic_derivation==1
LIK={LIK,DLIK};
end
\ No newline at end of file
diff --git a/matlab/kalman/steady_state_kalman_gain.m b/matlab/kalman/steady_state_kalman_gain.m
index 460534e1b..c40761d4a 100644
--- a/matlab/kalman/steady_state_kalman_gain.m
+++ b/matlab/kalman/steady_state_kalman_gain.m
@@ -1,23 +1,23 @@
function [K,iF,P] = steady_state_kalman_gain(T,R,Q,H,mf)
% Given the invariant state space representation of a model, this
% function computes the gain matrix and the covariance matrix of the
-% state vector at the steady state of the kalman filter.
-%
-% INPUTS
-% T [double] m*m transition matrix of the state vector.
+% state vector at the steady state of the kalman filter.
+%
+% INPUTS
+% T [double] m*m transition matrix of the state vector.
% R [double] m*q matrix (q is the number of structural innovations).
% Q [double] q*q covariance matrix of the structural innovations.
% H [double] p*p covariance matrix of the measurement error.
% mf [integer] p*1 vector, indices for the observed variables
-%
-% OUTPUTS
+%
+% OUTPUTS
% K [double] kalman gain matrix.
% P [double] covariance matrix of the state vector.
-%
+%
% SPECIAL REQUIREMENTS
% Needs a solver for Riccati equations (dare.m)
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/kalman_transition_matrix.m b/matlab/kalman_transition_matrix.m
index 77b3a4d3a..f79b436cd 100644
--- a/matlab/kalman_transition_matrix.m
+++ b/matlab/kalman_transition_matrix.m
@@ -1,21 +1,21 @@
function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr)
%function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr)
% Builds the transition equation of the state space representation out of ghx and ghu for Kalman filter
-%
+%
% INPUTS
% dr: structure of decisions rules for stochastic simulations
% iv: selected variables
% ic: state variables position in the transition matrix columns
% exo_nbr: number of exogenous variables
-%
+%
% OUTPUTS
% A: matrix of predetermined variables effects in linear solution (ghx)
% B: matrix of shocks effects in linear solution (ghu)
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -41,4 +41,3 @@ A(:,ic) = dr.ghx(iv,:);
if nargout>1
B = dr.ghu(iv,:);
end
-
diff --git a/matlab/kernel_density_estimate.m b/matlab/kernel_density_estimate.m
index 172097c87..c04927681 100644
--- a/matlab/kernel_density_estimate.m
+++ b/matlab/kernel_density_estimate.m
@@ -1,30 +1,30 @@
-function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function)
-% Estimates a continuous density.
-%
+function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function)
+% Estimates a continuous density.
+%
% INPUTS
% data [double] Vector (number_of_draws*1) of draws.
% number_of_grid_points [integer] Scalar, number of points where the density is estimated.
-% This (positive) integer must be a power of two.
+% This (positive) integer must be a power of two.
% number_of_draws [integer] Scalar, number of draws.
-% bandwidth [double] Real positive scalar.
+% bandwidth [double] Real positive scalar.
% kernel_function [string] Name of the kernel function: 'gaussian', 'triweight',
-% 'uniform', 'triangle', 'epanechnikov', 'quartic',
+% 'uniform', 'triangle', 'epanechnikov', 'quartic',
% 'triweight' and 'cosinus'
%
% OUTPUTS
% abscissa [double] Vector (number_of_grid_points*1) of values on the abscissa axis.
-% f: [double] Vector (number_of_grid_points*1) of values on the ordinate axis,
+% f: [double] Vector (number_of_grid_points*1) of values on the ordinate axis,
% (density estimates).
-%
+%
% SPECIAL REQUIREMENTS
% none.
%
% REFERENCES
% A kernel density estimator is used (see Silverman [1986], "Density estimation for statistics and data analysis")
-% The code is adapted from Anders Holtsberg's matlab toolbox (stixbox).
+% The code is adapted from Anders Holtsberg's matlab toolbox (stixbox).
%
-% Copyright (C) 2004-2008 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -53,19 +53,19 @@ if (abs(test-round(test)) > 1e-12)
end
%% Kernel specification.
-if strcmpi(kernel_function,'gaussian')
+if strcmpi(kernel_function,'gaussian')
kernel = @(x) inv(sqrt(2*pi))*exp(-0.5*x.^2);
-elseif strcmpi(kernel_function,'uniform')
- kernel = @(x) 0.5*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'triangle')
+elseif strcmpi(kernel_function,'uniform')
+ kernel = @(x) 0.5*(abs(x) <= 1);
+elseif strcmpi(kernel_function,'triangle')
kernel = @(x) (1-abs(x)).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'epanechnikov')
+elseif strcmpi(kernel_function,'epanechnikov')
kernel = @(x) 0.75*(1-x.^2).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'quartic')
+elseif strcmpi(kernel_function,'quartic')
kernel = @(x) 0.9375*((1-x.^2).^2).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'triweight')
+elseif strcmpi(kernel_function,'triweight')
kernel = @(x) 1.09375*((1-x.^2).^3).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'cosinus')
+elseif strcmpi(kernel_function,'cosinus')
kernel = @(x) (pi/4)*cos((pi/2)*x).*(abs(x) <= 1);
end
@@ -73,9 +73,9 @@ end
lower_bound = min(data) - (max(data)-min(data))/3;
upper_bound = max(data) + (max(data)-min(data))/3;
abscissa = linspace(lower_bound,upper_bound,number_of_grid_points)';
-inc = abscissa(2)-abscissa(1);
+inc = abscissa(2)-abscissa(1);
xi = zeros(number_of_grid_points,1);
-xa = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points;
+xa = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points;
for i = 1:number_of_draws
indx = floor(xa(i));
temp = xa(i)-indx;
diff --git a/matlab/list_of_parameters_calibrated_as_NaN.m b/matlab/list_of_parameters_calibrated_as_NaN.m
index 603a9f2e1..01964a89a 100644
--- a/matlab/list_of_parameters_calibrated_as_NaN.m
+++ b/matlab/list_of_parameters_calibrated_as_NaN.m
@@ -1,19 +1,19 @@
function list = list_of_parameters_calibrated_as_NaN(M_)
% The name of the function is explicit enough...
-%
+%
% INPUTS
% M_ [structure] Description of the (simulated or estimated) model.
-%
+%
% OUTPUTS
% list [char] n*p array of characters, each line is the name of parameter without value.
-%
+%
% ALGORITHM
% none
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/lmmcp/catstruct.m b/matlab/lmmcp/catstruct.m
index 040c0b7ed..3f1784367 100644
--- a/matlab/lmmcp/catstruct.m
+++ b/matlab/lmmcp/catstruct.m
@@ -6,13 +6,13 @@ function A = catstruct(varargin)
%
% A.name = 'Me' ;
% B.income = 99999 ;
-% X = catstruct(A,B)
+% X = catstruct(A,B)
% % -> X.name = 'Me' ;
% % X.income = 99999 ;
%
% If a fieldname is not unique among structures (i.e., a fieldname is
% present in more than one structure), only the value from the last
-% structure with this field is used. In this case, the fields are
+% structure with this field is used. In this case, the fields are
% alphabetically sorted. A warning is issued as well. An axample:
%
% S1.name = 'Me' ;
@@ -28,7 +28,7 @@ function A = catstruct(varargin)
% CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa
%
% The last input can be the string 'sorted'. In this case,
-% CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically.
+% CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically.
% To sort the fieldnames of a structure A, you could use
% CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that.
%
@@ -36,7 +36,7 @@ function A = catstruct(varargin)
% struct (0x0 struct array with no fields).
%
% NOTE: To concatenate similar arrays of structs, you can use simple
-% concatenation:
+% concatenation:
% A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ;
%
% See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS
@@ -48,18 +48,18 @@ function A = catstruct(varargin)
% Copyright (C) 2005 Jos van der Geest
% Copyright (C) 2013 Christophe Gouel
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
-%
+%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
-%
+%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -87,8 +87,8 @@ function A = catstruct(varargin)
narginchk(1, Inf);
N = nargin ;
-if ~isstruct(varargin{end}),
- if isequal(varargin{end},'sorted'),
+if ~isstruct(varargin{end})
+ if isequal(varargin{end},'sorted')
sorted = 1 ;
N = N-1 ;
if N<1
@@ -104,7 +104,7 @@ end
sz0 = [] ; % used to check that all inputs have the same size
% used to check for a few trivial cases
-NonEmptyInputs = false(N,1) ;
+NonEmptyInputs = false(N,1) ;
NonEmptyInputsN = 0 ;
% used to collect the fieldnames and the inputs
@@ -112,13 +112,13 @@ FN = cell(N,1) ;
VAL = cell(N,1) ;
% parse the inputs
-for ii=1:N,
+for ii=1:N
X = varargin{ii} ;
- if ~isstruct(X),
+ if ~isstruct(X)
error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ;
end
-
- if ~isempty(X),
+
+ if ~isempty(X)
% empty structs are ignored
if ii > 1 && ~isempty(sz0)
if ~isequal(size(X), sz0)
@@ -137,38 +137,35 @@ end
if NonEmptyInputsN == 0
% all structures were empty
A = struct([]) ;
-elseif NonEmptyInputsN == 1,
+elseif NonEmptyInputsN == 1
% there was only one non-empty structure
A = varargin{NonEmptyInputs} ;
- if sorted,
+ if sorted
A = orderfields(A) ;
end
else
% there is actually something to concatenate
- FN = cat(1,FN{:}) ;
- VAL = cat(1,VAL{:}) ;
+ FN = cat(1,FN{:}) ;
+ VAL = cat(1,VAL{:}) ;
FN = squeeze(FN) ;
VAL = squeeze(VAL) ;
MatlabVersion = version;
if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1')
- [UFN,ind] = unique(FN) ;
+ [UFN,ind] = unique(FN) ;
else
[UFN,ind] = unique(FN,'legacy') ;
end
-
- if numel(UFN) ~= numel(FN),
+
+ if numel(UFN) ~= numel(FN)
warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ;
sorted = 1 ;
end
-
- if sorted,
+
+ if sorted
VAL = VAL(ind,:) ;
FN = FN(ind,:) ;
end
-
+
A = cell2struct(VAL, FN);
A = reshape(A, sz0) ; % reshape into original format
-end
-
-
-
+end
\ No newline at end of file
diff --git a/matlab/lmmcp/dyn_lmmcp_func.m b/matlab/lmmcp/dyn_lmmcp_func.m
index f08da101e..c25eff690 100644
--- a/matlab/lmmcp/dyn_lmmcp_func.m
+++ b/matlab/lmmcp/dyn_lmmcp_func.m
@@ -3,7 +3,7 @@ function [F,A] = dyn_lmmcp_func(x, model_dynamic, Y0, YT, exo_simul, params, ...
i_cols_A1, i_cols_1, i_cols_T, i_cols_j, ...
nnzA,eq_index)
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -32,11 +32,11 @@ i_cols = find(lead_lag_incidence');
i_cols_A = i_cols;
for it = 2:(periods+1)
-
+
[res,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ...
steady_state,it);
F(i_rows) = res(eq_index);
-
+
if nargout == 2
if it == 2
A(i_rows,i_cols_A1) = jacobian(eq_index,i_cols_1);
@@ -46,7 +46,6 @@ for it = 2:(periods+1)
A(i_rows,i_cols_A) = jacobian(eq_index,i_cols_j);
end
end
-
i_rows = i_rows + ny;
i_cols = i_cols + ny;
if nargout == 2 && it > 2
@@ -54,3 +53,9 @@ for it = 2:(periods+1)
end
end
+ i_rows = i_rows + ny;
+ i_cols = i_cols + ny;
+ if nargout == 2 && it > 2
+ i_cols_A = i_cols_A + ny;
+ end
+end
diff --git a/matlab/lmmcp/get_complementarity_conditions.m b/matlab/lmmcp/get_complementarity_conditions.m
index 291627f59..fb48ece9a 100644
--- a/matlab/lmmcp/get_complementarity_conditions.m
+++ b/matlab/lmmcp/get_complementarity_conditions.m
@@ -2,17 +2,17 @@ function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
% [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
% INPUTS
% - M [struct] contains a description of the model.
-% - ramsey_policy [boolean] indicator whether a Ramsey problem is considered
+% - ramsey_policy [boolean] indicator whether a Ramsey problem is considered
% OUTPUTS
% - lb [double] endo_nbr*1 array of lower bounds for
% endogenous variables
% - ub [double] endo_nbr*1 array of upper bounds for
% endogenous variables
-% - eq_index [struct] endo_nbr*1 index vector describing residual mapping resulting
+% - eq_index [struct] endo_nbr*1 index vector describing residual mapping resulting
% from complementarity setup used in
% perfect_foresight_mcp_problem.m
-% Copyright (C) 2014-16 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -81,4 +81,3 @@ for i=1:size(etags,1)
end
end
end
-
diff --git a/matlab/lmmcp/lmmcp.m b/matlab/lmmcp/lmmcp.m
index 76cb49a98..50404ac7c 100644
--- a/matlab/lmmcp/lmmcp.m
+++ b/matlab/lmmcp/lmmcp.m
@@ -24,7 +24,7 @@ function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin)
% Termination parameters
% MaxIter : Maximum number of iterations (default = 500)
% tmin : safeguard stepsize (default = 1E-12)
-% TolFun : Termination tolerance on the function value, a positive
+% TolFun : Termination tolerance on the function value, a positive
% scalar (default = sqrt(eps))
% Stepsize parameters
% m : number of previous function values to use in the nonmonotone
@@ -92,7 +92,7 @@ function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin)
% Copyright (C) 2005 Christian Kanzow and Stefania Petra
% Copyright (C) 2013 Christophe Gouel
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% Unlimited permission is granted to everyone to use, copy, modify or
% distribute this software.
@@ -249,11 +249,11 @@ if preprocess==1
if verbosity > 1
disp('************************** Preprocessor ****************************')
end
-
+
normpLM=1;
while (k < presteps) && (Psix > eps2) && (normpLM>null)
k = k+1;
-
+
% choice of Levenberg-Marquardt parameter, note that we do not use
% the condition estimator for large-scale problems, although this
% may cause numerical problems in some examples
@@ -273,7 +273,7 @@ if preprocess==1
pLM = -DPhix\Phix;
end
normpLM = norm(pLM);
-
+
% compute the projected Levenberg-Marquard step onto box Xk
lbnew = max(min(lb-x,0),-delta);
ubnew = min(max(ub-x,0),delta);
@@ -285,7 +285,7 @@ if preprocess==1
Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
Psixnew = 0.5*(Phixnew'*Phixnew);
normPhixnew = norm(Phixnew);
-
+
% update of delta
if normPhixnew<=eta*normPhix
delta = max(deltamin,sigma2*delta);
@@ -303,7 +303,7 @@ if preprocess==1
DPhix = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
DPsix = DPhix'*Phix;
normDPsix = norm(DPsix,inf);
-
+
% output at each iteration
t=1;
if verbosity > 1
@@ -357,7 +357,7 @@ while (k < kmax) && (Psix > eps2)
mu = 1e-1/(k+1);
end
end
-
+
% compute a Levenberg-Marquard direction
if i
@@ -378,7 +378,7 @@ while (k < kmax) && (Psix > eps2)
Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
Psixnew = 0.5*(Phixnew'*Phixnew);
const = sigma*DPsix'*d;
-
+
while (Psixnew > MaxPsi + const*t) && (t > tmin)
t = t*beta;
xnew = x+t*d;
@@ -398,7 +398,7 @@ while (k < kmax) && (Psix > eps2)
normDPsix = norm(DPsix);
k = k+1;
k_main = k_main+1;
-
+
if k_main<=5
aux(mod(k_main,m)+1) = Psix;
MaxPsi = Psix;
@@ -406,7 +406,7 @@ while (k < kmax) && (Psix > eps2)
aux(mod(k_main,m)+1) = Psix;
MaxPsi = max(aux);
end
-
+
% updatings for the watchdog strategy
if watchdog ==1
if Psix1
+if nargout >1
if length(a)==1
Dldens(idx) = (a-1)./(x(idx)) - ones(length(idx),1)/b ;
else
diff --git a/matlab/lpdfgbeta.m b/matlab/lpdfgbeta.m
index e8d8af521..6f0dd0fd8 100644
--- a/matlab/lpdfgbeta.m
+++ b/matlab/lpdfgbeta.m
@@ -1,20 +1,20 @@
-function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb);
-% Evaluates the logged BETA PDF at x.
+function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb)
+% Evaluates the logged BETA PDF at x.
%
-% INPUTS
+% INPUTS
% x [double] m*n matrix of loactions,
-% a [double] m*n matrix of First BETA distribution parameters,
-% b [double] m*n matrix of Second BETA distribution parameters,
-% aa [double] m*n matrix of lower bounds for (generalized) distribution,
+% a [double] m*n matrix of First BETA distribution parameters,
+% b [double] m*n matrix of Second BETA distribution parameters,
+% aa [double] m*n matrix of lower bounds for (generalized) distribution,
% bb [double] m*n matrix of upper bounds for (generalized) distribution
%
-% OUTPUTS
+% OUTPUTS
% ldens [double] m*n matrix of logged (generalized) BETA densities.
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -41,7 +41,7 @@ else
end
-if nargout >1
+if nargout >1
if length(a)==1
Dldens(idx) = (a-1)./(x(idx)-aa) - (b-1)./(bb-x(idx)) ;
else
@@ -50,7 +50,7 @@ if nargout >1
end
-if nargout == 3
+if nargout == 3
if length(a)==1
D2ldens(idx) = -(a-1)./(x(idx)-aa).^2 - (b-1)./(bb-x(idx)).^2 ;
else
diff --git a/matlab/lpdfig1.m b/matlab/lpdfig1.m
index 5aeb05f90..2b14c8fab 100644
--- a/matlab/lpdfig1.m
+++ b/matlab/lpdfig1.m
@@ -1,15 +1,15 @@
function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
% Evaluates the logged INVERSE-GAMMA-1 PDF at x.
%
-% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution)
+% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution)
%
% See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details.
%
%
-% INPUTS
+% INPUTS
% x [double] m*n matrix of locations,
-% s [double] m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters,
-% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters.
+% s [double] m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters,
+% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters.
%
% OUTPUTS
% ldens [double] m*n matrix of logged INVERSE-GAMMA-1 densities evaluated at x.
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
% along with Dynare. If not, see .
ldens = -Inf( size(x) ) ;
-idx = find( x>0 ) ;
+idx = find( x>0 ) ;
if length(s)==1
ldens(idx) = log(2) - gammaln(.5*nu) - .5*nu*(log(2)-log(s)) - (nu+1)*log(x(idx)) - .5*s./(x(idx).*x(idx)) ;
@@ -43,7 +43,7 @@ else
ldens(idx) = log(2) - gammaln(.5*nu(idx)) - .5*nu(idx).*(log(2)-log(s(idx))) - (nu(idx)+1).*log(x(idx)) - .5*s(idx)./(x(idx).*x(idx)) ;
end
-if nargout >1
+if nargout >1
if length(s)==1
Dldens(idx) = - (nu+1)./(x(idx)) + s./(x(idx).^3) ;
else
@@ -51,11 +51,10 @@ if nargout >1
end
end
-if nargout == 3
+if nargout == 3
if length(s)==1
D2ldens(idx) = (nu+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ;
else
D2ldens(idx) = (nu(idx)+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ;
end
end
-
diff --git a/matlab/lpdfig2.m b/matlab/lpdfig2.m
index 00de3abb1..e1b3ca2a1 100644
--- a/matlab/lpdfig2.m
+++ b/matlab/lpdfig2.m
@@ -1,15 +1,15 @@
function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
% Evaluates the logged INVERSE-GAMMA-2 PDF at x.
%
-% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution)
+% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution)
%
% See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details.
%
%
-% INPUTS
+% INPUTS
% x [double] m*n matrix of locations,
-% s [double] m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters,
-% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters.
+% s [double] m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters,
+% nu [double] m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters.
%
% OUTPUTS
% ldens [double] m*n matrix of logged INVERSE-GAMMA-2 densities evaluated at x.
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
% along with Dynare. If not, see .
ldens = -Inf( size(x) ) ;
-idx = find( x>0 ) ;
+idx = find( x>0 ) ;
if length(s)==1
ldens(idx) = -gammaln(.5*nu) - (.5*nu)*(log(2)-log(s)) - .5*(nu+2)*log(x(idx)) -.5*s./x(idx);
@@ -43,7 +43,7 @@ else
ldens(idx) = -gammaln(.5*nu(idx)) - (.5*nu(idx)).*(log(2)-log(s(idx))) - .5*(nu(idx)+2).*log(x(idx)) -.5*s(idx)./x(idx);
end
-if nargout >1
+if nargout >1
if length(s)==1
Dldens(idx) = - .5*(nu+2)./(x(idx)) + .5*s./x(idx).^2;
else
@@ -51,7 +51,7 @@ if nargout >1
end
end
-if nargout == 3
+if nargout == 3
if length(s)==1
D2ldens(idx) = .5*(nu+2)./(x(idx)).^2 - s./x(idx).^3;
else
diff --git a/matlab/lpdfnorm.m b/matlab/lpdfnorm.m
index bb9da98d8..2c1249996 100644
--- a/matlab/lpdfnorm.m
+++ b/matlab/lpdfnorm.m
@@ -1,19 +1,19 @@
function [ldens,Dldens,D2ldens] = lpdfnorm(x,a,b)
% Evaluates the logged UNIVARIATE GAUSSIAN PDF at x.
%
-% INPUTS
+% INPUTS
% x [double] m*n matrix of locations,
-% a [double] m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation)
-% b [double] m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation).
+% a [double] m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation)
+% b [double] m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation).
%
-% OUTPUTS
+% OUTPUTS
% ldens [double] m*n matrix of logged GAUSSIAN densities evaluated at x.
-%
-%
+%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,10 +34,10 @@ if nargin<3, b=1; end
if nargin<2, a=0; end
ldens = -log(b) -.5*log(2*pi) - .5*((x-a)./b).*((x-a)./b) ;
-if nargout >1
+if nargout >1
Dldens = - (1./b).*((x-a)./b) ;
end
-if nargout == 3
+if nargout == 3
D2ldens = - (1./b).^2 ;
end
\ No newline at end of file
diff --git a/matlab/lyapunov_solver.m b/matlab/lyapunov_solver.m
index a7b96c997..98d782cdf 100644
--- a/matlab/lyapunov_solver.m
+++ b/matlab/lyapunov_solver.m
@@ -1,14 +1,14 @@
function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*--
% function P=lyapunov_solver(T,R,Q,DynareOptions)
% Solves the Lyapunov equation P-T*P*T' = R*Q*R' arising in a state-space
-% system, where P is the variance of the states
+% system, where P is the variance of the states
%
% Inputs
% T [double] n*n matrix.
% R [double] n*m matrix.
% Q [double] m*m matrix.
% DynareOptions [structure] Dynare options
-%
+%
% Outputs
% P [double] n*n matrix.
%
@@ -20,10 +20,10 @@ function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*--
% DynareOptions.lyapunov_db == 1
% doubling algorithm
% DynareOptions.lyapunov_srs == 1
-% Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox
+% Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox
% or Octave control package)
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -60,10 +60,10 @@ elseif DynareOptions.lyapunov_srs == 1
end
chol_Q = R*chol(Q,'lower');
R_P = dlyapchol(T,chol_Q);
- P = R_P' * R_P;
+ P = R_P' * R_P;
else
P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
-end;
+end
%@test:1
%$ t = NaN(10,1);
@@ -81,7 +81,7 @@ end;
%$ tmp2=randn(m_small,m_small);
%$ Q_small=tmp2*tmp2';
%$ R_small=randn(n_small,m_small);
-%$
+%$
%$ n_large=9;
%$ m_large=11;
%$ T_large=randn(n_large,n_large);
@@ -89,7 +89,7 @@ end;
%$ tmp2=randn(m_large,m_large);
%$ Q_large=tmp2*tmp2';
%$ R_large=randn(n_large,m_large);
-%$
+%$
%$ % DynareOptions.lyapunov_fp == 1
%$ options_.lyapunov_fp = 1;
%$ try
diff --git a/matlab/lyapunov_symm.m b/matlab/lyapunov_symm.m
index a4618b171..53eaf9e4c 100644
--- a/matlab/lyapunov_symm.m
+++ b/matlab/lyapunov_symm.m
@@ -1,22 +1,22 @@
function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapunov_complex_threshold,method,debug) % --*-- Unitary tests --*--
% Solves the Lyapunov equation x-a*x*a' = b, for b and x symmetric matrices.
% If a has some unit roots, the function computes only the solution of the stable subsystem.
-%
+%
% INPUTS:
% a [double] n*n matrix.
% b [double] n*n matrix.
% qz_criterium [double] unit root threshold for eigenvalues
% lyapunov_fixed_point_tol [double] convergence criteria for fixed_point algorithm.
% lyapunov_complex_threshold [double] scalar, complex block threshold for the upper triangular matrix T.
-% method [integer] Scalar, if method=0 [default] then U, T, n and k are not persistent.
-% method=1 then U, T, n and k are declared as persistent
-% variables and the Schur decomposition is triggered.
-% method=2 then U, T, n and k are declared as persistent
+% method [integer] Scalar, if method=0 [default] then U, T, n and k are not persistent.
+% method=1 then U, T, n and k are declared as persistent
+% variables and the Schur decomposition is triggered.
+% method=2 then U, T, n and k are declared as persistent
% variables and the Schur decomposition is not performed.
% method=3 fixed point method
% OUTPUTS
% x: [double] m*m solution matrix of the lyapunov equation, where m is the dimension of the stable subsystem.
-% u: [double] Schur vectors associated with unit roots
+% u: [double] Schur vectors associated with unit roots
%
% ALGORITHM
% Uses reordered Schur decomposition (Bartels-Stewart algorithm)
@@ -25,7 +25,7 @@ function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapuno
% SPECIAL REQUIREMENTS
% None
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -54,7 +54,7 @@ if method == 3
persistent X method1;
if ~isempty(method1)
method = method1;
- end;
+ end
if debug
fprintf('lyapunov_symm:: [method=%d] \n',method);
end
@@ -67,16 +67,16 @@ if method == 3
max_it_fp = 2000;
else
max_it_fp = 300;
- end;
+ end
at = a';
%fixed point iterations
- while evol > lyapunov_fixed_point_tol && it_fp < max_it_fp;
+ while evol > lyapunov_fixed_point_tol && it_fp < max_it_fp
X_old = X;
X = a * X * at + b;
evol = max(sum(abs(X - X_old))); %norm_1
%evol = max(sum(abs(X - X_old)')); %norm_inf
it_fp = it_fp + 1;
- end;
+ end
if debug
fprintf('lyapunov_symm:: lyapunov fixed_point iterations=%d norm=%g\n',it_fp,evol);
end
@@ -87,9 +87,9 @@ if method == 3
else
method1 = 3;
x = X;
- return;
- end;
- end;
+ return
+ end
+ end
end
if method
@@ -110,7 +110,7 @@ end
if method<2
[U,T] = schur(a);
e1 = abs(ordeig(T)) > 2-qz_criterium;
- k = sum(e1); % Number of unit roots.
+ k = sum(e1); % Number of unit roots.
n = length(e1)-k; % Number of stationary variables.
if k > 0
% Selects stable roots
diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m
index 58e293da8..e5683da2c 100644
--- a/matlab/marginal_density.m
+++ b/matlab/marginal_density.m
@@ -15,7 +15,7 @@ function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bay
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -64,7 +64,7 @@ end
% save the posterior mean and the inverse of the covariance matrix
% (usefull if the user wants to perform some computations using
-% the posterior mean instead of the posterior mode ==> ).
+% the posterior mean instead of the posterior mode ==> ).
parameter_names = bayestopt_.name;
save([M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA');
@@ -76,7 +76,7 @@ linee = 0;
check_coverage = 1;
increase = 1;
while check_coverage
- for p = 0.1:0.1:0.9;
+ for p = 0.1:0.1:0.9
critval = chi2inv(p,npar);
ifil = FirstLine;
tmp = 0;
@@ -106,7 +106,7 @@ while check_coverage
disp('Estimation::marginal density: The support of the weighting density function is not large enough...')
disp('Estimation::marginal density: I increase the variance of this distribution.')
increase = 1.2*increase;
- linee = 0;
+ linee = 0;
else
disp('Estimation::marginal density: Let me try again.')
increase = 1.2*increase;
@@ -114,9 +114,9 @@ while check_coverage
if increase > 20
check_coverage = 0;
clear invSIGMA detSIGMA increase;
- disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.')
+ disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.')
end
- end
+ end
else
check_coverage = 0;
clear invSIGMA detSIGMA increase;
@@ -130,17 +130,17 @@ return
function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name)
%function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name)
-%
-% INPUTS
+%
+% INPUTS
% o xparam1 [double] (p*1) vector of estimate parameters.
% o stdh [double] (p*1) vector of estimate parameters.
-% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
+% o M_ Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
% o estim_params_ Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}).
% o options_ Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
% o bayestopt_ Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}).
% o oo_ Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}).
-%
-% OUTPUTS
+%
+% OUTPUTS
% o oo_ Matlab's structure gathering the results
%
% SPECIAL REQUIREMENTS
diff --git a/matlab/matlab_ver_less_than.m b/matlab/matlab_ver_less_than.m
index 53dd8d7ef..10cd640d2 100644
--- a/matlab/matlab_ver_less_than.m
+++ b/matlab/matlab_ver_less_than.m
@@ -8,14 +8,14 @@ function r = matlab_ver_less_than(verstr)
%
% INPUTS
% verstr: a string of the format 'x.y' or 'x.y.z'
-%
+%
% OUTPUTS
% r: 0 or 1
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2014 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m
index 72df861a4..9f79e44a4 100644
--- a/matlab/maximize_prior_density.m
+++ b/matlab/maximize_prior_density.m
@@ -1,21 +1,21 @@
function [xparams,lpd,hessian_mat] = ...
maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,BayesInfo,EstimatedParams,DynareResults)
% Maximizes the logged prior density using Chris Sims' optimization routine.
-%
-% INPUTS
+%
+% INPUTS
% iparams [double] vector of initial parameters.
% prior_shape [integer] vector specifying prior densities shapes.
% prior_hyperparameter_1 [double] vector, first hyperparameter.
% prior_hyperparameter_2 [double] vector, second hyperparameter.
% prior_inf_bound [double] vector, prior's lower bound.
-% prior_sup_bound [double] vector, prior's upper bound.
+% prior_sup_bound [double] vector, prior's upper bound.
%
-% OUTPUTS
+% OUTPUTS
% xparams [double] vector, prior mode.
% lpd [double] scalar, value of the logged prior density at the mode.
% hessian_mat [double] matrix, Hessian matrix at the prior mode.
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/mcforecast3.m b/matlab/mcforecast3.m
index 3e1de2888..b318d46f4 100644
--- a/matlab/mcforecast3.m
+++ b/matlab/mcforecast3.m
@@ -2,7 +2,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% forcs = mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% Computes the shock values for constrained forecasts necessary to keep
% endogenous variables at their constrained paths
-%
+%
% INPUTS
% o cL [scalar] number of controlled periods
% o H [scalar] number of forecast periods
@@ -14,7 +14,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% o mv [n_controlled_exo by n_endovars boolean] indicator vector selecting constrained endogenous variables
% o mu [n_controlled_vars by nexo boolean] indicator vector
% selecting controlled exogenous variables
-%
+%
% Algorithm:
% Relies on state-space form:
% y_t=T*y_{t-1}+R*shocks(:,t)
@@ -30,8 +30,8 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
% After obtaining the shocks, and for uncontrolled periods, the state-space representation
% y_t=T*y_{t-1}+R*shocks(:,t)
% is used for forecasting
-%
-% Copyright (C) 2006-2013 Dynare Team
+%
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/mcompare.m b/matlab/mcompare.m
index 9bf0f1713..f3f052f68 100644
--- a/matlab/mcompare.m
+++ b/matlab/mcompare.m
@@ -1,7 +1,7 @@
function mcompare(s1,s2)
-% MCOMPARE : MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )
+% MCOMPARE : MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )
% This optional command plots the relative differences between
-% two different simulations for a list of variables. One plot
+% two different simulations for a list of variables. One plot
% is drawn for each variable. The trajectories must have been
% previously saved by the instruction DYNASAVE. The simulation
% in file1 serves as the base simulation and the ploted quantity
@@ -10,7 +10,7 @@ function mcompare(s1,s2)
% value of the base simulation, the absolute difference is ploted
% instead of the relative one.
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/mcp_func.m b/matlab/mcp_func.m
index 424b9203f..30494b95a 100644
--- a/matlab/mcp_func.m
+++ b/matlab/mcp_func.m
@@ -1,17 +1,17 @@
function [res,fjac,domer] = mcp_func(x,jacflag)
% function [res,fjac,domer] = mcp_func(x,jacflag)
% wrapper function for mixed complementarity problem when using PATH
-%
-% INPUTS
+%
+% INPUTS
% - x [double] N*T array, paths for the endogenous variables (initial guess).
% - jacflag [scalar] indicator whether Jacobian is requested
%
-% OUTPUTS
+% OUTPUTS
% - res [double] (N*T)*1 array, residuals of the stacked problem
% - fjac [double] (N*T)*(N*T) array, Jacobian of the stacked problem
% - domer [scalar] errorflag that is 1 if solution is not real
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m
index a8e1e602d..94c421278 100644
--- a/matlab/metropolis_draw.m
+++ b/matlab/metropolis_draw.m
@@ -1,12 +1,12 @@
function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params_,M_)
-% function [xparams, logpost]=metropolis_draw(init)
+% function [xparams, logpost]=metropolis_draw(init)
% Builds draws from metropolis
%
% INPUTS:
-% init: scalar equal to
-% 1: first call to store the required information
-% on files, lines, and chains to be read
-% in persistent variables to make them available
+% init: scalar equal to
+% 1: first call to store the required information
+% on files, lines, and chains to be read
+% in persistent variables to make them available
% for future calls
% 0: load a parameter draw
% Additional Inputs required for initialization
@@ -19,12 +19,12 @@ function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params
% if init==1: error flaog
% logpost: log of posterior density
% options_: [structure] Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
-%
+%
% SPECIAL REQUIREMENTS
%
% Requires CutSample to be run before in order to set up mh_history-file
-% Copyright (C) 2003-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -61,9 +61,9 @@ if init
%load mh_history-file with info on what to load
load_last_mh_history_file(MetropolisFolder, FileName);
FirstMhFile = record.KeepedDraws.FirstMhFile;
- FirstLine = record.KeepedDraws.FirstLine;
- TotalNumberOfMhFiles = sum(record.MhDraws(:,2));
- LastMhFile = TotalNumberOfMhFiles;
+ FirstLine = record.KeepedDraws.FirstLine;
+ TotalNumberOfMhFiles = sum(record.MhDraws(:,2));
+ LastMhFile = TotalNumberOfMhFiles;
TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); %number of parameters plus posterior plus ?
@@ -89,9 +89,9 @@ else %not initialization, return one draw
if DrawNumber <= MAX_nruns-FirstLine+1 %draw in first file, needs to account for first line
MhFilNumber = FirstMhFile;
MhLine = FirstLine+DrawNumber-1;
- else %draw in other file
+ else %draw in other file
DrawNumber = DrawNumber-(MAX_nruns-FirstLine+1);
- MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns);
+ MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns);
MhLine = DrawNumber-(MhFilNumber-FirstMhFile-1)*MAX_nruns;
end
%load parameters and posterior
diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m
index 97a454eee..e9d97a0ea 100644
--- a/matlab/metropolis_hastings_initialization.m
+++ b/matlab/metropolis_hastings_initialization.m
@@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d ] = ...
% metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
% Metropolis-Hastings initialization.
-%
-% INPUTS
+%
+% INPUTS
% o TargetFun [char] string specifying the name of the objective
% function (posterior kernel).
% o xparam1 [double] (p*1) vector of parameters to be estimated (initial values).
% o vv [double] (p*p) matrix, posterior covariance matrix (at the mode).
-% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
+% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
% o dataset_ data structure
% o dataset_info dataset info structure
% o options_ options structure
@@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% o estim_params_ estimated parameters structure
% o bayestopt_ estimation options structure
% o oo_ outputs structure
-%
-% OUTPUTS
+%
+% OUTPUTS
% o ix2 [double] (NumberOfBlocks*npar) vector of starting points for different chains
% o ilogpo2 [double] (NumberOfBlocks*1) vector of initial posterior values for different chains
% o ModelName [string] name of the mod-file
% o MetropolisFolder [string] path to the Metropolis subfolder
-% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
-% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
+% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
+% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
% o npar [scalar] number of parameters estimated
-% o NumberOfBlocks [scalar] Number of MCM chains requested
-% o nruns [double] (NumberOfBlocks*1) number of draws in each chain
+% o NumberOfBlocks [scalar] Number of MCM chains requested
+% o nruns [double] (NumberOfBlocks*1) number of draws in each chain
% o NewFile [scalar] (NumberOfBlocks*1) vector storing the number
% of the first MH-file to created for each chain when saving additional
% draws
@@ -37,7 +37,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -57,7 +57,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
%Initialize outputs
ix2 = [];
ilogpo2 = [];
-ModelName = [];
+ModelName = [];
MetropolisFolder = [];
FirstBlock = [];
FirstLine = [];
@@ -124,7 +124,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
trial = 1;
while validate == 0 && trial <= 10
candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar);
- if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
+ if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
ix2(j,:) = candidate;
ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
if ~isfinite(ilogpo2(j)) % if returned log-density is
@@ -167,7 +167,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
else% Case 2: one chain (we start from the posterior mode)
fprintf(fidlog,[' Initial values of the parameters:\n']);
candidate = transpose(xparam1(:));%
- if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
+ if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
ix2 = candidate;
ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
disp('Estimation::mcmc: Initialization at the posterior mode.')
@@ -223,7 +223,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']);
fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']);
fprintf(fidlog,['\n']);
- for j = 1:NumberOfBlocks,
+ for j = 1:NumberOfBlocks
fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']);
for i=1:length(record.InitialSeeds(j).Normal)
fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']);
@@ -232,7 +232,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
for i=1:length(record.InitialSeeds(j).Unifor)
fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']);
end
- end,
+ end
fprintf(fidlog,' \n');
fclose(fidlog);
elseif options_.load_mh_file && ~options_.mh_recover
@@ -281,7 +281,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns);
- AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
+ AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles;
record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
record.MhDraws(end,1) = nruns(1);
@@ -300,15 +300,15 @@ elseif options_.mh_recover
load_last_mh_history_file(MetropolisFolder, ModelName);
NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
options_.mh_nblck = NumberOfBlocks;
-
+
%% check consistency of options
if record.MhDraws(end,1)~=options_.mh_replic
fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n')
fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1))
options_.mh_replic=record.MhDraws(end,1);
nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
- end
-
+ end
+
if ~isnan(record.MAX_nruns(end,1)) %field exists
if record.MAX_nruns(end,1)~=MAX_nruns
fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n')
@@ -335,8 +335,8 @@ elseif options_.mh_recover
if OldMhExists
LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session.
LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions.
- %Test if the last mh files of the previous session were not full yet
- if LastLineNumberInThePreviousMh < MAX_nruns%not full
+ %Test if the last mh files of the previous session were not full yet
+ if LastLineNumberInThePreviousMh < MAX_nruns%not full
%store starting point if whole chain needs to be redone
NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1);
@@ -354,9 +354,9 @@ elseif options_.mh_recover
FirstLine = ones(NumberOfBlocks,1);
LastFileFullIndicator=1;
end
-
+
%% Now find out what exactly needs to be redone
- % 1. Check if really something needs to be done
+ % 1. Check if really something needs to be done
% How many mh files should we have ?
ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
@@ -366,7 +366,7 @@ elseif options_.mh_recover
% Quit if no crashed mcmc chain can be found as there are as many files as expected
if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles)
disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!')
- disp(' You have to edit the mod file and remove the mh_recover option')
+ disp(' You have to edit the mod file and remove the mh_recover option')
disp(' in the estimation command')
error('Estimation::mcmc: mh_recover option not required!')
end
@@ -389,15 +389,15 @@ elseif options_.mh_recover
end
FirstBlock = FirstBlock+1;
end
-
- %% 3. Overwrite default settings for
+
+ %% 3. Overwrite default settings for
% How many mh-files are saved in this block?
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
% Check whether last present file is a file included in the last MCMC run
- if ~LastFileFullIndicator
+ if ~LastFileFullIndicator
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
- loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
+ loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
%check whether that last file was filled
if size(loaded_results.x2,1)==MAX_nruns %file is full
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
@@ -407,20 +407,20 @@ elseif options_.mh_recover
ExistingDrawsInLastMCFile=0;
end
end
- elseif LastFileFullIndicator
+ elseif LastFileFullIndicator
ExistingDrawsInLastMCFile=0;
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
end
end
% % Correct the number of saved mh files if the crashed Metropolis was not the first session (so
- % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
- % % of the current session).
+ % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
+ % % of the current session).
% if OldMhExists
% NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
% end
% NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
-
+
% Correct initial conditions.
if NumberOfSavedMhFilesInTheCrashedBlck.
% Cet the column index:
-if nargin<7
+if nargin<7
column = name2index(options_, M_, estim_params_, type, name1);
else
column = name2index(options_, M_, estim_params_, type, name1, name2);
@@ -88,7 +88,7 @@ else
end
if options_.mh_nblck>1
- FigureName = [ FigureName , ' (block number' int2str(blck) ').'];
+ FigureName = [ FigureName , ' (block number' int2str(blck) ').'];
end
hh=dyn_figure(options_.nodisplay,'Name',FigureName);
diff --git a/matlab/mh_optimal_bandwidth.m b/matlab/mh_optimal_bandwidth.m
index 7355fddbd..7d1858285 100644
--- a/matlab/mh_optimal_bandwidth.m
+++ b/matlab/mh_optimal_bandwidth.m
@@ -1,30 +1,30 @@
-function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function)
+function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function)
% This function gives the optimal bandwidth parameter of a kernel estimator
-% used to estimate a posterior univariate density from realisations of a
-% Metropolis-Hastings algorithm.
+% used to estimate a posterior univariate density from realisations of a
+% Metropolis-Hastings algorithm.
%
% INPUTS:
% data [double] Vector (number_of_draws*1) of draws.
% number_of_draws [integer] Scalar, number of draws.
-% bandwidth [integer] Scalar equal to 0,-1 or -2.
+% bandwidth [integer] Scalar equal to 0,-1 or -2.
% bandwidth = 0 => Silverman [1986] rule of thumb.
% bandwidth = -1 => Sheather and Jones [1991].
-% bandwidth = -2 => Local bandwith parameters.
+% bandwidth = -2 => Local bandwith parameters.
% kernel_function [string] Name of the kernel function: 'gaussian', 'triweight',
-% 'uniform', 'triangle', 'epanechnikov', 'quartic',
+% 'uniform', 'triangle', 'epanechnikov', 'quartic',
% 'triweight' and 'cosinus'
%
% OUTPUTS:
% optimal_bandwidth: [double] Scalar or vector, optimal window width.
-%
+%
% SPECIAL REQUIREMENTS:
% none.
%
% REFERENCES:
-% [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm".
-% [2] Silverman [1986], "Density estimation for statistics and data analysis".
+% [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm".
+% [2] Silverman [1986], "Density estimation for statistics and data analysis".
-% Copyright (C) 2004-2015 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -53,30 +53,30 @@ if strcmpi(kernel_function,'gaussian')
k6 = @(x)inv(sqrt(2*pi))*(-15*exp(-0.5*x.^2)+45*(x.^2).*exp(-0.5*x.^2)-15*(x.^4).*exp(-0.5*x.^2)+(x.^6).*exp(-0.5*x.^2));
mu02 = inv(2*sqrt(pi));
mu21 = 1;
-elseif strcmpi(kernel_function,'uniform')
+elseif strcmpi(kernel_function,'uniform')
k = @(x)0.5*(abs(x) <= 1);
mu02 = 0.5;
mu21 = 1/3;
-elseif strcmpi(kernel_function,'triangle')
+elseif strcmpi(kernel_function,'triangle')
k = @(x)(1-abs(x)).*(abs(x) <= 1);
mu02 = 2/3;
mu21 = 1/6;
-elseif strcmpi(kernel_function,'epanechnikov')
+elseif strcmpi(kernel_function,'epanechnikov')
k = @(x)0.75*(1-x.^2).*(abs(x) <= 1);
mu02 = 3/5;
mu21 = 1/5;
-elseif strcmpi(kernel_function,'quartic')
+elseif strcmpi(kernel_function,'quartic')
k = @(x)0.9375*((1-x.^2).^2).*(abs(x) <= 1);
mu02 = 15/21;
mu21 = 1/7;
-elseif strcmpi(kernel_function,'triweight')
+elseif strcmpi(kernel_function,'triweight')
k = @(x)1.09375*((1-x.^2).^3).*(abs(x) <= 1);
k2 = @(x)(105/4*(1-x.^2).*x.^2-105/16*(1-x.^2).^2).*(abs(x) <= 1);
k4 = @(x)(-1575/4*x.^2+315/4).*(abs(x) <= 1);
k6 = @(x)(-1575/2).*(abs(x) <= 1);
mu02 = 350/429;
mu21 = 1/9;
-elseif strcmpi(kernel_function,'cosinus')
+elseif strcmpi(kernel_function,'cosinus')
k = @(x)(pi/4)*cos((pi/2)*x).*(abs(x) <= 1);
k2 = @(x)(-1/16*cos(pi*x/2)*pi^3).*(abs(x) <= 1);
k4 = @(x)(1/64*cos(pi*x/2)*pi^5).*(abs(x) <= 1);
@@ -98,23 +98,23 @@ end
%% Compute the standard deviation of the draws.
sigma = std(data);
%% Optimal bandwidth parameter.
-if bandwidth == 0; % Rule of thumb bandwidth parameter (Silverman [1986].
+if bandwidth == 0 % Rule of thumb bandwidth parameter (Silverman [1986].
h = 2*sigma*(sqrt(pi)*mu02/(12*(mu21^2)*number_of_draws))^(1/5);
h = h*correction^(1/5);
-elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the optimal bandwidth parameter.
- if strcmp(kernel_function,'uniform') || ...
- strcmp(kernel_function,'triangle') || ...
- strcmp(kernel_function,'epanechnikov') || ...
+elseif bandwidth == -1 % Sheather and Jones [1991] plug-in estimation of the optimal bandwidth parameter.
+ if strcmp(kernel_function,'uniform') || ...
+ strcmp(kernel_function,'triangle') || ...
+ strcmp(kernel_function,'epanechnikov') || ...
strcmp(kernel_function,'quartic')
error(['I can''t compute the optimal bandwidth with this kernel...' ...
'Try the gaussian, triweight or cosinus kernels.']);
- end
+ end
Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi));
g3 = abs(2*correction*k6(0)/(mu21*Itilda4*number_of_draws))^(1/9);
Ihat3 = 0;
for i=1:number_of_draws
Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3));
- end
+ end
Ihat3 = - Ihat3/((number_of_draws^2)*g3^7);
g2 = abs(2*correction*k4(0)/(mu21*Ihat3*number_of_draws))^(1/7);
Ihat2 = 0;
@@ -122,12 +122,12 @@ elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the op
Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2));
end
Ihat2 = Ihat2/((number_of_draws^2)*g2^5);
- h = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003].
-elseif bandwidth == -2; % Bump killing... I compute local bandwith parameters in order to remove
- % spurious bumps introduced by long rejecting periods.
- if strcmp(kernel_function,'uniform') || ...
- strcmp(kernel_function,'triangle') || ...
- strcmp(kernel_function,'epanechnikov') || ...
+ h = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003].
+elseif bandwidth == -2 % Bump killing... I compute local bandwith parameters in order to remove
+ % spurious bumps introduced by long rejecting periods.
+ if strcmp(kernel_function,'uniform') || ...
+ strcmp(kernel_function,'triangle') || ...
+ strcmp(kernel_function,'epanechnikov') || ...
strcmp(kernel_function,'quartic')
error(['I can''t compute the optimal bandwidth with this kernel...' ...
'Try the gaussian, triweight or cosinus kernels.']);
@@ -135,9 +135,9 @@ elseif bandwidth == -2; % Bump killing... I compute local bandwith parameter
T = zeros(n,1);
for i=1:n
j = i;
- while j<= n && (data(j,1)-data(i,1))<2*eps;
+ while j<= n && (data(j,1)-data(i,1))<2*eps
j = j+1;
- end
+ end
T(i) = (j-i);
correction = correction + 2*T(i) - 1;
end
@@ -151,11 +151,11 @@ elseif bandwidth == -2; % Bump killing... I compute local bandwith parameter
Ihat3 = -Ihat3/((n^2)*g3^7);
g2 = abs(2*correction*k4(0)/(mu21*Ihat3*n))^(1/7);
Ihat2 = 0;
- for i=1:number_of_draws;
+ for i=1:number_of_draws
Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2));
- end
+ end
Ihat2 = Ihat2/((number_of_draws^2)*g2^5);
- h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters).
+ h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters).
else
disp('mh_optimal_bandwidth:: ');
error('Parameter bandwidth must be equal to 0, -1 or -2.');
@@ -169,7 +169,7 @@ function correction = correction_for_repeated_draws(draws,n)
correction = 0;
for i=1:n
j = i;
- while j<=n && ( draws(j,1) - draws(i,1) )<2*eps;
+ while j<=n && ( draws(j,1) - draws(i,1) )<2*eps
j = j+1;
end
correction = correction + 2*(j-i) - 1;
diff --git a/matlab/minus_logged_prior_density.m b/matlab/minus_logged_prior_density.m
index 60208647f..0b5b1e815 100644
--- a/matlab/minus_logged_prior_density.m
+++ b/matlab/minus_logged_prior_density.m
@@ -1,19 +1,19 @@
function [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,DynareOptions,DynareModel,EstimatedParams,DynareResults)
% Evaluates minus the logged prior density.
-%
-% INPUTS
+%
+% INPUTS
% xparams [double] vector of parameters.
% pshape [integer] vector specifying prior densities shapes.
% p6 [double] vector, first hyperparameter.
% p7 [double] vector, second hyperparameter.
% p3 [double] vector, prior's lower bound.
-% p4 [double] vector, prior's upper bound.
+% p4 [double] vector, prior's upper bound.
%
-% OUTPUTS
+% OUTPUTS
% f [double] value of minus the logged prior density.
% info [double] vector: second entry stores penalty, first entry the error code.
%
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -138,7 +138,7 @@ if info(1)
else
fval = Inf;
info(4) = 0.1;
- exit_flag = 0;
+ exit_flag = 0;
return
end
end
diff --git a/matlab/missing/corrcoef/corrcoef.m b/matlab/missing/corrcoef/corrcoef.m
index ec3b67091..893fd7c57 100644
--- a/matlab/missing/corrcoef/corrcoef.m
+++ b/matlab/missing/corrcoef/corrcoef.m
@@ -91,7 +91,7 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin)
% $Id: corrcoef.m 9387 2011-12-15 10:42:14Z schloegl $
% Copyright (C) 2000-2004,2008,2009,2011 by Alois Schloegl
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
@@ -138,22 +138,22 @@ elseif nargin>1
Y=[];
else
varg = varargin;
- end;
+ end
- if length(varg)<1,
+ if length(varg)<1
Mode = 'Pearson';
- elseif length(varg)==1,
+ elseif length(varg)==1
Mode = varg{1};
else
- for k = 2:2:length(varg),
+ for k = 2:2:length(varg)
mode = setfield(mode,lower(varg{k-1}),varg{k});
- end;
+ end
if isfield(mode,'mode')
Mode = mode.mode;
- end;
- end;
-end;
-if isempty(Mode) Mode='pearson'; end;
+ end
+ end
+end
+if isempty(Mode), Mode='pearson'; end
Mode=[Mode,' '];
@@ -164,19 +164,19 @@ warning('off');
[r1,c1]=size(X);
if ~isempty(Y)
[r2,c2]=size(Y);
- if r1~=r2,
+ if r1~=r2
fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n');
- return;
- end;
+ return
+ end
NN = real(~isnan(X)')*real(~isnan(Y));
else
[r2,c2]=size(X);
NN = real(~isnan(X)')*real(~isnan(X));
-end;
+end
%%%%% generate combinations using indices for pairwise calculation of the correlation
YESNAN = any(isnan(X(:))) | any(isnan(Y(:)));
-if YESNAN,
+if YESNAN
FLAG_NANS_OCCURED=(1==1);
if isfield(mode,'rows')
if strcmp(mode.rows,'complete')
@@ -184,7 +184,7 @@ if YESNAN,
X = X(ix,:);
if ~isempty(Y)
Y = Y(ix,:);
- end;
+ end
YESNAN = 0;
NN = size(X,1);
elseif strcmp(mode.rows,'all')
@@ -192,10 +192,10 @@ if YESNAN,
%%NN(NN < size(X,1)) = NaN;
elseif strcmp(mode.rows,'pairwise')
%%% default
- end;
- end;
-end;
-if isempty(Y),
+ end
+ end
+end
+if isempty(Y)
IX = ones(c1)-diag(ones(c1,1));
[jx, jy ] = find(IX);
[jxo,jyo] = find(IX);
@@ -208,13 +208,13 @@ else
IX = ones(c1,c2);
[jxo,jyo] = find(IX);
R = zeros(c1,c2);
-end;
+end
-if strcmp(lower(Mode(1:7)),'pearson');
+if strcmp(lower(Mode(1:7)),'pearson')
% see http://mathworld.wolfram.com/CorrelationCoefficient.html
- if ~YESNAN,
+ if ~YESNAN
[S,N,SSQ] = sumskipnan(X,1);
- if ~isempty(Y),
+ if ~isempty(Y)
[S2,N2,SSQ2] = sumskipnan(Y,1);
CC = X'*Y;
M1 = S./N;
@@ -227,12 +227,12 @@ if strcmp(lower(Mode(1:7)),'pearson');
cc = CC./NN - M'*M;
v = SSQ./N - M.*M; %max(N-1,0);
R = cc./sqrt(v'*v);
- end;
+ end
else
- if ~isempty(Y),
+ if ~isempty(Y)
X = [X,Y];
- end;
- for k = 1:length(jx),
+ end
+ for k = 1:length(jx)
%ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
[s,n,s2] = sumskipnan(X(ik,[jx(k),jy(k)]),1);
@@ -241,83 +241,83 @@ if strcmp(lower(Mode(1:7)),'pearson');
cc = cc/n(1) - prod(s./n);
%r(k) = cc./sqrt(prod(v));
R(jxo(k),jyo(k)) = cc./sqrt(prod(v));
- end;
+ end
end
-elseif strcmp(lower(Mode(1:4)),'rank');
+elseif strcmp(lower(Mode(1:4)),'rank')
% see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
- if ~YESNAN,
+ if ~YESNAN
if isempty(Y)
R = corrcoef(ranks(X));
else
R = corrcoef(ranks(X),ranks(Y));
- end;
+ end
else
- if ~isempty(Y),
+ if ~isempty(Y)
X = [X,Y];
- end;
- for k = 1:length(jx),
+ end
+ for k = 1:length(jx)
%ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
il = ranks(X(ik,[jx(k),jy(k)]));
R(jxo(k),jyo(k)) = corrcoef(il(:,1),il(:,2));
- end;
+ end
X = ranks(X);
- end;
+ end
-elseif strcmp(lower(Mode(1:8)),'spearman');
+elseif strcmp(lower(Mode(1:8)),'spearman')
% see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
- if ~isempty(Y),
+ if ~isempty(Y)
X = [X,Y];
- end;
+ end
n = repmat(nan,c1,c2);
- if ~YESNAN,
+ if ~YESNAN
iy = ranks(X); % calculates ranks;
- for k = 1:length(jx),
+ for k = 1:length(jx)
[R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((iy(:,jx(k)) - iy(:,jy(k))).^2); % NN is the number of non-missing values
- end;
+ end
else
- for k = 1:length(jx),
+ for k = 1:length(jx)
%ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
il = ranks(X(ik,[jx(k),jy(k)]));
% NN is the number of non-missing values
[R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((il(:,1) - il(:,2)).^2);
- end;
+ end
X = ranks(X);
- end;
+ end
R = 1 - 6 * R ./ (n.*(n.*n-1));
-elseif strcmp(lower(Mode(1:7)),'partial');
+elseif strcmp(lower(Mode(1:7)),'partial')
fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode);
- return;
+ return
-elseif strcmp(lower(Mode(1:7)),'kendall');
+elseif strcmp(lower(Mode(1:7)),'kendall')
fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode);
- return;
+ return
else
fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode);
-end;
+end
-if (NARG<2),
+if (NARG<2)
warning(FLAG_WARNING); % restore warning status
- return;
-end;
+ return
+end
% CONFIDENCE INTERVAL
if isfield(mode,'alpha')
alpha = mode.alpha;
-elseif exist('flag_implicit_significance','file'),
+elseif exist('flag_implicit_significance','file')
alpha = flag_implicit_significance;
else
alpha = 0.01;
-end;
+end
% fprintf(1,'CORRCOEF: confidence interval is based on alpha=%f\n',alpha);
@@ -327,21 +327,21 @@ tmp = 1 - R.*R;
tmp(tmp<0) = 0; % prevent tmp<0 i.e. imag(t)~=0
t = R.*sqrt(max(NN-2,0)./tmp);
-if exist('t_cdf','file');
+if exist('t_cdf','file')
sig = t_cdf(t,NN-2);
-elseif exist('tcdf','file')>1;
+elseif exist('tcdf','file')>1
sig = tcdf(t,NN-2);
else
fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n')
sig = repmat(nan,size(R));
-end;
+end
sig = 2 * min(sig,1 - sig);
-if NARG<3,
+if NARG<3
warning(FLAG_WARNING); % restore warning status
- return;
-end;
+ return
+end
tmp = R;
@@ -356,11 +356,11 @@ ci2 = tanh(z+sz);
%ci1(isnan(ci1))=R(isnan(ci1)); % in case of isnan(ci), the interval limits are exactly the R value
%ci2(isnan(ci2))=R(isnan(ci2));
-if (NARG<5) || ~YESNAN,
+if (NARG<5) || ~YESNAN
nan_sig = repmat(NaN,size(R));
warning(FLAG_WARNING); % restore warning status
- return;
-end;
+ return
+end
%%%%% ----- check independence of NaNs (missing values) -----
[nan_R, nan_sig] = corrcoef(X,double(isnan(X)));
@@ -370,7 +370,7 @@ nan_sig(isnan(nan_R)) = nan;
% remove diagonal elements, because these have not any meaning %
nan_R(isnan(nan_R)) = 0;
-if 0, any(nan_sig(:) < alpha),
+if 0, any(nan_sig(:) < alpha)
tmp = nan_sig(:); % Hack to skip NaN's in MIN(X)
min_sig = min(tmp(~isnan(tmp))); % Necessary, because Octave returns NaN rather than min(X) for min(NaN,X)
fprintf(1,'CORRCOFF Warning: Missing Values (i.e. NaNs) are not independent of data (p-value=%f)\n', min_sig);
@@ -378,10 +378,8 @@ if 0, any(nan_sig(:) < alpha),
fprintf(1,' The null-hypotheses (NaNs are uncorrelated) is rejected for the following parameter pair(s).\n');
[ix,iy] = find(nan_sig < alpha);
disp([ix,iy])
-end;
+end
%%%%% ----- end of independence check ------
warning(FLAG_WARNING); % restore warning status
-return;
-
diff --git a/matlab/missing/corrcoef/flag_implicit_skip_nan.m b/matlab/missing/corrcoef/flag_implicit_skip_nan.m
index bf162f071..e8fd0fec6 100644
--- a/matlab/missing/corrcoef/flag_implicit_skip_nan.m
+++ b/matlab/missing/corrcoef/flag_implicit_skip_nan.m
@@ -41,8 +41,10 @@ function FLAG = flag_implicit_skip_nan(i)
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
% $Id: flag_implicit_skip_nan.m 8351 2011-06-24 17:35:07Z carandraug $
+
% Copyright (C) 2001-2003,2009 by Alois Schloegl
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
+%
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
@@ -52,15 +54,14 @@ persistent FLAG_implicit_skip_nan;
%% if strcmp(version,'3.6'), FLAG_implicit_skip_nan=(1==1); end; %% hack for the use with Freemat3.6
%%% set DEFAULT value of FLAG
-if isempty(FLAG_implicit_skip_nan),
+if isempty(FLAG_implicit_skip_nan)
FLAG_implicit_skip_nan = (1==1); %logical(1); % logical.m not available on 2.0.16
-end;
+end
FLAG = FLAG_implicit_skip_nan;
-if nargin>0,
+if nargin>0
FLAG_implicit_skip_nan = (i~=0); %logical(i); %logical.m not available in 2.0.16
if (~i)
warning('flag_implicit_skipnan(0): You are warned!!! You have turned off skipping NaN in sumskipnan. This is not recommended. Make sure you really know what you do.')
- end;
-end;
-
+ end
+end
diff --git a/matlab/missing/corrcoef/sumskipnan.m b/matlab/missing/corrcoef/sumskipnan.m
index 15768dc09..a1054c3f8 100644
--- a/matlab/missing/corrcoef/sumskipnan.m
+++ b/matlab/missing/corrcoef/sumskipnan.m
@@ -48,20 +48,21 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W)
% along with this program; If not, see .
% $Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $
+%
% Copyright (C) 2000-2005,2009,2011 by Alois Schloegl
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
global FLAG_NANS_OCCURED;
-if nargin<2,
+if nargin<2
DIM = [];
-end;
-if nargin<3,
+end
+if nargin<3
W = [];
-end;
+end
% an efficient implementation in C of the following lines
% could significantly increase performance
@@ -78,19 +79,19 @@ end;
% o3 += tmp.*tmp;
% };
-if isempty(DIM),
+if isempty(DIM)
DIM = find(size(x)>1,1);
- if isempty(DIM), DIM = 1; end;
+ if isempty(DIM), DIM = 1; end
end
-if (DIM<1), DIM = 1; end; %% Hack, because min([])=0 for FreeMat v3.5
+if (DIM<1), DIM = 1; end %% Hack, because min([])=0 for FreeMat v3.5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% non-float data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan(), %%% skip always NaN's
+if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan() %%% skip always NaN's
if ~isempty(W)
error('SUMSKIPNAN: weighted sum of integers not supported, yet');
- end;
+ end
x = double(x);
o = sum(x,DIM);
if nargout>1
@@ -101,16 +102,16 @@ if (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_ski
if nargout>2
x = x.*x;
SSQ = sum(x,DIM);
- end;
- end;
- return;
-end;
+ end
+ end
+ return
+end
if (length(size(x))=3),
+ end
+ end
+ return
+ elseif (nargout>=3)
[o,count,SSQ] = sumskipnan_mex(real(x),DIM,FLAG_NANS_OCCURED,W);
if (~isreal(x))
[io,icount,iSSQ] = sumskipnan_mex(imag(x),DIM,FLAG_NANS_OCCURED,W);
@@ -155,23 +156,23 @@ try
else
o = o+i*io;
SSQ = SSQ+iSSQ;
- end;
- end;
- return;
- end;
-end;
+ end
+ end
+ return
+ end
+end
if ~isempty(W)
error('weighted sumskipnan requires sumskipnan_mex');
-end;
+end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% count non-NaN's
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-if nargout>1,
+if nargout>1
count = sum(x==x,DIM);
FLAG_NANS_OCCURED = any(count(:)2,
+if nargout>2
x = real(x).^2 + imag(x).^2;
SSQ = sum(x,DIM);
-end;
+end
%!assert(sumskipnan([1,2],1),[1,2])
%!assert(sumskipnan([1,NaN],2),1)
%!assert(sumskipnan([1,NaN],2),1)
%!assert(sumskipnan([nan,1,4,5]),10)
%!assert(sumskipnan([nan,1,4,5]',1,[3;2;1;0]),6)
-
-
-
diff --git a/matlab/missing/corrcoef/tcdf.m b/matlab/missing/corrcoef/tcdf.m
index b3827862a..8d76f7657 100644
--- a/matlab/missing/corrcoef/tcdf.m
+++ b/matlab/missing/corrcoef/tcdf.m
@@ -12,8 +12,10 @@ function p = tcdf(x,n)
% Reference(s):
% $Id: tcdf.m 9033 2011-11-08 20:58:07Z schloegl $
-% Copyright (C) 2000-2003,2009 by Alois Schloegl
-% Copyright (C) 2014 Dynare Team
+
+% Copyright (C) 2000-2003,2009 by Alois Schloegl
+% Copyright (C) 2014-2017 Dynare Team
+%
% This is part of the NaN-toolbox. For more details see
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
@@ -37,10 +39,10 @@ if all(size(x)==1)
elseif all(size(n)==1)
n = repmat(n,size(x));
elseif all(size(x)==size(n))
- ; %% OK, do nothing
+ % OK, do nothing
else
error('size of input arguments must be equal or scalar')
-end;
+end
% allocate memory
p = zeros(size(x));
diff --git a/matlab/missing/ilu/ilu.m b/matlab/missing/ilu/ilu.m
index 0b8f8df73..6e53e59df 100644
--- a/matlab/missing/ilu/ilu.m
+++ b/matlab/missing/ilu/ilu.m
@@ -1,7 +1,7 @@
function [L, U, P] = ilu(A, setup)
% Partially implement function ilu using the (now deprecated) luinc
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/issquare/issquare.m b/matlab/missing/issquare/issquare.m
index dfbfe8925..0b28884a0 100644
--- a/matlab/missing/issquare/issquare.m
+++ b/matlab/missing/issquare/issquare.m
@@ -27,7 +27,7 @@ function i = issquare(A)
%! @end deftypefn
%@eod:
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/ordeig/ordeig.m b/matlab/missing/ordeig/ordeig.m
index 6004fd86f..e7ddfd744 100644
--- a/matlab/missing/ordeig/ordeig.m
+++ b/matlab/missing/ordeig/ordeig.m
@@ -11,7 +11,7 @@ function eigs = ordeig(t)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,7 +34,7 @@ i = 1;
while i <= n
if i == n
eigs(n) = t(n,n);
- break;
+ break
elseif t(i+1,i) == 0
eigs(i) = t(i,i);
i = i+1;
diff --git a/matlab/missing/stats/betacdf.m b/matlab/missing/stats/betacdf.m
index 2ba7cc53e..d1ac509f7 100644
--- a/matlab/missing/stats/betacdf.m
+++ b/matlab/missing/stats/betacdf.m
@@ -10,7 +10,7 @@ function cdf = betacdf (x, a, b)
% Original author: KH
% Copyright (C) 1995, 1996, 1997, 2005, 2006, 2007 Kurt Hornik
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -61,4 +61,3 @@ if (any (k))
end
end
-
diff --git a/matlab/missing/stats/betainv.m b/matlab/missing/stats/betainv.m
index 8273fc356..a7300d1b1 100644
--- a/matlab/missing/stats/betainv.m
+++ b/matlab/missing/stats/betainv.m
@@ -84,7 +84,7 @@ if (any (k))
end
h = y_old - y_new;
if (max (abs (h)) < sqrt (eps))
- break;
+ break
end
y_old = y_new;
end
diff --git a/matlab/missing/stats/betarnd.m b/matlab/missing/stats/betarnd.m
index f27fca441..a2d0c9fe8 100644
--- a/matlab/missing/stats/betarnd.m
+++ b/matlab/missing/stats/betarnd.m
@@ -1,19 +1,19 @@
function rnd = betarnd(a, b)
% This function produces independent random variates from the Beta distribution.
%
-% INPUTS
+% INPUTS
% a [double] n*1 vector of positive parameters.
% b [double] n*1 vector of positive parameters.
%
-% OUTPUT
+% OUTPUT
% rnd [double] n*1 vector of independent variates from the beta(a,b) distribution.
-% rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and
-% variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1).
-%
-% ALGORITHMS
+% rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and
+% variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1).
+%
+% ALGORITHMS
% Described and Devroye (1986, chapter 9).
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/stats/corr.m b/matlab/missing/stats/corr.m
index c862e1e67..ec2f719a1 100644
--- a/matlab/missing/stats/corr.m
+++ b/matlab/missing/stats/corr.m
@@ -25,7 +25,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*--
%! the correlation between the columns of @var{x}.
%! @end deftypefn
%@eod:
-%
+%
% Notes: - the original Octave code has been rewritten to avoid calling cov, since
% there is a long-standing incompatiblity between Matlab's cov and Octave's cov
% (see https://savannah.gnu.org/bugs/?40751)
@@ -39,7 +39,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*--
% Copyright (C) 1993-1996 Kurt Hornik
% Copyright (C) 1996-2015 John W. Eaton
% Copyright (C) 2013-2015 Julien Bect
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -82,14 +82,14 @@ if isscalar(x)
if nargin==1
retval = NaN;
else
- retval = NaN(size(y));
+ retval = NaN(size(y));
end
- return;
+ return
end
if nargin==2 && isscalar(y)
- retval = NaN(size(x'));
- return;
+ retval = NaN(size(x'));
+ return
end
n = size (x, 1);
diff --git a/matlab/missing/stats/exprnd.m b/matlab/missing/stats/exprnd.m
index 65855db6e..b59daf904 100644
--- a/matlab/missing/stats/exprnd.m
+++ b/matlab/missing/stats/exprnd.m
@@ -2,22 +2,22 @@ function rnd = exprnd(a)
% Random samples from the exponential distribution with expectation a
% and variance a^2.
%
-% INPUTS
+% INPUTS
% a [double] m*n matrix of positive parameters
%
-% OUTPUT
+% OUTPUT
% rnd [double] m*n matrix, independent draws from the exponential
-% distribution rnd(j,j) has expectation a(i,j) and
-% variance a(i,j)^2.
+% distribution rnd(j,j) has expectation a(i,j) and
+% variance a(i,j)^2.
%
-% ALGORITHM
+% ALGORITHM
% Inverse transform sampling.
%
% SPECIAL REQUIREMENTS
% None.
-%
+%
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/stats/gaminv.m b/matlab/missing/stats/gaminv.m
index e879616c4..96c4a0a3f 100644
--- a/matlab/missing/stats/gaminv.m
+++ b/matlab/missing/stats/gaminv.m
@@ -76,7 +76,7 @@ if (any (k))
h = y_old - y_new;
end
if (max (abs (h)) < sqrt (eps))
- break;
+ break
end
y_old = y_new;
end
diff --git a/matlab/missing/stats/gamrnd.m b/matlab/missing/stats/gamrnd.m
index b75b7868f..af2124753 100644
--- a/matlab/missing/stats/gamrnd.m
+++ b/matlab/missing/stats/gamrnd.m
@@ -1,19 +1,19 @@
function rnd = gamrnd(a,b,method)
% This function produces independent random variates from the Gamma distribution.
%
-% INPUTS
+% INPUTS
% a [double] n*1 vector of positive parameters.
-% b [double] n*1 vector of positive parameters.
+% b [double] n*1 vector of positive parameters.
% method [string] 'BawensLubranoRichard' or anything else (see below).
%
-% OUTPUT
+% OUTPUT
% rnd [double] n*1 vector of independent variates from the gamma(a,b) distribution.
% rnd(i) is gamma distributed with mean a(i)b(i) and variance a(i)b(i)^2.
-%
-% ALGORITHMS
+%
+% ALGORITHMS
% Described in Bauwens, Lubrano and Richard (1999, page 316) and Devroye (1986, chapter 9).
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -39,13 +39,13 @@ if nargin==2
if any(a<1)
method = 'Devroye';
Devroye.small = 'Best'; % 'Weibull' , 'Johnk' , 'Berman' , 'GS' , 'Best'
- % REMARK: The first algorithm (Weibull) is producing too much extreme values.
+ % REMARK: The first algorithm (Weibull) is producing too much extreme values.
end
if ~strcmpi(method,'BauwensLubranoRichard')
- Devroye.big = 'Best'; % 'Cheng' , 'Best'
+ Devroye.big = 'Best'; % 'Cheng' , 'Best'
% REMARK 1: The first algorithm (Cheng) is still producing obviously wrong simulations.
- % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens,
- % Lubrano and Richard, but the comparison depends on the value of a (this should be
+ % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens,
+ % Lubrano and Richard, but the comparison depends on the value of a (this should be
% investigated further).
end
else
@@ -96,7 +96,7 @@ if number_of_double_a
if strcmpi(method,'BauwensLubranoRichard')
% Algorithm given in Bauwens, Lubrano & Richard (1999) page 316.
rnd(double_idx) = knuth_algorithm(a(double_idx),b(double_idx));
- else% Algorithm given in Devroye (1986, chapter 9)
+ else% Algorithm given in Devroye (1986, chapter 9)
small_idx = find(a(double_idx)<1);
big_idx = find(a(double_idx)>1);
number_of_small_a = length(small_idx);
@@ -180,7 +180,7 @@ end
gamma_variates = exprnd(ones(nn,1)).*X./(X+Y);
-function gamma_variates = berman_algorithm(a,b)
+function gamma_variates = berman_algorithm(a,b)
nn = length(a);
mm = nn;
aa = 1./a ;
@@ -206,7 +206,7 @@ Z = gamrnd(2*ones(nn,1),ones(nn,1));
gamma_variates = Z.*X.*b ;
-function gamma_variates = ahrens_dieter_algorithm(a,b)
+function gamma_variates = ahrens_dieter_algorithm(a,b)
nn = length(a);
mm = nn;
bb = (exp(1)+a)/exp(1);
@@ -246,7 +246,7 @@ end
gamma_variates = X.*b ;
-function gamma_variates = best_1983_algorithm(a,b)
+function gamma_variates = best_1983_algorithm(a,b)
nn = length(a);
mm = nn;
tt = .07 + .75*sqrt(1-a);
diff --git a/matlab/missing/stats/quantile.m b/matlab/missing/stats/quantile.m
index 54c77c3f9..a63baada0 100644
--- a/matlab/missing/stats/quantile.m
+++ b/matlab/missing/stats/quantile.m
@@ -8,18 +8,18 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
% a matrix, the i-th row of Q contains the P(i)-th quantiles of each
% column of X. For N-D arrays, QUANTILE2 operates along the first
% non-singleton dimension.
-%
+%
% Q = QUANTILE2(X,P,DIM) calculates quantiles along dimension DIM. The
% DIM'th dimension of Q has length LENGTH(P).
-%
+%
% Q = QUANTILE2(X,P,DIM,METHOD) calculates quantiles using one of the
% methods described in http://en.wikipedia.org/wiki/Quantile. The method
% are designated 'R-1'...'R-9'; the default is R-8 as described in
% http://bit.ly/1kX4NcT, whereas Matlab uses 'R-5'.
-%
+%
% Q = QUANTILE2(X,P,[],METHOD) uses the specified METHOD, but calculates
% quantiles along the first non-singleton dimension.
-%
+%
% Q = QUANTILE2(X,P,[],METHOD,WEIGHTS) and QUANTILE2(X,P,[],[],WEIGHTS)
% uses the array WEIGHTS to weight the values in X when calculating
% quantiles. If no weighting is specified, the method determines the
@@ -33,12 +33,12 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
% equal, then the weighted and unweighted index (and correpsonding
% quantile) are identical. The default method R-8 is used if METHOD is
% specified as an empty array ([]).
-%
+%
% [Q,N] = QUANTILE2(...) returns an array that is the same size as Q such
% that N(i) is the number of points used to calculate Q(i).
-%
+%
% Further reading
-%
+%
% Hyndman, R.J.; Fan, Y. (November 1996). "Sample Quantiles in
% Statistical Packages". The American Statistician 50 (4): 361-365.
% Frigge, Michael; Hoaglin, David C.; Iglewicz, Boris (February 1989).
@@ -47,9 +47,9 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
% Original file downloaded from:
% http://fr.mathworks.com/matlabcentral/fileexchange/46555-quantile-calculation
-%
-% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone)
-% Copyright (C) 2016 Dynare Team
+%
+% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone)
+% Copyright (C) 2016-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/stats/stdnormal_inv.m b/matlab/missing/stats/stdnormal_inv.m
index bc52845a5..9859efde7 100644
--- a/matlab/missing/stats/stdnormal_inv.m
+++ b/matlab/missing/stats/stdnormal_inv.m
@@ -10,7 +10,7 @@ function inv = stdnormal_inv (x)
% Copyright (C) 1995, 1996, 1997, 1998, 2000, 2002, 2005, 2006, 2007
% Kurt Hornik
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,4 +34,3 @@ end
inv = sqrt (2) * erfinv (2 * x - 1);
end
-
diff --git a/matlab/missing/stats/wblcdf.m b/matlab/missing/stats/wblcdf.m
index 14b0fc8e8..6246a01cf 100644
--- a/matlab/missing/stats/wblcdf.m
+++ b/matlab/missing/stats/wblcdf.m
@@ -2,15 +2,15 @@ function p = wblcdf(x, scale, shape) % --*-- Unitary tests --*--
% Cumulative distribution function for the Weibull distribution.
%
-% INPUTS
+% INPUTS
% - x [double] Positive real scalar.
% - scale [double] Positive hyperparameter.
% - shape [double] Positive hyperparameter.
%
-% OUTPUTS
-% - p [double] Positive scalar between
+% OUTPUTS
+% - p [double] Positive scalar between
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -58,7 +58,7 @@ if isinf(x)
return
end
-% Evaluate the CDF.
+% Evaluate the CDF.
p = 1-exp(-(x/scale)^shape);
@@ -146,4 +146,3 @@ p = 1-exp(-(x/scale)^shape);
%$ end
%$ T = all(t);
%@eof:4
-
diff --git a/matlab/missing/stats/wblinv.m b/matlab/missing/stats/wblinv.m
index 1b87c9fcb..363d51801 100644
--- a/matlab/missing/stats/wblinv.m
+++ b/matlab/missing/stats/wblinv.m
@@ -2,15 +2,15 @@ function t = wblinv(proba, scale, shape) % --*-- Unitary tests --*--
% Inverse cumulative distribution function.
%
-% INPUTS
+% INPUTS
% - proba [double] Probability, scalar between 0 and 1.
% - scale [double] Positive hyperparameter.
% - shape [double] Positive hyperparameter.
%
-% OUTPUTS
+% OUTPUTS
% - t [double] scalar such that P(X<=t)=proba
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -156,7 +156,7 @@ t = exp(log(scale)+log(-log(1-proba))/shape);
%$ [s, abs(p-s)]
%$ end
%$ if isoctave
-%$ t(k) = abs(p-s)<1e-10;
+%$ t(k) = abs(p-s)<1e-10;
%$ else
%$ t(k) = abs(p-s)<1e-12;
%$ end
@@ -165,4 +165,3 @@ t = exp(log(scale)+log(-log(1-proba))/shape);
%$ end
%$ T = all(t);
%@eof:4
-
diff --git a/matlab/missing/stats/wblrnd.m b/matlab/missing/stats/wblrnd.m
index 2f55bc8b7..e2a6911d9 100644
--- a/matlab/missing/stats/wblrnd.m
+++ b/matlab/missing/stats/wblrnd.m
@@ -1,14 +1,14 @@
function rnd = wblrnd(a, b)
% This function produces independent random variates from the Weibull distribution.
%
-% INPUTS
+% INPUTS
% a [double] m*n matrix of positive parameters (scale).
% b [double] m*n matrix of positive parameters (shape).
%
-% OUTPUT
+% OUTPUT
% rnd [double] m*n matrix of independent variates from the beta(a,b) distribution.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing/struct2array/struct2array.m b/matlab/missing/struct2array/struct2array.m
index b1c1370dd..92aaab35f 100644
--- a/matlab/missing/struct2array/struct2array.m
+++ b/matlab/missing/struct2array/struct2array.m
@@ -1,9 +1,9 @@
function a = struct2array(s)
-% INPUTS
+% INPUTS
% - s [struct] with N fields, field i contains a n_i*m_i array of doubles.
%
-% OUPUTS
+% OUPUTS
% - a [double] column vector with sum(n_i*m_i, i=1,...,N) elements.
% Copyright (C) 2017 Dynare Team
diff --git a/matlab/missing/vec/vec.m b/matlab/missing/vec/vec.m
index 225c5f9ec..fd9e36b79 100644
--- a/matlab/missing/vec/vec.m
+++ b/matlab/missing/vec/vec.m
@@ -1,13 +1,13 @@
function Vector = vec(Matrix)
% This function implements the vec operator.
-%
-% INPUTS
+%
+% INPUTS
% Matrix [double] a squared n*n matrix.
-%
-% OUTPUTS
+%
+% OUTPUTS
% Vector [double] a n*n vector.
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
index 6595daf67..5ba614f94 100644
--- a/matlab/missing_DiffuseKalmanSmootherH1_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
@@ -5,10 +5,10 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
%
% INPUTS
% T: mm*mm matrix
-% Z: pp*mm matrix
+% Z: pp*mm matrix
% R: mm*rr matrix
% Q: rr*rr matrix
-% H: pp*pp matrix variance of measurement errors
+% H: pp*pp matrix variance of measurement errors
% Pinf1: mm*mm diagonal matrix with with q ones and m-q zeros
% Pstar1: mm*mm variance-covariance matrix with stationary variables
% Y: pp*1 vector
@@ -22,7 +22,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
% decomp_flag if true, compute filter decomposition
% state_uncertainty_flag if true, compute uncertainty about smoothed
% state estimate
-%
+%
% OUTPUTS
% alphahat: smoothed variables (a_{t|T})
% epsilonhat:smoothed measurement errors
@@ -36,20 +36,20 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
% matrices (meaningless for periods 1:d)
% decomp: decomposition of the effect of shocks on filtered values
% V: 3D array of state uncertainty matrices
-%
+%
% Notes:
% Outputs are stored in decision-rule order, i.e. to get variables in order of declaration
% as in M_.endo_names, ones needs code along the lines of:
% variables_declaration_order(dr.order_var,:) = alphahat
-%
+%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
-% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
-% Analysis, vol. 24(1), pp. 85-98).
+% Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
+% Analysis, vol. 24(1), pp. 85-98).
% Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 5
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -70,7 +70,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
% new output argument aK (1-step to k-step predictions)
% new options_.nk: the max step ahed prediction in aK (default is 4)
% new crit1 value for rank of Pinf
-% it is assured that P is symmetric
+% it is assured that P is symmetric
d = 0;
decomp = [];
@@ -92,9 +92,9 @@ Lstar = zeros(mm,mm,smpl);
Kstar = zeros(mm,pp,smpl);
Kinf = zeros(mm,pp,smpl);
P = zeros(mm,mm,smpl+1);
-Pstar = zeros(spstar(1),spstar(2),smpl+1);
+Pstar = zeros(spstar(1),spstar(2),smpl+1);
Pstar(:,:,1) = Pstar1;
-Pinf = zeros(spinf(1),spinf(2),smpl+1);
+Pinf = zeros(spinf(1),spinf(2),smpl+1);
Pinf(:,:,1) = Pinf1;
rr = size(Q,1);
QQ = R*Q*transpose(R);
@@ -127,7 +127,7 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && td+1
end
if d %diffuse periods
% initialize r_d^(0) and r_d^(1) as below DK (2012), eq. 5.23
- r0 = zeros(mm,d+1);
+ r0 = zeros(mm,d+1);
r0(:,d+1) = r(:,d+1); %set r0_{d}, i.e. shifted by one period
r1 = zeros(mm,d+1); %set r1_{d}, i.e. shifted by one period
if state_uncertainty_flag
diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
index 665f28532..de40741fc 100644
--- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
@@ -43,20 +43,20 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman
% variables_declaration_order(dr.order_var,:) = alphahat
%
% Algorithm:
-%
+%
% Uses the univariate filter as described in Durbin/Koopman (2012): "Time
% Series Analysis by State Space Methods", Oxford University Press,
% Second Edition, Ch. 6.4 + 7.2.5
-% and
+% and
% Koopman/Durbin (2000): "Fast Filtering and Smoothing for Multivariatze State Space
% Models", in Journal of Time Series Analysis, vol. 21(3), pp. 281-296.
%
% SPECIAL REQUIREMENTS
% See "Filtering and Smoothing of State Vector for Diffuse State Space
-% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
-% Analysis, vol. 24(1), pp. 85-98.
+% Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+% Analysis, vol. 24(1), pp. 85-98.
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -78,7 +78,7 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman
% New input argument nk: max order of predictions in aK
-if size(H,2)>1
+if size(H,2)>1
error('missing_DiffuseKalmanSmootherH3_Z:: H is not a vector. This must not happens')
end
@@ -100,9 +100,9 @@ Kinf = zeros(spstar(1),pp,smpl);
P = zeros(mm,mm,smpl+1);
P1 = P;
PK = zeros(nk,mm,mm,smpl+nk);
-Pstar = zeros(spstar(1),spstar(2),smpl);
+Pstar = zeros(spstar(1),spstar(2),smpl);
Pstar(:,:,1) = Pstar1;
-Pinf = zeros(spinf(1),spinf(2),smpl);
+Pinf = zeros(spinf(1),spinf(2),smpl);
Pinf(:,:,1) = Pinf1;
Pstar1 = Pstar;
Pinf1 = Pinf;
@@ -135,13 +135,13 @@ while newRank && t < smpl
di = data_index{t}';
for i=di
Zi = Z(i,:);
- v(i,t) = Y(i,t)-Zi*a(:,t); % nu_{t,i} in 6.13 in DK (2012)
+ v(i,t) = Y(i,t)-Zi*a(:,t); % nu_{t,i} in 6.13 in DK (2012)
Fstar(i,t) = Zi*Pstar(:,:,t)*Zi' +H(i); % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal
Finf(i,t) = Zi*Pinf(:,:,t)*Zi'; % F_{\infty,t} in 5.7 in DK (2012)
Kstar(:,i,t) = Pstar(:,:,t)*Zi'; % KD (2000), eq. (15)
if Finf(i,t) > diffuse_kalman_tol && newRank % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i}
icc=icc+1;
- Kinf(:,i,t) = Pinf(:,:,t)*Zi'; % KD (2000), eq. (15)
+ Kinf(:,i,t) = Pinf(:,:,t)*Zi'; % KD (2000), eq. (15)
Kinf_Finf = Kinf(:,i,t)/Finf(i,t);
a(:,t) = a(:,t) + Kinf_Finf*v(i,t); % KD (2000), eq. (16)
Pstar(:,:,t) = Pstar(:,:,t) + ...
@@ -149,14 +149,14 @@ while newRank && t < smpl
Kstar(:,i,t)*Kinf_Finf' - ...
Kinf_Finf*Kstar(:,i,t)'; % KD (2000), eq. (16)
Pinf(:,:,t) = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); % KD (2000), eq. (16)
- elseif Fstar(i,t) > kalman_tol
+ elseif Fstar(i,t) > kalman_tol
a(:,t) = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t); % KD (2000), eq. (17)
Pstar(:,:,t) = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t); % KD (2000), eq. (17)
% Pinf is passed through unaltered, see eq. (17) of
% Koopman/Durbin (2000)
else
% do nothing as a_{t,i+1}=a_{t,i} and P_{t,i+1}=P_{t,i}, see
- % p. 157, DK (2012)
+ % p. 157, DK (2012)
end
end
if newRank
@@ -164,12 +164,12 @@ while newRank && t < smpl
oldRank = rank(Z*Pinf(:,:,t)*Z',diffuse_kalman_tol);
else
oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol);
- end
+ end
else
oldRank = 0;
end
a1(:,t+1) = T*a(:,t);
- aK(1,:,t+1) = a1(:,t+1);
+ aK(1,:,t+1) = a1(:,t+1);
for jnk=2:nk
aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));
end
@@ -183,7 +183,7 @@ while newRank && t < smpl
end
end
if oldRank ~= newRank
- disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')
+ disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')
end
end
@@ -206,7 +206,7 @@ while notsteady && t kalman_tol
a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t); %filtering according to (6.13) in DK (2012)
@@ -216,17 +216,17 @@ while notsteady && t1
- aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));
+ aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));
end
end
- P(:,:,t+1) = T*P(:,:,t)*T' + QQ; %transition according to (6.14) in DK (2012)
+ P(:,:,t+1) = T*P(:,:,t)*T' + QQ; %transition according to (6.14) in DK (2012)
% notsteady = ~(max(max(abs(P(:,:,t+1)-P(:,:,t)))) d+1
end
end
end
- r(:,t) = ri; % DK (2012), below 6.15, r_{t-1}=r_{t,0}
+ r(:,t) = ri; % DK (2012), below 6.15, r_{t-1}=r_{t,0}
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
etahat(:,t) = QRt*r(:,t);
- ri = T'*ri; % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}}
+ ri = T'*ri; % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}}
if state_uncertainty_flag
- N(:,:,t) = Ni; % DK (2012), below 6.15, N_{t-1}=N_{t,0}
+ N(:,:,t) = Ni; % DK (2012), below 6.15, N_{t-1}=N_{t,0}
V(:,:,t) = P1(:,:,t)-P1(:,:,t)*N(:,:,t)*P1(:,:,t); % KD (2000), eq. (7) with N_{t-1} stored in N(:,:,t)
- Ni = T'*Ni*T; % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}}
+ Ni = T'*Ni*T; % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}}
end
end
if d
- r0 = zeros(mm,d);
+ r0 = zeros(mm,d);
r0(:,d) = ri;
r1 = zeros(mm,d);
if state_uncertainty_flag
@@ -304,10 +304,10 @@ if d
di = flipud(data_index{t})';
for i = di
if Finf(i,t) > diffuse_kalman_tol
- % recursions need to be from highest to lowest term in order to not
+ % recursions need to be from highest to lowest term in order to not
% overwrite lower terms still needed in this step
Linf = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
- L0 = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t);
+ L0 = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t);
r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
L0'*r0(:,t) + ...
Linf'*r1(:,t); % KD (2000), eq. (25) for r_1
@@ -362,11 +362,11 @@ if decomp_flag
ri_d = Z(i,:)'/Fi(i,t)*v(i,t)+ri_d-Ki(:,i,t)'*ri_d/Fi(i,t)*Z(i,:)';
end
end
-
+
% calculate eta_tm1t
eta_tm1t = QRt*ri_d;
% calculate decomposition
- Ttok = eye(mm,mm);
+ Ttok = eye(mm,mm);
AAA = P1(:,:,t)*Z'*ZRQinv*Z*R;
for h = 1:nk
BBB = Ttok*AAA;
@@ -382,6 +382,6 @@ epsilonhat = Y - Z*alphahat;
if (d==smpl)
- warning(['missing_DiffuseKalmanSmootherH3_Z:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']);
+ warning(['missing_DiffuseKalmanSmootherH3_Z:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']);
return
end
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index bd003bd8e..2df26ff0c 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -58,13 +58,13 @@ function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Mo
% along with Dynare. If not, see .
TeX = DynareOptions.TeX;
-if ~isempty(hessian_mat);
+if ~isempty(hessian_mat)
[ s_min, k ] = min(diag(hessian_mat));
end
fval = feval(fun,x,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
-if ~isempty(hessian_mat);
+if ~isempty(hessian_mat)
skipline()
disp('MODE CHECK')
skipline()
@@ -85,13 +85,13 @@ if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
end
ll = DynareOptions.mode_check.neighbourhood_size;
-if isinf(ll),
+if isinf(ll)
DynareOptions.mode_check.symmetric_plots = 0;
end
mcheck = struct('cross',struct(),'emode',struct());
-for plt = 1:nbplt,
+for plt = 1:nbplt
if TeX
NAMES = [];
TeXNAMES = [];
@@ -121,7 +121,7 @@ for plt = 1:nbplt,
elseif isequal(x(kk),BoundsInfo.ub(kk))
binding_upper_bound=1;
bound_value=BoundsInfo.ub(kk);
- end
+ end
if DynareOptions.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
if l2<(1+ll)*x(kk) %test whether upper bound is too small due to prior binding
l1 = x(kk) - (l2-x(kk)); %adjust lower bound to become closer
@@ -134,7 +134,7 @@ for plt = 1:nbplt,
z1 = l1:((x(kk)-l1)/(DynareOptions.mode_check.number_of_points/2)):x(kk);
z2 = x(kk):((l2-x(kk))/(DynareOptions.mode_check.number_of_points/2)):l2;
z = union(z1,z2);
- if DynareOptions.mode_check.nolik==0,
+ if DynareOptions.mode_check.nolik==0
y = zeros(length(z),2);
dy = priordens(xx,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
end
@@ -174,7 +174,7 @@ for plt = 1:nbplt,
hold off
drawnow
end
- if DynareOptions.mode_check.nolik==0,
+ if DynareOptions.mode_check.nolik==0
if isoctave
axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'),
else
diff --git a/matlab/model_comparison.m b/matlab/model_comparison.m
index fd179b454..07935af6f 100644
--- a/matlab/model_comparison.m
+++ b/matlab/model_comparison.m
@@ -5,9 +5,9 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
%
% INPUTS
% ModelNames [string] m*1 cell array of string.
-% ModelPriors [double] m*1 vector of prior probabilities
+% ModelPriors [double] m*1 vector of prior probabilities
% oo [struct] Dynare results structure
-% options_ [struct] Dynare options structure
+% options_ [struct] Dynare options structure
% fname [string] name of the current mod-file
%
% OUTPUTS
@@ -20,7 +20,7 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -61,14 +61,14 @@ if isfield(options_,'mc_marginal_density')
type = options_.mc_marginal_density;
if strcmp(type,'laplace') || strcmp(type,'Laplace')
type = 'LaplaceApproximation';
- title = 'Model Comparison (based on Laplace approximation)';
- elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean')
+ title = 'Model Comparison (based on Laplace approximation)';
+ elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean')
type = 'ModifiedHarmonicMean';
- title = 'Model Comparison (based on Modified Harmonic Mean Estimator)';
+ title = 'Model Comparison (based on Modified Harmonic Mean Estimator)';
end
else
type = 'LaplaceApproximation';
- title = 'Model Comparison (based on Laplace approximation)';
+ title = 'Model Comparison (based on Laplace approximation)';
end
% Get the estimated logged marginal densities.
@@ -87,7 +87,7 @@ for i=1:NumberOfModels
end
end
try
- eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';'])
+ eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';'])
catch
if strcmpi(type,'LaplaceApproximation')
if isfield(mstruct.oo_,'mle_mode')
@@ -119,13 +119,13 @@ if prior_flag
labels = char('Priors','Log Marginal Density','Bayes Ratio', ...
'Posterior Model Probability');
field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio', ...
- 'Posterior_Model_Probability'};
+ 'Posterior_Model_Probability'};
values = [ModelPriors';MarginalLogDensity';exp(lmpd-lmpd(1))'; ...
elmpd'/sum(elmpd)];
else
labels = char('Priors','Log Marginal Density','Bayes Ratio','Posterior Odds Ratio', ...
'Posterior Model Probability');
- field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'};
+ field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'};
values = [ModelPriors';MarginalLogDensity'; exp(MarginalLogDensity-MarginalLogDensity(1))'; ...
exp(lmpd-lmpd(1))'; elmpd'/sum(elmpd)];
end
@@ -148,7 +148,7 @@ if options_.TeX
for ii=1:size(labels,1)
labels_tex=strvcat(labels_tex,strrep(labels(ii,:),' ', '\ '));
end
-
+
dyn_latex_table(M_temp,options_,title,['model_comparison',type],headers_tex,labels_tex,values,0,16,6);
end
diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m
index 5b4b4221e..673429115 100644
--- a/matlab/model_diagnostics.m
+++ b/matlab/model_diagnostics.m
@@ -1,22 +1,22 @@
function model_diagnostics(M,options,oo)
% function model_diagnostics(M,options,oo)
-% computes various diagnostics on the model
+% computes various diagnostics on the model
% INPUTS
-% M [matlab structure] Definition of the model.
+% M [matlab structure] Definition of the model.
% options [matlab structure] Global options.
-% oo [matlab structure] Results
-%
+% oo [matlab structure] Results
+%
% OUTPUTS
% none
-%
+%
% ALGORITHM
% ...
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
+%
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -67,7 +67,7 @@ end
info=test_for_deep_parameters_calibration(M);
if info
problem_dummy=1;
-end;
+end
% check if ys is steady state
options.debug=1; %locally set debug option to 1
@@ -83,7 +83,7 @@ if check1(1)
if any(isinf(dr.ys))
disp(['MODEL_DIAGNOSTICS: Steady state contains Inf'])
end
- return;
+ return
end
if ~isreal(dr.ys)
@@ -174,7 +174,7 @@ for b=1:nb
end
end
-if singularity_problem
+if singularity_problem
try
options_check=options;
options_check.noprint=1;
@@ -210,7 +210,7 @@ if ~options.block
else
[junk,jacobia_] = feval([M.fname '_dynamic'],z(iyr0),exo_simul, ...
M.params, dr.ys, it_);
- end;
+ end
elseif options.order >= 2
if (options.bytecode)
[chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
@@ -220,14 +220,14 @@ if ~options.block
[junk,jacobia_,hessian1] = feval([M.fname '_dynamic'],z(iyr0),...
exo_simul, ...
M.params, dr.ys, it_);
- end;
+ end
if options.use_dll
% In USE_DLL mode, the hessian is in the 3-column sparse representation
hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2));
end
end
-
+
if any(any(isinf(jacobia_) | isnan(jacobia_)))
problem_dummy=1;
[infrow,infcol]=find(isinf(jacobia_) | isnan(jacobia_));
@@ -245,7 +245,7 @@ if ~options.block
problem_dummy=1;
fprintf('\nMODEL_DIAGNOSTICS: The Hessian of the dynamic model contains Inf or NaN.\n')
end
- end
+ end
else
fprintf('\nMODEL_DIAGNOSTICS: This command currently does not support the block option for checking.\n')
fprintf('\nMODEL_DIAGNOSTICS: the dynamic model. You may want to disable it for doing model_diagnostics. Skipping this part.\n')
@@ -254,4 +254,3 @@ end
if problem_dummy==0
fprintf('MODEL_DIAGNOSTICS: No obvious problems with this mod-file were detected.\n')
end
-
diff --git a/matlab/model_info.m b/matlab/model_info.m
index 281bfa09a..e27779225 100644
--- a/matlab/model_info.m
+++ b/matlab/model_info.m
@@ -1,7 +1,7 @@
-function model_info(varargin);
+function model_info(varargin)
%function model_info;
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -23,12 +23,12 @@ if sum(strcmp(varargin,'static')) > 0
static_ = 1;
else
static_ = 0;
-end;
+end
if sum(strcmp(varargin,'incidence')) > 0
incidence = 1;
else
incidence = 0;
-end;
+end
if static_
fprintf(' Informations about %s (static model)\n',M_.fname);
block_structre_str = 'block_structure_stat';
@@ -37,13 +37,13 @@ else
fprintf(' Informations about %s (dynamic model)\n',M_.fname);
block_structre_str = 'block_structure';
nb_leadlag = 3;
-end;
+end
if(isfield(M_,block_structre_str))
if static_
block_structure = M_.block_structure_stat;
else
block_structure = M_.block_structure;
- end;
+ end
fprintf(strcat(' ===================',char(ones(1,length(M_.fname))*'='),'\n\n'));
nb_blocks=length(block_structure.block);
fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks);
@@ -54,15 +54,15 @@ if(isfield(M_,block_structre_str))
size_block=length(block_structure.block(i).equation);
if(i>1)
fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n');
- end;
+ end
for j=1:size_block
if(j==1)
fprintf('| %10d | %10d | %30s | %14d | %-6d %24s |\n',i,size_block,Sym_type(block_structure.block(i).Simulation_Type),block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
else
fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
- end;
- end;
- end;
+ end
+ end
+ end
fprintf('===============================================================================================================\n');
fprintf('\n');
if static_
@@ -71,16 +71,16 @@ if(isfield(M_,block_structre_str))
IM=sortrows(block_structure.incidence.sparse_IM,2);
else
IM=[];
- end;
+ end
size_IM=size(IM,1);
last=99999999;
for i=1:size_IM
if(last~=IM(i,2))
fprintf('\n%-30s',M_.endo_names(IM(i,2),:));
- end;
+ end
fprintf(' %5d',IM(i,1));
last=IM(i,2);
- end;
+ end
fprintf('\n\n');
else
for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1
@@ -90,25 +90,25 @@ if(isfield(M_,block_structre_str))
fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k);
else
fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1));
- end;
+ end
if(size(block_structure.incidence(k).sparse_IM,1)>0)
IM=sortrows(block_structure.incidence(k).sparse_IM,2);
else
IM=[];
- end;
+ end
size_IM=size(IM,1);
last=99999999;
for i=1:size_IM
if(last~=IM(i,2))
fprintf('\n%-30s',M_.endo_names(IM(i,2),:));
- end;
+ end
fprintf(' %5d',IM(i,1));
last=IM(i,2);
- end;
+ end
fprintf('\n\n');
- end;
- end;
-
+ end
+ end
+
%printing the gross incidence matrix
IM_star = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
for i = 1:nb_leadlag
@@ -118,9 +118,9 @@ if(isfield(M_,block_structre_str))
IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = 'X';
else
IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = '1';
- end;
- end;
- end;
+ end
+ end
+ end
seq = 1: M_.endo_nbr;
blank = [ blanks(size(M_.endo_names,2)); blanks(size(M_.endo_names,2))];
for i = 1:M_.endo_nbr
@@ -128,15 +128,15 @@ if(isfield(M_,block_structre_str))
var_names = [blank; M_.endo_names(i,:)];
else
var_names = [var_names; blank; M_.endo_names(i,:)];
- end;
- end;
+ end
+ end
if incidence
topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
bott = [int2str(seq') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star];
fprintf('\n Gross incidence matrix\n');
fprintf(' =======================\n');
disp([topp; bott]);
-
+
%printing the reordered incidence matrix
IM_star_reordered = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
eq(block_structure.equation_reordered) = seq;
@@ -145,9 +145,9 @@ if(isfield(M_,block_structre_str))
cur_block = 1;
for i = 1:M_.endo_nbr
past_block = cur_block;
- while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
+ while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0
cur_block = cur_block + 1;
- end;
+ end
if i == 1
var_names = [blank; M_.endo_names(block_structure.variable_reordered(i),:)];
else
@@ -156,8 +156,8 @@ if(isfield(M_,block_structre_str))
else
var_names = [var_names; blank; M_.endo_names(block_structure.variable_reordered(i),:)];
end
- end;
- end;
+ end
+ end
topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
n_state_var = length(M_.state_var);
IM_state_var = zeros(n_state_var, n_state_var);
@@ -172,49 +172,49 @@ if(isfield(M_,block_structre_str))
[tfi, loci] = ismember(block_structure.incidence(i).sparse_IM(j,1), state_equation);
if tfi
IM_state_var(loci, loc) = 1;
- end;
+ end
else
IM_star_reordered(eq(block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = '1';
- end;
- end;
- end;
+ end
+ end
+ end
fprintf('1: non nul element, X: non nul element related to a state variable\n');
-
+
cur_block = 1;
i_last = 0;
block = {};
- for i = 1:n_state_var;
+ for i = 1:n_state_var
past_block = cur_block;
- while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0;
+ while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0
cur_block = cur_block + 1;
- end;
+ end
if (past_block ~= cur_block) || (past_block == cur_block && i == n_state_var)
block(past_block).IM_state_var(1:(i - 1 - i_last), 1:i - 1) = IM_state_var(i_last+1:i - 1, 1:i - 1);
i_last = i - 1;
- end;
- end;
+ end
+ end
cur_block = 1;
for i = 1:M_.endo_nbr
past_block = cur_block;
- while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
+ while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0
cur_block = cur_block + 1;
- end;
+ end
if past_block ~= cur_block
for j = 1:i-1
IM_star_reordered(j, 3 * (i - 1) - 1) = '|';
- end;
- end;
+ end
+ end
end
-
+
bott = [int2str(block_structure.equation_reordered') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star_reordered];
fprintf('\n Reordered incidence matrix\n');
fprintf(' ==========================\n');
disp([topp; bott]);
fprintf('1: non nul element, X: non nul element related to a state variable\n');
- end;
+ end
else
fprintf('There is no block decomposition of the model.\nUse ''block'' model''s option.\n');
-end;
+end
function ret=Sym_type(type)
UNKNOWN=0;
@@ -229,33 +229,30 @@ SOLVE_TWO_BOUNDARIES_COMPLETE=8;
EVALUATE_FORWARD_R=9;
EVALUATE_BACKWARD_R=10;
switch (type)
- case (UNKNOWN),
+ case (UNKNOWN)
ret='UNKNOWN ';
- case {EVALUATE_FORWARD,EVALUATE_FORWARD_R},
+ case {EVALUATE_FORWARD,EVALUATE_FORWARD_R}
ret='EVALUATE FORWARD ';
- case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R},
+ case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R}
ret='EVALUATE BACKWARD ';
- case SOLVE_FORWARD_SIMPLE,
+ case SOLVE_FORWARD_SIMPLE
ret='SOLVE FORWARD SIMPLE ';
- case SOLVE_BACKWARD_SIMPLE,
+ case SOLVE_BACKWARD_SIMPLE
ret='SOLVE BACKWARD SIMPLE ';
- case SOLVE_TWO_BOUNDARIES_SIMPLE,
+ case SOLVE_TWO_BOUNDARIES_SIMPLE
ret='SOLVE TWO BOUNDARIES SIMPLE ';
- case SOLVE_FORWARD_COMPLETE,
+ case SOLVE_FORWARD_COMPLETE
ret='SOLVE FORWARD COMPLETE ';
- case SOLVE_BACKWARD_COMPLETE,
+ case SOLVE_BACKWARD_COMPLETE
ret='SOLVE BACKWARD COMPLETE ';
- case SOLVE_TWO_BOUNDARIES_COMPLETE,
+ case SOLVE_TWO_BOUNDARIES_COMPLETE
ret='SOLVE TWO BOUNDARIES COMPLETE';
-end;
+end
function ret = barre(n)
s = [];
-for i=1:n;
+for i=1:n
s = [s '|'];
-end;
+end
ret = s;
-
-
-
diff --git a/matlab/model_inversion.m b/matlab/model_inversion.m
index 75594ecca..4d01412f9 100644
--- a/matlab/model_inversion.m
+++ b/matlab/model_inversion.m
@@ -2,18 +2,18 @@ function [endogenousvariables, exogenousvariables] = model_inversion(constraints
exogenousvariables, ...
initialconditions, DynareModel, DynareOptions, DynareOutput)
-% INPUTS
+% INPUTS
% - constraints [dseries] with N constrained endogenous variables from t1 to t2.
% - exogenousvariables [dseries] with Q exogenous variables.
% - initialconditions [dseries] with M endogenous variables starting before t1 (M initialcond must contain at least the state variables).
% - DynareModel [struct] M_, Dynare global structure containing informations related to the model.
% - DynareOptions [struct] options_, Dynare global structure containing all the options.
%
-% OUTPUTS
-% - endogenous [dseries]
+% OUTPUTS
+% - endogenous [dseries]
% - exogenous [dseries]
%
-% REMARKS
+% REMARKS
% Copyright (C) 2017 Dynare Team
%
@@ -52,7 +52,7 @@ if ~isstruct(DynareModel)
error('model_inversion: Last input argument must be structures (M_)!')
end
-% Set range where the endogenous variables are constrained.
+% Set range where the endogenous variables are constrained.
crange = constraints.dates;
% Check that the number of instruments match the number of constrained endogenous variables.
diff --git a/matlab/modules/reporting b/matlab/modules/reporting
index af39a2c97..bc59736f5 160000
--- a/matlab/modules/reporting
+++ b/matlab/modules/reporting
@@ -1 +1 @@
-Subproject commit af39a2c97ea01de6a1451071e58d4fce8f4b9d03
+Subproject commit bc59736f5b50454cea925c99b98a757a0494f3e8
diff --git a/matlab/moment_function.m b/matlab/moment_function.m
index af0488a59..fb42db9e8 100644
--- a/matlab/moment_function.m
+++ b/matlab/moment_function.m
@@ -3,19 +3,19 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt
% ).
%
% INPUTS:
-% xparams [double] p*1 vector of estimated parameters.
+% xparams [double] p*1 vector of estimated parameters.
% sample_moments [double] n*1 vector of sample moments (n>=p).
% options [ ] Structure defining options for SMM.
% parallel [ ] Structure defining the parallel mode settings (optional).
%
-% OUTPUTS:
+% OUTPUTS:
% g [double] n*1 vector, the gap between simulated and sample moments.
% flag [intger] empty matrix.
%
% SPECIAL REQUIREMENTS
% The user has to provide a file where the moment conditions are defined.
-% Copyright (C) 2010-2012 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -30,7 +30,7 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt
% 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 .
+% along with Dynare. If not, see .
global M_ options_
persistent mainStream mainState
@@ -61,7 +61,7 @@ end
if penalty>0
flag = 0;
- return;
+ return
end
save('estimated_parameters.mat','xparams');
@@ -106,7 +106,7 @@ else% parallel mode.
end
end
for j=1:parallel(i).number_of_jobs
- if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
+ if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
job_number = job_number + 1;
unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']);
end
@@ -117,7 +117,7 @@ else% parallel mode.
eval('job1;')
tElapsedMasterJob = etime(clock, tStartMasterJob);
TimeLimit = tElapsedMasterJob*1.2;
- % Master waits for the slaves' output...
+ % Master waits for the slaves' output...
tStart = clock;
tElapsed = 0;
while tElapsed 0 && options_.noprint == 0
for i=1:length(varlist)
k = strmatch(varlist{i},M_.endo_names(dr.order_var,:),'exact');
headers = char(headers,varlist{i});
-
+
res_table(1:nm_nbr,i) = M1(k,:)';
res_table(nm_nbr+(1:nm_nbr),i) = M2(k,:)';
res_table(2*nm_nbr+(1:M_.exo_nbr),i) = M3(k,:)';
res_table(2*nm_nbr+M_.exo_nbr+(1:M_.exo_nbr),i) = M4(k,:)';
end
-
+
my_title='ELIMINATION OF THE MULTIPLIERS';
lab = nstates(nil,:);
labels = strcat(deblank(lab(i,:)),'(-1)');
diff --git a/matlab/multivariate_sample_autocovariance.m b/matlab/multivariate_sample_autocovariance.m
index 6bc0ea32e..40af07015 100644
--- a/matlab/multivariate_sample_autocovariance.m
+++ b/matlab/multivariate_sample_autocovariance.m
@@ -1,17 +1,17 @@
function autocov = multivariate_sample_autocovariance(data,q)
% Computes the autocovariance function of multivariate time series.
-%
%
-% INPUTS
+%
+% INPUTS
% data [double] T*m matrix of data.
-% q [integer] Order of the autocovariance function.
-%
-% OUTPUTS
+% q [integer] Order of the autocovariance function.
+%
+% OUTPUTS
% autocov [double] m*m*(q+1) array, autocovariance function.
%
% SPECIAL REQUIREMENTS
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/myboxplot.m b/matlab/myboxplot.m
index fc54607e2..b3490a4b3 100644
--- a/matlab/myboxplot.m
+++ b/matlab/myboxplot.m
@@ -4,7 +4,7 @@ function sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
% sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
%
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,7 +33,7 @@ if notched==1, notched=0.25; end
a=1-notched;
% ## figure out how many data sets we have
-if iscell(data),
+if iscell(data)
nc = length(data);
else
% if isvector(data), data = data(:); end
@@ -133,7 +133,7 @@ whisker_x(:,[chop,chop+nc]) = [];
whisker_y(:,[chop,chop+nc]) = [];
median_x(:,chop) = [];
median_y(:,chop) = [];
-% % % %
+% % % %
% ## Add caps to the remaining whiskers
cap_x = whisker_x;
cap_x(1,:) =cap_x(1,:)- 0.05;
@@ -144,12 +144,12 @@ cap_y = whisker_y([1,1],:);
% #whisker_x,whisker_y
% #median_x,median_y
% #cap_x,cap_y
-%
+%
% ## Do the plot
mm=min(min(data));
MM=max(max(data));
-if isnan(mm), mm=0; MM=0; end,
+if isnan(mm), mm=0; MM=0; end
if vertical
plot (quartile_x, quartile_y, 'b', ...
@@ -171,7 +171,7 @@ else
% % % % % outliers2_y, outliers2_x, [symbol(2),"r;;"]);
end
-if nargout,
+if nargout
sout=s;
end
% % % endfunction
\ No newline at end of file
diff --git a/matlab/mydelete.m b/matlab/mydelete.m
index 13ef6ee9d..c28d5ad94 100644
--- a/matlab/mydelete.m
+++ b/matlab/mydelete.m
@@ -1,7 +1,7 @@
function mydelete(fname,pname)
% Specialized version of delete() function
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -18,16 +18,16 @@ function mydelete(fname,pname)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin ==0,
+if nargin ==0
disp('mydelete(fname)')
return
end
-if nargin ==1,
+if nargin ==1
pname='';
end
file_to_delete = dir([pname,fname]);
-for j=1:length(file_to_delete),
+for j=1:length(file_to_delete)
delete([pname,file_to_delete(j).name]);
end
diff --git a/matlab/name2index.m b/matlab/name2index.m
index b653e71c6..22d116c79 100644
--- a/matlab/name2index.m
+++ b/matlab/name2index.m
@@ -2,21 +2,21 @@ function i = name2index(options_, M_, estim_params_, type, name1, name2 )
% Returns the index associated to an estimated object (deep parameter,
% variance of a structural shock or measurement error, covariance between
% two structural shocks, covariance between two measurement errors).
-%
+%
% INPUTS:
% options_ [structure] Dynare structure.
% M_ [structure] Dynare structure (related to model definition).
% estim_params_ [structure] Dynare structure (related to estimation).
% type [string] 'DeepParameter', 'MeasurementError' (for measurement equation error) or 'StructuralShock' (for structural shock).
-% name1 [string]
-% name2 [string]
+% name1 [string]
+% name2 [string]
% OUTPUTS
% i [integer] column index (in x2, an array of mh draws) associated to name1[,name2].
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -63,7 +63,7 @@ if strcmpi(type,'StructuralShock')
end
else% Covariance matrix off-diagonal term
offset = nvx+nvn;
- try
+ try
list_of_structural_shocks = { M_.exo_names(estim_params_.corrx(:,1),:) , M_.exo_names(estim_params_.corrx(:,2),:) };
k1 = strmatch(name1,list_of_structural_shocks(:,1),'exact');
k2 = strmatch(name2,list_of_structural_shocks(:,2),'exact');
diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m
index 43574d4e9..1f56c3be4 100644
--- a/matlab/non_linear_dsge_likelihood.m
+++ b/matlab/non_linear_dsge_likelihood.m
@@ -376,4 +376,3 @@ if isinf(LIK)~=0
exit_flag = 0;
return
end
-
diff --git a/matlab/occbin/call_solve_one_constraint.m b/matlab/occbin/call_solve_one_constraint.m
index d7a83c836..65b98c431 100755
--- a/matlab/occbin/call_solve_one_constraint.m
+++ b/matlab/occbin/call_solve_one_constraint.m
@@ -1,12 +1,12 @@
% Solve model, generate model IRFs
-[zdatalinear zdatapiecewise zdatass oobase_ Mbase_ ] = ...
+[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ...
solve_one_constraint(modnam,modnamstar,...
constraint, constraint_relax,...
shockssequence,irfshock,nperiods,maxiter);
-% unpack the IRFs
+% unpack the IRFs
for i=1:Mbase_.endo_nbr
eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
diff --git a/matlab/occbin/call_solve_two_constraints.m b/matlab/occbin/call_solve_two_constraints.m
index 1b54718e5..5bbc1beb8 100755
--- a/matlab/occbin/call_solve_two_constraints.m
+++ b/matlab/occbin/call_solve_two_constraints.m
@@ -1,4 +1,4 @@
-[zdatalinear zdatapiecewise zdatass oobase_ Mbase_] = solve_two_constraints(...
+[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(...
modnam_00,modnam_10,modnam_01,modnam_11,...
constraint1, constraint2,...
constraint_relax1, constraint_relax2,...
diff --git a/matlab/occbin/get_deriv.m b/matlab/occbin/get_deriv.m
index 19fe87001..214b1cf42 100755
--- a/matlab/occbin/get_deriv.m
+++ b/matlab/occbin/get_deriv.m
@@ -13,11 +13,11 @@ if size(iy_,1)==3
con_cols = find(iy_(2,:));
% find non-zero columns of hl1
lea_cols = find(iy_(3,:));
-
- % If models either lacks leads or lags, iy_ will have two rows
+
+ % If models either lacks leads or lags, iy_ will have two rows
% In this case, we guess that the row with more nonzeros is the row with current variables
elseif size(iy_,1)==2
- % if first row has more nonzero entries than the second, assume model lacks lagged variables
+ % if first row has more nonzero entries than the second, assume model lacks lagged variables
if length(find(iy_(1,:)))>length(find(iy_(2,:)))
warning('Model does not have lagged endogenous variables')
con_cols = find(iy_(1,:));
@@ -29,7 +29,7 @@ elseif size(iy_,1)==2
con_cols = find(iy_(2,:));
lea_cols = [];
end
-
+
end
@@ -45,7 +45,7 @@ y = [y;ys_(lea_cols)];
if ismac
eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
- % Older versions of DYNARE for Mac did not include ys_ in the call structure
+ % Older versions of DYNARE for Mac did not include ys_ in the call structure
%eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']);
else
eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
@@ -77,7 +77,6 @@ for i=1:nlea_cols
end
-for i = 1:M_.exo_nbr;
+for i = 1:M_.exo_nbr
j(:,i) =g1(:,i+ny);
end
-
diff --git a/matlab/occbin/get_pq.m b/matlab/occbin/get_pq.m
index 6ef8c8ec7..99888b806 100755
--- a/matlab/occbin/get_pq.m
+++ b/matlab/occbin/get_pq.m
@@ -1,4 +1,4 @@
-function [p,q]=get_pq(dr_,nstatic,nfwrd);
+function [p,q]=get_pq(dr_,nstatic,nfwrd)
nvars = size(dr_.ghx,1);
nshocks = size(dr_.ghu,2);
@@ -21,8 +21,8 @@ p_reordered = zeros(nvars);
q = zeros(nvars,nshocks);
for i=1:nvars
for j=1:nvars
- p_reordered(i,j)=p(inverse_order(i),inverse_order(j));
+ p_reordered(i,j)=p(inverse_order(i),inverse_order(j));
end
- q(i,:)=dr_.ghu(inverse_order(i),:);
+ q(i,:)=dr_.ghu(inverse_order(i),:);
end
p=p_reordered;
\ No newline at end of file
diff --git a/matlab/occbin/makechart.m b/matlab/occbin/makechart.m
index 496a136ba..934e8463b 100755
--- a/matlab/occbin/makechart.m
+++ b/matlab/occbin/makechart.m
@@ -22,7 +22,7 @@ nobs = size(zdata1,1);
xvalues = (1:nobs)';
nvars = size(titlelist,1);
-if nvars==1
+if nvars==1
nrows=1;
ncols = 1;
elseif nvars==2
@@ -40,7 +40,7 @@ elseif (nvars==7 | nvars==8)
elseif (nvars==9 | nvars==10)
nrows = 5;
ncols = 2;
-else
+else
error('too many variables (makechart)')
end
@@ -49,15 +49,15 @@ for i = 1:nvars
h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on
h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on
h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3);
- [x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
- [x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
- [x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
+ [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
+ [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
+ [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
y0 = min([y10,y20,y30]);
y1 = max([y11,y21,y31]);
if y0==y1
y1=y0+1;
end
-
+
axis([x0 x1 y0 y1])
set(h1);
@@ -66,13 +66,13 @@ for i = 1:nvars
text('String',figlabel,'Units','normalized','Position',[1.2 1.24],...
'FontSize',14,'FontWeight','bold','HorizontalAlignment','center');
end
-
+
if i==nvars | i==nvars-1
xlabel('Time');
end
% set(gca,'XTick',xtick)
% set(gca,'XTickLabel',xticklabel)
-
+
title([num2str(i),'. ',titlelist(i,:)]);
ylabel(ylabels(i,:))
end
diff --git a/matlab/occbin/makechart9.m b/matlab/occbin/makechart9.m
index e87618959..264f9f58f 100755
--- a/matlab/occbin/makechart9.m
+++ b/matlab/occbin/makechart9.m
@@ -54,31 +54,31 @@ else
end
nvars = size(titlelist,1);
-if nvars==1
+if nvars==1
nrows=1;
ncols = 1;
elseif nvars==2
nrows =2;
ncols = 1;
-elseif nvars == 3
+elseif nvars == 3
nrows = 3;
ncols = 1;
-elseif nvars==4
+elseif nvars==4
nrows = 2;
ncols = 2;
elseif (nvars==5 | nvars ==6)
nrows = 3;
- ncols = 2;
+ ncols = 2;
elseif (nvars==7 | nvars==8)
nrows = 4;
ncols = 2;
-elseif nvars>8 & nvars<=12;
+elseif nvars>8 & nvars<=12
nrows = 3;
ncols = 4;
-elseif nvars>12 & nvars<=15;
+elseif nvars>12 & nvars<=15
nrows = 5;
ncols = 3;
-else
+else
error('too many variables (makechart)')
end
@@ -92,20 +92,20 @@ for i = 1:nvars
xvalues,zdata5(:,i),'g',...
xvalues,zdata6(:,i),'c',...
xvalues,zdata7(:,i),'y');
- [x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
- [x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
- [x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
- [x0 x1 y40 y41] = pickaxes(xvalues,zdata4(:,i));
- [x0 x1 y50 y51] = pickaxes(xvalues,zdata5(:,i));
- [x0 x1 y60 y61] = pickaxes(xvalues,zdata6(:,i));
- [x0 x1 y70 y71] = pickaxes(xvalues,zdata7(:,i));
+ [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
+ [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
+ [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
+ [x0, x1, y40, y41] = pickaxes(xvalues,zdata4(:,i));
+ [x0, x1, y50, y51] = pickaxes(xvalues,zdata5(:,i));
+ [x0, x1, y60, y61] = pickaxes(xvalues,zdata6(:,i));
+ [x0, x1, y70, y71] = pickaxes(xvalues,zdata7(:,i));
grid on
y0 = min([y10,y20,y30,y40,y50,y60,y70]);
y1 = max([y11,y21,y31,y41,y51,y61,y71]);
if y0==y1
y1=y0+1;
end
-
+
axis([x0 x1 y0 y1])
set(h1,'linewidth',2);
if i==1
@@ -123,10 +123,10 @@ for i = 1:nvars
'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
end
end
-
+
%set(gca,'XTick',xtick)
%set(gca,'XTickLabel',xticklabel)
-
+
title(titlelist(i,:),'Fontsize',11);
ylabel(ylabels(i,:))
diff --git a/matlab/occbin/map_regime.m b/matlab/occbin/map_regime.m
index 64a87250e..1a8b8e796 100755
--- a/matlab/occbin/map_regime.m
+++ b/matlab/occbin/map_regime.m
@@ -1,4 +1,4 @@
-function [regime regimestart]=map_regime(violvecbool)
+function [regime, regimestart]=map_regime(violvecbool)
nperiods = length(violvecbool)-1;
@@ -21,5 +21,4 @@ end
if (regime(end)==1)
warning('Increase nperiods');
-end
-
+endx
\ No newline at end of file
diff --git a/matlab/occbin/mkdata.m b/matlab/occbin/mkdata.m
index 02b2eb703..f22fb45f6 100755
--- a/matlab/occbin/mkdata.m
+++ b/matlab/occbin/mkdata.m
@@ -2,7 +2,7 @@ function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshoc
%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_)
-% given decision rule
+% given decision rule
neqs = size(endog_,1);
if nargin<9
diff --git a/matlab/occbin/mkdatap_anticipated.m b/matlab/occbin/mkdatap_anticipated.m
index 6e745e0a4..a9c924966 100755
--- a/matlab/occbin/mkdatap_anticipated.m
+++ b/matlab/occbin/mkdatap_anticipated.m
@@ -12,7 +12,7 @@ if nargin<16
init=zeros(nvars,1);
end
-if nargin<15;
+if nargin<15
scalefactormod=1;
end
@@ -48,21 +48,21 @@ Tmax = regimestart(nregimes)-1; % Tmax is the position of the last period
if Tmax > 0
P = zeros(nvars,nvars,Tmax);
D = zeros(nvars,Tmax);
-
-
+
+
invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
P(:,:,Tmax) = -invmat*Cstarbarmat;
D(:,Tmax) = -invmat*Dstarbarmat;
-
-
+
+
% equivalent to pre-multiplying by the inverse above if the target
% matrix is invertible. Otherwise it yields the minimum state solution
%P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat;
%D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat;
-
-
+
+
for i = Tmax-1:-1:1
-
+
if violvecbool(i)
invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1));
P(:,:,i)=-invmat*Cstarbarmat;
@@ -74,7 +74,7 @@ if Tmax > 0
end
end
- if Tmax > 1
+ if Tmax > 1
if violvecbool(1)
E = -invmat*Jstarbarmat;
else
@@ -86,7 +86,7 @@ if Tmax > 0
end
-
+
end
% generate data
diff --git a/matlab/occbin/mkdatap_anticipated_2constraints.m b/matlab/occbin/mkdatap_anticipated_2constraints.m
index c18cef2f9..496f5a931 100755
--- a/matlab/occbin/mkdatap_anticipated_2constraints.m
+++ b/matlab/occbin/mkdatap_anticipated_2constraints.m
@@ -16,7 +16,7 @@ if nargin<16
init=zeros(nvars,1);
end
-if nargin<15;
+if nargin<15
scalefactormod=1;
end
@@ -63,17 +63,17 @@ Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1; % Tmax is the
if Tmax > 0
P = zeros(nvars,nvars,Tmax);
D = zeros(nvars,Tmax);
-
+
% invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
% P(:,:,Tmax) = -invmat*Cstarbarmat;
% D(:,Tmax) = -invmat*Dstarbarmat;
-
-
+
+
if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2))
%XXX fix next three lines
invmat = inv((Abarmat10*decrulea+Bbarmat10));
P(:,:,Tmax) = -invmat*Cbarmat10;
- D(:,Tmax) = -invmat*Dbarmat10;
+ D(:,Tmax) = -invmat*Dbarmat10;
elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2))
invmat = inv((Abarmat11*decrulea+Bbarmat11));
P(:,:,Tmax) = -invmat*Cbarmat11;
@@ -81,14 +81,14 @@ if Tmax > 0
else
invmat = inv((Abarmat01*decrulea+Bbarmat01));
P(:,:,Tmax) = -invmat*Cbarmat01;
- D(:,Tmax) = -invmat*Dbarmat01;
+ D(:,Tmax) = -invmat*Dbarmat01;
end
-
-
-
-
- for i = Tmax-1:-1:1
-
+
+
+
+
+ for i = Tmax-1:-1:1
+
if (violvecbool(i,1) & ~violvecbool(i,2))
invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1));
P(:,:,i)=-invmat*Cbarmat10;
@@ -106,14 +106,14 @@ if Tmax > 0
P(:,:,i)=-invmat*Cbarmat;
D(:,i) = -invmat*(Abarmat*D(:,i+1));
end
-
+
end
-
+
% Double check the appropriate invmat in each case
% right now -- inherited from previous loop
if Tmax > 1
-
+
if ( ~violvecbool(1,1) & violvecbool(1,2) )
E = -invmat*Jbarmat01;
elseif ( violvecbool(1,1) & ~violvecbool(1,2) )
@@ -123,26 +123,26 @@ if Tmax > 0
else
E = -invmat*Jbarmat;
end
-
- else % Tmax is equal to 1
+
+ else % Tmax is equal to 1
% invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
% E = -invmat*Jstarbarmat;
-
+
if ( ~violvecbool(1,1) & violvecbool(1,2) )
invmat = inv((Abarmat01*decrulea+Bbarmat01));
- E = -invmat*Jbarmat01;
+ E = -invmat*Jbarmat01;
elseif ( violvecbool(1,1) & violvecbool(1,2) )
invmat = inv((Abarmat11*decrulea+Bbarmat11));
- E = -invmat*Jbarmat11;
+ E = -invmat*Jbarmat11;
else
invmat = inv((Abarmat10*decrulea+Bbarmat10));
E = -invmat*Jbarmat10;
-
+
end
-
+
end
-
+
end
% generate data
diff --git a/matlab/occbin/pickaxes.m b/matlab/occbin/pickaxes.m
index c2e2d5e0d..26c9b6b1a 100755
--- a/matlab/occbin/pickaxes.m
+++ b/matlab/occbin/pickaxes.m
@@ -9,7 +9,7 @@ miny = min(yvalues);
y0 = miny - .05*abs(miny);
-if (miny>0 & y0<0)
+if (miny>0 & y0<0)
y0 = 0;
end
diff --git a/matlab/occbin/process_constraint.m b/matlab/occbin/process_constraint.m
index 0573eb641..2d2b35f36 100755
--- a/matlab/occbin/process_constraint.m
+++ b/matlab/occbin/process_constraint.m
@@ -22,7 +22,7 @@ for i=1:ntokens
% suffix
tokens(i) = cellstr([char(tokens(i)),suffix]);
end
-
+
% if the invert_switch is true
% reverse the direction of the inequality
if invert_switch
diff --git a/matlab/occbin/setss.m b/matlab/occbin/setss.m
index 39e269d51..8d2e71763 100755
--- a/matlab/occbin/setss.m
+++ b/matlab/occbin/setss.m
@@ -10,5 +10,4 @@ nparams = size(Mbase_.param_names);
for i = 1:nparams
eval([Mbase_.param_names(i,:),'= M_.params(i);']);
-end
-
+end
\ No newline at end of file
diff --git a/matlab/occbin/solve_no_constraint.m b/matlab/occbin/solve_no_constraint.m
index d4f61a3f4..169c74ebd 100755
--- a/matlab/occbin/solve_no_constraint.m
+++ b/matlab/occbin/solve_no_constraint.m
@@ -46,5 +46,4 @@ wishlist = endog_;
nwishes = size(wishlist,1);
-zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
-
+zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
\ No newline at end of file
diff --git a/matlab/occbin/solve_no_constraint_noclear.m b/matlab/occbin/solve_no_constraint_noclear.m
index b899708e2..8012f9126 100755
--- a/matlab/occbin/solve_no_constraint_noclear.m
+++ b/matlab/occbin/solve_no_constraint_noclear.m
@@ -1,6 +1,6 @@
-function [zdata oobase_ Mbase_ ] = ...
+function [zdata, oobase_, Mbase_ ] = ...
solve_no_constraint_noclear(modnam,...
- shockssequence,irfshock,nperiods);
+ shockssequence,irfshock,nperiods)
global M_ oo_
@@ -45,4 +45,3 @@ nwishes = size(wishlist,1);
zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
-
diff --git a/matlab/occbin/solve_one_constraint.1.m b/matlab/occbin/solve_one_constraint.1.m
index 344e85f5a..aa155c234 100755
--- a/matlab/occbin/solve_one_constraint.1.m
+++ b/matlab/occbin/solve_one_constraint.1.m
@@ -1,11 +1,11 @@
% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-%
-% Inputs:
+%
+% Inputs:
% modnam: name of .mod file for the reference regime (excludes the .mod extension).
% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
+% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
@@ -115,7 +115,7 @@ if ~exist('nperiods_')
end
-% set some initial conditions and loop through the shocks
+% set some initial conditions and loop through the shocks
% period by period
init_orig_ = init_;
zdatapiecewise_ = zeros(nperiods_,nvars_);
@@ -125,35 +125,35 @@ violvecbool_ = zeros(nperiods_+1,1);
for ishock_ = 1:nshocks_
-
+
changes_=1;
iter_ = 0;
-
-
+
+
while (changes_ & iter_0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
@@ -161,24 +161,24 @@ for ishock_ = 1:nshocks_
else
changes_ = 0;
end
-
-
+
+
violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-
-
+
+
end
-
+
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
-
- % reset violvecbool_ for next period's shock -- this resetting is
+
+ % reset violvecbool_ for next period's shock -- this resetting is
% consistent with expecting no additional shocks
violvecbool_=[violvecbool_(2:end);0];
-
+
end
-% if necessary, fill in the rest of the path with the remainder of the
+% if necessary, fill in the rest of the path with the remainder of the
% last IRF computed.
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
diff --git a/matlab/occbin/solve_one_constraint.m b/matlab/occbin/solve_one_constraint.m
index ee59e9a3d..5959636bf 100755
--- a/matlab/occbin/solve_one_constraint.m
+++ b/matlab/occbin/solve_one_constraint.m
@@ -1,11 +1,11 @@
% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-%
-% Inputs:
+%
+% Inputs:
% modnam: name of .mod file for the reference regime (excludes the .mod extension).
% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
+% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
@@ -24,7 +24,7 @@
% 6/17/2013 -- Luca replaced external .m file setss.m
-function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_ ] = ...
+function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_ ] = ...
solve_one_constraint(modnam_,modnamstar_,...
constraint_, constraint_relax_,...
shockssequence_,irfshock_,nperiods_,maxiter_,init_)
@@ -121,7 +121,7 @@ if ~exist('nperiods_')
end
-% set some initial conditions and loop through the shocks
+% set some initial conditions and loop through the shocks
% period by period
init_orig_ = init_;
zdatapiecewise_ = zeros(nperiods_,nvars_);
@@ -131,36 +131,36 @@ violvecbool_ = zeros(nperiods_+1,1);
for ishock_ = 1:nshocks_
-
+
changes_=1;
iter_ = 0;
-
-
+
+
while (changes_ & iter_0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
@@ -168,25 +168,25 @@ for ishock_ = 1:nshocks_
else
changes_ = 0;
end
-
-
-
+
+
+
violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-
-
+
+
end
-
+
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
-
- % reset violvecbool_ for next period's shock -- this resetting is
+
+ % reset violvecbool_ for next period's shock -- this resetting is
% consistent with expecting no additional shocks
violvecbool_=[violvecbool_(2:end);0];
-
+
end
-% if necessary, fill in the rest of the path with the remainder of the
+% if necessary, fill in the rest of the path with the remainder of the
% last IRF computed.
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
diff --git a/matlab/occbin/solve_two_constraints.m b/matlab/occbin/solve_two_constraints.m
index 0ca5d559a..775adc30a 100755
--- a/matlab/occbin/solve_two_constraints.m
+++ b/matlab/occbin/solve_two_constraints.m
@@ -1,5 +1,5 @@
% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init);
-%
+%
% Inputs:
% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first
% constraint.
@@ -29,7 +29,7 @@
% to be processed.
% 6/17/2013 -- Luca replaced external .m file setss.m
-function [ zdatalinear_ zdatapiecewise_ zdatass_ oo00_ M00_ ] = ...
+function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ...
solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,...
constrain1_, constrain2_,...
constraint_relax1_, constraint_relax2_,...
@@ -140,7 +140,7 @@ Dbarmat11_ = resid_;
if isfield(M00_,'nfwrd') % needed for bakward compatibility with older Dynare releases
[decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd);
else
- [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);
+ [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);
end
endog_ = M00_.endo_names;
exog_ = M00_.exo_names;
@@ -210,20 +210,20 @@ violvecbool_ = zeros(nperiods_+1,2); % This sets the first guess for when
wishlist_ = endog_;
nwishes_ = size(wishlist_,1);
for ishock_ = 1:nshocks
-
-
+
+
changes_=1;
iter_ = 0;
-
+
while (changes_ & iter_0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
changes_ = 1;
else
changes_ = 0;
end
-
+
if curb_retrench_ % apply Gauss-Sidel idea of slowing down the change in the guess
% for the constraint -- only relax one
% period at a time starting from the last
@@ -278,28 +278,27 @@ for ishock_ = 1:nshocks
else
violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:));
end
-
+
violvecbool_ = reshape(violvecbool_,nperiods_+1,2);
-
-
-
+
+
+
end
if changes_ ==1
display('Did not converge -- increase maxiter')
end
-
+
init_ = zdatalinear_(1,:);
zdatapiecewise_(ishock_,:)=init_;
init_= init_';
-
+
% update the guess for constraint violations for next period
% update is consistent with expecting no additional shocks next period
violvecbool_=[violvecbool_(2:end,:);zeros(1,2)];
-
+
end
zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);
-
+zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);
\ No newline at end of file
diff --git a/matlab/occbin/tokenize.m b/matlab/occbin/tokenize.m
index 257be9131..1789d095a 100755
--- a/matlab/occbin/tokenize.m
+++ b/matlab/occbin/tokenize.m
@@ -28,7 +28,7 @@ else
ndelims = length(posdelims);
% build positions for substrings
delims = zeros(ndelims+1,2);
- for i=1:ndelims+1;
+ for i=1:ndelims+1
if i==1
if posdelims(1) == 1
tokens = cellstr(source(1));
@@ -51,5 +51,4 @@ else
end
end
-end
-
+end
\ No newline at end of file
diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m
index 9d702d597..3c1a6a6a0 100644
--- a/matlab/octave_ver_less_than.m
+++ b/matlab/octave_ver_less_than.m
@@ -8,14 +8,14 @@ function r = octave_ver_less_than(verstr)
%
% INPUTS
% verstr: a string of the format 'x.y' or 'x.y.z'
-%
+%
% OUTPUTS
% r: 0 or 1
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/one_sided_hp_filter.m b/matlab/one_sided_hp_filter.m
index 46fed2343..9715a3351 100644
--- a/matlab/one_sided_hp_filter.m
+++ b/matlab/one_sided_hp_filter.m
@@ -32,13 +32,13 @@ function [ytrend,ycycle]=one_sided_hp_filter(y,lambda,x_user,P_user,discard)
%
% y_t=tau_t+epsilon_t
% (1-L)^2 tau_t=eta_t"
-%
-% The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994).
+%
+% The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994).
% Time Series Analysis, with the exception of H, which is equivalent to his H'.
% Copyright (C) 200?-2015 Alexander Meyer-Gohde
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -66,23 +66,23 @@ F=[2,-1;
1,0]; % state transition matrix
H=[1,0]; % observation matrix
Q=[q,0;
- 0,0]; % covariance matrix state equation errors
+ 0,0]; % covariance matrix state equation errors
R=1; % variance observation equation error
for k=1:n %Run the Kalman filter for each variable
if nargin < 4 || isempty(x_user) %no intial value for state, extrapolate back two periods from the observations
- x=[2*y(1,k)-y(2,k);
- 3*y(1,k)-2*y(2,k)];
+ x=[2*y(1,k)-y(2,k);
+ 3*y(1,k)-2*y(2,k)];
else
x=x_user(:,k);
- end
+ end
if nargin < 4 || isempty(P_user) %no initial value for the MSE, set a rather high one
P= [1e5 0;
- 0 1e5];
+ 0 1e5];
else
P=P_user{k};
- end
-
+ end
+
for j=1:T %Get the estimates for each period
[x,P]=kalman_update(F,H,Q,R,y(j,k),x,P); %get new state estimate and update recursion
ytrend(j,k)=x(2);%second state is trend estimate
@@ -103,9 +103,9 @@ end
function [x,P]=kalman_update(F,H,Q,R,obs,x,P)
% Updates the Kalman filter estimation of the state and MSE
-S=H*P*H'+R;
-K=F*P*H';
-K=K/S;
+S=H*P*H'+R;
+K=F*P*H';
+K=K/S;
x=F*x+K*(obs -H*x); %State estimate
Temp=F-K*H;
P=Temp*P*Temp';
diff --git a/matlab/optimization/apprgrdn.m b/matlab/optimization/apprgrdn.m
index 9f16e4466..2d79f0489 100644
--- a/matlab/optimization/apprgrdn.m
+++ b/matlab/optimization/apprgrdn.m
@@ -2,7 +2,7 @@ function g = apprgrdn(x,f,fun,deltax,obj,varargin)
% g = apprgrdn(x,f,fun,deltax,obj,varargin)
% Performs the finite difference approximation of the gradient at a
% point used in solveopt
-%
+%
% Inputs:
% x: point at which to evaluate gradient
% f: calculated function value at a point x;
@@ -14,10 +14,10 @@ function g = apprgrdn(x,f,fun,deltax,obj,varargin)
% Modified by Giovanni Lombardo and Johannes Pfeifer to accomodate Dynare
% structure
%
-%
-% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
+%
+% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
% Copyright (C) 2008-2015 Giovanni Lombardo
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -38,10 +38,10 @@ n=max(size(x)); ee=ones(size(x));
di=abs(x); idx=find(di<5e-15); di(idx)=5e-15*ee(idx);
di=deltax.*di;
if obj
- idx=find(abs(di)<2e-10);
+ idx=find(abs(di)<2e-10);
di(idx)=2e-10*sign(di(idx));
else
- idx=find(abs(di)<5e-15);
+ idx=find(abs(di)<5e-15);
di(idx)=5e-15*sign(di(idx));
end
y=x;
@@ -51,7 +51,7 @@ for i=1:n
y(i)=x(i)+di(i);
fi=feval(fun,y,varargin{:});
if obj
- if fi==f,
+ if fi==f
for j=1:3
di(i)=di(i)*10; y(i)=x(i)+di(i);
fi=feval(fun,y,varargin{:});
diff --git a/matlab/optimization/bfgsi1.m b/matlab/optimization/bfgsi1.m
index 696ee410b..7a76a89b2 100644
--- a/matlab/optimization/bfgsi1.m
+++ b/matlab/optimization/bfgsi1.m
@@ -1,22 +1,22 @@
function H = bfgsi1(H0,dg,dx,Verbose,Save_files)
% H = bfgsi1(H0,dg,dx,Verbose,Save_files)
% Update Inverse Hessian matrix
-%
+%
% Inputs:
% H0 [npar by npar] initial inverse Hessian matrix
% dg [npar by 1] previous change in gradient
% dx [npar by 1] previous change in x;
% Verbose [scalar] Indicator for silent mode
-% Save_files [scalar] Indicator whether to save files
-%
+% Save_files [scalar] Indicator whether to save files
+%
% 6/8/93 version that updates inverse Hessian instead of Hessian
% itself.
-%
+%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/bfgsi.m
-%
+%
% Copyright (C) 1993-2009 Christopher Sims
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/optimization/cmaes.m b/matlab/optimization/cmaes.m
index b4790786a..2ead9b50e 100644
--- a/matlab/optimization/cmaes.m
+++ b/matlab/optimization/cmaes.m
@@ -9,26 +9,26 @@ function [xmin, ... % minimum search point of last iteration
xstart, ... % objective variables initial point, determines N
insigma, ... % initial coordinate wise standard deviation(s)
inopts, ... % options struct, see defopts below
- varargin ) % arguments passed to objective function
- % cmaes.m, Version 3.56.beta, last change: February, 2012
+ varargin ) % arguments passed to objective function
+ % cmaes.m, Version 3.56.beta, last change: February, 2012
% CMAES implements an Evolution Strategy with Covariance Matrix
% Adaptation (CMA-ES) for nonlinear function minimization. For
- % introductory comments and copyright (GPL) see end of file (type
- % 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and,
- % without data logging and plotting, it should run under Octave
+ % introductory comments and copyright (GPL) see end of file (type
+ % 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and,
+ % without data logging and plotting, it should run under Octave
% (Linux, package octave-forge is needed).
%
- % OPTS = CMAES returns default options.
+ % OPTS = CMAES returns default options.
% OPTS = CMAES('defaults') returns default options quietly.
- % OPTS = CMAES('displayoptions') displays options.
- % OPTS = CMAES('defaults', OPTS) supplements options OPTS with default
- % options.
+ % OPTS = CMAES('displayoptions') displays options.
+ % OPTS = CMAES('defaults', OPTS) supplements options OPTS with default
+ % options.
%
% XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of
% function FUN starting from column vector X0 with the initial
% coordinate wise search standard deviation SIGMA.
%
- % Input arguments:
+ % Input arguments:
%
% FUN is a string function name like 'myfun'. FUN takes as argument a
% column vector of size of X0 and returns a scalar. An easy way to
@@ -59,7 +59,7 @@ function [xmin, ... % minimum search point of last iteration
% abbreviations can be used for the field names. If a string is
% given where a numerical value is needed, the string is evaluated
% by eval, where 'N' expands to the problem dimension
- % (==size(X0,1)) and 'popsize' to the population size.
+ % (==size(X0,1)) and 'popsize' to the population size.
%
% [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ...
% CMAES(FITFUN, X0, SIGMA)
@@ -74,9 +74,9 @@ function [xmin, ... % minimum search point of last iteration
% 'tolx')) for further processing); a record struct OUT with some
% more output, where the struct SOLUTIONS.BESTEVER contains the overall
% best evaluated point X with function value F evaluated at evaluation
- % count EVALS. The last output argument BESTEVER equals
- % OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and
- % parameters is written to files according to the Log-options.
+ % count EVALS. The last output argument BESTEVER equals
+ % OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and
+ % parameters is written to files according to the Log-options.
%
% A regular manual stop can be achieved via the file signals.par. The
% program is terminated if the first two non-white sequences in any
@@ -84,7 +84,7 @@ function [xmin, ... % minimum search point of last iteration
% option (by default 'outcmaes'). Also a run can be skipped.
% Given, for example, 'skip outcmaes run 2', skips the second run
% if option Restarts is at least 2, and another run will be started.
- %
+ %
% To run the code completely silently set Disp, Save, and Log options
% to 0. With OPTS.LogModulo > 0 (1 by default) the most important
% data are written to ASCII files permitting to investigate the
@@ -96,30 +96,30 @@ function [xmin, ... % minimum search point of last iteration
%
% To find the best ever evaluated point load the variables typing
% "es=load('variablescmaes')" and investigate the variable
- % es.out.solutions.bestever.
+ % es.out.solutions.bestever.
%
% In case of a noisy objective function (uncertainties) set
- % OPTS.Noise.on = 1. This option interferes presumably with some
+ % OPTS.Noise.on = 1. This option interferes presumably with some
% termination criteria, because the step-size sigma will presumably
- % not converge to zero anymore. If CMAES was provided with a
- % fifth argument (P1 in the below example, which is passed to the
- % objective function FUN), this argument is multiplied with the
- % factor given in option Noise.alphaevals, each time the detected
- % noise exceeds a threshold. This argument can be used within
- % FUN, for example, as averaging number to reduce the noise level.
+ % not converge to zero anymore. If CMAES was provided with a
+ % fifth argument (P1 in the below example, which is passed to the
+ % objective function FUN), this argument is multiplied with the
+ % factor given in option Noise.alphaevals, each time the detected
+ % noise exceeds a threshold. This argument can be used within
+ % FUN, for example, as averaging number to reduce the noise level.
%
% OPTS.DiagonalOnly > 1 defines the number of initial iterations,
% where the covariance matrix remains diagonal and the algorithm has
% internally linear time complexity. OPTS.DiagonalOnly = 1 means
% keeping the covariance matrix always diagonal and this setting
% also exhibits linear space complexity. This can be particularly
- % useful for dimension > 100. The default is OPTS.DiagonalOnly = 0.
- %
- % OPTS.CMA.active = 1 turns on "active CMA" with a negative update
- % of the covariance matrix and checks for positive definiteness.
+ % useful for dimension > 100. The default is OPTS.DiagonalOnly = 0.
+ %
+ % OPTS.CMA.active = 1 turns on "active CMA" with a negative update
+ % of the covariance matrix and checks for positive definiteness.
% OPTS.CMA.active = 2 does not check for pos. def. and is numerically
- % faster. Active CMA usually speeds up the adaptation and might
- % become a default in near future.
+ % faster. Active CMA usually speeds up the adaptation and might
+ % become a default in near future.
%
% The primary strategy parameter to play with is OPTS.PopSize, which
% can be increased from its default value. Increasing the population
@@ -135,7 +135,7 @@ function [xmin, ... % minimum search point of last iteration
% program, all others including MaxIter invoke another restart, where
% the iteration counter is reset to zero.
%
- % Examples:
+ % Examples:
%
% XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at
% 10D-point 5 and initially searches mainly between 5-3 and 5+3
@@ -143,22 +143,22 @@ function [xmin, ... % minimum search point of last iteration
% 'myfun' is a name of a function that returns a scalar from a 10D
% column vector.
%
- % opts.LBounds = 0; opts.UBounds = 10;
+ % opts.LBounds = 0; opts.UBounds = 10;
% X=cmaes('myfun', 10*rand(10,1), 5, opts);
% search within lower bound of 0 and upper bound of 10. Bounds can
% also be given as column vectors. If the optimum is not located
- % on the boundary, use rather a penalty approach to handle bounds.
+ % on the boundary, use rather a penalty approach to handle bounds.
%
% opts=cmaes; opts.StopFitness=1e-10;
% X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if
% the function value is smaller than 1e-10.
- %
- % [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2);
+ %
+ % [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2);
% passes two additional parameters to the function MYFUN2.
%
-% Copyright (C) 2001-2012 Nikolaus Hansen,
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2001-2012 Nikolaus Hansen,
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -176,7 +176,7 @@ function [xmin, ... % minimum search point of last iteration
% along with Dynare. If not, see .
-cmaVersion = '3.60.beta';
+cmaVersion = '3.60.beta';
% ----------- Set Defaults for Input Parameters and Options -------------
% These defaults may be edited for convenience
@@ -197,47 +197,47 @@ defopts.TolFun = '1e-10 % stop if fun-changes smaller TolFun';
defopts.TolHistFun = '1e-11 % stop if back fun-changes smaller TolHistFun';
defopts.StopOnStagnation = 'on % stop when fitness stagnates for a long time';
defopts.StopOnWarnings = 'yes % ''no''==''off''==0, ''on''==''yes''==1 ';
-defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations';
+defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations';
% Options defaults: Other
defopts.DiffMaxChange = 'Inf % maximal variable change(s), can be Nx1-vector';
defopts.DiffMinChange = '0 % minimal variable change(s), can be Nx1-vector';
defopts.WarnOnEqualFunctionValues = ...
'yes % ''no''==''off''==0, ''on''==''yes''==1 ';
-defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector';
-defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector';
+defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector';
+defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector';
defopts.EvalParallel = 'no % objective function FUN accepts NxM matrix, with M>1?';
defopts.EvalInitialX = 'yes % evaluation of initial solution';
defopts.Restarts = '0 % number of restarts ';
defopts.IncPopSize = '2 % multiplier for population size before each restart';
-defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda';
+defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda';
defopts.ParentNumber = 'floor(popsize/2) % AKA mu, popsize equals lambda';
defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal';
-defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always';
-defopts.Noise.on = '0 % uncertainty handling is off by default';
+defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always';
+defopts.Noise.on = '0 % uncertainty handling is off by default';
defopts.Noise.reevals = '1*ceil(0.05*lambda) % nb. of re-evaluated for uncertainty measurement';
defopts.Noise.theta = '0.5 % threshold to invoke uncertainty treatment'; % smaller: more likely to diverge
-defopts.Noise.cum = '0.3 % cumulation constant for uncertainty';
+defopts.Noise.cum = '0.3 % cumulation constant for uncertainty';
defopts.Noise.cutoff = '2*lambda/3 % rank change cutoff for summation';
defopts.Noise.alphasigma = '1+2/(N+10) % factor for increasing sigma'; % smaller: slower adaptation
defopts.Noise.epsilon = '1e-7 % additional relative perturbation before reevaluation';
-defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes';
-defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun';
+defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes';
+defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun';
defopts.Noise.callback = '[] % callback function when uncertainty threshold is exceeded';
-% defopts.TPA = 0;
-defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size';
+% defopts.TPA = 0;
+defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size';
%qqq cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version
defopts.CMA.damps = '1 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
-% defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix';
+% defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix';
defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc';
-defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update';
-defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update';
-defopts.CMA.on = 'yes';
-defopts.CMA.active = '0 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
+defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update';
+defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update';
+defopts.CMA.on = 'yes';
+defopts.CMA.active = '0 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
flg_future_setting = 0; % testing for possible future variant(s)
-if flg_future_setting
+if flg_future_setting
disp('in the future')
% damps setting from Brockhoff et al 2010
@@ -247,29 +247,29 @@ if flg_future_setting
% how about:
% defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
- % ccum adjusted for large mueff, better on schefelmult?
- % TODO: this should also depend on diagonal option!?
+ % ccum adjusted for large mueff, better on schefelmult?
+ % TODO: this should also depend on diagonal option!?
defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc';
- defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
+ defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
end
-defopts.Resume = 'no % resume former run from SaveFile';
-defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE';
+defopts.Resume = 'no % resume former run from SaveFile';
+defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE';
defopts.ReadSignals = 'on % from file signals.par for termination, yet a stumb';
defopts.Seed = 'sum(100*clock) % evaluated if it is a string';
defopts.DispFinal = 'on % display messages like initial and final message';
defopts.DispModulo = '100 % [0:Inf], disp messages after every i-th iteration';
defopts.SaveVariables = 'on % [on|final|off][-v6] save variables to .mat file';
-defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables';
+defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables';
defopts.LogModulo = '1 % [0:Inf] if >1 record data less frequently after gen=100';
defopts.LogTime = '25 % [0:100] max. percentage of time for recording data';
-defopts.LogFilenamePrefix = 'outcmaes % files for output data';
+defopts.LogFilenamePrefix = 'outcmaes % files for output data';
defopts.LogPlot = 'off % plot while running using output data files';
-%qqqkkk
-%defopts.varopt1 = ''; % 'for temporary and hacking purposes';
-%defopts.varopt2 = ''; % 'for temporary and hacking purposes';
+%qqqkkk
+%defopts.varopt1 = ''; % 'for temporary and hacking purposes';
+%defopts.varopt2 = ''; % 'for temporary and hacking purposes';
defopts.UserData = 'for saving data/comments associated with the run';
defopts.UserDat2 = ''; 'for saving data/comments associated with the run';
@@ -283,20 +283,20 @@ if nargin < 1 || isequal(fitfun, 'defaults') % pass default options
if nargin > 1 % supplement second argument with default options
xmin = getoptions(xstart, defopts);
end
- return;
+ return
end
if isequal(fitfun, 'displayoptions')
- names = fieldnames(defopts);
+ names = fieldnames(defopts);
for name = names'
- disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']);
+ disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']);
end
- return;
+ return
end
input.fitfun = fitfun; % record used input
if isempty(fitfun)
- % fitfun = definput.fitfun;
+ % fitfun = definput.fitfun;
% warning(['Objective function not determined, ''' fitfun ''' used']);
error(['Objective function not determined']);
end
@@ -305,7 +305,7 @@ if ~ischar(fitfun)
end
-if nargin < 2
+if nargin < 2
xstart = [];
end
@@ -316,7 +316,7 @@ if isempty(xstart)
error('Initial search point, and problem dimension, not determined');
end
-if nargin < 3
+if nargin < 3
insigma = [];
end
if isa(insigma, 'struct')
@@ -326,7 +326,7 @@ end
input.sigma = insigma;
if isempty(insigma)
if all(size(myeval(xstart)) > 1)
- insigma = std(xstart, 0, 2);
+ insigma = std(xstart, 0, 2);
if any(insigma == 0)
error(['Initial search volume is zero, choose SIGMA or X0 appropriate']);
end
@@ -338,7 +338,7 @@ end
% Compose options opts
if nargin < 4 || isempty(inopts) % no input options available
- inopts = [];
+ inopts = [];
opts = defopts;
else
opts = getoptions(inopts, defopts);
@@ -348,59 +348,59 @@ if ~isempty(i)
opts.SaveFilename = opts.SaveFilename(1:i(1)-1);
end
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-counteval = 0; countevalNaN = 0;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+counteval = 0; countevalNaN = 0;
irun = 0;
while irun <= myeval(opts.Restarts) % for-loop does not work with resume
- irun = irun + 1;
+ irun = irun + 1;
% ------------------------ Initialization -------------------------------
% Handle resuming of old run
flgresume = myevalbool(opts.Resume);
- xmean = myeval(xstart);
+ xmean = myeval(xstart);
if all(size(xmean) > 1)
xmean = mean(xmean, 2); % in case if xstart is a population
elseif size(xmean, 2) > 1
xmean = xmean';
- end
+ end
if ~flgresume % not resuming a former run
% Assign settings from input parameters and options for myeval...
- N = size(xmean, 1); numberofvariables = N;
- lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1));
- % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2));
+ N = size(xmean, 1); numberofvariables = N;
+ lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1));
+ % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2));
popsize = lambda0;
lambda = lambda0;
insigma = myeval(insigma);
- if all(size(insigma) == [N 2])
+ if all(size(insigma) == [N 2])
insigma = 0.5 * (insigma(:,2) - insigma(:,1));
end
else % flgresume is true, do resume former run
tmp = whos('-file', opts.SaveFilename);
for i = 1:length(tmp)
- if strcmp(tmp(i).name, 'localopts');
+ if strcmp(tmp(i).name, 'localopts')
error('Saved variables include variable "localopts", please remove');
end
end
local.opts = opts; % keep stopping and display options
local.varargin = varargin;
- load(opts.SaveFilename);
+ load(opts.SaveFilename);
varargin = local.varargin;
flgresume = 1;
% Overwrite old stopping and display options
- opts.StopFitness = local.opts.StopFitness;
+ opts.StopFitness = local.opts.StopFitness;
%%opts.MaxFunEvals = local.opts.MaxFunEvals;
- %%opts.MaxIter = local.opts.MaxIter;
- opts.StopFunEvals = local.opts.StopFunEvals;
- opts.StopIter = local.opts.StopIter;
+ %%opts.MaxIter = local.opts.MaxIter;
+ opts.StopFunEvals = local.opts.StopFunEvals;
+ opts.StopIter = local.opts.StopIter;
opts.TolX = local.opts.TolX;
opts.TolUpX = local.opts.TolUpX;
opts.TolFun = local.opts.TolFun;
opts.TolHistFun = local.opts.TolHistFun;
- opts.StopOnStagnation = local.opts.StopOnStagnation;
- opts.StopOnWarnings = local.opts.StopOnWarnings;
- opts.ReadSignals = local.opts.ReadSignals;
+ opts.StopOnStagnation = local.opts.StopOnStagnation;
+ opts.StopOnWarnings = local.opts.StopOnWarnings;
+ opts.ReadSignals = local.opts.ReadSignals;
opts.DispFinal = local.opts.DispFinal;
opts.LogPlot = local.opts.LogPlot;
opts.DispModulo = local.opts.DispModulo;
@@ -409,38 +409,38 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
opts.LogTime = local.opts.LogTime;
clear local; % otherwise local would be overwritten during load
end
-
+
%--------------------------------------------------------------
% Evaluate options
- stopFitness = myeval(opts.StopFitness);
- stopMaxFunEvals = myeval(opts.MaxFunEvals);
- stopMaxIter = myeval(opts.MaxIter);
- stopFunEvals = myeval(opts.StopFunEvals);
- stopIter = myeval(opts.StopIter);
+ stopFitness = myeval(opts.StopFitness);
+ stopMaxFunEvals = myeval(opts.MaxFunEvals);
+ stopMaxIter = myeval(opts.MaxIter);
+ stopFunEvals = myeval(opts.StopFunEvals);
+ stopIter = myeval(opts.StopIter);
stopTolX = myeval(opts.TolX);
stopTolUpX = myeval(opts.TolUpX);
stopTolFun = myeval(opts.TolFun);
stopTolHistFun = myeval(opts.TolHistFun);
- stopOnStagnation = myevalbool(opts.StopOnStagnation);
- stopOnWarnings = myevalbool(opts.StopOnWarnings);
+ stopOnStagnation = myevalbool(opts.StopOnStagnation);
+ stopOnWarnings = myevalbool(opts.StopOnWarnings);
flgreadsignals = myevalbool(opts.ReadSignals);
flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues);
flgEvalParallel = myevalbool(opts.EvalParallel);
stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues);
arrEqualFunvals = zeros(1,10+N);
- flgDiagonalOnly = myeval(opts.DiagonalOnly);
- flgActiveCMA = myeval(opts.CMA.active);
+ flgDiagonalOnly = myeval(opts.DiagonalOnly);
+ flgActiveCMA = myeval(opts.CMA.active);
noiseHandling = myevalbool(opts.Noise.on);
noiseMinMaxEvals = myeval(opts.Noise.minmaxevals);
noiseAlphaEvals = myeval(opts.Noise.alphaevals);
- noiseCallback = myeval(opts.Noise.callback);
+ noiseCallback = myeval(opts.Noise.callback);
flgdisplay = myevalbool(opts.DispFinal);
flgplotting = myevalbool(opts.LogPlot);
verbosemodulo = myeval(opts.DispModulo);
flgscience = myevalbool(opts.Science);
flgsaving = [];
strsaving = [];
- if strfind(opts.SaveVariables, '-v6')
+ if strfind(opts.SaveVariables, '-v6')
i = strfind(opts.SaveVariables, '%');
if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i
strsaving = '-v6';
@@ -464,7 +464,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1);
end
- % TODO here silent option? set disp, save and log options to 0
+ % TODO here silent option? set disp, save and log options to 0
%--------------------------------------------------------------
@@ -473,27 +473,27 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
- % Do more checking and initialization
+ % Do more checking and initialization
if flgresume % resume is on
time.t0 = clock;
if flgdisplay
- disp([' resumed from ' opts.SaveFilename ]);
+ disp([' resumed from ' opts.SaveFilename ]);
end
- if counteval >= stopMaxFunEvals
+ if counteval >= stopMaxFunEvals
error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ...
'criterion before resume']);
end
- if countiter >= stopMaxIter
+ if countiter >= stopMaxIter
error(['MaxIter exceeded, use StopIter as stopping criterion ' ...
'before resume']);
end
-
+
else % flgresume
% xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun
maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change
- mindx = myeval(opts.DiffMinChange); % minimal sensible variable change
+ mindx = myeval(opts.DiffMinChange); % minimal sensible variable change
% can both also be defined as Nx1 vectors
- lbounds = myeval(opts.LBounds);
+ lbounds = myeval(opts.LBounds);
ubounds = myeval(opts.UBounds);
if length(lbounds) == 1
lbounds = repmat(lbounds, N, 1);
@@ -540,9 +540,9 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
error(['option ubounds should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
end
-
+
% Initialize dynamic internal state parameters
- if any(insigma <= 0)
+ if any(insigma <= 0)
error(['Initial search volume (SIGMA) must be greater than zero']);
end
if max(insigma)/min(insigma) > 1e6
@@ -555,14 +555,14 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
insigma = insigma * ones(N,1) ;
end
diagD = insigma/max(insigma); % diagonal matrix D defines the scaling
- diagC = diagD.^2;
+ diagC = diagD.^2;
if flgDiagonalOnly ~= 1 % use at some point full covariance matrix
B = eye(N,N); % B defines the coordinate system
BD = B.*repmat(diagD',N,1); % B*D for speed up only
C = diag(diagC); % covariance matrix == BD*(BD)'
end
if flgDiagonalOnly
- B = 1;
+ B = 1;
end
fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
@@ -571,30 +571,30 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
fitness.histmedian=[]; % history of fitness values
% Initialize boundary handling
- bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf);
+ bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf);
if bnd.isactive
if any(lbounds>ubounds)
error('lower bound found to be greater than upper bound');
end
- [xmean ti] = xintobounds(xmean, lbounds, ubounds); % just in case
+ [xmean, ti] = xintobounds(xmean, lbounds, ubounds); % just in case
if any(ti)
warning('Initial point was out of bounds, corrected');
end
bnd.weights = zeros(N,1); % weights for bound penalty
% scaling is better in axis-parallel case, worse in rotated
- bnd.flgscale = 0; % scaling will be omitted if zero
- if bnd.flgscale ~= 0
+ bnd.flgscale = 0; % scaling will be omitted if zero
+ if bnd.flgscale ~= 0
bnd.scale = diagC/mean(diagC);
else
bnd.scale = ones(N,1);
end
-
+
idx = (lbounds > -Inf) | (ubounds < Inf);
if length(idx) == 1
idx = idx * ones(N,1);
end
bnd.isbounded = zeros(N,1);
- bnd.isbounded(find(idx)) = 1;
+ bnd.isbounded(find(idx)) = 1;
maxdx = min(maxdx, (ubounds - lbounds)/2);
if any(sigma*sqrt(diagC) > maxdx)
fac = min(maxdx ./ sqrt(diagC))/sigma;
@@ -611,7 +611,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
'given boundary intervals. For reasonable ' ...
'global search performance SIGMA should be ' ...
'between 0.2 and 0.5 of the bounded interval in ' ...
- 'each coordinate. If all coordinates have ' ...
+ 'each coordinate. If all coordinates have ' ...
'lower and upper bounds SIGMA can be empty']);
end
bnd.dfithist = 1; % delta fit for setting weights
@@ -622,27 +622,27 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
% ooo initial feval, for output only
- if irun == 1
+ if irun == 1
out.solutions.bestever.x = xmean;
out.solutions.bestever.f = Inf; % for simpler comparison below
out.solutions.bestever.evals = counteval;
bestever = out.solutions.bestever;
end
if myevalbool(opts.EvalInitialX)
- fitness.hist(1)=feval(fitfun, xmean, varargin{:});
+ fitness.hist(1)=feval(fitfun, xmean, varargin{:});
fitness.histsel(1)=fitness.hist(1);
counteval = counteval + 1;
- if fitness.hist(1) < out.solutions.bestever.f
+ if fitness.hist(1) < out.solutions.bestever.f
out.solutions.bestever.x = xmean;
out.solutions.bestever.f = fitness.hist(1);
out.solutions.bestever.evals = counteval;
bestever = out.solutions.bestever;
end
else
- fitness.hist(1)=NaN;
- fitness.histsel(1)=NaN;
+ fitness.hist(1)=NaN;
+ fitness.histsel(1)=NaN;
end
-
+
% initialize random number generator
% $$$ if ischar(opts.Seed)
% $$$ randn('state', eval(opts.Seed)); % random number generator state
@@ -656,22 +656,22 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% startseed = randn('state'); % for retrieving in saved variables
% Initialize further constants
- chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of
+ chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of
% ||N(0,I)|| == norm(randn(N,1))
-
+
countiter = 0;
% Initialize records and output
if irun == 1
time.t0 = clock;
-
- % TODO: keep also median solution?
+
+ % TODO: keep also median solution?
out.evals = counteval; % should be first entry
out.stopflag = {};
outiter = 0;
- % Write headers to output data files
- filenameprefix = opts.LogFilenamePrefix;
+ % Write headers to output data files
+ filenameprefix = opts.LogFilenamePrefix;
if savemodulo && savetime
filenames = {};
filenames(end+1) = {'axlen'};
@@ -685,7 +685,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
name = namecell{:};
[fid, err] = fopen(['./' filenameprefix name '.dat'], 'w');
- if fid < 1 % err ~= 0
+ if fid < 1 % err ~= 0
warning(['could not open ' filenameprefix name '.dat']);
filenames(find(strcmp(filenames,name))) = [];
else
@@ -719,20 +719,20 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
fprintf(fid, '\n'); % DATA
if strcmp(name, 'xmean')
- fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval);
- % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
- %qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n');
+ fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval);
+ % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
+ %qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n');
fprintf(fid, '%e ', xmean);
- fprintf(fid, '\n');
+ fprintf(fid, '\n');
end
- fclose(fid);
- clear fid; % preventing
+ fclose(fid);
+ clear fid; % preventing
end
end % for files
end % savemodulo
end % irun == 1
-
- end % else flgresume
+
+ end % else flgresume
% -------------------- Generation Loop --------------------------------
stopflag = {};
@@ -744,15 +744,15 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
disp([' lambda = ' num2str(lambda)]);
lambda_hist(:,end+1) = [countiter+1; lambda];
else
- lambda_hist = [countiter+1; lambda];
+ lambda_hist = [countiter+1; lambda];
end
lambda_last = lambda;
- % Strategy internal parameter setting: Selection
+ % Strategy internal parameter setting: Selection
mu = myeval(opts.ParentNumber); % number of parents/points for recombination
if strncmp(lower(opts.RecombinationWeights), 'equal', 3)
weights = ones(mu,1); % (mu_I,lambda)-CMA-ES
elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3)
- weights = mu+0.5-(1:mu)';
+ weights = mu+0.5-(1:mu)';
elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3)
weights = log(mu+0.5)-log(1:mu)'; % muXone array for weighted recombination
% qqq mu can be non-integer and
@@ -767,50 +767,50 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
error(['Combination of values for PopSize, ParentNumber and ' ...
' and RecombinationWeights is not reasonable']);
end
-
+
% Strategy internal parameter setting: Adaptation
cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix
- cs = myeval(opts.CMA.cs);
+ cs = myeval(opts.CMA.cs);
% old way TODO: remove this at some point
% mucov = mueff; % size of mu used for calculating learning rate ccov
% ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix
- % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov));
+ % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov));
% new way
- if myevalbool(opts.CMA.on)
- ccov1 = myeval(opts.CMA.ccov1);
+ if myevalbool(opts.CMA.on)
+ ccov1 = myeval(opts.CMA.ccov1);
ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu));
else
ccov1 = 0;
ccovmu = 0;
end
-
+
% flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed
% 0 : C will never be diagonal anymore
% 1 : C will always be diagonal
% >1: C is diagonal for first iterations, set to 0 afterwards
if flgDiagonalOnly < 1
- flgDiagonalOnly = 0;
+ flgDiagonalOnly = 0;
end
if flgDiagonalOnly
- ccov1_sep = min(1, ccov1 * (N+1.5) / 3);
- ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3);
+ ccov1_sep = min(1, ccov1 * (N+1.5) / 3);
+ ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3);
elseif N > 98 && flgdisplay && countiter == 0
disp('consider option DiagonalOnly for high-dimensional problems');
end
% ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness
- %damps = ... % damping for step size control, usually close to one
+ %damps = ... % damping for step size control, usually close to one
% (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase
% * max(0.3, ... % reduce damps, if max. iteration number is small
- % 1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs;
- damps = myeval(opts.CMA.damps);
+ % 1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs;
+ damps = myeval(opts.CMA.damps);
if noiseHandling
- noiseReevals = min(myeval(opts.Noise.reevals), lambda);
- noiseAlpha = myeval(opts.Noise.alphasigma);
- noiseEpsilon = myeval(opts.Noise.epsilon);
- noiseTheta = myeval(opts.Noise.theta);
+ noiseReevals = min(myeval(opts.Noise.reevals), lambda);
+ noiseAlpha = myeval(opts.Noise.alphasigma);
+ noiseEpsilon = myeval(opts.Noise.epsilon);
+ noiseTheta = myeval(opts.Noise.theta);
noisecum = myeval(opts.Noise.cum);
noiseCutOff = myeval(opts.Noise.cutoff); % arguably of minor relevance
else
@@ -818,25 +818,25 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
%qqq hacking of a different parameter setting, e.g. for ccov or damps,
- % can be done here, but is not necessary anymore, see opts.CMA.
+ % can be done here, but is not necessary anymore, see opts.CMA.
% ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]);
% ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]);
% damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]);
% cc = 1; disp(['CAVE: cc=' num2str(cc)]);
- end
+ end
% Display initial message
- if countiter == 0 && flgdisplay
+ if countiter == 0 && flgdisplay
if mu == 1
strw = '100';
elseif mu < 8
- strw = [sprintf('%.0f', 100*weights(1)) ...
+ strw = [sprintf('%.0f', 100*weights(1)) ...
sprintf(' %.0f', 100*weights(2:end)')];
else
strw = [sprintf('%.2g ', 100*weights(1:2)') ...
sprintf('%.2g', 100*weights(3)') '...' ...
- sprintf(' %.2g', 100*weights(end-1:end)') ']%, '];
+ sprintf(' %.2g', 100*weights(end-1:end)') ']%, '];
end
if irun > 1
strrun = [', run ' num2str(irun)];
@@ -858,10 +858,10 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
flush;
- countiter = countiter + 1;
+ countiter = countiter + 1;
% Generate and evaluate lambda offspring
-
+
fitness.raw = repmat(NaN, 1, lambda + noiseReevals);
% parallel evaluation
@@ -871,20 +871,20 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
if ~flgDiagonalOnly
arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1)
else
- arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz;
+ arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz;
end
- if noiseHandling
+ if noiseHandling
if noiseEpsilon == 0
- arx = [arx arx(:,1:noiseReevals)];
+ arx = [arx arx(:,1:noiseReevals)];
elseif flgDiagonalOnly
arx = [arx arx(:,1:noiseReevals) + ...
repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ...
- .* randn(N,noiseReevals)];
- else
+ .* randn(N,noiseReevals)];
+ else
arx = [arx arx(:,1:noiseReevals) + ...
noiseEpsilon * sigma * ...
- (BD * randn(N,noiseReevals))];
+ (BD * randn(N,noiseReevals))];
end
end
@@ -893,7 +893,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% (the latter will decrease the overall step size) and
% recalculate arx accordingly. Do not change arx or arz in any
% other way.
-
+
if ~bnd.isactive
arxvalid = arx;
else
@@ -902,41 +902,41 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% You may handle constraints here. You may copy and alter
% (columns of) arxvalid(:,k) only for the evaluation of the
% fitness function. arx and arxvalid should not be changed.
- fitness.raw = feval(fitfun, arxvalid, varargin{:});
+ fitness.raw = feval(fitfun, arxvalid, varargin{:});
countevalNaN = countevalNaN + sum(isnan(fitness.raw));
- counteval = counteval + sum(~isnan(fitness.raw));
+ counteval = counteval + sum(~isnan(fitness.raw));
end
% non-parallel evaluation and remaining NaN-values
% set also the reevaluated solution to NaN
- fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN;
- for k=find(isnan(fitness.raw)),
- % fitness.raw(k) = NaN;
+ fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN;
+ for k=find(isnan(fitness.raw))
+ % fitness.raw(k) = NaN;
tries = 0;
% Resample, until fitness is not NaN
while isnan(fitness.raw(k))
if k <= lambda % regular samples (not the re-evaluation-samples)
arz(:,k) = randn(N,1); % (re)sample
- if flgDiagonalOnly
+ if flgDiagonalOnly
arx(:,k) = xmean + sigma * diagD .* arz(:,k); % Eq. (1)
else
arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1)
end
else % re-evaluation solution with index > lambda
- if flgDiagonalOnly
+ if flgDiagonalOnly
arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1);
else
arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1));
end
end
-
+
% You may handle constraints here. You may either resample
% arz(:,k) and/or multiply it with a factor between -1 and 1
% (the latter will decrease the overall step size) and
% recalculate arx accordingly. Do not change arx or arz in any
% other way.
-
+
if ~bnd.isactive
arxvalid(:,k) = arx(:,k);
else
@@ -945,7 +945,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% You may handle constraints here. You may copy and alter
% (columns of) arxvalid(:,k) only for the evaluation of the
% fitness function. arx should not be changed.
- fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:});
+ fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:});
tries = tries + 1;
if isnan(fitness.raw(k))
countevalNaN = countevalNaN + 1;
@@ -959,7 +959,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
counteval = counteval + 1; % retries due to NaN are not counted
end
- fitness.sel = fitness.raw;
+ fitness.sel = fitness.raw;
% ----- handle boundaries -----
if 1 < 3 && bnd.isactive
@@ -969,10 +969,10 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
val = (val(2) - val(1)) / N / mean(diagC) / sigma^2;
%val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ...
% / N / mean(diagC) / sigma^2;
- % Catch non-sensible values
+ % Catch non-sensible values
if ~isfinite(val)
warning('Non-finite fitness range');
- val = max(bnd.dfithist);
+ val = max(bnd.dfithist);
elseif val == 0 % happens if all points are out of bounds
val = min(bnd.dfithist(bnd.dfithist>0)); % seems not to make sense, given all solutions are out of bounds
elseif bnd.validfitval == 0 % flag that first sensible val was found
@@ -987,17 +987,17 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
bnd.dfithist = [bnd.dfithist(2:end) val];
end
- [tx ti] = xintobounds(xmean, lbounds, ubounds);
+ [tx, ti] = xintobounds(xmean, lbounds, ubounds);
% Set initial weights
- if bnd.iniphase
- if any(ti)
+ if bnd.iniphase
+ if any(ti)
bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist);
if bnd.flgscale == 0 % scale only initial weights then
- dd = diagC;
- idx = find(bnd.isbounded);
+ dd = diagC;
+ idx = find(bnd.isbounded);
dd = dd(idx) / mean(dd); % remove mean scaling
- bnd.weights(idx) = bnd.weights(idx) ./ dd;
+ bnd.weights(idx) = bnd.weights(idx) ./ dd;
end
if bnd.validfitval && countiter > 2
bnd.iniphase = 0;
@@ -1009,40 +1009,40 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
if 1 < 3 && any(ti) % any coordinate of xmean out of bounds
% judge distance of xmean to boundary
tx = xmean - tx;
- idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ...
+ idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ...
* sigma*sqrt(diagC)) ;
% only increase if xmean is moving away
idx = idx & (sign(tx) == sign(xmean - xold));
if ~isempty(idx) % increase
% the factor became 1.2 instead of 1.1, because
% changed from max to min in version 3.52
- bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx);
+ bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx);
end
end
% Calculate scaling biased to unity, product is one
- if bnd.flgscale ~= 0
- bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC))));
+ if bnd.flgscale ~= 0
+ bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC))));
end
% Assigned penalized fitness
- bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2;
+ bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2;
fitness.sel = fitness.raw + bnd.arpenalty;
end % handle boundaries
% ----- end handle boundaries -----
-
+
% compute noise measurement and reduce fitness arrays to size lambda
- if noiseHandling
+ if noiseHandling
[noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ...
fitness.sel(lambda+(1:noiseReevals)), ...
- noiseReevals, noiseTheta, noiseCutOff);
+ noiseReevals, noiseTheta, noiseCutOff);
if countiter == 1 % TODO: improve this very rude way of initialization
noiseSS = 0;
noiseN = 0; % counter for mean
end
- noiseSS = noiseSS + noisecum * (noiseS - noiseSS);
+ noiseSS = noiseSS + noisecum * (noiseS - noiseSS);
% noise-handling could be done here, but the original sigma is still needed
% disp([noiseS noiseSS noisecum])
@@ -1050,19 +1050,19 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
fitness.rawar12 = fitness.raw; % just documentary
fitness.selar12 = fitness.sel; % just documentary
% qqq refine fitness based on both values
- if 11 < 3 % TODO: in case of outliers this mean is counterproductive
- % median out of three would be ok
+ if 11 < 3 % TODO: in case of outliers this mean is counterproductive
+ % median out of three would be ok
fitness.raw(1:noiseReevals) = ... % not so raw anymore
- (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2;
- fitness.sel(1:noiseReevals) = ...
- (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2;
- end
- fitness.raw = fitness.raw(1:lambda);
- fitness.sel = fitness.sel(1:lambda);
+ (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2;
+ fitness.sel(1:noiseReevals) = ...
+ (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2;
+ end
+ fitness.raw = fitness.raw(1:lambda);
+ fitness.sel = fitness.sel(1:lambda);
end
-
- % Sort by fitness
- [fitness.raw, fitness.idx] = sort(fitness.raw);
+
+ % Sort by fitness
+ [fitness.raw, fitness.idx] = sort(fitness.raw);
[fitness.sel, fitness.idxsel] = sort(fitness.sel); % minimization
fitness.hist(2:end) = fitness.hist(1:end-1); % record short history of
fitness.hist(1) = fitness.raw(1); % best fitness values
@@ -1071,17 +1071,17 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
fitness.histbest = [fitness.raw(1) fitness.histbest]; % best fitness values
fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values
else
- fitness.histbest(2:end) = fitness.histbest(1:end-1);
- fitness.histmedian(2:end) = fitness.histmedian(1:end-1);
+ fitness.histbest(2:end) = fitness.histbest(1:end-1);
+ fitness.histmedian(2:end) = fitness.histmedian(1:end-1);
fitness.histbest(1) = fitness.raw(1); % best fitness values
fitness.histmedian(1) = median(fitness.raw); % median fitness values
end
fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of
fitness.histsel(1) = fitness.sel(1); % best sel fitness values
- % Calculate new xmean, this is selection and recombination
+ % Calculate new xmean, this is selection and recombination
xold = xmean; % for speed up of Eq. (2) and (3)
- xmean = arx(:,fitness.idxsel(1:mu))*weights;
+ xmean = arx(:,fitness.idxsel(1:mu))*weights;
zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma
if mu == 1
fmean = fitness.sel(1);
@@ -1090,7 +1090,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
% counteval = counteval + 1;
end
-
+
% Cumulation: update evolution paths
ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean); % Eq. (4)
hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
@@ -1112,7 +1112,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
neg.ccov = 0; % TODO: move parameter setting upwards at some point
if ccov1 + ccovmu > 0 % Eq. (3)
if flgDiagonalOnly % internal linear(?) complexity
- diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix
+ diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix
+ ccov1_sep * pc.^2 ... % plus rank one update
+ ccovmu_sep ... % plus rank mu update
* (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights));
@@ -1120,37 +1120,37 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
diagD = sqrt(diagC); % replaces eig(C)
else
arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma;
- % "active" CMA update: negative update, in case controlling pos. definiteness
+ % "active" CMA update: negative update, in case controlling pos. definiteness
if flgActiveCMA > 0
% set parameters
- neg.mu = mu;
+ neg.mu = mu;
neg.mueff = mueff;
if flgActiveCMA > 10 % flat weights with mu=lambda/2
- neg.mu = floor(lambda/2);
+ neg.mu = floor(lambda/2);
neg.mueff = neg.mu;
end
- % neg.mu = ceil(min([N, lambda/4, mueff])); neg.mueff = mu; % i.e. neg.mu <= N
- % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a
- % three times larger neg.ccov does not work.
+ % neg.mu = ceil(min([N, lambda/4, mueff])); neg.mueff = mu; % i.e. neg.mu <= N
+ % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a
+ % three times larger neg.ccov does not work.
% increasing all ccov rates three times does work (probably because of the factor (1-ccovmu))
% in 30-D to looks fine
neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff);
neg.minresidualvariance = 0.66; % keep at least 0.66 in all directions, small popsize are most critical
neg.alphaold = 0.5; % where to make up for the variance loss, 0.5 means no idea what to do
- % 1 is slightly more robust and gives a better "guaranty" for pos. def.,
- % but does it make sense from the learning perspective for large ccovmu?
+ % 1 is slightly more robust and gives a better "guaranty" for pos. def.,
+ % but does it make sense from the learning perspective for large ccovmu?
neg.ccovfinal = neg.ccov;
% prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck
arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1));
% i-th longest becomes i-th shortest
- % TODO: this is not in compliance with the paper Hansen&Ros2010,
- % where simply arnorms = arnorms(end:-1:1) ?
- [arnorms idxnorms] = sort(sqrt(sum(arzneg.^2, 1)));
- [ignore idxnorms] = sort(idxnorms); % inverse index
- arnormfacs = arnorms(end:-1:1) ./ arnorms;
+ % TODO: this is not in compliance with the paper Hansen&Ros2010,
+ % where simply arnorms = arnorms(end:-1:1) ?
+ [arnorms, idxnorms] = sort(sqrt(sum(arzneg.^2, 1)));
+ [ignore, idxnorms] = sort(idxnorms); % inverse index
+ arnormfacs = arnorms(end:-1:1) ./ arnorms;
% arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms;
arnorms = arnorms(end:-1:1); % for the record
if flgActiveCMA < 20
@@ -1158,7 +1158,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1); % E x*x' is N
end
if flgActiveCMA < 10 && neg.mu == mu % weighted sum
- if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below)
+ if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below)
Ccheck = arzneg * diag(weights) * arzneg'; % in order to check the largest EV
end
artmp = BD * arzneg;
@@ -1172,14 +1172,14 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
- % check pos.def. and set learning rate neg.ccov accordingly,
- % this check makes the original choice of neg.ccov extremly failsafe
- % still assuming C == BD*BD', which is only approxim. correct
+ % check pos.def. and set learning rate neg.ccov accordingly,
+ % this check makes the original choice of neg.ccov extremly failsafe
+ % still assuming C == BD*BD', which is only approxim. correct
if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance
% TODO: the simple and cheap way would be to set
% fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and
% neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights)
- % this is the more sophisticated way:
+ % this is the more sophisticated way:
% maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts); % not faster
maxeigenval = max(eig(Ccheck)); % norm is much slower, because (norm()==max(svd())
%disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ...
@@ -1187,22 +1187,22 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% pause
% remove less than ??34*(1-cmu)%?? of variance in any direction
% 1-ccovmu is the variance left from the old C
- neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval);
+ neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval);
% -ccov1 removed to avoid error message??
if neg.ccovfinal < neg.ccov
disp(['active CMA at iteration ' num2str(countiter) ...
': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]);
end
end
- % xmean = xold; % the distribution does not degenerate!?
+ % xmean = xold; % the distribution does not degenerate!?
% update C
- C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+ C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+ ccov1 * pc*pc' ... % plus rank one update
+ (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ... % plus rank mu update
* arpos * (repmat(weights,1,N) .* arpos') ...
- neg.ccovfinal * Cneg; % minus rank mu update
else % no active (negative) update
- C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+ C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+ ccov1 * pc*pc' ... % plus rank one update
+ ccovmu ... % plus rank mu update
* arpos * (repmat(weights,1,N) .* arpos');
@@ -1212,12 +1212,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
diagC = diag(C);
end
end
-
+
% the following is de-preciated and will be removed in future
% better setting for cc makes this hack obsolete
- if 11 < 2 && ~flgscience
+ if 11 < 2 && ~flgscience
% remove momentum in ps, if ps is large and fitness is getting worse.
- % this should rarely happen.
+ % this should rarely happen.
% this might very well be counterproductive in dynamic environments
if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ...
fitness.histsel(1) > max(fitness.histsel(2:3))
@@ -1238,7 +1238,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps)); % Eq. (5)
end
% disp([countiter norm(ps)/chiN]);
-
+
if 11 < 3 % testing with optimal step-size
if countiter == 1
disp('*********** sigma set to const * ||x|| ******************');
@@ -1248,23 +1248,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% 75e3 with def (1.5)
% 35e3 with damps=0.25
end
- if 11 < 3
+ if 11 < 3
if countiter == 1
disp('*********** xmean set to const ******************');
end
xmean = ones(N,1);
end
-
+
% Update B and D from C
if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1
C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers
[B,tmp] = eig(C); % eigen decomposition, B==normalized eigenvectors
% effort: approx. 15*N matrix-vector multiplications
- diagD = diag(tmp);
+ diagD = diag(tmp);
if any(~isfinite(diagD))
- clear idx; % prevents error under octave
+ clear idx; % prevents error under octave
save(['tmp' opts.SaveFilename]);
error(['function eig returned non-finited eigenvalues, cond(C)=' ...
num2str(cond(C)) ]);
@@ -1285,21 +1285,21 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
': Eigenvalue (smaller) zero']);
diagD(diagD<0) = 0;
tmp = max(diagD)/1e14;
- C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
+ C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
end
end
- if max(diagD) > 1e14*min(diagD)
+ if max(diagD) > 1e14*min(diagD)
if stopOnWarnings
stopflag(end+1) = {'warnconditioncov'};
else
warning(['Iteration ' num2str(countiter) ': condition of C ' ...
'at upper limit' ]);
tmp = max(diagD)/1e14 - min(diagD);
- C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
+ C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
end
end
- diagC = diag(C);
+ diagC = diag(C);
diagD = sqrt(diagD); % D contains standard deviations now
% diagD = diagD / prod(diagD)^(1/N); C = C / prod(diagD)^(2/N);
BD = B.*repmat(diagD',N,1); % O(n^2)
@@ -1311,23 +1311,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
fac = sigma / max(diagD);
sigma = sigma/fac;
pc = fac * pc;
- diagD = fac * diagD;
+ diagD = fac * diagD;
if ~flgDiagonalOnly
C = fac^2 * C; % disp(fac);
BD = B.*repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo?
end
- diagC = fac^2 * diagC;
+ diagC = fac^2 * diagC;
end
- if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly
- % full covariance matrix from now on
- flgDiagonalOnly = 0;
+ if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly
+ % full covariance matrix from now on
+ flgDiagonalOnly = 0;
B = eye(N,N);
BD = diag(diagD);
C = diag(diagC); % is better, because correlations are spurious anyway
end
- if noiseHandling
+ if noiseHandling
if countiter == 1 % assign firstvarargin for noise treatment e.g. as #reevaluations
if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1})
if irun == 1
@@ -1342,18 +1342,18 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4)); % still experimental
elseif noiseSS > 0
- if ~isempty(noiseCallback) % to be removed?
+ if ~isempty(noiseCallback) % to be removed?
res = feval(noiseCallback); % should also work without output argument!?
if ~isempty(res) && res > 1 % TODO: decide for interface of callback
- % also a dynamic popsize could be done here
+ % also a dynamic popsize could be done here
sigma = sigma * noiseAlpha;
end
else
if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals);
end
-
- sigma = sigma * noiseAlpha;
+
+ sigma = sigma * noiseAlpha;
% lambda = ceil(0.1 * sqrt(lambda) + lambda);
% TODO: find smallest increase of lambda with log-linear
% convergence in iterations
@@ -1361,9 +1361,9 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
% qqq experimental: take a mean to estimate the true optimum
noiseN = noiseN + 1;
if noiseN == 1
- noiseX = xmean;
+ noiseX = xmean;
else
- noiseX = noiseX + (3/noiseN) * (xmean - noiseX);
+ noiseX = noiseX + (3/noiseN) * (xmean - noiseX);
end
end
end
@@ -1378,13 +1378,13 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
% Adjust minimal coordinate axis deviations
if any(sigma*sqrt(diagC) < mindx)
- sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps);
+ sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps);
%warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
% 'deviation at lower limit of ' num2str(mindx)]);
% stopflag(end+1) = {'mincoorddev'};;
end
% Adjust too low coordinate axis deviations
- if any(xmean == xmean + 0.2*sigma*sqrt(diagC))
+ if any(xmean == xmean + 0.2*sigma*sqrt(diagC))
if stopOnWarnings
stopflag(end+1) = {'warnnoeffectcoord'};
else
@@ -1397,12 +1397,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
C = C + (ccov1+ccovmu) * diag(diagC .* ...
(xmean == xmean + 0.2*sigma*sqrt(diagC)));
end
- sigma = sigma * exp(0.05+cs/damps);
+ sigma = sigma * exp(0.05+cs/damps);
end
end
- % Adjust step size in case of (numerical) precision problem
+ % Adjust step size in case of (numerical) precision problem
if flgDiagonalOnly
- tmp = 0.1*sigma*diagD;
+ tmp = 0.1*sigma*diagD;
else
tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N)));
end
@@ -1414,18 +1414,18 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
warning(['Iteration ' num2str(countiter) ...
': main axis standard deviation ' ...
num2str(sigma*diagD(i)) ' has no effect' ]);
- sigma = sigma * exp(0.2+cs/damps);
+ sigma = sigma * exp(0.2+cs/damps);
end
end
% Adjust step size in case of equal function values (flat fitness)
- % isequalfuncvalues = 0;
+ % isequalfuncvalues = 0;
if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4))
- % isequalfuncvalues = 1;
+ % isequalfuncvalues = 1;
if stopOnEqualFunctionValues
arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)];
% stop if this happens in more than 33%
if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals)
- stopflag(end+1) = {'equalfunvals'};
+ stopflag(end+1) = {'equalfunvals'};
end
else
if flgWarnOnEqualFunctionValues
@@ -1434,23 +1434,23 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
' at maximal main axis sigma ' ...
num2str(sigma*max(diagD))]);
end
- sigma = sigma * exp(0.2+cs/damps);
+ sigma = sigma * exp(0.2+cs/damps);
end
end
% Adjust step size in case of equal function values
- if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0
+ if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0
if stopOnWarnings
stopflag(end+1) = {'warnequalfunvalhist'};
else
warning(['Iteration ' num2str(countiter) ...
': equal function values in history at maximal main ' ...
'axis sigma ' num2str(sigma*max(diagD))]);
- sigma = sigma * exp(0.2+cs/damps);
+ sigma = sigma * exp(0.2+cs/damps);
end
end
-
+
% ----- end numerical error management -----
-
+
% Keep overall best solution
out.evals = counteval;
out.solutions.evals = counteval;
@@ -1474,25 +1474,25 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end
if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end
if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end
- if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX)
+ if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX)
stopflag(end+1) = {'tolx'};
end
- if any(sigma*sqrt(diagC) > stopTolUpX)
+ if any(sigma*sqrt(diagC) > stopTolUpX)
stopflag(end+1) = {'tolupx'};
end
if sigma*max(diagD) == 0 % should never happen
stopflag(end+1) = {'bug'};
end
- if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun
+ if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun
stopflag(end+1) = {'tolfun'};
end
- if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun
+ if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun
stopflag(end+1) = {'tolhistfun'};
end
l = floor(length(fitness.histbest)/3);
if 1 < 2 && stopOnStagnation && ... % leads sometimes early stop on ftablet, fcigtab
- countiter > N * (5+100/lambda) && ...
- length(fitness.histbest) > 100 && ...
+ countiter > N * (5+100/lambda) && ...
+ length(fitness.histbest) > 100 && ...
median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ...
median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end))
stopflag(end+1) = {'stagnation'};
@@ -1504,19 +1504,19 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
error('To resume later the saving option needs to be set');
end
end
- % read stopping message from file signals.par
+ % read stopping message from file signals.par
if flgreadsignals
- fid = fopen('./signals.par', 'rt'); % can be performance critical
+ fid = fopen('./signals.par', 'rt'); % can be performance critical
while fid > 0
strline = fgetl(fid); %fgets(fid, 300);
if strline < 0 % fgets and fgetl returns -1 at end of file
- break;
+ break
end
% 'stop filename' sets stopflag to manual
str = sscanf(strline, ' %s %s', 2);
- if strcmp(str, ['stop' opts.LogFilenamePrefix])
+ if strcmp(str, ['stop' opts.LogFilenamePrefix])
stopflag(end+1) = {'manual'};
- break;
+ break
end
% 'skip filename run 3' skips a run, but not the last
str = sscanf(strline, ' %s %s %s', 3);
@@ -1524,29 +1524,29 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
i = strfind(strline, 'run');
if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts)
stopflag(end+1) = {'skipped'};
- end
+ end
end
- end % while, break
+ end % while, break
if fid > 0
fclose(fid);
clear fid; % prevents strange error under octave
end
end
-
+
out.stopflag = stopflag;
% ----- output generation -----
if verbosemodulo > 0 && isfinite(verbosemodulo)
- if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1
+ if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1
disp(['Iterat, #Fevals: Function Value (median,worst) ' ...
'|Axis Ratio|' ...
- 'idx:Min SD idx:Max SD']);
+ 'idx:Min SD idx:Max SD']);
end
if mod(countiter, verbosemodulo) < 1 ...
|| (verbosemodulo > 0 && isfinite(verbosemodulo) && ...
(countiter < 3 || ~isempty(stopflag)))
- [minstd minstdidx] = min(sigma*sqrt(diagC));
- [maxstd maxstdidx] = max(sigma*sqrt(diagC));
+ [minstd, minstdidx] = min(sigma*sqrt(diagC));
+ [maxstd, maxstdidx] = max(sigma*sqrt(diagC));
% format display nicely
disp([repmat(' ',1,4-floor(log10(countiter))) ...
num2str(countiter) ' , ' ...
@@ -1565,7 +1565,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
% measure time for recording data
- if countiter < 3
+ if countiter < 3
time.c = 0.05;
time.nonoutput = 0;
time.recording = 0;
@@ -1573,93 +1573,93 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
time.plotting = 0;
elseif countiter > 300
% set backward horizon, must be long enough to cover infrequent plotting etc
- % time.c = min(1, time.nonoutput/3 + 1e-9);
+ % time.c = min(1, time.nonoutput/3 + 1e-9);
time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5
end
% get average time per iteration
time.t1 = clock;
time.act = max(0,etime(time.t1, time.t0));
time.nonoutput = (1-time.c) * time.nonoutput ...
- + time.c * time.act;
+ + time.c * time.act;
time.recording = (1-time.c) * time.recording; % per iteration
time.saving = (1-time.c) * time.saving;
time.plotting = (1-time.c) * time.plotting;
-
+
% record output data, concerning time issues
if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ...
countiter >= outiter + savemodulo)
- outiter = countiter;
- % Save output data to files
+ outiter = countiter;
+ % Save output data to files
for namecell = filenames(:)'
name = namecell{:};
[fid, err] = fopen(['./' filenameprefix name '.dat'], 'a');
- if fid < 1 % err ~= 0
+ if fid < 1 % err ~= 0
warning(['could not open ' filenameprefix name '.dat']);
else
if strcmp(name, 'axlen')
fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ...
- max(diagD), min(diagD));
- fprintf(fid, '%e ', sort(diagD));
+ max(diagD), min(diagD));
+ fprintf(fid, '%e ', sort(diagD));
fprintf(fid, '\n');
elseif strcmp(name, 'disp') % TODO
elseif strcmp(name, 'fit')
fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ...
countiter, counteval, sigma, max(diagD)/min(diagD), ...
out.solutions.bestever.f, ...
- fitness.raw(1), median(fitness.raw), fitness.raw(end));
+ fitness.raw(1), median(fitness.raw), fitness.raw(end));
if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0
fprintf(fid, ' %f', varargin{1});
- end
+ end
fprintf(fid, '\n');
elseif strcmp(name, 'stddev')
- fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma);
- fprintf(fid, '%e ', sigma*sqrt(diagC));
+ fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma);
+ fprintf(fid, '%e ', sigma*sqrt(diagC));
fprintf(fid, '\n');
elseif strcmp(name, 'xmean')
if isnan(fmean)
- fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval);
+ fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval);
else
- fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
+ fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
end
- fprintf(fid, '%e ', xmean);
+ fprintf(fid, '%e ', xmean);
fprintf(fid, '\n');
elseif strcmp(name, 'xrecentbest')
% TODO: fitness is inconsistent with x-value
- fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1));
- fprintf(fid, '%e ', arx(:,fitness.idx(1)));
+ fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1));
+ fprintf(fid, '%e ', arx(:,fitness.idx(1)));
fprintf(fid, '\n');
end
- fclose(fid);
+ fclose(fid);
end
end
% get average time for recording data
time.t2 = clock;
- time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1));
-
+ time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1));
+
% plot
if flgplotting && countiter > 1
if countiter == 2
iterplotted = 0;
end
- if ~isempty(stopflag) || ...
+ if ~isempty(stopflag) || ...
((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ...
time.plotting < 0.05 * (time.nonoutput+time.recording))
local_plotcmaesdat(324, filenameprefix);
- iterplotted = countiter;
+ iterplotted = countiter;
% outplot(out); % outplot defined below
if time.plotting == 0 % disregard opening of the window
time.plotting = time.nonoutput+time.recording;
else
- time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2));
+ time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2));
end
end
end
if countiter > 100 + 20 && savemodulo && ...
time.recording * countiter > 0.1 && ... % absolute time larger 0.1 second
- time.recording > savetime * (time.nonoutput+time.recording) / 100
+ time.recording > savetime * (time.nonoutput+time.recording) / 100
savemodulo = floor(1.1 * savemodulo) + 1;
% disp('++savemodulo'); %qqq
end
@@ -1674,11 +1674,11 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
clear idx; % prevents error under octave
% -v6 : non-compressed non-unicode for version 6 and earlier
if ~isempty(strsaving) && ~isoctave
- save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
- else
+ save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
+ else
save('-mat', opts.SaveFilename); % for inspection and possible restart
end
- time.saving = time.saving + time.c * max(0,etime(clock, time.t3));
+ time.saving = time.saving + time.c * max(0,etime(clock, time.t3));
end
end
time.t0 = clock;
@@ -1703,7 +1703,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
end
if out.solutions.mean.f < out.solutions.bestever.f
out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point
- out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds);
+ out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds);
bestever = out.solutions.bestever;
end
end
@@ -1712,8 +1712,8 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
if flgsavingfinal
clear idx; % prevents error under octave
if ~isempty(strsaving) && ~isoctave
- save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
- else
+ save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
+ else
save('-mat', opts.SaveFilename); % for inspection and possible restart
end
message = [' (saved to ' opts.SaveFilename ')'];
@@ -1725,7 +1725,7 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
disp(['#Fevals: f(returned x) | bestever.f | stopflag' ...
message]);
if isoctave
- strstop = stopflag(:);
+ strstop = stopflag(:);
else
strcat(stopflag(:), '.');
end
@@ -1739,8 +1739,8 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
disp(['std deviation:' sprintf(' %.1e', sigma*sqrt(diagC))]);
disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)'));
end
- if exist('sfile', 'var')
- disp(['Results saved in ' sfile]);
+ if exist('sfile', 'var')
+ disp(['Results saved in ' sfile]);
end
end
@@ -1749,12 +1749,12 @@ while irun <= myeval(opts.Restarts) % for-loop does not work with resume
|| any(strcmp(stopflag, 'maxfunevals')) ...
|| any(strcmp(stopflag, 'stoptoresume')) ...
|| any(strcmp(stopflag, 'manual'))
- break;
+ break
end
end % while irun <= Restarts
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function [x, idx] = xintobounds(x, lbounds, ubounds)
%
% x can be a column vector or a matrix consisting of column vectors
@@ -1783,10 +1783,10 @@ if ~isempty(ubounds)
else
idx2 = 0;
end
-idx = idx2-idx;
+idx = idx2-idx;
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function opts=getoptions(inopts, defopts)
% OPTS = GETOPTIONS(INOPTS, DEFOPTS) handles an arbitrary number of
% optional arguments to a function. The given arguments are collected
@@ -1812,7 +1812,7 @@ function opts=getoptions(inopts, defopts)
% defopts.ParentNumber = 50;
% defopts.MaxIterations = 1e6;
% defopts.MaxSigma = 1;
-%
+%
% % merge default options with input options
% opts = getoptions(inopts, defopts);
%
@@ -1823,40 +1823,40 @@ function opts=getoptions(inopts, defopts)
% % do whatever
% end
% end
-%
+%
% For calling the function myfunction with default options:
% myfunction(argument1, []);
% For calling the function myfunction with modified options:
% opt.pop = 100; % redefine PopulationSize option
% opt.PAR = 10; % redefine ParentNumber option
-% opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error
+% opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error
% myfunction(argument1, opt);
%
% 04/07/19: Entries can be structs itself leading to a recursive
-% call to getoptions.
+% call to getoptions.
%
if nargin < 2 || isempty(defopts) % no default options available
opts=inopts;
- return;
+ return
elseif isempty(inopts) % empty inopts invoke default options
opts = defopts;
- return;
+ return
elseif ~isstruct(defopts) % handle a single option value
- if isempty(inopts)
+ if isempty(inopts)
opts = defopts;
elseif ~isstruct(inopts)
opts = inopts;
else
error('Input options are a struct, while default options are not');
end
- return;
+ return
elseif ~isstruct(inopts) % no valid input options
error('The options need to be a struct or empty');
end
-opts = defopts; % start from defopts
+opts = defopts; % start from defopts
% if necessary overwrite opts fields by inopts values
defnames = fieldnames(defopts);
idxmatched = []; % indices of defopts that already matched
@@ -1875,7 +1875,7 @@ for name = fieldnames(inopts)'
''') to remove the field from the struct.']);
end
if sum(idx) == 1
- defname = defnames{find(idx)};
+ defname = defnames{find(idx)};
if ismember(find(idx), idxmatched)
error(['input options match more than ones with "' ...
defname '". ' ...
@@ -1888,26 +1888,26 @@ for name = fieldnames(inopts)'
% val = inopts.(name);
if isstruct(val) % valid syntax only from version 6.5.0
opts = setfield(opts, defname, ...
- getoptions(val, getfield(defopts, defname)));
- elseif isstruct(getfield(defopts, defname))
- % next three lines can replace previous three lines from MATLAB
+ getoptions(val, getfield(defopts, defname)));
+ elseif isstruct(getfield(defopts, defname))
+ % next three lines can replace previous three lines from MATLAB
% version 6.5.0 on
% opts.(defname) = ...
- % getoptions(val, defopts.(defname));
- % elseif isstruct(defopts.(defname))
- warning(['option "' name '" disregarded (must be struct)']);
+ % getoptions(val, defopts.(defname));
+ % elseif isstruct(defopts.(defname))
+ warning(['option "' name '" disregarded (must be struct)']);
elseif ~isempty(val) % empty value: do nothing, i.e. stick to default
opts = setfield(opts, defnames{find(idx)}, val);
% next line can replace previous line from MATLAB version 6.5.0 on
- % opts.(defname) = inopts.(name);
+ % opts.(defname) = inopts.(name);
end
else
warning(['option "' name '" disregarded (unknown field name)']);
end
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function res=myeval(s)
if ischar(s)
res = evalin('caller', s);
@@ -1915,8 +1915,8 @@ else
res = s;
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function res=myevalbool(s)
if ~ischar(s) % s may not and cannot be empty
res = s;
@@ -1938,8 +1938,8 @@ else % evaluation string s
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function res = isoctave
% any hack to find out whether we are running octave
s = version;
@@ -1948,23 +1948,23 @@ if exist('fflush', 'builtin') && eval(s(1)) < 7
res = 1;
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function flush
if isoctave
feval('fflush', stdout);
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
% ----- replacements for statistic toolbox functions ------------
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function res=myrange(x)
res = max(x) - min(x);
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
function res = myprctile(inar, perc, idx)
%
% Computes the percentiles in vector perc from vector inar
@@ -1975,7 +1975,7 @@ function res = myprctile(inar, perc, idx)
N = length(inar);
flgtranspose = 0;
-% sizes
+% sizes
if size(perc,1) > 1
perc = perc';
flgtranspose = 1;
@@ -1989,7 +1989,7 @@ end
% sort inar
if nargin < 3 || isempty(idx)
- [sar idx] = sort(inar);
+ [sar, idx] = sort(inar);
else
sar = inar(idx);
end
@@ -2017,41 +2017,41 @@ if flgtranspose
end
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
-function [s ranks rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit)
+function [s, ranks, rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit)
% function [s ranks rankDelta] = noisemeasurement(arf1, arf2, lamreev, theta)
%
-% Input:
-% arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda,
-% arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values
-% in arf2 are (re-)evaluations of the respective solutions, i.e.
+% Input:
+% arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda,
+% arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values
+% in arf2 are (re-)evaluations of the respective solutions, i.e.
% arf1(1) and arf2(1) are two evaluations of "the first" solution.
-% lamreev: number of reevaluated individuals in arf2
-% theta : parameter theta for the rank change limit, between 0 and 1,
-% typically between 0.2 and 0.7.
-% cutlimit (optional): output s is computed as a mean of rankchange minus
-% threshold, where rankchange is <=2*(lambda-1). cutlimit limits
-% abs(rankchange minus threshold) in this calculation to cutlimit.
-% cutlimit=1 evaluates basically the sign only. cutlimit=2 could be
-% the rank change with one solution (both evaluations of it).
-%
-% Output:
+% lamreev: number of reevaluated individuals in arf2
+% theta : parameter theta for the rank change limit, between 0 and 1,
+% typically between 0.2 and 0.7.
+% cutlimit (optional): output s is computed as a mean of rankchange minus
+% threshold, where rankchange is <=2*(lambda-1). cutlimit limits
+% abs(rankchange minus threshold) in this calculation to cutlimit.
+% cutlimit=1 evaluates basically the sign only. cutlimit=2 could be
+% the rank change with one solution (both evaluations of it).
+%
+% Output:
% s : noise measurement, s>0 means the noise measure is above the
% acceptance threshold
-% ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks
+% ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks
% of arf1 and arf2 in the set [arf1 arf2], values are in [1:2*lambda]
% rankDelta: 1xlambda array of rank movements of arf2 compared to
% arf1. rankDelta(i) agrees with the number of values from
% the set [arf1 arf2] that lie between arf1(i) and arf2(i).
%
% Note: equal function values might lead to somewhat spurious results.
-% For this case a revision is advisable.
+% For this case a revision is advisable.
%%% verify input argument sizes
if size(arf1,1) ~= 1
@@ -2089,9 +2089,9 @@ for i = 1:lamreev
sumlim(i) = ...
0.5 * (...
myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ...
- theta*50) ...
+ theta*50) ...
+ myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ...
- theta*50));
+ theta*50));
end
%%% compute measurement
@@ -2101,39 +2101,39 @@ end
s = abs(rankDelta(1:lamreev)) - max(1, sumlim); % lives roughly in 0..2*lambda
% cut-off limit
-idx = abs(s) > cutlimit;
+idx = abs(s) > cutlimit;
s(idx) = sign(s(idx)) * cutlimit;
s = mean(s);
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
% just a "local" copy of plotcmaesdat.m, with manual_mode set to zero
function local_plotcmaesdat(figNb, filenameprefix, filenameextension, objectvarname)
% PLOTCMAESDAT;
% PLOTCMAES(FIGURENUMBER_iBEGIN_iEND, FILENAMEPREFIX, FILENAMEEXTENSION, OBJECTVARNAME);
-% plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy...
-% mod(figNb,100)==1 plots versus iterations.
+% plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy...
+% mod(figNb,100)==1 plots versus iterations.
%
-% PLOTCMAES([101 300]) plots versus iteration, from iteration 300.
-% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800.
+% PLOTCMAES([101 300]) plots versus iteration, from iteration 300.
+% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800.
%
-% Upper left subplot: blue/red: function value of the best solution in the
+% Upper left subplot: blue/red: function value of the best solution in the
% recent population, cyan: same function value minus best
-% ever seen function value, green: sigma, red: ratio between
+% ever seen function value, green: sigma, red: ratio between
% longest and shortest principal axis length which is equivalent
-% to sqrt(cond(C)).
+% to sqrt(cond(C)).
% Upper right plot: time evolution of the distribution mean (default) or
-% the recent best solution vector.
-% Lower left: principal axes lengths of the distribution ellipsoid,
-% equivalent with the sqrt(eig(C)) square root eigenvalues of C.
-% Lower right: magenta: minimal and maximal "true" standard deviation
-% (with sigma included) in the coordinates, other colors: sqrt(diag(C))
+% the recent best solution vector.
+% Lower left: principal axes lengths of the distribution ellipsoid,
+% equivalent with the sqrt(eig(C)) square root eigenvalues of C.
+% Lower right: magenta: minimal and maximal "true" standard deviation
+% (with sigma included) in the coordinates, other colors: sqrt(diag(C))
% of all diagonal elements of C, if C is diagonal they equal to the
-% lower left.
+% lower left.
%
-% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where
+% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where
% name = axlen, OBJECTVARNAME (xmean|xrecentbest), fit, or stddev.
%
@@ -2149,14 +2149,14 @@ if nargin < 3 || isempty(filenameextension)
filenameextension = '.dat';
end
if nargin < 4 || isempty(objectvarname)
- objectvarname = 'xmean';
+ objectvarname = 'xmean';
objectvarname = 'xrecentbest';
end
% load data
-d.x = load([filenameprefix objectvarname filenameextension]);
-% d.x = load([filenameprefix 'xmean' filenameextension]);
-% d.x = load([filenameprefix 'xrecentbest' filenameextension]);
-d.f = load([filenameprefix 'fit' filenameextension]);
+d.x = load([filenameprefix objectvarname filenameextension]);
+% d.x = load([filenameprefix 'xmean' filenameextension]);
+% d.x = load([filenameprefix 'xrecentbest' filenameextension]);
+d.f = load([filenameprefix 'fit' filenameextension]);
d.std = load([filenameprefix 'stddev' filenameextension]);
d.D = load([filenameprefix 'axlen' filenameextension]);
@@ -2180,9 +2180,9 @@ if mod(figNb,100) == 1
iabscissa = 1; % a short hack
end
if iabscissa == 1
- xlab ='iterations';
+ xlab ='iterations';
elseif iabscissa == 2
- xlab = 'function evaluations';
+ xlab = 'function evaluations';
end
if size(d.x, 2) < 1000
@@ -2195,7 +2195,7 @@ end
if manual_mode
figure(figNb); % just create and raise the figure window
else
- if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1
+ if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1
figure(figNb); % incomment this, if figure raise in the beginning is not desired
elseif ismember(figNb, findobj('Type', 'figure'))
set(0, 'CurrentFigure', figNb); % prevents raise of existing figure window
@@ -2206,18 +2206,18 @@ end
% plot fitness etc
foffset = 1e-99;
-dfit = d.f(:,6)-min(d.f(:,6));
-[ignore idxbest] = min(dfit);
+dfit = d.f(:,6)-min(d.f(:,6));
+[ignore, idxbest] = min(dfit);
dfit(dfit<1e-98) = NaN;
-subplot(2,2,1); hold off;
-dd = abs(d.f(:,7:8)) + foffset;
+subplot(2,2,1); hold off;
+dd = abs(d.f(:,7:8)) + foffset;
dd(d.f(:,7:8)==0) = NaN;
semilogy(d.f(:,iabscissa), dd, '-k'); hold on;
% additional fitness data, for example constraints values
if size(d.f,2) > 8
dd = abs(d.f(:,9:end)) + 10*foffset; % a hack
- % dd(d.f(:,9:end)==0) = NaN;
- semilogy(d.f(:,iabscissa), dd, '-m'); hold on;
+ % dd(d.f(:,9:end)==0) = NaN;
+ semilogy(d.f(:,iabscissa), dd, '-m'); hold on;
if size(d.f,2) > 12
semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on;
end
@@ -2225,11 +2225,11 @@ end
idx = find(d.f(:,6)>1e-98); % positive values
if ~isempty(idx) % otherwise non-log plot gets hold
- semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on;
+ semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on;
end
idx = find(d.f(:,6) < -1e-98); % negative values
if ~isempty(idx)
- semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on;
+ semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on;
end
semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on;
semilogy(d.f(:,iabscissa),dfit,'-c'); hold on;
@@ -2247,37 +2247,37 @@ semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on;
semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on;
ax = axis;
-ax(2) = max(minxend, ax(2));
+ax(2) = max(minxend, ax(2));
axis(ax);
-yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3))));
+yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3))));
text(ax(1), yannote, ...
[ 'f=' num2str(d.f(end,6), '%.15g') ]);
title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio');
-grid on;
+grid on;
-subplot(2,2,2); hold off;
+subplot(2,2,2); hold off;
plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on;
ax = axis;
-ax(2) = max(minxend, ax(2));
-axis(ax);
+ax(2) = max(minxend, ax(2));
+axis(ax);
% add some annotation lines
[ignore idx] = sort(d.x(end,6:end));
-% choose no more than 25 indices
-idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
+% choose no more than 25 indices
+idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
yy = repmat(NaN, 2, size(d.x,2)-5);
yy(1,:) = d.x(end, 6:end);
yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs));
-plot([d.x(end,iabscissa) ax(2)], yy, '-');
+plot([d.x(end,iabscissa) ax(2)], yy, '-');
plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-');
for i = idx(idxs)
text(ax(2), yy(2,i), ...
['x(' num2str(i) ')=' num2str(yy(1,i))]);
end
-lam = 'NA';
+lam = 'NA';
if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1)
lam = num2str((d.x(end, 2) - d.x(end-1, 2)) / (d.x(end, 1) - d.x(end-1, 1)));
end
@@ -2286,16 +2286,16 @@ title(['Object Variables (' num2str(size(d.x, 2)-5) ...
subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-');
ax = axis;
-ax(2) = max(minxend, ax(2));
+ax(2) = max(minxend, ax(2));
axis(ax);
title('Principal Axes Lengths');grid on;
-xlabel(xlab);
+xlabel(xlab);
-subplot(2,2,4); hold off;
-% semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on;
+subplot(2,2,4); hold off;
+% semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on;
% remove sigma from stds
d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5));
-semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on;
+semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on;
if 11 < 3 % max and min std
semilogy(d.std(:,iabscissa), [d.std(:,3).*max(d.std(:,6:end)')' ...
d.std(:,3).*min(d.std(:,6:end)')'], '-m', 'linewidth', 2);
@@ -2305,16 +2305,16 @@ if 11 < 3 % max and min std
text(d.std(end,iabscissa), d.std(end,3)*minval, sprintf('min=%.0e', minval));
end
ax = axis;
-ax(2) = max(minxend, ax(2));
+ax(2) = max(minxend, ax(2));
axis(ax);
% add some annotation lines
-[ignore idx] = sort(d.std(end,6:end));
-% choose no more than 25 indices
-idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
+[ignore, idx] = sort(d.std(end,6:end));
+% choose no more than 25 indices
+idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
yy = repmat(NaN, 2, size(d.std,2)-5);
yy(1,:) = d.std(end, 6:end);
yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs));
-semilogy([d.std(end,iabscissa) ax(2)], yy, '-');
+semilogy([d.std(end,iabscissa) ax(2)], yy, '-');
semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-');
for i = idx(idxs)
text(ax(2), yy(2,i), [' ' num2str(i)]);
@@ -2327,9 +2327,9 @@ if figNb ~= 324
end
drawnow;
-% ---------------------------------------------------------------
-% --------------- TEST OBJECTIVE FUNCTIONS ----------------------
-% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% --------------- TEST OBJECTIVE FUNCTIONS ----------------------
+% ---------------------------------------------------------------
%%% Unimodal functions
@@ -2356,12 +2356,12 @@ f = max(abs(x), [], 1);
function f=fssphere(x)
f=sqrt(sum(x.^2, 1));
-% lb = -0.512; ub = 512;
-% xfeas = x;
+% lb = -0.512; ub = 512;
+% xfeas = x;
% xfeas(xub) = ub;
+% xfeas(x>ub) = ub;
% f=sum(xfeas.^2, 1);
-% f = f + 1e-9 * sum((xfeas-x).^2);
+% f = f + 1e-9 * sum((xfeas-x).^2);
function f=fspherenoise(x, Nevals)
if nargin < 2 || isempty(Nevals)
@@ -2369,11 +2369,11 @@ if nargin < 2 || isempty(Nevals)
end
[N,popsi] = size(x);
% x = x .* (1 + 0.3e-0 * randn(N, popsi)/(2*N)); % actuator noise
-fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2;
+fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2;
% f = 0*rand(1,1) ...
% + fsum ...
% + fsum .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)) ...
-% + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); %
+% + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); %
% f = fsum .* exp(0.1*randn(1,popsi));
f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi));
@@ -2387,13 +2387,13 @@ end
function f=fmixranks(x)
N = size(x,1);
f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5;
-if size(x, 2) > 1 % compute ranks, if it is a population
+if size(x, 2) > 1 % compute ranks, if it is a population
[ignore, idx] = sort(f);
[ignore, ranks] = sort(idx);
k = 9; % number of solutions randomly permuted, lambda/2-1
% works still quite well (two time slower)
for i = k+1:k-0:size(x,2)
- idx(i-k+(1:k)) = idx(i-k+randperm(k));
+ idx(i-k+(1:k)) = idx(i-k+randperm(k));
end
%disp([ranks' f'])
[ignore, ranks] = sort(idx);
@@ -2441,7 +2441,7 @@ end
xopt = 0.1;
x(idxM) = x(idxM) + xopt;
f = scale.^2*x.^2;
-f = f - sum((xopt*scale(idxM)).^2);
+f = f - sum((xopt*scale(idxM)).^2);
% f = exp(f) - 1;
% f = log10(f+1e-19) + 19;
@@ -2460,12 +2460,12 @@ function f=fsectorsphere(x, scal)
% This is deceptive for cumulative sigma control CSA in large dimension:
% The strategy (initially) diverges for N=50 and popsize = 150. (Even
% for cs==1 this can be observed for larger settings of N and
-% popsize.) The reason is obvious from the function topology.
+% popsize.) The reason is obvious from the function topology.
% Divergence can be avoided by setting boundaries or adding a
-% penalty for large ||x||. Then, convergence can be observed again.
+% penalty for large ||x||. Then, convergence can be observed again.
% Conclusion: for popsize>N cumulative sigma control is not completely
% reasonable, but I do not know better alternatives. In particular:
-% TPA takes longer to converge than CSA when the latter still works.
+% TPA takes longer to converge than CSA when the latter still works.
%
if nargin < 2 || isempty (scal)
scal = 1e3;
@@ -2509,7 +2509,7 @@ else
f=sum(abs(scale.*x).^e);
end
-function f=fneumaier3(x)
+function f=fneumaier3(x)
% in -n^2..n^2
% x^*-i = i(n+1-i)
N = size(x,1);
@@ -2520,15 +2520,15 @@ function f = fmaxmindist(y)
% y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc
% points best
% 5 1.4142
-% 8 1.03527618
-% 10 0.842535997
-% 20 0.5997
+% 8 1.03527618
+% 10 0.842535997
+% 20 0.5997
pop = size(y,2);
N = size(y,1)/2;
-f = [];
+f = [];
for ipop = 1:pop
if any(abs(y(:,ipop)) > 1)
- f(ipop) = NaN;
+ f(ipop) = NaN;
else
x = reshape(y(:,ipop), [2, N]);
f(ipop) = inf;
@@ -2565,7 +2565,7 @@ f = 1e5 - 1/(1e-5 + sum(abs(y)));
function f=fschwefel(x)
f = 0;
-for i = 1:size(x,1),
+for i = 1:size(x,1)
f = f+sum(x(1:i))^2;
end
@@ -2600,7 +2600,7 @@ f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2);
function f=fellitest(x)
beta = 0.9;
N = size(x,1);
-f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta;
+f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta;
function f=fellii(x, scal)
@@ -2637,16 +2637,16 @@ else
arN = N;
end
global ORTHOGONALCOORSYSTEM_G
-ORTHOGONALCOORSYSTEM_G{1} = 1;
+ORTHOGONALCOORSYSTEM_G{1} = 1;
for N = arN
ar = randn(N,N);
- for i = 1:N
+ for i = 1:N
for j = 1:i-1
ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j);
end
ar(:,i) = ar(:,i) / norm(ar(:,i));
end
- ORTHOGONALCOORSYSTEM_G{N} = ar;
+ ORTHOGONALCOORSYSTEM_G{N} = ar;
end
function f=fplane(x)
@@ -2662,11 +2662,11 @@ function f=fsharpR(x)
f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1));
function f=frosen(x)
-if size(x,1) < 2 error('dimension must be greater one'); end
-N = size(x,1);
-popsi = size(x,2);
+if size(x,1) < 2, error('dimension must be greater one'); end
+N = size(x,1);
+popsi = size(x,2);
f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1);
-% f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N));
+% f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N));
function f=frosenlin(x)
if size(x,1) < 2 error('dimension must be greater one'); end
@@ -2679,7 +2679,7 @@ f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ...
sum((x(1:end-1,:)-1).^2,1);
f = f + sum((x-x_org).^2,1);
-% f(any(abs(x)>30,1)) = NaN;
+% f(any(abs(x)>30,1)) = NaN;
function f=frosenrot(x)
N = size(x,1);
@@ -2696,46 +2696,46 @@ f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ...
- 400*exp(-sum((x+1).^2)/2/0.05);
function f=fschwefelrosen1(x)
-% in [-10 10]
+% in [-10 10]
f=sum((x.^2-x(1)).^2 + (x-1).^2);
function f=fschwefelrosen2(x)
-% in [-10 10]
+% in [-10 10]
f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2);
function f=fdiffpow(x)
-[N popsi] = size(x); if N < 2 error('dimension must be greater one'); end
+[N, popsi] = size(x); if N < 2 error('dimension must be greater one'); end
f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1);
-f = sqrt(f);
+f = sqrt(f);
function f=fabsprod(x)
f = sum(abs(x),1) + prod(abs(x),1);
function f=ffloor(x)
-f = sum(floor(x+0.5).^2,1);
+f = sum(floor(x+0.5).^2,1);
function f=fmaxx(x)
f = max(abs(x), [], 1);
-%%% Multimodal functions
+%%% Multimodal functions
function f=fbirastrigin(x)
-% todo: the volume needs to be a constant
-N = size(x,1);
+% todo: the volume needs to be a constant
+N = size(x,1);
idx = (sum(x, 1) < 0.5*N); % global optimum
f = zeros(1,size(x,2));
-f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1);
+f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1);
idx = ~idx;
-f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1);
+f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1);
function f=fackley(x)
% -32.768..32.768
-% Adding a penalty outside the interval is recommended,
+% Adding a penalty outside the interval is recommended,
% because for large step sizes, fackley imposes like frand
-%
-N = size(x,1);
-f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N));
+%
+N = size(x,1);
+f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N));
f = f + (exp(1) - exp(sum(cos(2*pi*x))/N));
% add penalty outside the search interval
f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2);
@@ -2784,15 +2784,15 @@ end
if nargin < 2 || isempty(scal)
scal = 1;
end
-N = size(x,1);
+N = size(x,1);
scale = 1;
if N > 1
- scale=scal.^((0:N-1)'/(N-1));
+ scale=scal.^((0:N-1)'/(N-1));
end
-% simple version:
+% simple version:
% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
-% skew version:
+% skew version:
y = repmat(scale, 1, size(x,2)) .* x;
idx = find(x > skewstart);
if ~isempty(idx)
@@ -2815,18 +2815,18 @@ end
if nargin < 2 || isempty(scal)
scal = 1;
end
-N = size(x,1);
+N = size(x,1);
scale = 1;
if N > 1
- scale=scal.^((0:N-1)'/(N-1));
+ scale=scal.^((0:N-1)'/(N-1));
end
-% simple version:
+% simple version:
% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
-% skew version:
+% skew version:
y = repmat(scale, 1, size(x,2)) .* x;
idx = find(x > skewstart);
-% idx = intersect(idx, 2:2:10);
+% idx = intersect(idx, 2:2:10);
if ~isempty(idx)
y(idx) = skewfac*y(idx);
end
@@ -2845,21 +2845,21 @@ f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1);
function f=fschwefelmult(x)
% -500..500
-%
-N = size(x,1);
+%
+N = size(x,1);
f = - sum(x.*sin(sqrt(abs(x))), 1);
f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1);
-% penalty term
+% penalty term
f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1);
function f=ftwomax(x)
% Boundaries at +/-5
-N = size(x,1);
+N = size(x,1);
f = -abs(sum(x)) + 5*N;
function f=ftwomaxtwo(x)
% Boundaries at +/-10
-N = size(x,1);
+N = size(x,1);
f = abs(sum(x));
if f > 30
f = f - 30;
@@ -2872,117 +2872,117 @@ f=1./(1-rand(1, size(x,2))) - 1;
% CHANGES
% 12/02/19: "future" setting of ccum, correcting for large mueff, is default now
% 11/11/15: bug-fix: max value for ccovmu_sep setting corrected
-% 10/11/11: (3.52.beta) boundary handling: replace max with min in change
-% rate formula. Active CMA: check of pos.def. improved.
-% Plotting: value of lambda appears in the title.
+% 10/11/11: (3.52.beta) boundary handling: replace max with min in change
+% rate formula. Active CMA: check of pos.def. improved.
+% Plotting: value of lambda appears in the title.
% 10/04/03: (3.51.beta) active CMA cleaned up. Equal fitness detection
-% looks into history now.
+% looks into history now.
% 10/03/08: (3.50.beta) "active CMA" revised and bug-fix of ambiguous
-% option Noise.alpha -> Noise.alphasigma.
-% 09/10/12: (3.40.beta) a slightly modified version of "active CMA",
+% option Noise.alpha -> Noise.alphasigma.
+% 09/10/12: (3.40.beta) a slightly modified version of "active CMA",
% that is a negative covariance matrix update, use option
-% CMA.active. In 10;30;90-D the gain on ftablet is a factor
-% of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On
-% Rosenbrock the gain is about 25%. On sharp ridge the
-% behavior is improved. Cigar is unchanged.
-% 09/08/10: local plotcmaesdat remains in backround
-% 09/08/10: bug-fix in time management for data writing, logtime was not
-% considered properly (usually not at all).
-% 09/07/05: V3.24: stagnation termination added
+% CMA.active. In 10;30;90-D the gain on ftablet is a factor
+% of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On
+% Rosenbrock the gain is about 25%. On sharp ridge the
+% behavior is improved. Cigar is unchanged.
+% 09/08/10: local plotcmaesdat remains in backround
+% 09/08/10: bug-fix in time management for data writing, logtime was not
+% considered properly (usually not at all).
+% 09/07/05: V3.24: stagnation termination added
% 08/09/27: V3.23: momentum alignment is out-commented and de-preciated
% 08/09/25: V3.22: re-alignment of sigma and C was buggy
% 08/07/15: V3.20, CMA-parameters are options now. ccov and mucov were replaced
% by ccov1 \approx ccov/mucov and ccovmu \approx (1-1/mucov)*ccov
-% 08/06/30: file name xrecent was change to xrecentbest (compatible with other
+% 08/06/30: file name xrecent was change to xrecentbest (compatible with other
% versions)
-% 08/06/29: time stamp added to output files
-% 08/06/28: bug fixed with resume option, commentary did not work
+% 08/06/29: time stamp added to output files
+% 08/06/28: bug fixed with resume option, commentary did not work
% 08/06/28: V3.10, uncertainty (noise) handling added (re-implemented), according
% to reference "A Method for Handling Uncertainty..." from below.
-% 08/06/28: bug fix: file xrecent was empty
-% 08/06/01: diagonalonly clean up. >1 means some iterations.
+% 08/06/28: bug fix: file xrecent was empty
+% 08/06/01: diagonalonly clean up. >1 means some iterations.
% 08/05/05: output is written to file preventing an increasing data
-% array and ease long runs.
-% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the
-% diagonal with a larger learning rate.
-% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear
-% variant with only diagonal elements of the covariance matrix
-% updating. This can be useful for large dimensions, say > 100.
+% array and ease long runs.
+% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the
+% diagonal with a larger learning rate.
+% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear
+% variant with only diagonal elements of the covariance matrix
+% updating. This can be useful for large dimensions, say > 100.
% 08/02: diag(weights) * ... replaced with repmat(weights,1,N) .* ...
-% in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2).
+% in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2).
% 07/09: tolhistfun as termination criterion added, "<" changed to
-% "<=" also for TolFun to allow for stopping on zero difference.
-% Name tolfunhist clashes with option tolfun.
-% 07/07: hsig threshold made slighly smaller for large dimension,
-% useful for lambda < lambda_default.
+% "<=" also for TolFun to allow for stopping on zero difference.
+% Name tolfunhist clashes with option tolfun.
+% 07/07: hsig threshold made slighly smaller for large dimension,
+% useful for lambda < lambda_default.
% 07/06: boundary handling: scaling in the boundary handling
% is omitted now, see bnd.flgscale. This seems not to
% have a big impact. Using the scaling is worse on rotated
-% functions, but better on separable ones.
+% functions, but better on separable ones.
% 07/05: boundary handling: weight i is not incremented anymore
% if xmean(i) moves towards the feasible space. Increment
-% factor changed to 1.2 instead of 1.1.
+% factor changed to 1.2 instead of 1.1.
% 07/05: boundary handling code simplified not changing the algorithm
% 07/04: bug removed for saving in octave
% 06/11/10: more testing of outcome of eig, fixed max(D) to max(diag(D))
-% 06/10/21: conclusive final bestever assignment in the end
+% 06/10/21: conclusive final bestever assignment in the end
% 06/10/21: restart and incpopsize option implemented for restarts
-% with increasing population size, version 2.50.
+% with increasing population size, version 2.50.
% 06/09/16: output argument bestever inserted again for convenience and
% backward compatibility
-% 06/08: output argument out and struct out reorganized.
+% 06/08: output argument out and struct out reorganized.
% 06/01: Possible parallel evaluation included as option EvalParallel
% 05/11: Compatibility to octave implemented, package octave-forge
-% is needed.
+% is needed.
% 05/09: Raise of figure and waiting for first plots improved
-% 05/01: Function coordinatesystem cleaned up.
+% 05/01: Function coordinatesystem cleaned up.
% 05/01: Function prctile, which requires the statistics toolbox,
-% replaced by myprctile.
-% 05/01: Option warnonequalfunctionvalues included.
-% 04/12: Decrease of sigma removed. Problems on fsectorsphere can
-% be addressed better by adding search space boundaries.
-% 04/12: Boundary handling simpyfied.
-% 04/12: Bug when stopping criteria tolx or tolupx are vectors.
-% 04/11: Three input parameters are obligatory now.
-% 04/11: Bug in boundary handling removed: Boundary weights can decrease now.
-% 04/11: Normalization for boundary weights scale changed.
-% 04/11: VerboseModulo option bug removed. Documentation improved.
+% replaced by myprctile.
+% 05/01: Option warnonequalfunctionvalues included.
+% 04/12: Decrease of sigma removed. Problems on fsectorsphere can
+% be addressed better by adding search space boundaries.
+% 04/12: Boundary handling simpyfied.
+% 04/12: Bug when stopping criteria tolx or tolupx are vectors.
+% 04/11: Three input parameters are obligatory now.
+% 04/11: Bug in boundary handling removed: Boundary weights can decrease now.
+% 04/11: Normalization for boundary weights scale changed.
+% 04/11: VerboseModulo option bug removed. Documentation improved.
% 04/11: Condition for increasing boundary weights changed.
% 04/10: Decrease of sigma when fitness is getting consistenly
% worse. Addresses the problems appearing on fsectorsphere for
% large population size.
-% 04/10: VerboseModulo option included.
+% 04/10: VerboseModulo option included.
% 04/10: Bug for condition for increasing boundary weights removed.
% 04/07: tolx depends on initial sigma to achieve scale invariance
-% for this stopping criterion.
+% for this stopping criterion.
% 04/06: Objective function value NaN is not counted as function
-% evaluation and invokes resampling of the search point.
+% evaluation and invokes resampling of the search point.
% 04/06: Error handling for eigenvalue beeing zero (never happens
% with default parameter setting)
-% 04/05: damps further tuned for large mueff
-% o Details for stall of pc-adaptation added (variable hsig
-% introduced).
+% 04/05: damps further tuned for large mueff
+% o Details for stall of pc-adaptation added (variable hsig
+% introduced).
% 04/05: Bug in boundary handling removed: A large initial SIGMA was
% corrected not until *after* the first iteration, which could
% lead to a complete failure.
-% 04/05: Call of function range (works with stats toolbox only)
-% changed to myrange.
+% 04/05: Call of function range (works with stats toolbox only)
+% changed to myrange.
% 04/04: Parameter cs depends on mueff now and damps \propto sqrt(mueff)
-% instead of \propto mueff.
+% instead of \propto mueff.
% o Initial stall to adapt C (flginiphase) is removed and
% adaptation of pc is stalled for large norm(ps) instead.
-% o Returned default options include documentation.
+% o Returned default options include documentation.
% o Resume part reorganized.
-% 04/03: Stopflag becomes cell-array.
+% 04/03: Stopflag becomes cell-array.
% ---------------------------------------------------------------
% CMA-ES: Evolution Strategy with Covariance Matrix Adaptation for
% nonlinear function minimization. To be used under the terms of the
% GNU General Public License (http://www.gnu.org/copyleft/gpl.html).
-% Author (copyright): Nikolaus Hansen, 2001-2008.
+% Author (copyright): Nikolaus Hansen, 2001-2008.
% e-mail: nikolaus.hansen AT inria.fr
% URL:http://www.bionik.tu-berlin.de/user/niko
-% References: See below.
+% References: See below.
% ---------------------------------------------------------------
%
% GENERAL PURPOSE: The CMA-ES (Evolution Strategy with Covariance
@@ -2999,7 +2999,7 @@ f=1./(1-rand(1, size(x,2))) - 1;
% expected to take at least 30*N^2 and up to 300*N^2 function
% evaluations.
%
-% SOME MORE COMMENTS:
+% SOME MORE COMMENTS:
% The adaptation of the covariance matrix (e.g. by the CMA) is
% equivalent to a general linear transformation of the problem
% coding. Nevertheless every problem specific knowlegde about the best
@@ -3022,13 +3022,13 @@ f=1./(1-rand(1, size(x,2))) - 1;
% ---------------------------------------------------------------
%%% REFERENCES
%
-% The equation numbers refer to
+% The equation numbers refer to
% Hansen, N. and S. Kern (2004). Evaluating the CMA Evolution
% Strategy on Multimodal Test Functions. Eighth International
% Conference on Parallel Problem Solving from Nature PPSN VIII,
-% Proceedings, pp. 282-291, Berlin: Springer.
+% Proceedings, pp. 282-291, Berlin: Springer.
% (http://www.bionik.tu-berlin.de/user/niko/ppsn2004hansenkern.pdf)
-%
+%
% Further references:
% Hansen, N. and A. Ostermeier (2001). Completely Derandomized
% Self-Adaptation in Evolution Strategies. Evolutionary Computation,
@@ -3050,6 +3050,3 @@ f=1./(1-rand(1, size(x,2))) - 1;
% Optimization with an Application to Feedback Control of
% Combustion. To appear in IEEE Transactions on Evolutionary
% Computation.
-
-
-
diff --git a/matlab/optimization/csminit1.m b/matlab/optimization/csminit1.m
index 633e7dc9b..22391027e 100644
--- a/matlab/optimization/csminit1.m
+++ b/matlab/optimization/csminit1.m
@@ -1,7 +1,7 @@
function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin)
% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin)
-%
-% Inputs:
+%
+% Inputs:
% fcn: [string] string naming the objective function to be minimized
% x0: [npar by 1] initial value of the parameter vector
% penalty: [scalar] variable penalty in case of failure of objective function
@@ -20,7 +20,7 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb
% retcode [scalar] 0: normal step
% 1: zero gradient.
% 5: largest step still improves too fast.
-% 2,4: back and forth adjustment of stepsize didn't finish.
+% 2,4: back and forth adjustment of stepsize didn't finish.
% 3: smallest stepsize still improves too slow
% 6: no improvement found
%---------------------
@@ -33,12 +33,12 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb
%
% Fixed 7/19/93 to flip eigenvalues of H to get better performance when
% it's not psd.
-%
+%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminit.m
-%
+%
% Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -183,7 +183,7 @@ else
if Verbose
lambda = -lambda*factor^6
else
- lambda = -lambda*factor^6;
+ lambda = -lambda*factor^6;
end
else
if lambda < 0
@@ -216,7 +216,7 @@ else
end
end
lambda=lambda*factor;
- if abs(lambda) > 1e20;
+ if abs(lambda) > 1e20
retcode = 5;
done =1;
end
diff --git a/matlab/optimization/csminwel1.m b/matlab/optimization/csminwel1.m
index af341b11d..cfa869932 100644
--- a/matlab/optimization/csminwel1.m
+++ b/matlab/optimization/csminwel1.m
@@ -14,13 +14,13 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
% epsilon: [scalar] scalar double, numerical differentiation increment
% varargin: Optional additional inputs that get handed off to fcn each
% time it is called.
-%
+%
% Note that if the program ends abnormally, it is possible to retrieve the current x,
% f, and H from the files g1.mat and H.mat that are written at each iteration and at each
% hessian update, respectively. (When the routine hits certain kinds of difficulty, it
% writes g2.mat and g3.mat as well. If all were written at about the same time, any of them
% may be a decent starting point. One can also start from the one with best function value.)
-%
+%
% Outputs:
% fh: [scalar] function value at minimum
% xh: [npar by 1] parameter vector at minimum
@@ -30,19 +30,19 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
% fcount [scalar] function iteration count upon termination
% retcodeh [scalar] return code:
% 0: normal step
-% 1: zero gradient
+% 1: zero gradient
% 2: back and forth on step length never finished
% 3: smallest step still improving too slow
% 4: back and forth on step length never finished
% 5: largest step still improving too fast
% 6: smallest step still improving too slow, reversed gradient
% 7: warning: possible inaccuracy in H matrix
-%
+%
% Original file downloaded from:
% http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
-%
+%
% Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -59,7 +59,7 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-% initialize variable penalty
+% initialize variable penalty
penalty = 1e8;
fh = [];
xh = [];
@@ -139,7 +139,7 @@ while ~done
else
if NumGrad
[g1, badg1]=get_num_grad(method,fcn,penalty,f1,x1,epsilon,varargin{:});
- elseif ischar(grad),
+ elseif ischar(grad)
[g1, badg1] = grad(x1,varargin{:});
else
[junk1,cost_flag,g1] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -166,7 +166,7 @@ while ~done
else
if NumGrad
[g2, badg2]=get_num_grad(method,fcn,penalty,f2,x2,epsilon,varargin{:});
- elseif ischar(grad),
+ elseif ischar(grad)
[g2, badg2] = grad(x2,varargin{:});
else
[junk2,cost_flag,g2] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -193,12 +193,12 @@ while ~done
[f3, x3, fc, retcode3] = csminit1(fcn,x,penalty,f,gcliff,0,eye(nx),Verbose,varargin{:});
fcount = fcount+fc; % put by Jinill
if retcode3==2 || retcode3==4
- wall3=1;
+ wall3=1;
badg3=1;
else
if NumGrad
[g3, badg3]=get_num_grad(method,fcn,penalty,f3,x3,epsilon,varargin{:});
- elseif ischar(grad),
+ elseif ischar(grad)
[g3, badg3] = grad(x3,varargin{:});
else
[junk3,cost_flag,g3] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -258,7 +258,7 @@ while ~done
if nogh
if NumGrad
[gh, badgh]=get_num_grad(method,fcn,penalty,fh,xh,epsilon,varargin{:});
- elseif ischar(grad),
+ elseif ischar(grad)
[gh, badgh] = grad(xh,varargin{:});
else
[junkh,cost_flag,gh] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -302,7 +302,7 @@ while ~done
error('Unaccounted Case, please contact the developers',Verbose)
end
end
-
+
f=fh;
x=xh;
g=gh;
diff --git a/matlab/optimization/dynare_minimize_objective.m b/matlab/optimization/dynare_minimize_objective.m
index 8aca0d2e1..025d41189 100644
--- a/matlab/optimization/dynare_minimize_objective.m
+++ b/matlab/optimization/dynare_minimize_objective.m
@@ -8,12 +8,12 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i
% minimizer_algorithm [scalar double, or string] code of the optimizer algorithm, or string for the name of a user defined optimization routine (not shipped with dynare).
% options_ [matlab structure] Dynare options structure
% bounds [n_params by 2] vector of doubles 2 row vectors containing lower and upper bound for parameters
-% parameter_names [n_params by 1] cell array strings containing the parameters names
+% parameter_names [n_params by 1] cell array strings containing the parameters names
% prior_information [matlab structure] Dynare prior information structure (bayestopt_) provided for algorithm 6
% Initial_Hessian [n_params by n_params] matrix initial hessian matrix provided for algorithm 6
% new_rat_hess_info [matlab structure] step size info used by algorith 5
% varargin [cell array] Input arguments for objective function
-%
+%
% OUTPUTS
% opt_par_values [n_params by 1] vector of doubles optimal parameter values minimizing the objective
% fval [scalar double] value of the objective function at the minimum
@@ -21,12 +21,12 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i
% hessian_mat [n_params by n_params] matrix hessian matrix at the mode returned by optimizer
% options_ [matlab structure] Dynare options structure (to return options set by algorithms 5)
% Scale [scalar double] scaling parameter returned by algorith 6
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
-%
-% Copyright (C) 2014-2016 Dynare Team
+%
+%
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -77,7 +77,7 @@ switch minimizer_algorithm
if options_.silent_optimizer
optim_options = optimset(optim_options,'display','off');
end
- if options_.analytic_derivation,
+ if options_.analytic_derivation
optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
end
[opt_par_values,fval,exitflag,output,lamdba,grad,hessian_mat] = ...
@@ -148,7 +148,7 @@ switch minimizer_algorithm
if ~isempty(options_.optim_opt)
eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
end
- if options_.analytic_derivation,
+ if options_.analytic_derivation
optim_options = optimset(optim_options,'GradObj','on');
end
if options_.silent_optimizer
@@ -188,16 +188,16 @@ switch minimizer_algorithm
case 'verbosity'
Verbose = options_list{i,2};
case 'SaveFiles'
- Save_files = options_list{i,2};
+ Save_files = options_list{i,2};
otherwise
warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
- Save_files = 0;
+ Save_files = 0;
Verbose = 0;
- end
+ end
% Set flag for analytical gradient.
if options_.analytic_derivation
analytic_grad=1;
@@ -232,23 +232,23 @@ switch minimizer_algorithm
if options_.analytic_derivation && flag~=0
error('newrat: analytic_derivation is incompatible with numerical Hessian. Using analytic Hessian')
else
- newratflag=flag;
+ newratflag=flag;
end
case 'TolFun'
crit = options_list{i,2};
case 'verbosity'
Verbose = options_list{i,2};
case 'SaveFiles'
- Save_files = options_list{i,2};
+ Save_files = options_list{i,2};
otherwise
warning(['newrat: Unknown option (' options_list{i,1} ')!'])
end
end
end
if options_.silent_optimizer
- Save_files = 0;
+ Save_files = 0;
Verbose = 0;
- end
+ end
hess_info.gstep=options_.gstep;
hess_info.htol = 1.e-4;
hess_info.h1=options_.gradient_epsilon*ones(n_params,1);
@@ -307,13 +307,13 @@ switch minimizer_algorithm
end
if options_.silent_optimizer
simplexOptions.verbose = options_list{i,2};
- end
+ end
[opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:});
case 9
% Set defaults
H0 = (bounds(:,2)-bounds(:,1))*0.2;
H0(~isfinite(H0)) = 0.01;
- while max(H0)/min(H0)>1e6 %make sure initial search volume (SIGMA) is not badly conditioned
+ while max(H0)/min(H0)>1e6 %make sure initial search volume (SIGMA) is not badly conditioned
H0(H0==max(H0))=0.9*H0(H0==max(H0));
end
cmaesOptions = options_.cmaes;
@@ -358,7 +358,7 @@ switch minimizer_algorithm
cmaesOptions.SaveVariables='off';
cmaesOptions.LogModulo = '0'; % [0:Inf] if >1 record data less frequently after gen=100';
cmaesOptions.LogTime = '0'; % [0:100] max. percentage of time for recording data';
- end
+ end
warning('off','CMAES:NonfinitenessRange');
warning('off','CMAES:InitialSigma');
[x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),start_par_value,H0,cmaesOptions,varargin{:});
@@ -390,7 +390,7 @@ switch minimizer_algorithm
simpsaOptions.DISPLAY = 'none';
else
simpsaOptions.DISPLAY = 'iter';
- end
+ end
otherwise
warning(['simpsa: Unknown option (' options_list{i,1} ')!'])
end
diff --git a/matlab/optimization/gmhmaxlik.m b/matlab/optimization/gmhmaxlik.m
index bc800f8f8..4f1db628d 100644
--- a/matlab/optimization/gmhmaxlik.m
+++ b/matlab/optimization/gmhmaxlik.m
@@ -1,6 +1,6 @@
function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hinit, iscale, bounds, priorstd, gmhmaxlikOptions, OptimizationOptions, varargin)
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -19,7 +19,7 @@ function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hin
% Set default options
-if ~isempty(Hinit);
+if ~isempty(Hinit)
gmhmaxlikOptions.varinit = 'previous';
else
gmhmaxlikOptions.varinit = 'prior';
diff --git a/matlab/optimization/gmhmaxlik_core.m b/matlab/optimization/gmhmaxlik_core.m
index 2d7a3cb81..3e94d30ab 100644
--- a/matlab/optimization/gmhmaxlik_core.m
+++ b/matlab/optimization/gmhmaxlik_core.m
@@ -1,8 +1,8 @@
-function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)
+function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)
-% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function.
-%
-% INPUTS
+% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function.
+%
+% INPUTS
% o ObjFun [char] string specifying the name of the objective function.
% o xparam1 [double] (p*1) vector of parameters to be estimated.
% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
@@ -10,29 +10,29 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
% o iScale [double] scalar specifying the initial of the jumping distribution's scale parameter.
% o info [char] string, empty or equal to 'LastCall'.
% o MeanPar [double] (p*1) vector specifying the initial posterior mean.
-% o VarCov [double] (p*p) matrix specifying the initial posterior covariance matrix.
+% o VarCov [double] (p*p) matrix specifying the initial posterior covariance matrix.
% o gend [integer] scalar specifying the number of observations ==> varargin{1}.
% o data [double] (T*n) matrix of data ==> varargin{2}.
-%
-% OUTPUTS
+%
+% OUTPUTS
% o PostMod [double] (p*1) vector, evaluation of the posterior mode.
% o PostVar [double] (p*p) matrix, evaluation of the posterior covariance matrix.
-% o Scale [double] scalar specifying the scale parameter that should be used in
-% an eventual metropolis-hastings algorithm.
-% o PostMean [double] (p*1) vector, evaluation of the posterior mean.
+% o Scale [double] scalar specifying the scale parameter that should be used in
+% an eventual metropolis-hastings algorithm.
+% o PostMean [double] (p*1) vector, evaluation of the posterior mean.
%
-% ALGORITHM
+% ALGORITHM
% Metropolis-Hastings with an constantly updated covariance matrix for
% the jump distribution. The posterior mean, variance and mode are
% updated (in step 2) with the following rules:
%
-% \[
-% \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right)
-% \]
+% \[
+% \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right)
+% \]
%
-% \[
-% \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' +
-% \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right)
+% \[
+% \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' +
+% \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right)
% \]
%
% and
@@ -43,7 +43,7 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
% \theta_t, & \hbox{if } p(\theta_t|\mathcal Y) > p(\mathrm{mode}_{t-1}|\mathcal Y) \\
% \mathrm{mode}_{t-1}, & \hbox{otherwise.}
% \end{array}
-% \right.
+% \right.
% \]
%
% where $t$ is the iteration, $\mu_t$ the estimate of the posterior mean
@@ -51,12 +51,12 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
% covariance matrix after $t$ iterations, $\mathrm{mode}_t$ is the
% evaluation of the posterior mode after $t$ iterations and
% $p(\theta_t|\mathcal Y)$ is the posterior density of parameters
-% (specified by the user supplied function "fun").
+% (specified by the user supplied function "fun").
%
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -94,7 +94,7 @@ isux = 0; jsux = 0; test = 0;
ix2 = ModePar;% initial condition!
ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density
mlogpo2 = ilogpo2;
-try
+try
dd = transpose(chol(CovJump));
catch
dd = eye(length(CovJump));
@@ -108,7 +108,7 @@ while j<=MaxNumberOfTuningSimulations
end
% I move if the proposal is enough likely...
if logpo2 > -inf && log(rand) < logpo2 - ilogpo2
- ix2 = proposal;
+ ix2 = proposal;
if logpo2 > mlogpo2
ModePar = proposal;
mlogpo2 = logpo2;
@@ -165,7 +165,7 @@ while j<= NumberOfIterations
ilogpo2 = logpo2;
isux = isux + 1;
jsux = jsux + 1;
- end% ... otherwise I don't move.
+ end% ... otherwise I don't move.
prtfrc = j/NumberOfIterations;
if mod(j, 10)==0
dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio: %f',isux/j));
@@ -184,7 +184,7 @@ PostMean = MeanPar;
%% this is the last call to the routine, and I climb the hill (without
%% updating the covariance matrix)...
if strcmpi(info,'LastCall')
-
+
hh = dyn_waitbar(0,'Tuning of the scale parameter...');
set(hh,'Name','Tuning of the scale parameter.'),
j = 1; jj = 1;
@@ -214,8 +214,8 @@ if strcmpi(info,'LastCall')
if mod(j, 10)==0
dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio [during last 1000]: %f [%f]',isux/j,jsux/jj));
end
- if j/1000 == round(j/1000)
- test1 = jsux/jj;
+ if j/1000 == round(j/1000)
+ test1 = jsux/jj;
cfactor = test1/AcceptanceTarget;
iScale = iScale*cfactor;
jsux = 0; jj = 0;
diff --git a/matlab/optimization/mr_gstep.m b/matlab/optimization/mr_gstep.m
index 605508d2c..0836a7a87 100644
--- a/matlab/optimization/mr_gstep.m
+++ b/matlab/optimization/mr_gstep.m
@@ -11,7 +11,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil
% varargin{6} --> BayesInfo
% varargin{1} --> DynareResults
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -29,7 +29,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil
% along with Dynare. If not, see .
n=size(x,1);
-if isempty(h1),
+if isempty(h1)
h1=varargin{3}.gradient_epsilon*ones(n,1);
end
@@ -39,7 +39,7 @@ if isempty(htol0)
else
htol = htol0;
end
-if length(htol)==1,
+if length(htol)==1
htol=htol*ones(n,1);
end
f0=penalty_objective_function(x,func0,penalty,varargin{:});
@@ -72,7 +72,7 @@ while i htol(i)
- [f0 x fc retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:});
+ [f0, x, fc, retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:});
ig(i)=1;
if Verbose
fprintf(['Done for param %s = %8.4f\n'],varargin{6}.name{i},x(i))
@@ -95,13 +95,11 @@ return
function x = check_bounds(x,bounds)
inx = find(x>=bounds(:,2));
-if ~isempty(inx),
+if ~isempty(inx)
x(inx) = bounds(inx,2)-eps;
end
inx = find(x<=bounds(:,1));
-if ~isempty(inx),
+if ~isempty(inx)
x(inx) = bounds(inx,1)+eps;
end
-
-
diff --git a/matlab/optimization/mr_hessian.m b/matlab/optimization/mr_hessian.m
index c3ed29345..b234df9b7 100644
--- a/matlab/optimization/mr_hessian.m
+++ b/matlab/optimization/mr_hessian.m
@@ -33,7 +33,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f
% varargin{6} --> BayesInfo
% varargin{7} --> Bounds
% varargin{8} --> DynareResults
-%
+%
% Outputs
% - hessian_mat hessian
% - gg Jacobian
@@ -44,7 +44,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f
% - hh1 updated hess_info.h1
% - hess_info structure with updated step length
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -67,7 +67,7 @@ n=size(x,1);
h2=varargin{7}.ub-varargin{7}.lb;
hmax=varargin{7}.ub-x;
hmax=min(hmax,x-varargin{7}.lb);
-if isempty(ff0),
+if isempty(ff0)
outer_product_gradient=0;
else
outer_product_gradient=1;
@@ -109,7 +109,7 @@ while i(3*hess_info.htol)) && icount<10 && ic==0
icount=icount+1;
if abs(dx(it))<0.5*hess_info.htol
- if abs(dx(it)) ~= 0,
+ if abs(dx(it)) ~= 0
hess_info.h1(i)=min(max(1.e-10,0.3*abs(x(i))), 0.9*hess_info.htol/abs(dx(it))*hess_info.h1(i));
else
hess_info.h1(i)=2.1*hess_info.h1(i);
@@ -147,8 +147,8 @@ while i BayesInfo
% varargin{7} --> Bounds
% varargin{8} --> DynareResults
-%
+%
% Outputs
% - xparam1 parameter vector at optimum
% - hh hessian
@@ -39,7 +39,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
% - igg inverted outer product hessian
% - hess_info structure with updated step length
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -56,7 +56,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-% initialize variable penalty
+% initialize variable penalty
penalty = 1e8;
icount=0;
@@ -86,7 +86,7 @@ fval=fval0;
outer_product_gradient=1;
if isempty(hh)
[dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(x,func0,penalty,flagit,htol,hess_info,varargin{:});
- if isempty(dum),
+ if isempty(dum)
outer_product_gradient=0;
igg = 1e-4*eye(nx);
else
@@ -154,7 +154,7 @@ while norm(gg)>gtol && check==0 && jitgtol && check==0 && jitgtol && check==0 && jit1.e-12 && analytic_derivation==0,
+ if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0
try
if Save_files
save('m1.mat','x','fval0','nig','-append')
@@ -244,7 +244,7 @@ while norm(gg)>gtol && check==0 && jithtol
@@ -253,7 +253,7 @@ while norm(gg)>gtol && check==0 && jitgtol && check==0 && jit=bounds(:,2));
-if ~isempty(inx),
+if ~isempty(inx)
x(inx) = bounds(inx,2)-eps;
end
inx = find(x<=bounds(:,1));
-if ~isempty(inx),
+if ~isempty(inx)
x(inx) = bounds(inx,1)+eps;
end
diff --git a/matlab/optimization/penalty_objective_function.m b/matlab/optimization/penalty_objective_function.m
index c245800c2..e0c249251 100644
--- a/matlab/optimization/penalty_objective_function.m
+++ b/matlab/optimization/penalty_objective_function.m
@@ -2,13 +2,13 @@ function [fval, exit_flag, arg1, arg2] = penalty_objective_function(x, fcn, base
% Encapsulates an objective function to be minimized, adding a penalty if necessary.
%
-% INPUTS
+% INPUTS
% - x [double] n*1 vector of instrument values.
% - fcn [fhandle] objective function.
% - base_penalty [double] scalar, base of the penality (typically the value of the objective at the previous iteration).
% - varagin [cell] additional parameters for fcn.
%
-% OUTPUTS
+% OUTPUTS
% - fval [double] scalar, value of the objective function at x.
% - exit_flag [integer] scalar, flag returned by fcn (third output).
% - arg1, arg2 fourth and fifth output arguments of the objective function.
diff --git a/matlab/optimization/simplex_optimization_routine.m b/matlab/optimization/simplex_optimization_routine.m
index aff23b246..ccd81367e 100644
--- a/matlab/optimization/simplex_optimization_routine.m
+++ b/matlab/optimization/simplex_optimization_routine.m
@@ -7,7 +7,7 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
%
% The routine automatically restarts from the current solution while amelioration is possible.
%
-% INPUTS
+% INPUTS
% o objective_function [string] Name of the objective function to be minimized.
% o x [double] n*1 vector, starting guess of the optimization routine.
% o options [structure] Options of this implementation of the simplex algorithm.
@@ -23,13 +23,13 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
% varargin{6} --> BayesInfo
% varargin{1} --> DynareResults
%
-% OUTPUTS
+% OUTPUTS
% o x [double] n*1 vector, estimate of the optimal inputs.
% o fval [double] scalar, value of the objective at the optimum.
% o exitflag [integer] scalar equal to 0 or 1 (0 if the algorithm did not converge to
% a minimum).
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -396,7 +396,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex
disp(['Crit. x: ' num2str(critX)])
skipline()
end
- if verbose && max(abs(best_point-v(:,1)))>x_tolerance;
+ if verbose && max(abs(best_point-v(:,1)))>x_tolerance
if verbose<2
disp(['Simplex iteration number: ' int2str(simplex_iterations) '-' int2str(simplex_init) '-' int2str(simplex_algo_iterations)])
disp(['Objective function value: ' num2str(fv(1))])
diff --git a/matlab/optimization/simpsa.m b/matlab/optimization/simpsa.m
index 228a6bad2..87b881a2c 100644
--- a/matlab/optimization/simpsa.m
+++ b/matlab/optimization/simpsa.m
@@ -1,8 +1,8 @@
function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
-% Finds a minimum of a function of several variables using an algorithm
-% that is based on the combination of the non-linear smplex and the simulated
-% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996).
+% Finds a minimum of a function of several variables using an algorithm
+% that is based on the combination of the non-linear smplex and the simulated
+% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996).
% In this paper, the algorithm is shown to be adequate for the global optimi-
% zation of an example set of unconstrained and constrained NLP functions.
%
@@ -11,54 +11,54 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
% X
%
% Algorithm partly is based on paper of Cardoso et al, 1996.
-%
-% X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN.
+%
+% X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN.
% FUN accepts input X and returns a scalar function value F evaluated at X.
% X0 may be a scalar, vector, or matrix.
-%
-% X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the
-% design variables, X, so that a solution is found in the range
-% LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist.
-% Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is
+%
+% X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the
+% design variables, X, so that a solution is found in the range
+% LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist.
+% Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is
% unbounded above.
-%
+%
% X=SIMPSA(FUN,X0,LB,UB,OPTIONS) minimizes with the default optimization
-% parameters replaced by values in the structure OPTIONS, an argument
-% created with the SIMPSASET function. See SIMPSASET for details.
+% parameters replaced by values in the structure OPTIONS, an argument
+% created with the SIMPSASET function. See SIMPSASET for details.
% Used options are TEMP_START, TEMP_END, COOL_RATE, INITIAL_ACCEPTANCE_RATIO,
% MIN_COOLING_FACTOR, MAX_ITER_TEMP_FIRST, MAX_ITER_TEMP_LAST, MAX_ITER_TEMP,
% MAX_ITER_TOTAL, MAX_TIME, MAX_FUN_EVALS, TOLX, TOLFUN, DISPLAY and OUTPUT_FCN.
% Use OPTIONS = [] as a place holder if no options are set.
-%
-% X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable
+%
+% X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable
% number of input arguments to the objective function FUN.
-%
-% [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective
+%
+% [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective
% function FUN at the solution X.
-%
-% [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the
-% exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding
+%
+% [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the
+% exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding
% exit conditions are:
-%
+%
% 1 Change in the objective function value less than the specified tolerance.
% 2 Change in X less than the specified tolerance.
% 0 Maximum number of function evaluations or iterations reached.
% -1 Maximum time exceeded.
-%
-% [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with
+%
+% [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with
% the number of iterations taken in OUTPUT.nITERATIONS, the number of function
% evaluations in OUTPUT.nFUN_EVALS, the temperature profile in OUTPUT.TEMPERATURE,
-% the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in
-% OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and
-% from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time
+% the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in
+% OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and
+% from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time
% needed in OUTPUT.TIME and the options used in OUTPUT.OPTIONS.
-%
+%
% See also SIMPSASET, SIMPSAGET
% Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
% Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
%
% This file is part of Dynare.
%
@@ -77,11 +77,11 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
% handle variable input arguments
-if nargin < 5,
+if nargin < 5
OPTIONS = [];
- if nargin < 4,
+ if nargin < 4
UB = 1e5;
- if nargin < 3,
+ if nargin < 3
LB = -1e5;
end
end
@@ -89,22 +89,22 @@ end
% check input arguments
-if ~ischar(FUN),
+if ~ischar(FUN)
error('''FUN'' incorrectly specified in ''SIMPSA''');
end
-if ~isfloat(X0),
+if ~isfloat(X0)
error('''X0'' incorrectly specified in ''SIMPSA''');
end
-if ~isfloat(LB),
+if ~isfloat(LB)
error('''LB'' incorrectly specified in ''SIMPSA''');
end
-if ~isfloat(UB),
+if ~isfloat(UB)
error('''UB'' incorrectly specified in ''SIMPSA''');
end
-if length(X0) ~= length(LB),
+if length(X0) ~= length(LB)
error('''LB'' and ''X0'' have incompatible dimensions in ''SIMPSA''');
end
-if length(X0) ~= length(UB),
+if length(X0) ~= length(UB)
error('''UB'' and ''X0'' have incompatible dimensions in ''SIMPSA''');
end
@@ -167,7 +167,7 @@ TEMP_LOOP_NUMBER = 1;
% loop as described by Cardoso et al., 1996 (recommended)
% therefore, the temperature is set to YBEST*1e5 in the first loop
-if isempty(OPTIONS.TEMP_START),
+if isempty(OPTIONS.TEMP_START)
TEMP = abs(YBEST)*1e5;
else
TEMP = OPTIONS.TEMP_START;
@@ -195,51 +195,51 @@ nITERATIONS = 0;
% temperature loop: run SIMPSA till stopping criterion is met
% -----------------------------------------------------------
-while 1,
-
+while 1
+
% detect if termination criterium was met
% ---------------------------------------
-
+
% if a termination criterium was met, the value of EXITFLAG should have changed
% from its default value of -2 to -1, 0, 1 or 2
-
- if EXITFLAG ~= -2,
+
+ if EXITFLAG ~= -2
break
end
-
+
% set MAXITERTEMP: maximum number of iterations at current temperature
% --------------------------------------------------------------------
-
- if TEMP_LOOP_NUMBER == 1,
+
+ if TEMP_LOOP_NUMBER == 1
MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_FIRST*NDIM;
- % The initial temperature is estimated (is requested) as described in
- % Cardoso et al. (1996). Therefore, we need to store the number of
- % successful and unsuccessful moves, as well as the increase in cost
+ % The initial temperature is estimated (is requested) as described in
+ % Cardoso et al. (1996). Therefore, we need to store the number of
+ % successful and unsuccessful moves, as well as the increase in cost
% for the unsuccessful moves.
- if isempty(OPTIONS.TEMP_START),
+ if isempty(OPTIONS.TEMP_START)
[SUCCESSFUL_MOVES,UNSUCCESSFUL_MOVES,UNSUCCESSFUL_COSTS] = deal(0);
end
- elseif TEMP < OPTIONS.TEMP_END,
+ elseif TEMP < OPTIONS.TEMP_END
TEMP = 0;
MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_LAST*NDIM;
else
MAXITERTEMP = OPTIONS.MAX_ITER_TEMP*NDIM;
end
-
+
% construct initial simplex
% -------------------------
-
+
% 1st vertex of initial simplex
P(1,:) = PBEST;
Y(1) = CALCULATE_COST(FUN,P(1,:),LB,UB,varargin{:});
-
+
% if output function given then run output function to plot intermediate result
- if ~isempty(OPTIONS.OUTPUT_FCN),
+ if ~isempty(OPTIONS.OUTPUT_FCN)
feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1));
end
-
+
% remaining vertices of simplex
- for k = 1:NDIM,
+ for k = 1:NDIM
% copy first vertex in new vertex
P(k+1,:) = P(1,:);
% alter new vertex
@@ -247,20 +247,20 @@ while 1,
% calculate value of objective function at new vertex
Y(k+1) = CALCULATE_COST(FUN,P(k+1,:),LB,UB,varargin{:});
end
-
+
% store information on what step the algorithm just did
ALGOSTEP = 'initial simplex';
-
+
% add NDIM+1 to number of function evaluations
nFUN_EVALS = nFUN_EVALS + NDIM;
-
+
% note:
% dimensions of matrix P: (NDIM+1) x NDIM
% dimensions of vector Y: (NDIM+1) x 1
-
+
% give user feedback if requested
- if strcmp(OPTIONS.DISPLAY,'iter'),
- if nITERATIONS == 0,
+ if strcmp(OPTIONS.DISPLAY,'iter')
+ if nITERATIONS == 0
disp(' Nr Iter Nr Fun Eval Min function Best function TEMP Algorithm Step');
else
disp(sprintf('%5.0f %5.0f %12.6g %15.6g %12.6g %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,'best point'));
@@ -269,111 +269,111 @@ while 1,
% run full metropolis cycle at current temperature
% ------------------------------------------------
-
+
% initialize vector COSTS, needed to calculate new temperature using cooling
% schedule as described by Cardoso et al. (1996)
COSTS = zeros((NDIM+1)*MAXITERTEMP,1);
-
+
% initialize ITERTEMP to zero
-
+
ITERTEMP = 0;
-
+
% start
- for ITERTEMP = 1:MAXITERTEMP,
-
+ for ITERTEMP = 1:MAXITERTEMP
+
% add one to number of iterations
nITERATIONS = nITERATIONS + 1;
-
+
% Press and Teukolsky (1991) add a positive logarithmic distributed variable,
- % proportional to the control temperature T to the function value associated with
- % every vertex of the simplex. Likewise,they subtract a similar random variable
+ % proportional to the control temperature T to the function value associated with
+ % every vertex of the simplex. Likewise,they subtract a similar random variable
% from the function value at every new replacement point.
% Thus, if the replacement point corresponds to a lower cost, this method always
- % accepts a true down hill step. If, on the other hand, the replacement point
+ % accepts a true down hill step. If, on the other hand, the replacement point
% corresponds to a higher cost, an uphill move may be accepted, depending on the
% relative COSTS of the perturbed values.
% (taken from Cardoso et al.,1996)
-
+
% add random fluctuations to function values of current vertices
YFLUCT = Y+TEMP*abs(log(rand(NDIM+1,1)));
-
+
% reorder YFLUCT, Y and P so that the first row corresponds to the lowest YFLUCT value
help = sortrows([YFLUCT,Y,P],1);
YFLUCT = help(:,1);
Y = help(:,2);
P = help(:,3:end);
-
+
% store temperature at current iteration
OUTPUT.TEMPERATURE(nITERATIONS) = TEMP;
% store information about simplex at the current iteration
OUTPUT.SIMPLEX(:,:,nITERATIONS) = P;
OUTPUT.SIMPLEX_BEST(nITERATIONS,:) = PBEST;
-
+
% store cost function value of best vertex in current iteration
OUTPUT.COSTS(nITERATIONS,:) = Y;
OUTPUT.COST_BEST(nITERATIONS) = YBEST;
-
- if strcmp(OPTIONS.DISPLAY,'iter'),
+
+ if strcmp(OPTIONS.DISPLAY,'iter')
disp(sprintf('%5.0f %5.0f %12.6g %15.6g %12.6g %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,ALGOSTEP));
end
-
+
% if output function given then run output function to plot intermediate result
- if ~isempty(OPTIONS.OUTPUT_FCN),
+ if ~isempty(OPTIONS.OUTPUT_FCN)
feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1));
end
-
+
% end the optimization if one of the stopping criteria is met
- %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN
+ %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN
%% 2. maximum difference between the coordinates of the vertices in simplex is less than TOLX
%% 3. no convergence,but maximum number of iterations has been reached
%% 4. no convergence,but maximum time has been reached
-
- if (abs(max(Y)-min(Y)) < OPTIONS.TOLFUN) && (TEMP_LOOP_NUMBER ~= 1),
- if strcmp(OPTIONS.DISPLAY,'iter'),
+
+ if (abs(max(Y)-min(Y)) < OPTIONS.TOLFUN) && (TEMP_LOOP_NUMBER ~= 1)
+ if strcmp(OPTIONS.DISPLAY,'iter')
disp('Change in the objective function value less than the specified tolerance (TOLFUN).')
end
EXITFLAG = 1;
- break;
+ break
end
-
- if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1),
- if strcmp(OPTIONS.DISPLAY,'iter'),
+
+ if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1)
+ if strcmp(OPTIONS.DISPLAY,'iter')
disp('Change in X less than the specified tolerance (TOLX).')
end
EXITFLAG = 2;
- break;
+ break
end
-
- if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1)),
- if strcmp(OPTIONS.DISPLAY,'iter'),
+
+ if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1))
+ if strcmp(OPTIONS.DISPLAY,'iter')
disp('Maximum number of function evaluations or iterations reached.');
end
EXITFLAG = 0;
- break;
+ break
end
-
- if toc/60 > OPTIONS.MAX_TIME,
- if strcmp(OPTIONS.DISPLAY,'iter'),
+
+ if toc/60 > OPTIONS.MAX_TIME
+ if strcmp(OPTIONS.DISPLAY,'iter')
disp('Exceeded maximum time.');
end
EXITFLAG = -1;
- break;
+ break
end
-
+
% begin a new iteration
-
+
%% first extrapolate by a factor -1 through the face of the simplex
%% across from the high point,i.e.,reflect the simplex from the high point
[YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,-1,LB,UB,varargin{:});
-
+
%% check the result
- if YFTRY <= YFLUCT(1),
+ if YFTRY <= YFLUCT(1)
%% gives a result better than the best point,so try an additional
%% extrapolation by a factor 2
[YFTRYEXP,YTRYEXP,PTRYEXP] = AMOTRY(FUN,P,-2,LB,UB,varargin{:});
- if YFTRYEXP < YFTRY,
+ if YFTRYEXP < YFTRY
P(end,:) = PTRYEXP;
Y(end) = YTRYEXP;
ALGOSTEP = 'reflection and expansion';
@@ -382,12 +382,12 @@ while 1,
Y(end) = YTRY;
ALGOSTEP = 'reflection';
end
- elseif YFTRY >= YFLUCT(NDIM),
+ elseif YFTRY >= YFLUCT(NDIM)
%% the reflected point is worse than the second-highest, so look
%% for an intermediate lower point, i.e., do a one-dimensional
%% contraction
[YFTRYCONTR,YTRYCONTR,PTRYCONTR] = AMOTRY(FUN,P,-0.5,LB,UB,varargin{:});
- if YFTRYCONTR < YFLUCT(end),
+ if YFTRYCONTR < YFLUCT(end)
P(end,:) = PTRYCONTR;
Y(end) = YTRYCONTR;
ALGOSTEP = 'one dimensional contraction';
@@ -396,7 +396,7 @@ while 1,
%% around the lowest (best) point
X = ones(NDIM,NDIM)*diag(P(1,:));
P(2:end,:) = 0.5*(P(2:end,:)+X);
- for k=2:NDIM,
+ for k=2:NDIM
Y(k) = CALCULATE_COST(FUN,P(k,:),LB,UB,varargin{:});
end
ALGOSTEP = 'multiple contraction';
@@ -407,15 +407,15 @@ while 1,
Y(end) = YTRY;
ALGOSTEP = 'reflection';
end
-
- % the initial temperature is estimated in the first loop from
- % the number of successfull and unsuccesfull moves, and the average
+
+ % the initial temperature is estimated in the first loop from
+ % the number of successfull and unsuccesfull moves, and the average
% increase in cost associated with the unsuccessful moves
-
- if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START),
- if Y(1) > Y(end),
+
+ if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START)
+ if Y(1) > Y(end)
SUCCESSFUL_MOVES = SUCCESSFUL_MOVES+1;
- elseif Y(1) <= Y(end),
+ elseif Y(1) <= Y(end)
UNSUCCESSFUL_MOVES = UNSUCCESSFUL_MOVES+1;
UNSUCCESSFUL_COSTS = UNSUCCESSFUL_COSTS+(Y(end)-Y(1));
end
@@ -424,28 +424,28 @@ while 1,
end
% stop if previous for loop was broken due to some stop criterion
- if ITERTEMP < MAXITERTEMP,
- break;
+ if ITERTEMP < MAXITERTEMP
+ break
end
-
+
% store cost function values in COSTS vector
COSTS((ITERTEMP-1)*NDIM+1:ITERTEMP*NDIM+1) = Y;
-
- % calculated initial temperature or recalculate temperature
+
+ % calculated initial temperature or recalculate temperature
% using cooling schedule as proposed by Cardoso et al. (1996)
% -----------------------------------------------------------
-
- if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START),
+
+ if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START)
TEMP = -(UNSUCCESSFUL_COSTS/(SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES))/log(((SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES)*OPTIONS.INITIAL_ACCEPTANCE_RATIO-SUCCESSFUL_MOVES)/UNSUCCESSFUL_MOVES);
- elseif TEMP_LOOP_NUMBER ~= 0,
+ elseif TEMP_LOOP_NUMBER ~= 0
STDEV_Y = std(COSTS);
COOLING_FACTOR = 1/(1+TEMP*log(1+OPTIONS.COOL_RATE)/(3*STDEV_Y));
TEMP = TEMP*min(OPTIONS.MIN_COOLING_FACTOR,COOLING_FACTOR);
end
-
+
% add one to temperature loop number
TEMP_LOOP_NUMBER = TEMP_LOOP_NUMBER+1;
-
+
end
% return solution
@@ -476,8 +476,8 @@ return
% ---------------
function [YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,fac,LB,UB,varargin)
-% Extrapolates by a factor fac through the face of the simplex across from
-% the high point, tries it, and replaces the high point if the new point is
+% Extrapolates by a factor fac through the face of the simplex across from
+% the high point, tries it, and replaces the high point if the new point is
% better.
global NDIM TEMP
@@ -502,14 +502,14 @@ function [YTRY] = CALCULATE_COST(FUN,PTRY,LB,UB,varargin)
global YBEST PBEST NDIM nFUN_EVALS
-for i = 1:NDIM,
+for i = 1:NDIM
% check lower bounds
- if PTRY(i) < LB(i),
+ if PTRY(i) < LB(i)
YTRY = 1e12+(LB(i)-PTRY(i))*1e6;
return
end
% check upper bounds
- if PTRY(i) > UB(i),
+ if PTRY(i) > UB(i)
YTRY = 1e12+(PTRY(i)-UB(i))*1e6;
return
end
@@ -522,7 +522,7 @@ YTRY = feval(FUN,PTRY(:),varargin{:});
nFUN_EVALS = nFUN_EVALS + 1;
% save the best point ever
-if YTRY < YBEST,
+if YTRY < YBEST
YBEST = YTRY;
PBEST = PTRY;
end
diff --git a/matlab/optimization/simpsaget.m b/matlab/optimization/simpsaget.m
index c22c82df4..96eb36dc9 100644
--- a/matlab/optimization/simpsaget.m
+++ b/matlab/optimization/simpsaget.m
@@ -18,7 +18,7 @@ function o = simpsaget(options,name,default,flag)
% See also SIMPSASET, SIMPSA
% Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013-2016 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
%
% This file is part of Dynare.
%
@@ -56,7 +56,7 @@ end
if isempty(options)
o = default;
- return;
+ return
end
Names = [
@@ -122,4 +122,3 @@ if isfield(s,f) % s could be empty.
else
v = d;
end
-
diff --git a/matlab/optimization/simpsaset.m b/matlab/optimization/simpsaset.m
index 1944e024f..1d63c7bdc 100644
--- a/matlab/optimization/simpsaset.m
+++ b/matlab/optimization/simpsaset.m
@@ -28,7 +28,7 @@ function options = simpsaset(varargin)
% Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
% Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
%
% This file is part of Dynare.
%
@@ -64,7 +64,7 @@ if (nargin == 0) && (nargout == 0)
fprintf(' DISPLAY: [ ''iter'' or ''none'' {''iter''} ]\n');
fprintf(' OUTPUT_FCN: [ function_handle ]\n');
fprintf('\n');
- return;
+ return
end
Names = [
@@ -97,7 +97,7 @@ i = 1;
while i <= nargin
arg = varargin{i};
if ischar(arg) % arg is an option name
- break;
+ break
end
if ~isempty(arg) % [] is a valid options argument
if ~isa(arg,'struct')
@@ -127,13 +127,13 @@ end
expectval = 0; % start expecting a name, not a value
while i <= nargin
arg = varargin{i};
-
+
if ~expectval
if ~ischar(arg)
error('MATLAB:odeset:NoPropName',...
'Expected argument %d to be a string property name.', i);
end
-
+
lowArg = lower(arg);
j = strmatch(lowArg,names);
if isempty(j) % if no matches
@@ -155,11 +155,11 @@ while i <= nargin
end
end
expectval = 1; % we expect a value next
-
+
else
options.(deblank(Names(j,:))) = arg;
expectval = 0;
-
+
end
i = i + 1;
end
diff --git a/matlab/optimization/simulated_annealing.m b/matlab/optimization/simulated_annealing.m
index b2cfc52ee..7088685b3 100644
--- a/matlab/optimization/simulated_annealing.m
+++ b/matlab/optimization/simulated_annealing.m
@@ -5,7 +5,7 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
%
% Implements the continuous simulated annealing global optimization
% algorithm described in Corana et al. (1987)
-%
+%
% A very quick (perhaps too quick) overview of SA:
% SA tries to find the global optimum of an N dimensional function.
% It moves both up and downhill and as the optimization process
@@ -49,17 +49,17 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
% Note: The suggested values generally come from Corana et al. To
% drastically reduce runtime, see Goffe et al., pp. 90-1 for
% suggestions on choosing the appropriate RT and NT.
-%
+%
% fcn - function to be optimized.
% x - The starting values for the variables of the function to be
% optimized. (N)
% optim: Options structure with fields
-%
+%
% optim.maximizer_indicator - Denotes whether the function should be maximized or
% minimized. A value =1 denotes maximization while a
% value =0 denotes minimization. Intermediate output (see verbosity)
% takes this into account.
-% optim.RT - The temperature reduction factor
+% optim.RT - The temperature reduction factor
% optim.TolFun - Error tolerance for termination. If the final function
% values from the last neps temperatures differ from the
% corresponding value at the current temperature by less than
@@ -104,11 +104,11 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
% of all points are accepted, the input value is not very
% important (i.e. is the value is off, SA adjusts VM to the
% correct value)
-%
-% lb - The lower bound for the allowable solution variables.
-% ub - The upper bound for the allowable solution variables.
+%
+% lb - The lower bound for the allowable solution variables.
+% ub - The upper bound for the allowable solution variables.
% If the algorithm chooses X(I) < LB(I) or X(I) > UB(I),
-% I = 1, N, a point is from inside is randomly selected.
+% I = 1, N, a point is from inside is randomly selected.
% This focuses the algorithm on the region inside UB and LB.
% Unless the user wishes to concentrate the search to a par-
% ticular region, UB and LB should be set to very large positive
@@ -116,8 +116,8 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
% vector X should be inside this region. Also note that LB and
% UB are fixed in position, while VM is centered on the last
% accepted trial set of variables that optimizes the function.
-%
-%
+%
+%
% Input/Output Parameters:
%
% Output Parameters:
@@ -142,28 +142,28 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
% t: On output, the final temperature.
% vm: Final step length vector
%
-% Algorithm:
+% Algorithm:
% This routine implements the continuous simulated annealing global
% optimization algorithm described in Corana et al.'s article
% "Minimizing Multimodal Functions of Continuous Variables with the
% "Simulated Annealing" Algorithm" in the September 1987 (vol. 13,
% no. 3, pp. 262-280) issue of the ACM Transactions on Mathematical
% Software.
-%
+%
% For modifications to the algorithm and many details on its use,
% (particularly for econometric applications) see Goffe, Ferrier
% and Rogers, "Global Optimization of Statistical Functions with
% Simulated Annealing," Journal of Econometrics, vol. 60, no. 1/2,
% Jan./Feb. 1994, pp. 65-100.
-%
+%
% Based on the Matlab code written by Thomas Werner (Bundesbank December
-% 2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing
+% 2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing
% program for global optimization, written by E.G.Tsionas (9/4/95).
-%
-% Copyright (C) 1995 E.G.Tsionas
-% Copyright (C) 1995-2002 Thomas Werner
+%
+% Copyright (C) 1995 E.G.Tsionas
+% Copyright (C) 1995-2002 Thomas Werner
% Copyright (C) 2002-2015 Giovanni Lombardo
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -194,17 +194,17 @@ xopt=x;
nacp=zeros(n,1);
fstar=1e20*ones(optim.neps,1);
%* If the initial temperature is not positive, notify the user and abort. *
-if(t<=0.0);
+if(t<=0.0)
fprintf('\nThe initial temperature is not positive. Reset the variable t\n');
exitflag=3;
- return;
-end;
+ return
+end
%* If the initial value is out of bounds, notify the user and abort. *
-if(sum(x>ub)+sum(x0);
+if(sum(x>ub)+sum(x0)
fprintf('\nInitial condition out of bounds\n');
exitflag=2;
- return;
-end;
+ return
+end
%* Evaluate the function with input x and return value as f. *
f=feval(fcn,x,varargin{:});
%*
@@ -212,98 +212,98 @@ f=feval(fcn,x,varargin{:});
% Note that all intermediate and final output switches the sign back
% to eliminate any possible confusion for the user.
%*
-if(optim.maximizer_indicator==0);
+if(optim.maximizer_indicator==0)
f=-f;
-end;
+end
n_total_draws=n_total_draws+1;
fopt=f;
fstar(1)=f;
-if(optim.verbosity >1);
+if(optim.verbosity >1)
disp ' ';
disp(['initial x ' num2str(x(:)')]);
- if(optim.maximizer_indicator);
+ if(optim.maximizer_indicator)
disp(['initial f ' num2str(f)]);
else
disp(['initial f ' num2str(-f)]);
- end;
-end;
+ end
+end
% Start the main loop. Note that it terminates if (i) the algorithm
% succesfully optimizes the function or (ii) there are too many
% function evaluations (more than optim.MaxIter).
-while (1>0);
+while (1>0)
nup=0;
nrej=0;
nnew=0;
ndown=0;
lnobds=0;
m=1;
- while m<=optim.nt;
+ while m<=optim.nt
j=1;
- while j<=optim.ns;
+ while j<=optim.ns
h=1;
- while h<=n;
+ while h<=n
%* Generate xp, the trial value of x. Note use of vm to choose xp. *
i=1;
- while i<=n;
- if(i==h);
+ while i<=n
+ if(i==h)
xp(i)=x(i)+(rand(1,1)*2.0-1.0)*vm(i);
else
xp(i)=x(i);
- end;
+ end
%* If xp is out of bounds, select a point in bounds for the trial. *
- if((xp(i)ub(i)));
+ if((xp(i)ub(i)))
xp(i)=lb(i)+(ub(i)-lb(i))*rand(1,1);
lnobds=lnobds+1;
n_out_of_bounds_draws=n_out_of_bounds_draws+1;
- if(optim.verbosity >=3);
+ if(optim.verbosity >=3)
if exist('fp','var')
print_current_invalid_try(optim.maximizer_indicator,xp,x,fp,f);
end
- end;
- end;
+ end
+ end
i=i+1;
- end;
+ end
%* Evaluate the function with the trial point xp and return as fp. *
% fp=feval(fcn,xp,listarg);
fp=feval(fcn,xp,varargin{:});
- if(optim.maximizer_indicator==0);
+ if(optim.maximizer_indicator==0)
fp=-fp;
- end;
+ end
n_total_draws=n_total_draws+1;
- if(optim.verbosity >=3);
+ if(optim.verbosity >=3)
print_current_valid_try(optim.maximizer_indicator,xp,x,fp,f);
- end;
+ end
%* If too many function evaluations occur, terminate the algorithm. *
- if(n_total_draws>=optim.MaxIter);
+ if(n_total_draws>=optim.MaxIter)
fprintf('Too many function evaluations; consider\n');
fprintf('increasing optim.MaxIter or optim.TolFun or decreasing\n');
fprintf('optim.nt or optim.rt. These results are likely to be poor\n');
- if(optim.maximizer_indicator==0);
+ if(optim.maximizer_indicator==0)
fopt=-fopt;
- end;
+ end
exitflag=1;
- return;
- end;
+ return
+ end
%* Accept the new point if the function value increases. *
- if(fp>=f);
- if(optim.verbosity >=3);
+ if(fp>=f)
+ if(optim.verbosity >=3)
fprintf('point accepted\n');
- end;
+ end
x=xp;
f=fp;
n_accepted_draws=n_accepted_draws+1;
nacp(h)=nacp(h)+1;
nup=nup+1;
%* If greater than any other point, record as new optimum. *
- if(fp>fopt);
- if(optim.verbosity >=3);
+ if(fp>fopt)
+ if(optim.verbosity >=3)
fprintf('new optimum\n');
- end;
+ end
xopt=xp;
fopt=fp;
nnew=nnew+1;
- end;
+ end
%*
% If the point is lower, use the Metropolis criteria to decide on
% acceptance or rejection.
@@ -311,14 +311,14 @@ while (1>0);
else
p=exp((fp-f)/t);
pp=rand(1,1);
- if(pp=3);
- if(optim.maximizer_indicator);
+ if(pp
=3)
+ if(optim.maximizer_indicator)
fprintf('though lower, point accepted\n');
else
fprintf('though higher, point accepted\n');
- end;
- end;
+ end
+ end
x=xp;
f=fp;
n_accepted_draws=n_accepted_draws+1;
@@ -326,87 +326,87 @@ while (1>0);
ndown=ndown+1;
else
nrej=nrej+1;
- if(optim.verbosity >=3);
- if(optim.maximizer_indicator);
+ if(optim.verbosity >=3)
+ if(optim.maximizer_indicator)
fprintf('lower point rejected\n');
else
fprintf('higher point rejected\n');
- end;
- end;
- end;
- end;
+ end
+ end
+ end
+ end
h=h+1;
- end;
+ end
j=j+1;
- end;
+ end
%* Adjust vm so that approximately half of all evaluations are accepted. *
i=1;
- while i<=n;
+ while i<=n
ratio=nacp(i)/optim.ns;
- if(ratio>.6);
+ if(ratio>.6)
vm(i)=vm(i)*(1.+c(i)*(ratio-.6)/.4);
- elseif(ratio<.4);
+ elseif(ratio<.4)
vm(i)=vm(i)/(1.+c(i)*((.4-ratio)/.4));
- end;
- if(vm(i)>(ub(i)-lb(i)));
+ end
+ if(vm(i)>(ub(i)-lb(i)))
vm(i)=ub(i)-lb(i);
- end;
+ end
i=i+1;
- end;
- if(optim.verbosity >=2);
+ end
+ if(optim.verbosity >=2)
fprintf('intermediate results after step length adjustment\n');
fprintf('new step length(vm) %4.3f', vm(:)');
fprintf('current optimal x %4.3f', xopt(:)');
fprintf('current x %4.3f', x(:)');
- end;
+ end
nacp=zeros(n,1);
m=m+1;
- end;
- if(optim.verbosity >=1);
+ end
+ if(optim.verbosity >=1)
print_intermediate_statistics(optim.maximizer_indicator,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew);
- end;
+ end
%* Check termination criteria. *
quit=0;
fstar(1)=f;
- if((fopt-fstar(1))<=optim.TolFun);
+ if((fopt-fstar(1))<=optim.TolFun)
quit=1;
- end;
- if(sum(abs(f-fstar)>optim.TolFun)>0);
+ end
+ if(sum(abs(f-fstar)>optim.TolFun)>0)
quit=0;
- end;
+ end
%* Terminate SA if appropriate. *
- if(quit);
+ if(quit)
exitflag=0;
- if(optim.maximizer_indicator==0);
+ if(optim.maximizer_indicator==0)
fopt=-fopt;
- end;
- if(optim.verbosity >=1);
+ end
+ if(optim.verbosity >=1)
fprintf('SA achieved termination criteria.exitflag=0\n');
- end;
- return;
- end;
+ end
+ return
+ end
%* If termination criteria are not met, prepare for another loop. *
t=optim.rt*t;
i=optim.neps;
- while i>=2;
+ while i>=2
fstar(i)=fstar(i-1);
i=i-1;
- end;
+ end
f=fopt;
x=xopt;
%* Loop again. *
-end;
+end
end
function print_current_invalid_try(max,xp,x,fp,f)
fprintf('\n');
disp(['Current x ' num2str(x(:)')]);
-if(max);
+if(max)
disp(['Current f ' num2str(f)]);
else
disp(['Current f ' num2str(-f)]);
-end;
+end
disp(['Trial x ' num2str(xp(:)')]);
disp 'Point rejected since out of bounds';
end
@@ -414,7 +414,7 @@ end
function print_current_valid_try(max,xp,x,fp,f)
disp(['Current x ' num2str(x(:)')]);
-if(max);
+if(max)
disp(['Current f ' num2str(f)]);
disp(['Trial x ' num2str(xp(:)')]);
disp(['Resulting f ' num2str(fp)]);
@@ -422,7 +422,7 @@ else
disp(['Current f ' num2str(-f)]);
disp(['Trial x ' num2str(xp(:)')]);
disp(['Resulting f ' num2str(-fp)]);
-end;
+end
end
diff --git a/matlab/optimization/solvopt.m b/matlab/optimization/solvopt.m
index 6d5693e86..c4a819a26 100644
--- a/matlab/optimization/solvopt.m
+++ b/matlab/optimization/solvopt.m
@@ -1,10 +1,10 @@
function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gradient_evals]=solvopt(x,fun,grad,func,gradc,optim,varargin)
% [x,f,options]=solvopt(x,fun,grad,func,gradc,options,varargin)
-%
-% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe,
+%
+% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe,
% performs a modified version of Shor's r-algorithm in
% order to find a local minimum resp. maximum of a nonlinear function
-% defined on the n-dimensional Euclidean space or % a solution of a nonlinear
+% defined on the n-dimensional Euclidean space or % a solution of a nonlinear
% constrained problem:
% min { f(x): g(x) (<)= 0, g(x) in R(m), x in R(n) }
%
@@ -41,7 +41,7 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr
% *optim.LBGradientStep= lower bound for the stepsize used for the difference
% approximation of gradients (1e-12 by default, see more in the manual).
% (* ... changes should be done with care)
-%
+%
% Outputs:
% x optimal parameter vector (row resp. column),
% f optimum function value
@@ -51,15 +51,15 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr
% n_grad_evals: number of gradient evaluations,
% n_constraint_evals: number of constraint function evaluations,
% n_constraint_gradient_evals number of constraint gradient evaluations.
-%
-%
-% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems
-% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997.
-%
-%
-% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
+%
+%
+% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems
+% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997.
+%
+%
+% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
% Copyright (C) 2008-2015 Giovanni Lombardo
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -162,7 +162,7 @@ if isempty(func)
constr=0;
else
constr=1; % Constrained problem
- if isempty(gradc),
+ if isempty(gradc)
appconstr=1;
else
appconstr=0; % Exact gradients of constraints are supplied
@@ -201,7 +201,7 @@ end
epsnorm=1.e-15;
epsnorm2=1.e-30; % epsilon & epsilon^2
-if constr, h1=-1; % NLP: restricted to minimization
+if constr, h1=-1 % NLP: restricted to minimization
cnteps=optim.TolXConstraint; % Max. admissible residual
else
h1=sign(optim.minimizer_indicator); % Minimize resp. maximize a function
@@ -217,10 +217,10 @@ ajp=20;
ajpp=ajp; % Start value for the power
ajs=1.15; % Base II
knorms=0; gnorms=zeros(1,10); % Gradient norms stored
-%---}
+ %---}
%Display control ---{
-if optim.verbosity<=0, dispdata=0;
+if optim.verbosity<=0, dispdata=0
if optim.verbosity==-1
dispwarn=0;
else
@@ -243,7 +243,7 @@ else
des=3.3;
end
mxtc=3; % Number of trial cycles (steep wall detect)
-%---}
+ %---}
termx=0; limxterm=50; % Counter and limit for x-criterion
ddx =max(1e-11,optim.LBGradientStep); % stepsize for gradient approximation
@@ -253,7 +253,7 @@ low_bound=-1+1e-4; % Lower bound cosine used to detect a ravine
ZeroGrad=n*1.e-16; % Lower bound for a gradient norm
nzero=0; % Zero-gradient events counter
-% Lower bound for values of variables taking into account
+ % Lower bound for values of variables taking into account
lowxbound=max([optim.TolX,1e-3]);
% Lower bound for function values to be considered as making difference
lowfbound=optim.TolFun^2;
@@ -276,30 +276,79 @@ else
f=feval(fun,x,varargin{:});
end
n_f_evals=n_f_evals+1;
-if isempty(f), if dispwarn,disp(errmes);disp(error30);end
- exitflag=-3; if trx, x=x';end, return
-elseif isnan(f), if dispwarn,disp(errmes);disp(error31);disp(error6);end
- exitflag=-3; if trx, x=x';end, return
-elseif abs(f)==Inf, if dispwarn,disp(errmes);disp(error32);disp(error6);end
- exitflag=-3; if trx, x=x';end, return
+if isempty(f)
+ if dispwarn
+ disp(errmes)
+ disp(error30)
+ end
+ exitflag=-3;
+ if trx
+ x=x';
+ end
+ return
+elseif isnan(f)
+ if dispwarn
+ disp(errmes)
+ disp(error31)
+ disp(error6)
+ end
+ exitflag=-3;
+ if trx
+ x=x';
+ end
+ return
+elseif abs(f)==Inf
+ if dispwarn
+ disp(errmes)
+ disp(error32)
+ disp(error6)
+ end
+ exitflag=-3;
+ if trx
+ x=x';
+ end
+ return
end
xrec=x; frec=f; % record point and function value
-% Constrained problem
-if constr, fp=f; kless=0;
- if trx,
+ % Constrained problem
+if constr, fp=f; kless=0
+ if trx
fc=feval(func,x');
else
fc=feval(func,x);
end
- if isempty(fc),
- if dispwarn,disp(errmes);disp(error50);end
- exitflag=-5; if trx, x=x';end, return
- elseif isnan(fc),
- if dispwarn,disp(errmes);disp(error51);disp(error6);end
- exitflag=-5; if trx, x=x';end, return
- elseif abs(fc)==Inf,
- if dispwarn,disp(errmes);disp(error52);disp(error6);end
- exitflag=-5; if trx, x=x';end, return
+ if isempty(fc)
+ if dispwarn
+ disp(errmes)
+ disp(error50)
+ end
+ exitflag=-5;
+ if trx
+ x=x';
+ end
+ return
+ elseif isnan(fc)
+ if dispwarn
+ disp(errmes)
+ disp(error51)
+ disp(error6)
+ end
+ exitflag=-5;
+ if trx
+ x=x';
+ end
+ return
+ elseif abs(fc)==Inf
+ if dispwarn
+ disp(errmes)
+ disp(error52)
+ disp(error6)
+ end
+ exitflag=-5;
+ if trx
+ x=x';
+ end
+ return
end
n_constraint_evals=n_constraint_evals+1;
PenCoef=1; % first rough approximation
@@ -318,13 +367,13 @@ if app
if trx
g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
else
- g=apprgrdn(x ,fp,fun,deltax,1,varargin{:});
+ g=apprgrdn(x ,fp,fun,deltax,1,varargin{:});
end
else
if trx
g=apprgrdn(x',f,fun,deltax',1,varargin{:});
else
- g=apprgrdn(x ,f,fun,deltax,1,varargin{:});
+ g=apprgrdn(x ,f,fun,deltax,1,varargin{:});
end
end
n_f_evals=n_f_evals+n;
@@ -332,114 +381,151 @@ else
if trx
g=feval(grad,x',varargin{:});
else
- g=feval(grad,x,varargin{:});
+ g=feval(grad,x,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
-if size(g,2)==1, g=g'; end, ng=norm(g);
-if size(g,2)~=n, if dispwarn,disp(errmes);disp(error40);end
- exitflag=-4; if trx, x=x';end, return
-elseif isnan(ng), if dispwarn,disp(errmes);disp(error41);disp(error6);end
- exitflag=-4; if trx, x=x';end, return
-elseif ng==Inf, if dispwarn,disp(errmes);disp(error42);disp(error6);end
- exitflag=-4; if trx, x=x';end, return
-elseif ng2*kd, kd=kd+1; warnno=1;
- if any(abs(x-xx)2*kd
+ kd=kd+1;
+ warnno=1;
+ if any(abs(x-xx)1
idx=find(abs(g)>ZeroGrad); numelem=size(idx,2);
- if numelem>0, grbnd=epsnorm*numelem^2;
- if all(abs(g1(idx))<=abs(g(idx))*grbnd) | nrmz==0
- if dispwarn, disp(wrnmes); disp(warn20); end
+ if numelem>0, grbnd=epsnorm*numelem^2
+ if all(abs(g1(idx))<=abs(g(idx))*grbnd) || nrmz==0
+ if dispwarn
+ disp(wrnmes)
+ disp(warn20)
+ end
if abs(fst-f)1.2*PenCoef,
+ if PenCoefNew>1.2*PenCoef
PenCoef=PenCoefNew; Reset=1; kless=0; f=f+PenCoef*fc; break
end
end
@@ -547,98 +665,123 @@ while 1,
f=f+PenCoef*fc;
end
if abs(f)==Inf || isnan(f)
- if dispwarn, disp(wrnmes);
+ if dispwarn, disp(wrnmes)
if isnan(f)
- disp(error31);
+ disp(error31)
else
- disp(error32);
+ disp(error32)
end
end
if ksm || kc>=mxtc
- exitflag=-3;
+ exitflag=-3;
if trx
x=x';
end
return
else
k2=k2+1;
- k1=0;
- hp=hp/dq;
+ k1=0;
+ hp=hp/dq;
x=x1;
- f=f1;
+ f=f1;
knan=1;
if constr
- FP=FP1;
- fp=fp1;
+ FP=FP1;
+ fp=fp1;
end
end
% STEP SIZE IS ZERO TO THE EXTENT OF EPSNORM
- elseif all(abs(x-x1)=5,
+ if stepvanish>=5
exitflag=-14;
- if dispwarn, disp(termwarn1);
- disp(endwarn(4,:)); end
- if trx,x=x';end, return
+ if dispwarn
+ disp(termwarn1)
+ disp(endwarn(4,:))
+ end
+ if trx
+ x=x';
+ end
+ return
else
- x=x1;
- f=f1;
- hp=hp*10;
+ x=x1;
+ f=f1;
+ hp=hp*10;
ksm=1;
if constr
- FP=FP1;
- fp=fp1;
+ FP=FP1;
+ fp=fp1;
end
end
% USE SMALLER STEP
elseif h1*f=mxtc, break, end
% 1-D OPTIMIZER IS LEFT BEHIND
- else if h1*f<=h1*f1, break, end
+ else
+ if h1*f<=h1*f1
+ break
+ end
% USE LARGER STEP
- k1=k1+1; if k2>0, kc=kc+1; end, k2=0;
- if k1>=20, hp=du20*hp;
- elseif k1>=10, hp=du10*hp;
- elseif k1>=3, hp=du03*hp;
+ k1=k1+1;
+ if k2>0
+ kc=kc+1;
+ end
+ k2=0;
+ if k1>=20
+ hp=du20*hp;
+ elseif k1>=10
+ hp=du10*hp;
+ elseif k1>=3
+ hp=du03*hp;
end
end
end
% ----} End of 1-D search
% ADJUST THE TRIAL STEP SIZE ----{
dx=norm(xopt-x);
- if kg=2, nsteps(2:kg)=nsteps(1:kg-1); end
+ if kg=2
+ nsteps(2:kg)=nsteps(1:kg-1);
+ end
nsteps(1)=dx/(abs(h)*norm(g0));
kk=sum(nsteps(1:kg).*[kg:-1:1])/sum([kg:-1:1]);
if kk>des
if kg==1
h=h*(kk-des+1);
else
- h=h*sqrt(kk-des+1);
+ h=h*sqrt(kk-des+1);
end
elseif kk=20, PenCoef=PenCoef/10; Reset=1; kless=0; end
+ if kless>=20
+ PenCoef=PenCoef/10;
+ Reset=1;
+ kless=0;
+ end
else
kless=0;
end
- if appconstr,
+ if appconstr
deltax=sign(x); idx=find(deltax==0);
deltax(idx)=ones(size(idx)); deltax=ddx*deltax;
if trx
gc=apprgrdn(x',fc,func,deltax',0);
else
- gc=apprgrdn(x ,fc,func,deltax ,0);
+ gc=apprgrdn(x ,fc,func,deltax ,0);
end
n_constraint_evals=n_constraint_evals+n;
else
if trx
gc=feval(gradc,x');
else
- gc=feval(gradc,x );
+ gc=feval(gradc,x );
end
n_constraint_gradient_evals=n_constraint_gradient_evals+1;
end
- if size(gc,2)==1, gc=gc'; end, ngc=norm(gc);
- if isnan(ngc),
- if dispwarn,disp(errmes);disp(error61);end
- exitflag=-6; if trx, x=x';end, return
- elseif ngc==Inf,
- if dispwarn,disp(errmes);disp(error62);end
- exitflag=-6; if trx, x=x';end, return
- elseif ngch1*frec, frec=f; xrec=x; grec=g; end
+ end
+ end
+ if h1*f>h1*frec
+ frec=f;
+ xrec=x;
+ grec=g;
+ end
% ----}
- if ng>ZeroGrad,
- if knorms<10, knorms=knorms+1; end
- if knorms>=2, gnorms(2:knorms)=gnorms(1:knorms-1); end
+ if ng>ZeroGrad
+ if knorms<10
+ knorms=knorms+1;
+ end
+ if knorms>=2
+ gnorms(2:knorms)=gnorms(1:knorms-1);
+ end
gnorms(1)=ng;
nng=(prod(gnorms(1:knorms)))^(1/knorms);
end
-
+
% DISPLAY THE CURRENT VALUES ----{
if k==ld
disp('Iter.# ..... Function ... Step Value ... Gradient Norm ');
@@ -721,10 +925,20 @@ while 1,
%----}
% CHECK THE STOPPING CRITERIA ----{
termflag=1;
- if constr, if ~FP, termflag=0; end, end
- if kcheck<=5, termflag=0; end
- if knan, termflag=0; end
- if kc>=mxtc, termflag=0; end
+ if constr
+ if ~FP
+ termflag=0;
+ end
+ end
+ if kcheck<=5
+ termflag=0;
+ end
+ if knan
+ termflag=0
+ end
+ if kc>=mxtc
+ termflag=0;
+ end
% ARGUMENT
if termflag
idx=find(abs(x)>=lowxbound);
@@ -737,40 +951,48 @@ while 1,
~constr
if any(abs(xrec(idx)-x(idx))> detxr * abs(x(idx)))
if dispwarn
- disp(wrnmes);
- disp(warn09);
+ disp(wrnmes)
+ disp(warn09)
end
- x=xrec;
- f=frec;
- g=grec;
- ng=norm(g);
+ x=xrec;
+ f=frec;
+ g=grec;
+ ng=norm(g);
krerun=krerun+1;
h=h1*max([dx,detxr*norm(x)])/krerun;
- warnno=2;
+ warnno=2;
break
else
h=h*10;
end
elseif abs(f-frec)> optim.TolFun*abs(f) && ...
norm(x-xrec)=limxterm )
if stopf
if dx<=laststep
- if warnno==1 && ng=limxterm
exitflag=-14;
- if dispwarn, disp(termwarn1); disp(endwarn(4,:));
- if app, disp(appwarn); end
+ if dispwarn
+ disp(termwarn1)
+ disp(endwarn(4,:))
+ if app
+ disp(appwarn)
+ end
end
x=xrec; f=frec;
- if trx,x=x';end, return
+ if trx
+ x=x';
+ end
+ return
else
stopf=0;
end
@@ -795,57 +1024,67 @@ while 1,
end
% ITERATIONS LIMIT
if(k==optim.MaxIter)
- exitflag=-9;
+ exitflag=-9;
if trx
- x=x';
- end,
- if dispwarn, disp(wrnmes); disp(warn4); end
+ x=x';
+ end
+ if dispwarn
+ disp(wrnmes)
+ disp(warn4)
+ end
return
end
% ----}
% ZERO GRADIENT ----{
if constr
- if ng<=ZeroGrad,
- if dispwarn, disp(termwarn1); disp(warn1); end
- exitflag=-8;
+ if ng<=ZeroGrad
+ if dispwarn
+ disp(termwarn1)
+ disp(warn1)
+ end
+ exitflag=-8;
if trx
x=x';
end
return
end
else
- if ng<=ZeroGrad, nzero=nzero+1;
- if dispwarn, disp(wrnmes); disp(warn1); end
+ if ng<=ZeroGrad
+ nzero=nzero+1;
+ if dispwarn
+ disp(wrnmes)
+ disp(warn1)
+ end
if nzero>=3
- exitflag=-8;
+ exitflag=-8;
if trx
x=x';
end
return
end
g0=-h*g0/2;
- for i=1:10,
+ for i=1:10
x=x+g0;
if trx
f=feval(fun,x',varargin{:});
else
- f=feval(fun,x,varargin{:});
+ f=feval(fun,x,varargin{:});
end
n_f_evals=n_f_evals+1;
if abs(f)==Inf
if dispwarn
- disp(errmes);
- disp(error32);
+ disp(errmes)
+ disp(error32)
end
exitflag=-3;
if trx
x=x';
end
return
- elseif isnan(f),
+ elseif isnan(f)
if dispwarn
- disp(errmes);
- disp(error32);
+ disp(errmes)
+ disp(error32)
end
exitflag=-3;
if trx
@@ -853,47 +1092,47 @@ while 1,
end
return
end
- if app,
- deltax=sign(g0);
+ if app
+ deltax=sign(g0);
idx=find(deltax==0);
- deltax(idx)=ones(size(idx));
+ deltax(idx)=ones(size(idx));
deltax=h1*ddx*deltax;
- if trx
+ if trx
g=apprgrdn(x',f,fun,deltax',1,varargin{:});
else
g=apprgrdn(x,f,fun,deltax,1,varargin{:});
end
n_f_evals=n_f_evals+n;
else
- if trx
+ if trx
g=feval(grad,x',varargin{:});
else
- g=feval(grad,x,varargin{:});
+ g=feval(grad,x,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(g,2)==1
- g=g';
+ g=g';
end
ng=norm(g);
if ng==Inf
if dispwarn
- disp(errmes);
- disp(error42);
+ disp(errmes)
+ disp(error42)
end
- exitflag=-4;
+ exitflag=-4;
if trx
- x=x';
+ x=x';
end
return
elseif isnan(ng)
if dispwarn
- disp(errmes);
- disp(error41);
+ disp(errmes)
+ disp(error41)
end
- exitflag=-4;
+ exitflag=-4;
if trx
- x=x';
+ x=x';
end
return
end
@@ -901,41 +1140,54 @@ while 1,
break
end
end
- if ng<=ZeroGrad,
+ if ng<=ZeroGrad
if dispwarn
- disp(termwarn1);
- disp(warn1);
+ disp(termwarn1)
+ disp(warn1)
end
- exitflag=-8;
+ exitflag=-8;
if trx
x=x';
end
return
end
- h=h1*dx;
+ h=h1*dx;
break
end
end
% ----}
% FUNCTION IS FLAT AT THE POINT ----{
if ~constr && abs(f-fopt)5 && ng<1
- idx=find(abs(g)<=epsnorm2);
+ idx=find(abs(g)<=epsnorm2);
ni=size(idx,2);
- if ni>=1 && ni<=n/2 && kflat<=3, kflat=kflat+1;
- if dispwarn, disp(wrnmes); disp(warn31); end, warnno=1;
+ if ni>=1 && ni<=n/2 && kflat<=3
+ kflat=kflat+1;
+ if dispwarn
+ disp(wrnmes)
+ disp(warn31)
+ end
+ warnno=1;
x1=x; fm=f;
- for j=idx, y=x(j); f2=fm;
- if y==0, x1(j)=1; elseif abs(y)<1, x1(j)=sign(y); else, x1(j)=y; end
- for i=1:20, x1(j)=x1(j)/1.15;
+ for j=idx
+ y=x(j); f2=fm;
+ if y==0
+ x1(j)=1;
+ elseif abs(y)<1
+ x1(j)=sign(y);
+ else
+ x1(j)=y;
+ end
+ for i=1:20
+ x1(j)=x1(j)/1.15;
if trx
f1=feval(fun,x1',varargin{:});
else
- f1=feval(fun,x1,varargin{:});
+ f1=feval(fun,x1,varargin{:});
end
n_f_evals=n_f_evals+1;
- if abs(f1)~=Inf && ~isnan(f1),
+ if abs(f1)~=Inf && ~isnan(f1)
if h1*f1>h1*fm
- y=x1(j);
+ y=x1(j);
fm=f1;
elseif h1*f2>h1*f1
break
@@ -948,36 +1200,36 @@ while 1,
x1(j)=y;
end
if h1*fm>h1*f
- if app,
+ if app
deltax=h1*ddx*ones(size(deltax));
if trx
gt=apprgrdn(x1',fm,fun,deltax',1,varargin{:});
else
- gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:});
+ gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:});
end
n_f_evals=n_f_evals+n;
else
if trx
gt=feval(grad,x1',varargin{:});
else
- gt=feval(grad,x1,varargin{:});
+ gt=feval(grad,x1,varargin{:});
end
n_grad_evals=n_grad_evals+1;
end
if size(gt,2)==1
- gt=gt';
+ gt=gt';
end
ngt=norm(gt);
- if ~isnan(ngt) && ngt>epsnorm2,
+ if ~isnan(ngt) && ngt>epsnorm2
if dispwarn
- disp(warn32);
+ disp(warn32)
end
optim.TolFun=optim.TolFun/5;
- x=x1;
- g=gt;
- ng=ngt;
- f=fm;
- h=h1*dx/3;
+ x=x1;
+ g=gt;
+ ng=ngt;
+ f=fm;
+ h=h1*dx/3;
break
end
end
@@ -986,6 +1238,6 @@ while 1,
% ----}
end % iterations
end % restart
-% end of the function
-%
-end
\ No newline at end of file
+ % end of the function
+ %
+ end
\ No newline at end of file
diff --git a/matlab/optimize_prior.m b/matlab/optimize_prior.m
index cdb03ecff..adf4d9c0e 100644
--- a/matlab/optimize_prior.m
+++ b/matlab/optimize_prior.m
@@ -2,7 +2,7 @@ function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, Esti
% This routine computes the mode of the prior density using an optimization algorithm.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,7 +34,7 @@ while look_for_admissible_initial_condition
look_for_admissible_initial_condition = 0;
end
else
- if iter == 2000;
+ if iter == 2000
scale = scale/1.1;
iter = 0;
else
diff --git a/matlab/options2cell.m b/matlab/options2cell.m
index 1296df22d..697c24b87 100644
--- a/matlab/options2cell.m
+++ b/matlab/options2cell.m
@@ -2,13 +2,13 @@ function c = options2cell(o)
% Converts an option structure as a cell of NAME and VALUE pairs.
%
-% INPUTS
+% INPUTS
% o o matlab's structure holding a set of options (each field name is the name of an option and the associated content is the value of the option).
%
-% OUTPUTS
+% OUTPUTS
% o c matlab's cell row array of the form {NAME1, VALUE1, NAME2, VALUE2, NAME3, VALUE3, ...}.
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
%
% This file is part of Dynare.
%
@@ -27,10 +27,10 @@ function c = options2cell(o)
s = fieldnames(o);
c = {};
-j = 1;
+j = 1;
for i=1:length(s)
- c(j) = {s{i}};
- c(j+1) = {o.(s{i})};
- j = j+2;
+ c(j) = {s{i}};
+ c(j+1) = {o.(s{i})};
+ j = j+2;
end
\ No newline at end of file
diff --git a/matlab/osr.m b/matlab/osr.m
index d579c63ec..60039ac45 100644
--- a/matlab/osr.m
+++ b/matlab/osr.m
@@ -9,19 +9,19 @@ function osr_res = osr(var_list,params,i_var,W)
% optimal simple rule
% i_var [n_osr_vars by 1 double] indices of osr-variable in
% specified in optim_weights in declaration order
-% W [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables
-%
+% W [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables
+%
% OUTPUTS
% osr_res: [structure] results structure containing:
% - objective_function [scalar double] value of the objective
% function at the optimum
-% - optim_params [structure] parameter values at the optimum
-%
-%
+% - optim_params [structure] parameter values at the optimum
+%
+%
% SPECIAL REQUIREMENTS
% none.
-%
-% Copyright (C) 2001-2016 Dynare Team
+%
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -38,7 +38,7 @@ function osr_res = osr(var_list,params,i_var,W)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-global M_ options_ oo_
+global M_ options_ oo_
options_.order = 1;
diff --git a/matlab/osr1.m b/matlab/osr1.m
index a92dfedd5..b73db2b24 100644
--- a/matlab/osr1.m
+++ b/matlab/osr1.m
@@ -9,14 +9,14 @@ function osr_res = osr1(i_params,i_var,weights)
% osr_res: [structure] results structure containing:
% - objective_function [scalar double] value of the objective
% function at the optimum
-% - optim_params [structure] parameter values at the optimum
-%
+% - optim_params [structure] parameter values at the optimum
+%
% Algorithm:
-%
+%
% Uses Newton-type optimizer csminwel to directly solve quadratic
% osr-problem
-%
-% Copyright (C) 2005-2014 Dynare Team
+%
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -80,7 +80,7 @@ if isfield(options_.osr,'maxit') || isfield(options_.osr,'tolf')
options_.optim_opt=[options_.optim_opt,','];
end
options_.optim_opt=[options_.optim_opt,'''TolFun'',',num2str(options_.osr.tolf),''];
- end
+ end
end
end
@@ -102,12 +102,12 @@ i_var=unique(i_var);
[loss,info,exit_flag,vx]=osr_obj(t0,i_params,inv_order_var(i_var),weights(i_var,i_var));
if info~=0
print_info(info, options_.noprint, options_);
-else
+else
if ~options_.noprint
fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss);
end
end
-if ~options_.noprint && isinf(loss)
+if ~options_.noprint && isinf(loss)
fprintf('\nOSR: The initial value of the objective function is infinite.\n');
fprintf('\nOSR: Check whether the unconditional variance of a target variable is infinite\n');
fprintf('\nOSR: due to the presence of a unit root.\n');
@@ -120,13 +120,13 @@ if isequal(options_.osr.opt_algo,5)
elseif isequal(options_.osr.opt_algo,6)
error('OSR: OSR does not support opt_algo=6.')
elseif isequal(options_.osr.opt_algo,10)
- error('OSR: OSR does not support opt_algo=10.')
+ error('OSR: OSR does not support opt_algo=10.')
elseif isequal(options_.osr.opt_algo,11)
- error('OSR: OSR does not support opt_algo=11.')
+ error('OSR: OSR does not support opt_algo=11.')
else
-
+
if ~isempty(M_.osr.param_bounds) && ~(ismember(options_.osr.opt_algo,[1,2,5,9]) || ischar(options_.osr.opt_algo))
- error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.')
+ error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.')
end
%%do actual optimization
[p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,M_.osr.param_bounds,cellstr(M_.param_names(i_params,:)),[],[], i_params,...
diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m
index 5bea8e760..76db1da69 100644
--- a/matlab/osr_obj.m
+++ b/matlab/osr_obj.m
@@ -17,7 +17,7 @@ function [loss,info,exit_flag,vx,junk]=osr_obj(x,i_params,i_var,weights)
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2005-2016 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -58,7 +58,7 @@ if info(1)
return
else
loss = 1e8;
- info(4)=0.1;
+ info(4)=0.1;
return
end
end
diff --git a/matlab/parallel/AnalyseComputationalEnvironment.m b/matlab/parallel/AnalyseComputationalEnvironment.m
index ff9920abf..d00ca1b69 100644
--- a/matlab/parallel/AnalyseComputationalEnvironment.m
+++ b/matlab/parallel/AnalyseComputationalEnvironment.m
@@ -31,7 +31,7 @@ function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd)
% field RemoteTmpFolder (the temporary directory created/destroyed on remote
% computer) is used.
-if ispc,
+if ispc
[tempo, MasterName]=system('hostname');
MasterName=deblank(MasterName);
end
@@ -83,7 +83,7 @@ dynareParallelMkDir(RemoteTmpFolder,DataInput);
% Currently when errors are detected execution simply stops and users can
% fix configuration errors according to the error type.
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -106,38 +106,38 @@ ErrorCode=0;
for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
% and use AnalyseComputationalEnvironment with differents input!
-
-
+
+
% Determine the operating system or software version when necessary
% for different command types.
-
+
OScallerUnix=~ispc;
OScallerWindows=ispc;
OStargetUnix=strcmpi('unix',DataInput(Node).OperatingSystem);
- if isempty(DataInput(Node).OperatingSystem),
+ if isempty(DataInput(Node).OperatingSystem)
OStargetUnix=OScallerUnix;
end
OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem);
- if isempty(DataInput(Node).OperatingSystem),
+ if isempty(DataInput(Node).OperatingSystem)
OStargetWindows=OScallerWindows;
end
-
+
Environment= (OScallerUnix || OStargetUnix);
-
+
skipline(2)
disp(['Testing computer -> ',DataInput(Node).ComputerName,' <- ...']);
skipline(2)
-
+
% The function is composed by two main blocks, determined by the 'Local'
% variable.
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if ((DataInput(Node).Local == 0) |(DataInput(Node).Local == 1))
% Continue it is Ok!
disp('Check on Local Variable ..... Ok!');
- skipline()
+ skipline()
else
disp('The variable "Local" has a bad value!');
skipline()
@@ -146,33 +146,33 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=1;
return
end
-
+
% %%%%%%%%%% Local (No Network) Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Here only the multi-core, or multi-processor avaiable on local
% machine are involved in parallel computing. No network
% comunications are required!
-
-
+
+
% In this case we need to check only the variable 'CPUnbr'.
-
+
% We run the parallel code on local computer, so the others fields are automatically
% fixed by Dynare parser. Then the user can also fill them with wrong values.
-
-
+
+
% %%%%%%%%%% Cluster Computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Here we can have many computer with multi-core, or multi-processor avaiable on the
% network and involved in parallel computing.
% So in this case we need more sophisticated check.
-
-
+
+
if (DataInput(Node).Local == 0)
-
+
% Now we verify if it is possibile to be connected with the
% remote computer.
-
+
si1=[];
de1=[];
-
+
if Environment
if OScallerWindows
[si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
@@ -182,7 +182,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
else
[si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
end
-
+
if (si1)
disp(['It is impossibile to ping to the computer with name "',DataInput(Node).ComputerName,'" using the network!'])
skipline()
@@ -193,16 +193,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
disp('Check on ComputerName Variable ..... Ok!')
skipline(2)
end
-
-
+
+
% Now we verify if user name and password are correct and if remote
% drive and remote folder exist on the remote computer and it is
% possible to exchange data with them.
-
+
if Environment
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if (isempty(DataInput(Node).UserName))
disp('The fields UserName is empty!')
skipline()
@@ -213,9 +213,9 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
end
disp('Check on UserName Variable ..... Ok!')
skipline(2)
-
+
% This check can be removed ... according to the dynare parser
- % strategy.
+ % strategy.
if (~isempty(DataInput(Node).Password))
disp('[WARNING] The field Password should be empty under unix or mac!');
skipline()
@@ -229,10 +229,10 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
skipline(2)
end
else
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if (isempty(DataInput(Node).UserName)) || (isempty(DataInput(Node).Password))
disp('The fields UserName and/or Password are/is empty!');
skipline()
@@ -246,15 +246,15 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
disp('Check on Password Variable ..... Ok!');
skipline()
end
-
+
% Now we very if RemoteDrive and/or RemoteDirectory exist on remote
% computer!
-
+
if Environment
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if isempty(DataInput(Node).RemoteDirectory)
disp('The field RemoteDirectory is empty!')
skipline()
@@ -263,10 +263,10 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=5;
return
end
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if (~isempty(DataInput(Node).RemoteDrive))
disp('[WARNING] The fields RemoteDrive should be empty under unix or mac!')
skipline()
@@ -276,17 +276,17 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
skipline(2)
ErrorCode=5;
end
-
+
si2=[];
de2=[];
- if ~isempty(DataInput(Node).Port),
+ if ~isempty(DataInput(Node).Port)
ssh_token = ['-p ',DataInput(Node).Port];
else
ssh_token = '';
end
-
+
[si2 de2]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' ls ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,'/']);
-
+
if (si2)
disp ('Remote Directory does not exist or is not reachable!')
skipline()
@@ -295,16 +295,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=5;
return
end
-
+
disp('Check on RemoteDirectory Variable ..... Ok!')
skipline(2)
disp('Check on RemoteDrive Variable ..... Ok!')
skipline(2)
-
+
else
% This check can be removed ... according to the dynare parser
% strategy.
-
+
if (isempty(DataInput(Node).RemoteDrive)||isempty(DataInput(Node).RemoteDirectory))
disp('Remote RemoteDrive and/or RemoteDirectory is/are empty!')
skipline()
@@ -313,12 +313,12 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=5;
return
end
-
-
+
+
si2=[];
de2=[];
[si2 de2]=system(['dir \\',DataInput(Node).ComputerName,'\',DataInput(Node).RemoteDrive,'$\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder]);
-
+
if (si2)
disp ('Remote Directory does not exist or it is not reachable!')
skipline()
@@ -327,31 +327,31 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=5;
return
end
-
+
disp('Check on RemoteDirectory Variable ..... Ok!')
skipline(2)
disp('Check on RemoteDrive Variable ..... Ok!')
skipline(2)
-
+
end
-
-
+
+
% Now we verify if it possible to exchange data with the remote
% computer:
-
-
+
+
% Build a command file to test the matlab execution and dynare path ...
-
+
fid = fopen('Tracing.m', 'w+');
s1=(['fT = fopen(''MatlabOctaveIsOk.txt'',''w+'');\n']);
s2='fclose(fT);\n';
SBS=strfind(DataInput(Node).DynarePath,'\');
DPStr=DataInput(Node).DynarePath;
- if isempty(SBS),
+ if isempty(SBS)
DPStrNew=DPStr;
else
DPStrNew=[DPStr(1:SBS(1)),'\'];
- for j=2:length(SBS),
+ for j=2:length(SBS)
DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\'];
end
DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)];
@@ -370,7 +370,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
s8=['end,\n'];
send='exit';
StrCommand=([s1,s2,s3,s4,s41,s42,s5,s51,s52,s6,s7,s71,s72,s8,send]);
-
+
% Mettere controllo su NbW ...
% if isoctave
% NbW = fprintf(fid,StrCommand, '%s');
@@ -378,12 +378,12 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
NbW = fprintf(fid,StrCommand, '%s');
% end
fclose(fid);
-
+
dynareParallelSendFiles('Tracing.m', RemoteTmpFolder,DataInput(Node));
FindTracing = dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
-
+
delete ('Tracing.m');
-
+
if (isempty(FindTracing))
disp('It is impossible to exchange data with Remote Drive and/or Remote Directory! ErrorCode 6.')
skipline()
@@ -395,14 +395,14 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
disp('Check on Exchange File with Remote Computer ..... Ok!')
skipline(2)
end
-
-
+
+
% Now we verify if it is possible execute a matlab/octave section on remote
% machine when the user is .UserName with password .Password and
% the path is MatlabOctavePath.
-
- if Environment,
- if ~isempty(DataInput(Node).Port),
+
+ if Environment
+ if ~isempty(DataInput(Node).Port)
ssh_token = ['-p ',DataInput(Node).Port];
else
ssh_token = '';
@@ -413,7 +413,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder, '; ', DataInput(Node).MatlabOctavePath, ' -nosplash -nodesktop -minimize -r Tracing;" &']);
end
else
- if ~strcmp(DataInput(Node).ComputerName,MasterName), % run on remote machine
+ if ~strcmp(DataInput(Node).ComputerName,MasterName) % run on remote machine
if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
[NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' Tracing.m']);
else
@@ -426,21 +426,22 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
[NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']);
end
end
-
+
end
-
+
% Timer da fissare, nei valori di attesa!
-
+
t1=fix(clock);
-
- if t1(5)+1>60;
+
+ if t1(5)+1>60
t2=2;
- else t2=t1(5)+1;
+ else
+ t2=t1(5)+1;
end
-
+
Flag=0;
-
- while (1);
+
+ while (1)
if Flag==0
disp('Try to run matlab/octave on remote machine ... ')
skipline()
@@ -450,18 +451,18 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
end
nt=fix(clock);
nt(5)-t2;
-
+
if (~isempty (dynareParallelDir('MatlabOctaveIsOk.txt',RemoteTmpFolder,DataInput(Node)))) || ((nt(5)-t2)>0)
if ((nt(5)-t2)>0)
ErrorCode=7;
end
break
end
-
+
end
-
+
if (ErrorCode==7)
-
+
disp ('It is not possible execute a matlab session on remote machine!')
skipline()
disp('ErrorCode 7.')
@@ -472,18 +473,18 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
else
disp('Check on MatlabOctave Path and MatlabOctave Program Execution on remote machine ..... Ok!')
skipline(2)
-
+
% Now we verify if the DynarePath is correct ...
disp('Check the Dynare path on remote machine ... ')
skipline()
disp('please wait ... ')
skipline(2)
pause(2)
-
+
if isempty(dynareParallelDir('DynareIsOk.txt',RemoteTmpFolder,DataInput(Node)))
ErrorCode=8;
end
-
+
if (ErrorCode==8)
disp ('The DynarePath is incorrect!')
skipline()
@@ -497,21 +498,21 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node)))
RemoteEnvironment=Environment;
else
- RemoteEnvironment=2;
+ RemoteEnvironment=2;
end
skipline(2)
end
end
-
-
+
+
% Now we verify if it is possible delete remote computational traces!
-
+
dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
-
+
si3=[];
-
+
si3=dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
-
+
if (isempty(si3))
disp ('Check on Delete Remote Computational Traces ..... Ok!')
skipline(2)
@@ -523,16 +524,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=9;
return
end
-
-
+
+
end
% Now we check the variable 'CPUnbr'.
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
+
yn=isempty(DataInput(Node).CPUnbr);
-
+
if yn==1
% The field is empty!
disp('The field "CPUnbr" is empty!')
@@ -542,21 +543,21 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=2;
return
end
-
+
% This check can be removed ... according to the dynare parser
% strategy.
-
-
-
+
+
+
% We look for the information on local computer hardware.
-
+
si0=[];
de0=[];
-
+
Environment1=Environment;
disp('Checking Hardware please wait ...');
if (DataInput(Node).Local == 1)
- if Environment,
+ if Environment
if ~ismac
[si0 de0]=system('grep processor /proc/cpuinfo');
else
@@ -567,14 +568,14 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
[si0 de0]=system(['psinfo \\']);
end
else
- if Environment,
- if ~isempty(DataInput(Node).Port),
+ if Environment
+ if ~isempty(DataInput(Node).Port)
ssh_token = ['-p ',DataInput(Node).Port];
else
ssh_token = '';
end
- if OStargetUnix,
- if RemoteEnvironment ==1 ,
+ if OStargetUnix
+ if RemoteEnvironment ==1
[si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' grep processor /proc/cpuinfo']);
else % it is MAC
[si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' sysctl -n hw.ncpu']);
@@ -587,16 +588,16 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
[si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName,' -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password]);
end
end
-
-
+
+
RealCPUnbr='';
% keyboard;
RealCPUnbr=GiveCPUnumber(de0,Environment1);
-
+
% Questo controllo penso che si possa MIGLIORARE!!!!!
- if isempty (RealCPUnbr) && Environment1==0,
+ if isempty (RealCPUnbr) && Environment1==0
[si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]);
- end
+ end
RealCPUnbr=GiveCPUnumber(de0,Environment1);
if isempty (RealCPUnbr)
@@ -615,23 +616,23 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
ErrorCode=2;
return
end
-
-
+
+
% Trasforming the input data provided in a form [n1:n2] in a single numerical
% value.
-
-
+
+
CPUnbrUser=length(DataInput(Node).CPUnbr);
maxCPUnbrUser=max(DataInput(Node).CPUnbr)+1;
-
+
disp(['Hardware has ', num2str(RealCPUnbr),' Cpu/Cores!'])
disp(['User requires ',num2str(CPUnbrUser),' Cpu/Cores!'])
- if CPUnbrUser==RealCPUnbr,
+ if CPUnbrUser==RealCPUnbr
% It is Ok!
disp('Check on CPUnbr Variable ..... Ok!')
skipline(3)
end
-
+
if CPUnbrUser > RealCPUnbr
disp('Warning! The user asks to use more CPU''s than those available.')
skipline(2)
@@ -642,7 +643,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
skipline(2)
ErrorCode=2.2;
end
-
+
if mod(length(DataInput(Node).CPUnbr),DataInput(Node).NumberOfThreadsPerJob)
skipline()
disp(['NumberOfThreadsPerJob = ',int2str(DataInput(Node).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(DataInput(Node).CPUnbr),'!'])
@@ -651,7 +652,7 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
skipline()
ErrorCode=2.3;
end
-
+
disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!'])
- skipline(2)
+ skipline(2)
end
\ No newline at end of file
diff --git a/matlab/parallel/CreateTimeString.m b/matlab/parallel/CreateTimeString.m
index 8b82b1cc6..e78f8836a 100644
--- a/matlab/parallel/CreateTimeString.m
+++ b/matlab/parallel/CreateTimeString.m
@@ -6,9 +6,9 @@ function [TiSt] = CreateTimeString()
% None
%
% OUTPUTS
-% o TiSt [] ...
+% o TiSt [] ...
%
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/parallel/GiveCPUnumber.m b/matlab/parallel/GiveCPUnumber.m
index b45d3f879..cc2d45aa3 100644
--- a/matlab/parallel/GiveCPUnumber.m
+++ b/matlab/parallel/GiveCPUnumber.m
@@ -13,7 +13,7 @@ function [nCPU]= GiveCPUnumber (ComputerInformations, Environment)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,7 +33,7 @@ function [nCPU]= GiveCPUnumber (ComputerInformations, Environment)
nCPU='';
-if nargin < 2,
+if nargin < 2
% Determine a specific operating system or software version when necessary
% for different command (sintax, name, ...).
Environment=~ispc;
@@ -41,7 +41,7 @@ end
switch Environment
case 0 %WINDOWS OPERATING SYSTEM
-
+
OffSet=27;
SringPosition=strfind(ComputerInformations, 'Processors:');
@@ -64,7 +64,7 @@ switch Environment
return
case 1 %LIKE UNIX OPERATING SYSTEM
-
+
% Da generalizzare a un numero di CPu maggiore di 9!!!
nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1;
diff --git a/matlab/parallel/InitializeComputationalEnvironment.m b/matlab/parallel/InitializeComputationalEnvironment.m
index 02df7aad4..18ce19f11 100644
--- a/matlab/parallel/InitializeComputationalEnvironment.m
+++ b/matlab/parallel/InitializeComputationalEnvironment.m
@@ -10,7 +10,7 @@ function InitializeComputationalEnvironment()
% OUTPUTS
% None
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -37,7 +37,7 @@ function InitializeComputationalEnvironment()
% Comment the line 'warning('off');' in order to view the warning message
% in Octave!
-if isoctave
+if isoctave
warning('off');
end
@@ -46,15 +46,15 @@ end
global options_
isHybridMatlabOctave = false;
-for j=1:length(options_.parallel),
- if isempty(options_.parallel(j).MatlabOctavePath),
+for j=1:length(options_.parallel)
+ if isempty(options_.parallel(j).MatlabOctavePath)
if isoctave
options_.parallel(j).MatlabOctavePath = 'octave';
else
options_.parallel(j).MatlabOctavePath = 'matlab';
end
end
- if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath),
+ if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath)
dynareroot = strrep(which('dynare'),'dynare.m','');
options_.parallel(j).DynarePath=dynareroot;
end
@@ -62,7 +62,7 @@ for j=1:length(options_.parallel),
end
isHybridMatlabOctave = isHybridMatlabOctave && ~isoctave;
options_.parallel_info.isHybridMatlabOctave = isHybridMatlabOctave;
-if isHybridMatlabOctave,
+if isHybridMatlabOctave
% Reset dynare random generator and seed.
set_dynare_seed('default');
end
@@ -94,7 +94,7 @@ CPUWeightTemp=ones(1,lP)*(-1);
CPUWeightTemp=CPUWeight;
for i=1:lP
- [NoNServes mP]=max(CPUWeightTemp);
+ [NoNServes, mP]=max(CPUWeightTemp);
NewPosition(i)=mP;
CPUWeightTemp(mP)=-1;
end
diff --git a/matlab/parallel/closeSlave.m b/matlab/parallel/closeSlave.m
index 03e310606..49c14deb3 100644
--- a/matlab/parallel/closeSlave.m
+++ b/matlab/parallel/closeSlave.m
@@ -1,4 +1,4 @@
-function closeSlave(Parallel,TmpFolder,partial),
+function closeSlave(Parallel,TmpFolder,partial)
% PARALLEL CONTEXT
% In parallel context, this utility closes all remote matlab instances
% called by masterParallel when strategy (1) is active i.e. always open (which leaves
@@ -10,12 +10,12 @@ function closeSlave(Parallel,TmpFolder,partial),
% This directory is named using current date
% and is used only one time and then deleted.
% If islocal==1, TmpFolder=''.
-%
+%
%
% OUTPUTS
% None
%
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -32,7 +32,7 @@ function closeSlave(Parallel,TmpFolder,partial),
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin<3,
+if nargin<3
partial=0;
end
@@ -40,8 +40,8 @@ s=warning('off');
if partial==1
save('slaveParallel_break.mat','partial')
- for indPC=1:length(Parallel),
- if (Parallel(indPC).Local==0),
+ for indPC=1:length(Parallel)
+ if (Parallel(indPC).Local==0)
dynareParallelSendFiles('slaveParallel_break.mat',TmpFolder,Parallel(indPC));
end
end
@@ -50,8 +50,8 @@ if partial==1
end
if partial==-1
delete('slaveParallel_break.mat')
- for indPC=1:length(Parallel),
- if (Parallel(indPC).Local==0),
+ for indPC=1:length(Parallel)
+ if (Parallel(indPC).Local==0)
dynareParallelDelete( 'slaveParallel_break.mat',TmpFolder,Parallel(indPC));
end
end
@@ -59,31 +59,30 @@ if partial==-1
return
end
-for indPC=1:length(Parallel),
- if (Parallel(indPC).Local==0),
+for indPC=1:length(Parallel)
+ if (Parallel(indPC).Local==0)
dynareParallelDelete( 'slaveParallel_input*.mat',TmpFolder,Parallel(indPC));
end
-
-
+
+
delete( 'slaveParallel_input*.mat');
delete( 'slaveJob*.mat');
pause(1)
delete(['slaveParallel_*.log']);
delete ConcurrentCommand1.bat;
-
+
end
while(1)
- if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel));
- for indPC=1:length(Parallel),
- if (Parallel(indPC).Local==0),
- dynareParallelRmDir(TmpFolder,Parallel(indPC)),
+ if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel))
+ for indPC=1:length(Parallel)
+ if (Parallel(indPC).Local==0)
+ dynareParallelRmDir(TmpFolder,Parallel(indPC))
end
end
break
-
+
end
end
-s=warning('on');
-
+s=warning('on');
\ No newline at end of file
diff --git a/matlab/parallel/distributeJobs.m b/matlab/parallel/distributeJobs.m
index 65f2627a2..c0c41925f 100644
--- a/matlab/parallel/distributeJobs.m
+++ b/matlab/parallel/distributeJobs.m
@@ -21,7 +21,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo
% It is a number between 1 and length(Parallel).
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -40,7 +40,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo
% The Parallel vector has already been sorted
-% (in accord with the CPUWeight values) in DESCENDING order in
+% (in accord with the CPUWeight values) in DESCENDING order in
% InitializeComputationalEnvironment!
totCPU=0;
@@ -48,7 +48,7 @@ totCPU=0;
lP=length(Parallel);
CPUWeight=ones(1,length(Parallel))*(-1);
-for j=1:lP,
+for j=1:lP
if mod(length(Parallel(j).CPUnbr),Parallel(j).NumberOfThreadsPerJob)
skipline()
disp(['PARALLEL_ERROR:: NumberOfThreadsPerJob = ',int2str(Parallel(j).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(length(Parallel(j).CPUnbr)),'!'])
@@ -57,7 +57,7 @@ for j=1:lP,
error(['PARALLEL_ERROR:: NumberOfThreadsPerJob is not an exact divisor of CPUnbr'])
end
nCPU(j)=length(Parallel(j).CPUnbr)/Parallel(j).NumberOfThreadsPerJob;
- totCPU=totCPU+nCPU(j);
+ totCPU=totCPU+nCPU(j);
CPUWeight(j)=str2num(Parallel(j).NodeWeight);
end
@@ -77,7 +77,7 @@ NumbersOfJobs=nBlock-fBlock+1;
SumOfJobs=0;
JobsForNode=zeros(1,nC);
-for j=1:lP,
+for j=1:lP
CPUWeight(j)=str2num(Parallel(j).NodeWeight)*nCPUoriginal(j);
end
CPUWeight=CPUWeight./sum(CPUWeight);
@@ -85,15 +85,15 @@ CPUWeight=CPUWeight./sum(CPUWeight);
% Redistributing the jobs among the cluster nodes according to the
% CPUWeight.
for i=1:nC
-
+
JobsForNode(i)=CPUWeight(i)*NumbersOfJobs;
-
+
% Many choices are possible:
-
+
% JobsForNode(i)=round(JobsForNode(i));
% JobsForNode(i)=floor(JobsForNode(i));
JobsForNode(i)=ceil(JobsForNode(i));
-
+
end
% Check if there are more (fewer) jobs.
@@ -101,19 +101,19 @@ end
SumOfJobs=sum(JobsForNode);
if SumOfJobs~=NumbersOfJobs
-
+
if SumOfJobs>NumbersOfJobs
-
+
% Many choices are possible:
-
+
% - Remove the excess works at the node that has the greatest
% number of jobs.
% - Remove the excess works at the node slower.
-
+
VerySlow=nC;
-
+
while SumOfJobs>NumbersOfJobs
-
+
if JobsForNode(VerySlow)==0
VerySlow=VerySlow-1;
continue
@@ -121,21 +121,21 @@ if SumOfJobs~=NumbersOfJobs
JobsForNode(VerySlow)=JobsForNode(VerySlow)-1;
SumOfJobs=SumOfJobs-1;
end
-
+
end
-
+
if SumOfJobs=JobsForNode(i)
- break;
+ break
end
-
+
end
-
+
% Check if there are more (fewer) jobs.
% This can happen when we use ceil, round, ... functions.
-
+
if ChekOverFlow ~=(JobsForNode(i))
-
+
if ChekOverFlow >(JobsForNode(i))
while ChekOverFlow>JobsForNode(i)
JobsForCpu(nCPU(i))=JobsForCpu(nCPU(i))-1;
ChekOverFlow=ChekOverFlow-1;
end
end
-
+
if ChekOverFlow <(JobsForNode(i))
while ChekOverFlow.
-if nargin ==0,
+if nargin ==0
disp('dynareParallelDelete(fname)')
return
end
-if nargin ==1,
+if nargin ==1
pname='';
else
pname=[pname,filesep];
end
-for indPC=1:length(Parallel),
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
@@ -53,5 +53,5 @@ for indPC=1:length(Parallel),
delete(fname_temp);
end
end
-
+
end
diff --git a/matlab/parallel/dynareParallelDeleteNewFiles.m b/matlab/parallel/dynareParallelDeleteNewFiles.m
index 4f12357dd..34fdab44b 100644
--- a/matlab/parallel/dynareParallelDeleteNewFiles.m
+++ b/matlab/parallel/dynareParallelDeleteNewFiles.m
@@ -15,7 +15,7 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin)
%
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -35,11 +35,11 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin)
NewFilesFromSlaves={};
% try
-for indPC=1:length(Parallel),
-
- if Parallel(indPC).Local==0;
+for indPC=1:length(Parallel)
+
+ if Parallel(indPC).Local==0
[NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir);
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
fS='/';
else
fS='\';
@@ -59,7 +59,7 @@ for indPC=1:length(Parallel),
for indexc=1:length(varargin)
exception_flag=exception_flag+(~isempty(strfind(fileaddress{2},varargin{indexc})));
end
- if exception_flag==0,
+ if exception_flag==0
dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC));
disp('New file deleted in remote -->');
@@ -75,6 +75,3 @@ for indPC=1:length(Parallel),
end
end
-
-
-
diff --git a/matlab/parallel/dynareParallelDir.m b/matlab/parallel/dynareParallelDir.m
index 6a9dd492c..0625dd8e7 100644
--- a/matlab/parallel/dynareParallelDir.m
+++ b/matlab/parallel/dynareParallelDir.m
@@ -10,7 +10,7 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel)
% OUTPUTS
% o dirlist [] ...
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -28,10 +28,10 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel)
% along with Dynare. If not, see .
dirlist=[];
-for indPC=1:length(Parallel),
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if Parallel(indPC).Local==0,
- if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if Parallel(indPC).Local==0
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
@@ -45,7 +45,7 @@ for indPC=1:length(Parallel),
else
[check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename]);
end
- if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'));
+ if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'))
ax=[];
else
indax=regexp(ax,'\n');
@@ -57,11 +57,11 @@ for indPC=1:length(Parallel),
else
if isoctave % Patch for peculiar behaviour of ls under Linux.
-
+
% It is necessary to capture the ls warning message and properly manage the jolly char '*'!
[check ax]=system(['ls ' ,filename, ' 2> OctaveStandardOutputMessage.txt']);
-
- if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'));
+
+ if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'))
ax=[];
end
else
@@ -75,32 +75,32 @@ for indPC=1:length(Parallel),
end
else
if isoctave % Patch for peculiar behaviour of ls under Windows.
- if Parallel(indPC).Local==0,
+ if Parallel(indPC).Local==0
ax0=dir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]);
else
ax0=dir(filename);
end
- if isempty(ax0),
+ if isempty(ax0)
ax='';
else
clear ax1;
- for jax=1:length(ax0);
+ for jax=1:length(ax0)
ax1{jax}=ax0(jax).name;
end
ax=char(ax1{:});
end
else
- if Parallel(indPC).Local==0,
+ if Parallel(indPC).Local==0
ax=ls(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]);
else
ax=ls(filename);
end
end
end
- if isempty(dirlist),
+ if isempty(dirlist)
dirlist=ax;
- elseif ~isempty(ax),
+ elseif ~isempty(ax)
dirlist = char(dirlist, ax);
end
end
diff --git a/matlab/parallel/dynareParallelFindNewFiles.m b/matlab/parallel/dynareParallelFindNewFiles.m
index 143f20870..d8cb6a9d7 100644
--- a/matlab/parallel/dynareParallelFindNewFiles.m
+++ b/matlab/parallel/dynareParallelFindNewFiles.m
@@ -15,7 +15,7 @@ function [NewFilesFrom, NewFileList]=dynareParallelFindNewFiles(FileList,Paralle
% o NewFilesFrom [] ...
% o NewFileList [] ...
%
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -45,35 +45,34 @@ LnFl=length(NewFileList);
RelativePosition=1;
for i=1:LnFl
-
+
% Exception Handling
-
+
% If you comment the code below all new file will be copied!
-
+
% 1. The comp_status* files are managed separately.
-
+
FiCoS=strfind(NewFileList{i},'comp_status_');
if ~isempty(FiCoS)
continue
end
-
+
% 2. For the time being is not necessary to always copy *.log
% and *.txt files.
-
+
nC1 = strfind(NewFileList{i}, '.log');
nC2 = strfind(NewFileList{i}, '.txt');
-
+
if (~isempty(nC1) || ~isempty(nC2))
continue
end
-
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-
+
+
N=strmatch(NewFileList{i},FileList,'exact');
if isempty(N)
NewFilesFrom{RelativePosition}=NewFileList{i};
RelativePosition=RelativePosition+1;
end
end
-
diff --git a/matlab/parallel/dynareParallelGetFiles.m b/matlab/parallel/dynareParallelGetFiles.m
index 9ec95f386..6669f21a8 100644
--- a/matlab/parallel/dynareParallelGetFiles.m
+++ b/matlab/parallel/dynareParallelGetFiles.m
@@ -14,7 +14,7 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel)
%
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,32 +33,32 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel)
NamFileInput0=NamFileInput;
-for indPC=1:length(Parallel),
- if Parallel(indPC).Local==0,
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+ if Parallel(indPC).Local==0
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
end
- if ~isempty(Parallel(indPC).Port),
+ if ~isempty(Parallel(indPC).Port)
scp_token = ['-P ',Parallel(indPC).Port];
else
scp_token = '';
end
- if ischar(NamFileInput0),
- for j=1:size(NamFileInput0,1),
+ if ischar(NamFileInput0)
+ for j=1:size(NamFileInput0,1)
NamFile(j,:)={['./'],deblank(NamFileInput0(j,:))};
end
NamFileInput = NamFile;
end
- for jfil=1:size(NamFileInput,1),
+ for jfil=1:size(NamFileInput,1)
if isoctave % Patch for peculiar behaviour of ls under Linux.
% It is necessary to manage the jolly char '*'!
FindAst=strfind(NamFileInput{jfil,2},'comp_status_posterior_sampler_core*');
-
+
if isempty (FindAst)
[NonServeL NonServeR]= system(['scp ',scp_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',NamFileInput{jfil,1}]);
@@ -66,9 +66,9 @@ for indPC=1:length(Parallel),
else
filenameTemp=NamFileInput{jfil,2};
-
+
[NotUsed FlI]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filenameTemp, ' 2> OctaveStandardOutputMessage.txt']);
-
+
if isempty (FlI)
return
end
@@ -92,14 +92,14 @@ for indPC=1:length(Parallel),
end
else
- if ischar(NamFileInput0),
- for j=1:size(NamFileInput0,1),
+ if ischar(NamFileInput0)
+ for j=1:size(NamFileInput0,1)
NamFile(j,:)={['.\'],deblank(NamFileInput0(j,:))};
end
NamFileInput = NamFile;
end
- for jfil=1:size(NamFileInput,1),
- if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC))),
+ for jfil=1:size(NamFileInput,1)
+ if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC)))
copyfile(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1},NamFileInput{jfil,2}],NamFileInput{jfil,1});
end
end
diff --git a/matlab/parallel/dynareParallelGetNewFiles.m b/matlab/parallel/dynareParallelGetNewFiles.m
index 5f7eb43a3..8d42bd375 100644
--- a/matlab/parallel/dynareParallelGetNewFiles.m
+++ b/matlab/parallel/dynareParallelGetNewFiles.m
@@ -15,7 +15,7 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh
%
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -36,11 +36,11 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh
NewFilesFromSlaves={};
% try
-for indPC=1:length(Parallel),
-
- if Parallel(indPC).Local==0;
+for indPC=1:length(Parallel)
+
+ if Parallel(indPC).Local==0
[NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir);
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
fS='/';
else
fS='\';
@@ -71,6 +71,3 @@ for indPC=1:length(Parallel),
end
end
-
-
-
diff --git a/matlab/parallel/dynareParallelListAllFiles.m b/matlab/parallel/dynareParallelListAllFiles.m
index 189908b71..eab713422 100644
--- a/matlab/parallel/dynareParallelListAllFiles.m
+++ b/matlab/parallel/dynareParallelListAllFiles.m
@@ -14,7 +14,7 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel)
% OUTPUTS
% o fileList [] ...
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,33 +34,33 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel)
if (~ispc || strcmpi('unix',Parallel.OperatingSystem))
-
+
fileList={};
currentPath=[];
- if ~isempty(Parallel.Port),
+ if ~isempty(Parallel.Port)
ssh_token = ['-p ',Parallel.Port];
else
ssh_token = '';
end
% Get the data for the current remote directory.
- [Flag fL]=system(['ssh ',ssh_token,' ',' ',Parallel.UserName,'@',Parallel.ComputerName,' ls ',Parallel.RemoteDirectory,'/',PRCDir, ' -R -p -1']);
+ [Flag, fL]=system(['ssh ',ssh_token,' ',' ',Parallel.UserName,'@',Parallel.ComputerName,' ls ',Parallel.RemoteDirectory,'/',PRCDir, ' -R -p -1']);
% Format the return value fL.
-
+
nL=regexp(fL,'\n');
start=1;
j=1;
for (i=1:length(nL))
-
+
stringProcessed=fL(start:nL(i)-1);
-
+
if isempty(stringProcessed)
start=nL(i)+1;
continue
end
-
+
if strfind(stringProcessed,'/')
if strfind(stringProcessed,PRCDir)
DD=strfind(stringProcessed,':');
@@ -70,11 +70,11 @@ if (~ispc || strcmpi('unix',Parallel.OperatingSystem))
start=nL(i)+1;
continue
end
-
+
fileList{j,1}=[currentPath stringProcessed];
start=nL(i)+1;
j=j+1;
- end
+ end
else
@@ -112,5 +112,3 @@ else
fileList = [fileList; dynareParallelListAllFiles(nextDir,PRCDir,Parallel)];
end
end
-
-
diff --git a/matlab/parallel/dynareParallelMkDir.m b/matlab/parallel/dynareParallelMkDir.m
index 9e8d7b7de..e85d1af3a 100644
--- a/matlab/parallel/dynareParallelMkDir.m
+++ b/matlab/parallel/dynareParallelMkDir.m
@@ -3,14 +3,14 @@ function dynareParallelMkDir(PRCDir,Parallel)
% In a parallel context, this is a specialized version of rmdir() function.
%
% INPUTS
-% o PRCDir [] ...
-% o Parallel [] ...
+% o PRCDir [] ...
+% o Parallel [] ...
%
% OUTPUTS
% None
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -29,24 +29,22 @@ function dynareParallelMkDir(PRCDir,Parallel)
-if nargin ==0,
+if nargin ==0
disp('dynareParallelMkDir(dirname,Parallel)')
return
end
for indPC=1:length(Parallel)
- if Parallel(indPC).Local==0,
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if ~isempty(Parallel(indPC).Port),
+ if Parallel(indPC).Local==0
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
end
- [NonServeS NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]);
+ [NonServeS, NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]);
else
- [NonServeS NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]);
+ [NonServeS, NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]);
end
end
-end
-
-return
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/matlab/parallel/dynareParallelRmDir.m b/matlab/parallel/dynareParallelRmDir.m
index fbf7b7790..64f3c4fde 100644
--- a/matlab/parallel/dynareParallelRmDir.m
+++ b/matlab/parallel/dynareParallelRmDir.m
@@ -3,15 +3,15 @@ function dynareParallelRmDir(PRCDir,Parallel)
% In a parallel context, this is a specialized version of rmdir() function.
%
% INPUTS
-% o PRCDir [] ...
-% o Parallel [] ...
+% o PRCDir [] ...
+% o Parallel [] ...
%
% OUTPUTS
% None
%
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -30,7 +30,7 @@ function dynareParallelRmDir(PRCDir,Parallel)
-if nargin ==0,
+if nargin ==0
disp('dynareParallelRmDir(fname)')
return
end
@@ -45,7 +45,7 @@ ok(5)=~isempty(strfind(PRCDir,'m'));
ok(6)=~isempty(strfind(PRCDir,'s'));
ok(7)=~isempty(PRCDir);
-if sum(ok)<7,
+if sum(ok)<7
error('The name of the remote tmp folder does not comply the security standards!'),
end
@@ -53,34 +53,32 @@ if isoctave
confirm_recursive_rmdir(false, 'local');
end
-for indPC=1:length(Parallel),
+for indPC=1:length(Parallel)
ok(1)=isempty(strfind(Parallel(indPC).RemoteDirectory,'..'));
- if sum(ok)<7,
+ if sum(ok)<7
error('The remote folder path structure does not comply the security standards!'),
end
while (1)
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if ~isempty(Parallel(indPC).Port),
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
end
- [stat NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]);
- break;
+ [stat, NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]);
+ break
else
[stat, mess, id] = rmdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir],'s');
- if stat==1,
- break,
+ if stat==1
+ break
else
- if isempty(dynareParallelDir(PRCDir,'',Parallel));
- break,
+ if isempty(dynareParallelDir(PRCDir,'',Parallel))
+ break
else
pause(1);
end
end
end
end
-end
-
-return
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/matlab/parallel/dynareParallelSendFiles.m b/matlab/parallel/dynareParallelSendFiles.m
index f65697286..6a3c8904c 100644
--- a/matlab/parallel/dynareParallelSendFiles.m
+++ b/matlab/parallel/dynareParallelSendFiles.m
@@ -14,7 +14,7 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel)
%
%
%
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -32,83 +32,83 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel)
% along with Dynare. If not, see .
-if ischar(NamFileInput),
- for j=1:size(NamFileInput,1),
+if ischar(NamFileInput)
+ for j=1:size(NamFileInput,1)
NamFile(j,:)={'',deblank(NamFileInput(j,:))};
end
NamFileInput = NamFile;
end
-for indPC=1:length(Parallel),
- if Parallel(indPC).Local==0,
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
- if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+ if Parallel(indPC).Local==0
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
end
- if ~isempty(Parallel(indPC).Port),
+ if ~isempty(Parallel(indPC).Port)
scp_token = ['-P ',Parallel(indPC).Port];
else
scp_token = '';
end
- for jfil=1:size(NamFileInput,1),
+ for jfil=1:size(NamFileInput,1)
if ~isempty(NamFileInput{jfil,1})
- [NonServeL NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
+ [NonServeL, NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
end
- [NonServeL NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
+ [NonServeL, NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
end
else
for jfil=1:size(NamFileInput,1)
if ~isempty(NamFileInput{jfil,1})
if isempty(dynareParallelDir(NamFileInput{jfil,1},PRCDir,Parallel(indPC)))
-
+
if isoctave % Patch for peculiar behaviour of mkdir under Windows.
-
+
% It is Necessary because Octave is not able to
% create two nested directory at the same time.
-
+
% Remove (if present) the '/' chars. Can be easily transformed
% in a function.
-
+
NamFileInputTemp=NamFileInput{jfil,1};
while(1)
Bs=strfind(NamFileInputTemp,'/');
- if isempty(Bs),
- break;
+ if isempty(Bs)
+ break
else
NamFileInputTemp(1,Bs)='\';
end
end
-
- [NonServeL NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
+
+ [NonServeL, NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
else
mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]);
end
end
end
-
+
if isoctave % Patch for peculiar behaviour copyfile ls under Windows.
-
+
% It is Necessary because Octave is not able to
% use the jolly char '*' with copyfile.
-
+
% Remove (if present) the '/' chars. Can be easily transformed
% in a function.
-
+
NamFileInputTemp=NamFileInput{jfil,1};
while(1)
Bs=strfind(NamFileInputTemp,'/');
- if isempty(Bs),
- break;
+ if isempty(Bs)
+ break
else
NamFileInputTemp(1,Bs)='\';
end
end
-
- [NonServeS NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
-
+
+ [NonServeS, NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
+
else
copyfile([NamFileInput{jfil,1},NamFileInput{jfil,2}],['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]);
end
diff --git a/matlab/parallel/dynareParallelSnapshot.m b/matlab/parallel/dynareParallelSnapshot.m
index ebff7a33c..8566ebfe0 100644
--- a/matlab/parallel/dynareParallelSnapshot.m
+++ b/matlab/parallel/dynareParallelSnapshot.m
@@ -14,7 +14,7 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel)
%
%
%
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,10 +33,10 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel)
PRCDirSnapshot={};
-for indPC=1:length(Parallel),
- if Parallel(indPC).Local==0;
+for indPC=1:length(Parallel)
+ if Parallel(indPC).Local==0
% The first call ...
PRCDirSnapshot{indPC}=dynareParallelListAllFiles('Root',PRCDir,Parallel(indPC));
-
+
end
end
diff --git a/matlab/parallel/fMessageStatus.m b/matlab/parallel/fMessageStatus.m
index 6d84705ab..2c9f8ab5f 100644
--- a/matlab/parallel/fMessageStatus.m
+++ b/matlab/parallel/fMessageStatus.m
@@ -3,18 +3,18 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel)
% In parallel context, this function is launched on slave
% machines, and acts as a message passing device for the master machine.
-% INPUTS
+% INPUTS
% o prtfrc [double] fraction of iteration performed
% o njob [int] index number of this CPU among all CPUs in the
% cluster
-% o waitbarString [char] running message string to be displayed in the monitor window on master machine
+% o waitbarString [char] running message string to be displayed in the monitor window on master machine
% o waitbarTitle [char] title to be displayed in the monitor window on master machine
% o Parallel [struct] options_.parallel(ThisMatlab), i.e. the parallel settings for this slave machine in the cluster.
%
-% OUTPUTS
-% o None
+% OUTPUTS
+% o None
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,18 +33,17 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel)
global funcName
-if nargin<5,
+if nargin<5
Parallel.Local=1;
end
try
save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle');
-catch
+catch
end
fslave = dir( ['slaveParallel_input',int2str(njob),'.mat']);
fbreak = dir( ['slaveParallel_break.mat']);
-if isempty(fslave) || ~isempty(fbreak),
+if isempty(fslave) || ~isempty(fbreak)
error('Master asked to break the job');
end
-
diff --git a/matlab/parallel/fParallel.m b/matlab/parallel/fParallel.m
index 51e6ebe16..4bce41008 100644
--- a/matlab/parallel/fParallel.m
+++ b/matlab/parallel/fParallel.m
@@ -18,7 +18,7 @@ function fParallel(fblck,nblck,whoiam,ThisMatlab,fname)
% OUTPUTS
% None
%
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -53,7 +53,7 @@ load( [fname,'_input'])
if exist('fGlobalVar') && ~isempty (fGlobalVar)
globalVars = fieldnames(fGlobalVar);
- for j=1:length(globalVars),
+ for j=1:length(globalVars)
eval(['global ',globalVars{j},';'])
evalin('base',['global ',globalVars{j},';'])
end
@@ -67,12 +67,12 @@ fInputVar.Parallel = Parallel;
% Launch the routine to be run in parallel.
-try,
- tic,
-
+try
+ tic
+
fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab);
- toc,
- if isfield(fOutputVar,'OutputFileName'),
+ toc
+ if isfield(fOutputVar,'OutputFileName')
OutputFileName = fOutputVar.OutputFileName;
else
OutputFileName = '';
@@ -81,15 +81,15 @@ try,
% Save the output result.
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
end
- if isfield(fOutputVar,'CloseAllSlaves'),
+ if isfield(fOutputVar,'CloseAllSlaves')
CloseAllSlaves = 1;
fOutputVar = rmfield(fOutputVar,'CloseAllSlaves');
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
save(['comp_status_',funcName,int2str(whoiam),'.mat'],'CloseAllSlaves');
end
-
+
disp(['fParallel ',int2str(whoiam),' completed.'])
-catch,
+catch
theerror = lasterror;
if strfind(theerror.message,'Master asked to break the job')
fOutputVar.message = theerror;
@@ -101,14 +101,14 @@ catch,
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
waitbarString = theerror.message;
% waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).ComputerName];
- if Parallel(ThisMatlab).Local,
+ if Parallel(ThisMatlab).Local
waitbarTitle='Local ';
else
waitbarTitle=[Parallel(ThisMatlab).ComputerName];
end
fMessageStatus(NaN,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
end
-
+
end
diary off;
delete(['P_',fname,'_',int2str(whoiam),'End.txt']);
diff --git a/matlab/parallel/masterParallel.m b/matlab/parallel/masterParallel.m
index f5a5b50fd..e51c6d023 100644
--- a/matlab/parallel/masterParallel.m
+++ b/matlab/parallel/masterParallel.m
@@ -3,37 +3,37 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
% This is the most important function for the management of DYNARE parallel
% computing.
% It is the top-level function called on the master computer when parallelizing a task.
-%
+%
% This function has two main computational strategies for managing the
% matlab worker (slave process):
-%
+%
% 0 Simple Close/Open Stategy:
% In this case the new Matlab instances (slave process) are open when
% necessary and then closed. This can happen many times during the
% simulation of a model.
-%
+%
% 1 Always Open Strategy:
% In this case we have a more sophisticated management of slave processes,
% which are no longer closed at the end of each job. The slave processes
% wait for a new job (if it exists). If a slave does not receive a new job after a
% fixed time it is destroyed. This solution removes the computational
% time necessary to Open/Close new Matlab instances.
-%
+%
% The first (point 0) is the default Strategy
% i.e.(Parallel_info.leaveSlaveOpen=0). This value can be changed by the
% user in xxx.mod file or it is changed by the programmer if it is necessary to
% reduce the overall computational time. See for example the
% prior_posterior_statistics.m.
-%
+%
% The number of parallelized threads will be equal to (nBlock-fBlock+1).
%
% Treatment of global variables:
-% Global variables used within the called function are wrapped and passed by storing their
+% Global variables used within the called function are wrapped and passed by storing their
% values at the start of the parallel computation in a file via
% storeGlobalVars.m. This file is then loaded in the separate,
% independent slave Matlab sessions. By keeping them separate, no
-% interaction via global variables can take place.
-%
+% interaction via global variables can take place.
+%
% INPUTS
% o Parallel [struct vector] copy of options_.parallel
% o fBlock [int] index number of the first thread
@@ -62,7 +62,7 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
% the number of CPUs declared in "Parallel", if
% the number of required threads is lower)
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -91,11 +91,11 @@ Strategy=Parallel_info.leaveSlaveOpen;
islocal = 1;
isHybridMatlabOctave = Parallel_info.isHybridMatlabOctave;
-for j=1:length(Parallel),
+for j=1:length(Parallel)
islocal=islocal*Parallel(j).Local;
end
if nargin>8 && initialize==1
- if islocal == 0,
+ if islocal == 0
PRCDir=CreateTimeString();
assignin('base','PRCDirTmp',PRCDir),
evalin('base','options_.parallel_info.RemoteTmpFolder=PRCDirTmp;')
@@ -108,7 +108,7 @@ if nargin>8 && initialize==1
end
if isfield(Parallel_info,'local_files')
- if isempty(NamFileInput),
+ if isempty(NamFileInput)
NamFileInput=Parallel_info.local_files;
else
NamFileInput=[NamFileInput;Parallel_info.local_files];
@@ -120,26 +120,26 @@ end
% in Octave!
if isoctave
- warning('off');
+ warning('off')
end
% check if there are function_handles in the input or global vars when
% octave is used
if isHybridMatlabOctave || isoctave
fInputNames = fieldnames(fInputVar);
- for j=1:length(fInputNames),
+ for j=1:length(fInputNames)
TargetVar = fInputVar.(fInputNames{j});
- if isa(TargetVar,'function_handle'),
+ if isa(TargetVar,'function_handle')
TargetVar=func2str(TargetVar);
fInputVar.(fInputNames{j})=TargetVar;
end
end
-
- if exist('fGlobalVar','var') && ~isempty(fGlobalVar),
+
+ if exist('fGlobalVar','var') && ~isempty(fGlobalVar)
fInputNames = fieldnames(fGlobalVar);
- for j=1:length(fInputNames),
+ for j=1:length(fInputNames)
TargetVar = fGlobalVar.(fInputNames{j});
- if isa(TargetVar,'function_handle'),
+ if isa(TargetVar,'function_handle')
TargetVar=func2str(TargetVar);
fGlobalVar.(fInputNames{j})=TargetVar;
end
@@ -156,7 +156,7 @@ end
DyMo=pwd;
% fInputVar.DyMo=DyMo;
-if ispc,
+if ispc
[tempo, MasterName]=system('hostname');
MasterName=deblank(MasterName);
end
@@ -168,9 +168,9 @@ switch Strategy
case 0
storeGlobalVars([fname,'_input.mat']);
save([fname,'_input.mat'],'fInputVar','Parallel','-append')
-
+
case 1
- if exist('fGlobalVar','var'),
+ if exist('fGlobalVar','var')
save(['temp_input.mat'],'fInputVar','fGlobalVar')
else
save(['temp_input.mat'],'fInputVar')
@@ -184,7 +184,7 @@ end
% to run on each CPU.
[nCPU, totCPU, nBlockPerCPU, totSlaves] = distributeJobs(Parallel, fBlock, nBlock);
-for j=1:totSlaves,
+for j=1:totSlaves
PRCDirSnapshot{j}={};
end
offset0 = fBlock-1;
@@ -206,7 +206,7 @@ fid = fopen('ConcurrentCommand1.bat','w+');
% Create the directory devoted to remote computation.
-if isempty(PRCDir) && ~islocal,
+if isempty(PRCDir) && ~islocal
error('PRCDir not initialized!')
else
dynareParallelMkDir(PRCDir,Parallel(1:totSlaves));
@@ -238,27 +238,27 @@ end
% End
-for j=1:totCPU,
-
+for j=1:totCPU
+
if Strategy==1
command1 = ' ';
end
-
+
indPC=min(find(nCPU>=j));
-
+
% According to the information contained in configuration file, compThread can limit MATLAB
% to a single computational thread. By default, MATLAB makes use of the multithreading
% capabilities of the computer on which it is running. Nevertheless
% exsperimental results show as matlab native
% multithreading limit the performaces when the parallel computing is active.
-
-
- if strcmp('true',Parallel(indPC).SingleCompThread),
+
+
+ if strcmp('true',Parallel(indPC).SingleCompThread)
compThread = '-singleCompThread';
else
compThread = '';
end
-
+
nthreads=Parallel(indPC).NumberOfThreadsPerJob;
if indPC>1
nCPU0 = nCPU(indPC-1);
@@ -266,20 +266,20 @@ for j=1:totCPU,
nCPU0=0;
end
offset = sum(nBlockPerCPU(1:j-1))+offset0;
-
+
% Create a file used to monitoring if a parallel block (core)
% computation is finished or not.
-
+
fid1=fopen(['P_',fname,'_',int2str(j),'End.txt'],'w+');
fclose(fid1);
-
- if Strategy==1,
-
+
+ if Strategy==1
+
fblck = offset+1;
nblck = sum(nBlockPerCPU(1:j));
save temp_input.mat fblck nblck fname -append;
copyfile('temp_input.mat',['slaveJob',int2str(j),'.mat']);
- if Parallel(indPC).Local ==0,
+ if Parallel(indPC).Local ==0
fid1=fopen(['stayalive',int2str(j),'.txt'],'w+');
fclose(fid1);
dynareParallelSendFiles(['stayalive',int2str(j),'.txt'],PRCDir,Parallel(indPC));
@@ -289,57 +289,57 @@ for j=1:totCPU,
% internal criteria.
pause(1);
newInstance = 0;
-
+
% Check if j CPU is already alive.
- if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)));
+ if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)))
fid1=fopen(['P_slave_',int2str(j),'End.txt'],'w+');
fclose(fid1);
- if Parallel(indPC).Local==0,
+ if Parallel(indPC).Local==0
dynareParallelSendFiles(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
delete(['P_slave_',int2str(j),'End.txt']);
end
-
+
newInstance = 1;
storeGlobalVars( ['slaveParallel_input',int2str(j),'.mat']);
save( ['slaveParallel_input',int2str(j),'.mat'],'Parallel','-append');
% Prepare global vars for Slave.
end
else
-
+
% If the computation is executed remotely all the necessary files
% are created localy, then copied in remote directory and then
% deleted (loacal)!
-
+
save( ['slaveParallel_input',int2str(j),'.mat'],'j');
-
- if Parallel(indPC).Local==0,
+
+ if Parallel(indPC).Local==0
dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
delete(['P_',fname,'_',int2str(j),'End.txt']);
-
+
dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC));
delete(['slaveParallel_input',int2str(j),'.mat']);
-
+
end
-
+
end
-
+
% set affinity range on win CPU's
affinity_range = [1:nthreads]+(j-1-nCPU0)*nthreads;
my_affinity = int2str(Parallel(indPC).CPUnbr(affinity_range(1)));
- for jaff=2:length(affinity_range),
+ for jaff=2:length(affinity_range)
my_affinity = [my_affinity ',' int2str(Parallel(indPC).CPUnbr(affinity_range(jaff)))];
end
% % % int2str(Parallel(indPC).CPUnbr(j-nCPU0))
% DA SINTETIZZARE:
-
+
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following 'switch - case' code is the core of this function!
switch Strategy
case 0
-
- if Parallel(indPC).Local == 1, % 0.1 Run on the local machine (localhost).
-
- if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), % Hybrid computing Windows <-> Unix!
+
+ if Parallel(indPC).Local == 1 % 0.1 Run on the local machine (localhost).
+
+ if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) % Hybrid computing Windows <-> Unix!
if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &'];
else
@@ -353,16 +353,18 @@ for j=1:totCPU,
end
end
else % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine.
- if j==nCPU0+1,
+ if j==nCPU0+1
dynareParallelSendFiles([fname,'_input.mat'],PRCDir,Parallel(indPC));
dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
end
-
- if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)), % Hybrid computing Windows <-> Unix!
- if ispc, token='start /B ';
- else token = '';
+
+ if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix!
+ if ispc
+ token='start /B ';
+ else
+ token = '';
end
- if ~isempty(Parallel(indPC).Port),
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
@@ -370,7 +372,7 @@ for j=1:totCPU,
% To manage the diferences in Unix/Windows OS syntax.
remoteFile=['remoteDynare',int2str(j)];
fidRemote=fopen([remoteFile,'.m'],'w+');
- if regexpi([Parallel(indPC).MatlabOctavePath], 'octave'),% Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+ if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')'];
command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &'];
else
@@ -382,13 +384,13 @@ for j=1:totCPU,
dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC));
delete([remoteFile,'.m']);
else
- if ~strcmpi(Parallel(indPC).ComputerName,MasterName), % 0.3 Run on a remote machine!
- % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
+ if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 0.3 Run on a remote machine!
+ % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
if regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
else
-
+
command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
end
@@ -404,11 +406,11 @@ for j=1:totCPU,
end
end
end
-
-
+
+
case 1
- if Parallel(indPC).Local == 1 && newInstance, % 1.1 Run on the local machine.
- if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)), % Hybrid computing Windows <-> Unix!
+ if Parallel(indPC).Local == 1 && newInstance % 1.1 Run on the local machine.
+ if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix!
if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &'];
else
@@ -421,21 +423,23 @@ for j=1:totCPU,
command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
end
end
- elseif Parallel(indPC).Local==0, % 1.2 Run using network on remote machine or also on local machine.
- if j==nCPU0+1,
+ elseif Parallel(indPC).Local==0 % 1.2 Run using network on remote machine or also on local machine.
+ if j==nCPU0+1
dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
end
dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
delete(['P_',fname,'_',int2str(j),'End.txt']);
- if newInstance,
+ if newInstance
dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
delete(['slaveJob',int2str(j),'.mat']);
dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC))
- if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)), % Hybrid computing Windows <-> Unix!
- if ispc, token='start /B ';
- else token = '';
+ if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix!
+ if ispc
+ token='start /B ';
+ else
+ token = '';
end
- if ~isempty(Parallel(indPC).Port),
+ if ~isempty(Parallel(indPC).Port)
ssh_token = ['-p ',Parallel(indPC).Port];
else
ssh_token = '';
@@ -455,8 +459,8 @@ for j=1:totCPU,
dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC));
delete([remoteFile,'.m']);
else
- if ~strcmpi(Parallel(indPC).ComputerName,MasterName), % 1.3 Run on a remote machine.
- % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+ if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 1.3 Run on a remote machine.
+ % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
if regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
' -low ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
@@ -479,8 +483,8 @@ for j=1:totCPU,
% When the user user strategy is equal to 1, you must
% do PRCDirSnapshot here to to avoid problems of
% synchronization.
-
- if isempty(PRCDirSnapshot{indPC}),
+
+ if isempty(PRCDirSnapshot{indPC})
PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC));
PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC);
else
@@ -488,14 +492,14 @@ for j=1:totCPU,
end
dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
delete(['slaveJob',int2str(j),'.mat']);
-
+
end
end
-
+
end
-
+
fprintf(fid,'%s\n',command1);
-
+
end
% In This way we are sure that the file 'ConcurrentCommand1.bat' is
@@ -511,16 +515,16 @@ end
% the slaves ...
% If the compuation is 'Local' it is not necessary to do it ...
-if Strategy==0 || newInstance, % See above.
+if Strategy==0 || newInstance % See above.
PRCDirSnapshot=dynareParallelSnapshot(PRCDir,Parallel(1:totSlaves));
PRCDirSnapshotInit = PRCDirSnapshot;
-
+
% Run the slaves.
- if ~ispc,
+ if ~ispc
system('sh ConcurrentCommand1.bat &');
pause(1)
else
-
+
if isoctave
% Redirect the standard output to the file 'OctaveStandardOutputMessage.txt'!
% This file is saved in the Model directory.
@@ -556,7 +560,7 @@ else
'NumberTitle','off', ...
'Renderer','Painters', ...
'Resize','off');
-
+
ncol = ceil(totCPU/10);
hspace = 0.9/ncol;
hstatus(1) = axes('position',[0.05/ncol 0.92 0.9/ncol 0.03], ...
@@ -569,16 +573,16 @@ else
set(hstatus(1),'Units','normalized'),
vspace = max(0.1,1/totCPU);
vstart = 1-vspace+0.2*vspace;
- for j=1:totCPU,
+ for j=1:totCPU
jrow = mod(j-1,10)+1;
jcol = ceil(j/10);
hstatus(j) = axes('position',[0.05/ncol+(jcol-1)/ncol vstart-vspace*(jrow-1) 0.9/ncol 0.3*vspace], ...
'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]);
hpat(j) = patch([0 0 0 0],[0 1 1 0],'r','EdgeColor','r');
htit(j) = title(['Initialize ...']);
-
+
end
-
+
cumBlockPerCPU = cumsum(nBlockPerCPU);
end
pcerdone = NaN(1,totCPU);
@@ -592,20 +596,20 @@ idCPU = NaN(1,totCPU);
% Caption for console mode computing ...
if options_.console_mode || isoctave
-
+
if ~isoctave
if strcmpi([Parallel(indPC).MatlabOctavePath], 'octave')
RjInformation='Hybrid Computing Is Active: Remote jobs are computed by Octave!';
fprintf([RjInformation,'\n\n']);
end
end
-
+
fnameTemp=fname;
-
+
L=length(fnameTemp);
-
+
PoCo=strfind(fnameTemp,'_core');
-
+
for i=PoCo:L
if i==PoCo
fnameTemp(i)=' ';
@@ -613,27 +617,27 @@ if options_.console_mode || isoctave
fnameTemp(i)='.';
end
end
-
+
for i=1:L
- if fnameTemp(i)=='_';
+ if fnameTemp(i)=='_'
fnameTemp(i)=' ';
end
end
-
+
fnameTemp(L)='';
-
+
Information=['Parallel ' fnameTemp ' Computing ...'];
if isoctave
if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) && (Strategy==0)
printf('\n');
pause(2);
end
-
+
printf([Information,'\n\n']);
else
fprintf([Information,'\n\n']);
end
-
+
end
@@ -649,26 +653,26 @@ statusString = '';
flag_CloseAllSlaves=0;
while (ForEver)
-
+
waitbarString = '';
statusString0 = repmat('\b',1,length(sprintf(statusString, 100 .* pcerdone)));
statusString = '';
-
+
pause(1)
-
+
try
- if islocal ==0,
+ if islocal ==0
dynareParallelGetFiles(['comp_status_',fname,'*.mat'],PRCDir,Parallel(1:totSlaves));
end
catch
end
-
- for j=1:totCPU,
+
+ for j=1:totCPU
try
if ~isempty(['comp_status_',fname,int2str(j),'.mat'])
load(['comp_status_',fname,int2str(j),'.mat']);
% whoCloseAllSlaves = who(['comp_status_',fname,int2str(j),'.mat','CloseAllSlaves']);
- if exist('CloseAllSlaves') && flag_CloseAllSlaves==0,
+ if exist('CloseAllSlaves') && flag_CloseAllSlaves==0
flag_CloseAllSlaves=1;
whoiamCloseAllSlaves=j;
closeSlave(Parallel(1:totSlaves),PRCDir,1);
@@ -706,20 +710,20 @@ while (ForEver)
end
end
else
- for j=1:totCPU,
+ for j=1:totCPU
try
set(hpat(j),'XData',[0 0 pcerdone(j) pcerdone(j)]);
set(htit(j),'String',[status_Title{j},' - ',status_String{j}]);
catch
-
+
end
end
end
-
+
% Check if the slave(s) has generated some new files remotely.
% 1. The files .log and .txt are not copied.
% 2. The comp_status_*.mat files are managed separately.
-
+
if isoctave % to avoid synchronism problems
try
PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
@@ -728,11 +732,11 @@ while (ForEver)
else
PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
end
-
- if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves)));
+
+ if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves)))
HoTuttiGliOutput=0;
- for j=1:totCPU,
-
+ for j=1:totCPU
+
% Checking if the remote computation is finished and if we copied all the output here.
if ~isempty(dir([fname,'_output_',int2str(j),'.mat']))
HoTuttiGliOutput=HoTuttiGliOutput+1;
@@ -741,8 +745,8 @@ while (ForEver)
dynareParallelGetFiles([fname,'_output_',int2str(j),'.mat'],PRCDir,Parallel(indPC));
end
end
-
- if HoTuttiGliOutput==totCPU,
+
+ if HoTuttiGliOutput==totCPU
mydelete(['comp_status_',fname,'*.mat']);
if isoctave || options_.console_mode
if isoctave
@@ -754,15 +758,15 @@ while (ForEver)
end
diary on;
else
- close(hfigstatus),
+ close(hfigstatus)
end
-
+
break
else
disp('Waiting for output files from slaves ...')
end
end
-
+
end
@@ -770,19 +774,19 @@ end
iscrash = 0;
PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
-for j=1:totCPU,
+for j=1:totCPU
indPC=min(find(nCPU>=j));
load([fname,'_output_',int2str(j),'.mat'],'fOutputVar');
delete([fname,'_output_',int2str(j),'.mat']);
- if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0,
+ if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0
% Check if input files have been updated!
- OutputFileName=fOutputVar.OutputFileName;
+ OutputFileName=fOutputVar.OutputFileName;
tmp0='';
- for i=1:size(NamFileInput,1),
+ for i=1:size(NamFileInput,1)
FileList = regexp(strrep(PRCDirSnapshot{indPC},'\','/'),strrep(strrep([NamFileInput{i,:}],'\','/'),'*','(\w*)'),'match');
- for k=1:length(FileList),
- if ~isempty(FileList{k}),
- if isempty(tmp0),
+ for k=1:length(FileList)
+ if ~isempty(FileList{k})
+ if isempty(tmp0)
tmp0=FileList{k}{1};
else
tmp0=char(tmp0,FileList{k}{1});
@@ -790,78 +794,78 @@ for j=1:totCPU,
end
end
end
- for i=1:size(OutputFileName,1),
+ for i=1:size(OutputFileName,1)
tmp1='';
FileList = regexp(cellstr(tmp0),strrep(strrep([OutputFileName{i,:}],'\','/'),'*','(\w*)'),'match');
FileList0 = regexp(cellstr(tmp0),strrep([OutputFileName{i,2}],'*','(\w*)'),'match');
- for k=1:length(FileList),
- if ~isempty(FileList{k}),
- if isempty(tmp1),
+ for k=1:length(FileList)
+ if ~isempty(FileList{k})
+ if isempty(tmp1)
tmp1=FileList0{k}{1};
else
tmp1=char(tmp1,FileList0{k}{1});
end
end
end
- for k=1:size(tmp1,1),
+ for k=1:size(tmp1,1)
dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC));
end
end
% check if some output file is missing!
- for i=1:size(OutputFileName,1),
+ for i=1:size(OutputFileName,1)
tmp1=dynareParallelDir([OutputFileName{i,:}],PRCDir,Parallel(indPC));
tmp1 = regexp(cellstr(tmp1),strrep([OutputFileName{i,2}],'*','(\w*)'),'match');
tmp1 = char(tmp1{:});
tmp2=ls([OutputFileName{i,:}]);
- for ij=1:size(tmp1,1),
+ for ij=1:size(tmp1,1)
icheck = regexp(cellstr(tmp2),tmp1(ij,:),'once');
isOutputFileMissing=1;
- for ik=1:size(tmp2,1),
- if ~isempty(icheck{ik}),
+ for ik=1:size(tmp2,1)
+ if ~isempty(icheck{ik})
isOutputFileMissing=0;
end
end
- if isOutputFileMissing,
+ if isOutputFileMissing
dynareParallelGetFiles([OutputFileName(i,1) {tmp1(ij,:)}],PRCDir,Parallel(indPC));
end
end
end
end
- if isfield(fOutputVar,'error'),
+ if isfield(fOutputVar,'error')
disp(['Job number ',int2str(j),' crashed with error:']);
iscrash=1;
disp([fOutputVar.error.message]);
for jstack=1:length(fOutputVar.error.stack)
- fOutputVar.error.stack(jstack),
+ fOutputVar.error.stack(jstack)
end
- elseif flag_CloseAllSlaves==0,
+ elseif flag_CloseAllSlaves==0
fOutVar(j)=fOutputVar;
- elseif j==whoiamCloseAllSlaves,
- fOutVar=fOutputVar;
+ elseif j==whoiamCloseAllSlaves
+ fOutVar=fOutputVar;
end
end
-if flag_CloseAllSlaves==1,
+if flag_CloseAllSlaves==1
closeSlave(Parallel(1:totSlaves),PRCDir,-1);
end
-if iscrash,
+if iscrash
error('Remote jobs crashed');
end
-pause(1), % Wait for all remote diary off completed
+pause(1) % Wait for all remote diary off completed
% Cleanup.
dynareParallelGetFiles('*.log',PRCDir,Parallel(1:totSlaves));
switch Strategy
case 0
- for indPC=1:min(find(nCPU>=totCPU)),
+ for indPC=1:min(find(nCPU>=totCPU))
if Parallel(indPC).Local == 0
dynareParallelRmDir(PRCDir,Parallel(indPC));
end
-
+
if isempty(dir('dynareParallelLogFiles'))
[A B C]=rmdir('dynareParallelLogFiles');
mkdir('dynareParallelLogFiles');
@@ -871,29 +875,29 @@ switch Strategy
mydelete([fname,'*.log']);
catch
end
-
+
mydelete(['*_core*_input*.mat']);
-
+
end
-
+
delete ConcurrentCommand1.bat
case 1
delete(['temp_input.mat'])
- if newInstance,
+ if newInstance
if isempty(dir('dynareParallelLogFiles'))
[A B C]=rmdir('dynareParallelLogFiles');
mkdir('dynareParallelLogFiles');
end
end
copyfile('*.log','dynareParallelLogFiles');
- if newInstance,
+ if newInstance
delete ConcurrentCommand1.bat
end
dynareParallelDelete(['comp_status_',fname,'*.mat'],PRCDir,Parallel);
- for indPC=1:min(find(nCPU>=totCPU)),
- if Parallel(indPC).Local == 0,
+ for indPC=1:min(find(nCPU>=totCPU))
+ if Parallel(indPC).Local == 0
dynareParallelDeleteNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshotInit(indPC),'.log');
- for ifil=1:size(NamFileInput,1),
+ for ifil=1:size(NamFileInput,1)
dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC));
end
end
diff --git a/matlab/parallel/slaveParallel.m b/matlab/parallel/slaveParallel.m
index 5de311575..5e3fe460c 100644
--- a/matlab/parallel/slaveParallel.m
+++ b/matlab/parallel/slaveParallel.m
@@ -2,7 +2,7 @@ function slaveParallel(whoiam,ThisMatlab)
% PARALLEL CONTEXT
% In a parallelization context, this function is launched on slave
% machines, to initialize MATLAB and DYNARE environment and waits for
-% instructions sent by the Master.
+% instructions sent by the Master.
% This function is invoked by masterParallel only when the strategy (1),
% i.e. always open, is actived.
%
@@ -12,10 +12,10 @@ function slaveParallel(whoiam,ThisMatlab)
% cluster.
% o ThisMatlab [int] index number of this slave machine in the cluster.
%
-% OUTPUTS
-% None
+% OUTPUTS
+% None
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -48,9 +48,9 @@ dynareroot = dynare_config();
load( ['slaveParallel_input',int2str(whoiam)]);
%Loads fGlobalVar Parallel.
-if exist('fGlobalVar'),
+if exist('fGlobalVar')
globalVars = fieldnames(fGlobalVar);
- for j=1:length(globalVars),
+ for j=1:length(globalVars)
eval(['global ',globalVars{j},';']);
evalin('base',['global ',globalVars{j},';']);
end
@@ -65,50 +65,50 @@ end
t0=clock;
fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']);
-while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])),
- if ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])),
+while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt']))
+ if ~isempty(dir(['stayalive',int2str(whoiam),'.txt']))
t0=clock;
delete(['stayalive',int2str(whoiam),'.txt']);
end
% I wait for 20 min or while mater asks to exit (i.e. it cancels fslave file)
- pause(1);
-
+ pause(1)
+
fjob = dir(['slaveJob',int2str(whoiam),'.mat']);
-
- if ~isempty(fjob),
+
+ if ~isempty(fjob)
clear fGlobalVar fInputVar fblck nblck fname
-
+
while(1)
Go=0;
-
+
Go=fopen(['slaveJob',int2str(whoiam),'.mat']);
-
- if Go>0
+
+ if Go>0
fclose(Go);
- pause(1);
+ pause(1)
load(['slaveJob',int2str(whoiam),'.mat']);
break
else
% Only for testing, will be remouved!
-
+
% if isunix
% E1=fopen('/home/ivano/Works/Errore-slaveParallel.txt','w+');
% fclose(E1);
- % else
+ % else
% E1=fopen('c:\dynare_calcs\Errore-slaveParallel.txt','w+');
% fclose(E1);
% end
-
+
end
end
-
+
funcName=fname; % Update global job name.
if exist('fGlobalVar') && ~isempty (fGlobalVar)
globalVars = fieldnames(fGlobalVar);
- for j=1:length(globalVars),
+ for j=1:length(globalVars)
info_whos = whos(globalVars{j});
- if isempty(info_whos) || ~info_whos.global,
+ if isempty(info_whos) || ~info_whos.global
eval(['global ',globalVars{j},';']);
evalin('base',['global ',globalVars{j},';']);
end
@@ -120,13 +120,13 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
end
delete(['slaveJob',int2str(whoiam),'.mat']);
fInputVar.Parallel = Parallel;
-
+
% Launch the routine to be run in parallel.
- try,
- tic,
+ try
+ tic
fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab);
- toc,
- if isfield(fOutputVar,'OutputFileName'),
+ toc
+ if isfield(fOutputVar,'OutputFileName')
OutputFileName = fOutputVar.OutputFileName;
else
OutputFileName = '';
@@ -137,7 +137,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
% Save the output result.
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' );
% keyboard,
- if isfield(fOutputVar,'CloseAllSlaves'),
+ if isfield(fOutputVar,'CloseAllSlaves')
CloseAllSlaves = 1;
fOutputVar = rmfield(fOutputVar,'CloseAllSlaves');
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
@@ -150,7 +150,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
disp(['Job ',fname,' on CPU ',int2str(whoiam),' completed.']);
t0 =clock; % Re-set waiting time of 20 mins
- catch,
+ catch
theerror = lasterror;
if strfind(theerror.message,'Master asked to break the job')
disp(['Job ',fname,' on CPU ',int2str(whoiam),' broken from master.']);
@@ -162,7 +162,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
fOutputVar.error = lasterror;
save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' );
waitbarString = fOutputVar.error.message;
- if Parallel(ThisMatlab).Local,
+ if Parallel(ThisMatlab).Local
waitbarTitle='Local ';
else
waitbarTitle=[Parallel(ThisMatlab).ComputerName];
@@ -171,7 +171,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
delete(['P_',fname,'_',int2str(whoiam),'End.txt']);
break
end
-
+
end
end
fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']); % Check if Master asks to exit
diff --git a/matlab/parallel/storeGlobalVars.m b/matlab/parallel/storeGlobalVars.m
index cd0470c37..79b86aa35 100644
--- a/matlab/parallel/storeGlobalVars.m
+++ b/matlab/parallel/storeGlobalVars.m
@@ -1,6 +1,6 @@
function storeGlobalVars(fname,append)
% PARALLEL CONTEXT
-% In a parallel context, this function stores all global vars in structure
+% In a parallel context, this function stores all global vars in structure
% fGlobalVar and saves it in the file fname.mat
%
% INPUTS
@@ -12,7 +12,7 @@ function storeGlobalVars(fname,append)
% None
%
%
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -32,12 +32,12 @@ function storeGlobalVars(fname,append)
GlobalNames = who('global');
% varlist = '';
-for j=1:length(GlobalNames);
+for j=1:length(GlobalNames)
eval(['global ',GlobalNames{j},';']);
eval(['fGlobalVar.',GlobalNames{j},'=',GlobalNames{j},';']);
end
-if nargin<2,
+if nargin<2
save(fname,'fGlobalVar');
else
save(fname,'fGlobalVar','-append');
diff --git a/matlab/parallel/struct2local.m b/matlab/parallel/struct2local.m
index fbe9666f0..d45bc12b8 100644
--- a/matlab/parallel/struct2local.m
+++ b/matlab/parallel/struct2local.m
@@ -6,11 +6,11 @@ function struct2local(S)
%
% INPUTS
% o S [struc] This structure possibly containing several fields ...
-%
+%
% OUTPUTS
% None
%
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -30,6 +30,6 @@ function struct2local(S)
vnam = fieldnames(S);
-for j=1:length(vnam),
+for j=1:length(vnam)
assignin('caller',vnam{j},getfield(S,vnam{j}));
end
diff --git a/matlab/partial_information/PCL_Part_info_irf.m b/matlab/partial_information/PCL_Part_info_irf.m
index 2fc0ff1d8..0c3c17c2b 100644
--- a/matlab/partial_information/PCL_Part_info_irf.m
+++ b/matlab/partial_information/PCL_Part_info_irf.m
@@ -1,11 +1,11 @@
function y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii)
% sets up parameters and calls part-info kalman filter
-% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
-% suit partial information RE solution in accordance with, and based on, the
+% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
+% suit partial information RE solution in accordance with, and based on, the
% Pearlman, Currie and Levine 1986 solution.
-% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
+% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -23,8 +23,8 @@ function y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii)
% along with Dynare. If not, see .
-% Recall that the state space is given by the
-% predetermined variables s(t-1), x(t-1)
+% Recall that the state space is given by the
+% predetermined variables s(t-1), x(t-1)
% and the jump variables x(t).
% The jump variables have dimension NETA
@@ -66,7 +66,7 @@ U22=0;
% determine K1 and K2 observation mapping matrices
% This uses the fact that measurements are given by L1*s(t)+L2*x(t)
% and s(t) is expressed in the dynamics as
-% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
+% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
% Thus the observations o(t) can be written in the form
% o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where
% K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2
@@ -84,18 +84,18 @@ A21=G1(pd+1:end,1:pd);
Lambda= nmat*A12+A22;
I_L=inv(Lambda);
BB=A12*inv(A22);
-FF=K2*inv(A22);
-QQ=BB*U22*BB' + U11;
+FF=K2*inv(A22);
+QQ=BB*U22*BB' + U11;
UFT=U22*FF';
AA=A11-BB*A21;
CCCC=A11-A12*nmat; % F in new notation
DD=K1-FF*A21; % H in new notation
EE=K1-K2*nmat;
RR=FF*UFT+VV;
-if ~any(RR)
- % if zero add some dummy measurement err. variance-covariances
+if ~any(RR)
+ % if zero add some dummy measurement err. variance-covariances
% with diagonals 0.000001. This would not be needed if we used
- % the slow solver, or the generalised eigenvalue approach,
+ % the slow solver, or the generalised eigenvalue approach,
% but these are both slower.
RR=eye(size(RR,1))*1.0e-6;
end
@@ -128,14 +128,14 @@ imp=[impact(1:ss-FL_RANK,:); impact(1:ss-FL_RANK,:)];
I_PD=(eye(ss-FL_RANK)-PDIDPDRD);
LL0=[ EE (DD-EE)*I_PD];
VV = [ dr.PI_TT1 dr.PI_TT2];
-stderr=diag(M_.Sigma_e^0.5);
+stderr=diag(M_.Sigma_e^0.5);
irfmat=zeros(size(dr.PI_TT1 ,1),irfpers+1);
-irfst=zeros(size(GG,1),irfpers+1);
+irfst=zeros(size(GG,1),irfpers+1);
irfst(:,1)=stderr(ii)*imp(:,ii);
-for jj=2:irfpers+1;
+for jj=2:irfpers+1
irfst(:,jj)=GG*irfst(:,jj-1);
irfmat(:,jj-1)=VV*irfst(NX+1:ss-FL_RANK,jj);
-end
+end
y = irfmat(:,1:irfpers);
save ([M_.fname '_PCL_PtInfoIRFs_' num2str(ii) '_' deblank(exo_names(ii,:))], 'irfmat','irfst');
diff --git a/matlab/partial_information/PCL_Part_info_moments.m b/matlab/partial_information/PCL_Part_info_moments.m
index fdebe317f..bb16b6604 100644
--- a/matlab/partial_information/PCL_Part_info_moments.m
+++ b/matlab/partial_information/PCL_Part_info_moments.m
@@ -1,11 +1,11 @@
function AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar)
% sets up parameters and calls part-info kalman filter
-% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
-% suit partial information RE solution in accordance with, and based on, the
+% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
+% suit partial information RE solution in accordance with, and based on, the
% Pearlman, Currie and Levine 1986 solution.
-% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
+% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -22,8 +22,8 @@ function AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-% Recall that the state space is given by the
-% predetermined variables s(t-1), x(t-1)
+% Recall that the state space is given by the
+% predetermined variables s(t-1), x(t-1)
% and the jump variables x(t).
% The jump variables have dimension NETA
@@ -48,13 +48,13 @@ LL = sparse(1:NOBS,OBS,ones(NOBS,1),NY,NY);
if exist( 'irfpers')==1
if ~isempty(irfpers)
- if irfpers<=0, irfpers=20, end;
+ if irfpers<=0, irfpers=20, end
else
irfpers=20;
end
else
irfpers=20;
-end
+end
ss=size(G1,1);
@@ -78,7 +78,7 @@ U22=0;
% determine K1 and K2 observation mapping matrices
% This uses the fact that measurements are given by L1*s(t)+L2*x(t)
% and s(t) is expressed in the dynamics as
-% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
+% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
% Thus the observations o(t) can be written in the form
% o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where
% K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2
@@ -96,8 +96,8 @@ A21=G1(pd+1:end,1:pd);
Lambda= nmat*A12+A22;
I_L=inv(Lambda);
BB=A12*inv(A22);
-FF=K2*inv(A22);
-QQ=BB*U22*BB' + U11;
+FF=K2*inv(A22);
+QQ=BB*U22*BB' + U11;
UFT=U22*FF';
% kf_param structure:
AA=A11-BB*A21;
@@ -105,10 +105,10 @@ CCCC=A11-A12*nmat; % F in new notation
DD=K1-FF*A21; % H in new notation
EE=K1-K2*nmat;
RR=FF*UFT+VV;
-if ~any(RR)
- % if zero add some dummy measurement err. variance-covariances
+if ~any(RR)
+ % if zero add some dummy measurement err. variance-covariances
% with diagonals 0.000001. This would not be needed if we used
- % the slow solver, or the generalised eigenvalue approach,
+ % the slow solver, or the generalised eigenvalue approach,
% but these are both slower.
RR=eye(size(RR,1))*1.0e-6;
end
@@ -150,7 +150,7 @@ diagCovYR0=diag(COV_YR0);
labels = deblank(M_.endo_names(ivar,:));
if options_.nomoments == 0
- z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ];
+ z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ];
title='THEORETICAL MOMENTS';
headers=char('VARIABLE','STD. DEV.','VARIANCE');
dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,10);
@@ -168,9 +168,9 @@ end
ar = options_.ar;
if ar > 0
- COV_YRk= zeros(nn,ar);
- AutoCOR_YRk= zeros(nn,ar);
- for k=1:ar;
+ COV_YRk= zeros(nn,ar);
+ AutoCOR_YRk= zeros(nn,ar);
+ for k=1:ar
COV_P=GAM*COV_P;
COV_OMEGA= COV_P( end-nn+1:end, end-nn+1:end);
COV_YRk = VV*COV_OMEGA*VV';
diff --git a/matlab/partial_information/PCL_resol.m b/matlab/partial_information/PCL_resol.m
index ba0b1666f..8f6bf4239 100644
--- a/matlab/partial_information/PCL_resol.m
+++ b/matlab/partial_information/PCL_resol.m
@@ -17,7 +17,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
% info=6: The jacobian evaluated at the steady state is complex.
% info=19: The steadystate file did not compute the steady state (inconsistent deep parameters).
% info=20: can't find steady state info(2) contains sum of sqare residuals
-% info=21: steady state is complex
+% info=21: steady state is complex
% info(2) contains sum of sqare of
% imaginary part of steady state
% info=30: Variance can't be computed
@@ -25,7 +25,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -45,7 +45,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
global M_ options_ oo_
global it_
-jacobian_flag = 0;
+jacobian_flag = 0;
info = 0;
@@ -58,7 +58,7 @@ end
% check if ys is steady state
tempex = oo_.exo_simul;
oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+M_.maximum_lead+1,1);
-if M_.exo_det_nbr > 0
+if M_.exo_det_nbr > 0
tempexdet = oo_.exo_det_simul;
oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1);
end
@@ -70,7 +70,7 @@ if options_.steadystate_flag
[dr.ys,check1] = feval([M_.fname '_steadystate'],dr.ys,...
[oo_.exo_steady_state; ...
oo_.exo_det_steady_state]);
- if size(dr.ys,1) < M_.endo_nbr
+ if size(dr.ys,1) < M_.endo_nbr
if length(M_.aux_vars) > 0
dr.ys = add_auxiliary_variables_to_steadystate(dr.ys,M_.aux_vars,...
M_.fname,...
@@ -143,5 +143,5 @@ tempex = [];
% 01/01/2003 MJ added dr_algo == 1
% 08/24/2001 MJ uses Schmitt-Grohe and Uribe (2001) constant correction
-% in dr.ghs2
+% in dr.ghs2
% 05/26/2003 MJ added temporary values for oo_.exo_simul
diff --git a/matlab/partial_information/PI_gensys.m b/matlab/partial_information/PI_gensys.m
index c46d45d07..589e39dc1 100644
--- a/matlab/partial_information/PI_gensys.m
+++ b/matlab/partial_information/PI_gensys.m
@@ -16,7 +16,7 @@ function [G1pi,C,impact,nmat,TT1,TT2,gev,eu, DD, E2, E5, GAMMA, FL_RANK ]=PI_gen
% Corrected 10/28/96 by CAS
% Copyright (C) 1996-2009 Christopher Sims
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -83,12 +83,12 @@ try
end
if singular == 1 || strcmp('MATLAB:nearlySingularMatrix',LastWarningID) == 1 || ...
strcmp('MATLAB:illConditionedMatrix',LastWarningID)==1 || ...
- strcmp('MATLAB:singularMatrix',LastWarningID)==1
+ strcmp('MATLAB:singularMatrix',LastWarningID)==1
[C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02] = PI_gensys_singularC(C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, V01, V02, 0);
end
warning('on','MATLAB:singularMatrix');
warning('on','MATLAB:nearlySingularMatrix');
- if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv))))
+ if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv))))
if(options_.ACES_solver==1)
disp('ERROR! saving PI_gensys_data_dump');
save PI_gensys_data_dump
@@ -96,7 +96,7 @@ try
else
warning('PI_gensys: Evading inversion of zero matrix UAVinv=inv(U02''*a1*V02)!');
eu=[0,0];
- return;
+ return
end
end
catch
@@ -131,8 +131,8 @@ G23=eye(FL_RANK);
num_inst=0;
% New Definitions
-Ze11=zeros(NX,NX);
-Ze12=zeros(NX,(n-FL_RANK));
+Ze11=zeros(NX,NX);
+Ze12=zeros(NX,(n-FL_RANK));
Ze134=zeros(NX,FL_RANK);
Ze31=zeros(FL_RANK,NX);
@@ -149,7 +149,7 @@ impact=[eye(NX,NX); zeros(n+FL_RANK,NX)];
if(options_.ACES_solver==1)
if isfield(lq_instruments,'names')
num_inst=size(lq_instruments.names,1);
- if num_inst>0
+ if num_inst>0
i_var=lq_instruments.inst_var_indices;
N1=UAVinv*U02'*lq_instruments.B1;
N3=-FF*N1+Sinv*U01'*lq_instruments.B1;
@@ -171,14 +171,14 @@ if(options_.ACES_solver==1)
zeros(num_inst,size(E3,2)), II;
];
eu =[1; 1], nmat=[], gev=[];
- return; % do not check B&K compliancy
+ return % do not check B&K compliancy
end
G0pi=eye(n+FL_RANK+NX);
try
- % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb %
+ % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb %
% In Octave: [aa bb q z v w] = qz(a,b) s.t. q'az = aa, q'bz=bb %
- % and qzcomplex() extension based on lapack zgges produces same
+ % and qzcomplex() extension based on lapack zgges produces same
% qz output for Octave as Matlab qz() does for Matlab thus:
if isoctave
[a b q z]=qzcomplex(G0pi,G1pi);
@@ -192,12 +192,12 @@ catch
disp(['PI_Gensys: ' lerror.message]);
if 0==strcmp('MATLAB:qz:matrixWithNaNInf',lerror.identifier)
disp '** Unexpected Error PI_Gensys:qz: ** :';
- button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
- switch button
- case 'No'
+ button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
+ switch button
+ case 'No'
error ('Terminated')
%case 'Yes'
-
+
end
end
G1pi=[];impact=[];nmat=[]; gev=[];
@@ -206,11 +206,11 @@ catch
catch
disp '** Unexpected Error in qz ** :';
disp lerror.message;
- button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
- switch button
- case 'No'
- error ('Terminated')
- case 'Yes'
+ button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
+ switch button
+ case 'No'
+ error ('Terminated')
+ case 'Yes'
G1pi=[];impact=[];nmat=[]; gev=[];
eu=[-2;-2];
return
@@ -257,7 +257,7 @@ if zxz
end
if (FL_RANK ~= nunstab && options_.ACES_solver~=1)
disp(['Number of unstable variables ' num2str(nunstab)]);
- disp( ['does not match number of expectational equations ' num2str(FL_RANK)]);
+ disp( ['does not match number of expectational equations ' num2str(FL_RANK)]);
nmat=[];% gev=[];
eu=[-2;-2];
return
diff --git a/matlab/partial_information/PI_gensys_singularC.m b/matlab/partial_information/PI_gensys_singularC.m
index 5dc26ec63..b0c085faf 100644
--- a/matlab/partial_information/PI_gensys_singularC.m
+++ b/matlab/partial_information/PI_gensys_singularC.m
@@ -1,13 +1,13 @@
function [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02]=PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level)
% [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv,FL_RANK, V01, V02]...
% =PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level)
-%
+%
% Recursive extension for PI_gensys function PCL general DSGE solver
-% devised by Prof. Joseph Pearlman
+% devised by Prof. Joseph Pearlman
% developed by George Perendia
% December 2010
-% Copyright (C) 1996-2011 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -86,7 +86,4 @@ catch
[errmsg, errcode]=lasterr;
warning(['error callig PI_gensys_singularC: ' errmsg ],'errcode');
error('errcode',['error callig PI_gensys_singularC: ' errmsg ]);
-end
-
-return;
-
+end
\ No newline at end of file
diff --git a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
index d99e36ebb..f90e7f6b0 100644
--- a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
+++ b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
@@ -2,7 +2,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
exo_steady_state, exo_det_steady_state,params, byte_code)
% Add auxiliary variables to the steady state vector
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -21,7 +21,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
n = length(aux_vars);
ys1 = [ys;zeros(n,1)];
-for i=1:n+1;
+for i=1:n+1
if byte_code
[info, res] = bytecode('static','evaluate',ys1,...
[exo_steady_state; ...
@@ -30,7 +30,7 @@ for i=1:n+1;
res = feval([fname '_static'],ys1,...
[exo_steady_state; ...
exo_det_steady_state],params);
- end;
+ end
for j=1:n
el = aux_vars(j).endo_index;
ys1(el) = ys1(el)-res(el);
diff --git a/matlab/partial_information/disc_riccati_fast.m b/matlab/partial_information/disc_riccati_fast.m
index 4a0bd0401..c97da7a12 100644
--- a/matlab/partial_information/disc_riccati_fast.m
+++ b/matlab/partial_information/disc_riccati_fast.m
@@ -1,17 +1,17 @@
function Z=disc_riccati_fast(F,D,R,H,ch)
% function Z=disc_riccati_fast(F,D,R,H,ch)
-%
-% Solves discrete Riccati Equation:
-% Z=FZF' - FZD'inv(DZD'+R)DZF' + H
-% Using the Doubling Algorithm
%
-% George Perendia: based on the doubling algorithm for Riccati
-% and the disclyap_fast function provided by Prof. Joe Pearlman
+% Solves discrete Riccati Equation:
+% Z=FZF' - FZD'inv(DZD'+R)DZF' + H
+% Using the Doubling Algorithm
+%
+% George Perendia: based on the doubling algorithm for Riccati
+% and the disclyap_fast function provided by Prof. Joe Pearlman
% V.1 19/5/2006
% V.2 22/10/06
% =================================================================
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -28,16 +28,16 @@ function Z=disc_riccati_fast(F,D,R,H,ch)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin == 4 || isempty( ch ) == 1
- flag_ch = 0;
-else
- flag_ch = 1;
-end
+if nargin == 4 || isempty( ch ) == 1
+ flag_ch = 0;
+else
+ flag_ch = 1;
+end
% intialisation
tol = 1e-10; % iteration convergence threshold
-P0=H;
+P0=H;
X0=F;
if ~any(R) % i.e. ==0
warning('Dangerously evading inversion of zero matrix!');
@@ -50,21 +50,21 @@ I=eye(size(POYO));
clear POYO;
% iterate Riccati equation solution
-matd=1;
+matd=1;
count=0;
while matd > tol && count < 100
INVPY=inv(I+P0*Y0);
- P1=X0*INVPY*P0*X0'+ P0;
- Y1=X0'*Y0*INVPY*X0+ Y0;
- X1=X0*INVPY*X0;
- matd=sum( sum(abs( P1 - P0 )));
+ P1=X0*INVPY*P0*X0'+ P0;
+ Y1=X0'*Y0*INVPY*X0+ Y0;
+ X1=X0*INVPY*X0;
+ matd=sum( sum(abs( P1 - P0 )));
% P0=(P1+P1')/2
- P0=P1;
+ P0=P1;
X0=X1;
Y0=Y1;
count=count+1;
% matd;
-end
+end
Z=(P0+P0')/2;
%Z=P0
@@ -75,17 +75,17 @@ if count==100
% error.identifier='Riccati not converged!'
% error
end
-%if count >5
+%if count >5
% disp('Riccati count= ');
% count
%end
-clear X0 X1 Y0 Y1 P1 I INVPY;
+clear X0 X1 Y0 Y1 P1 I INVPY;
-% Check that X is positive definite
-if flag_ch==1
- [C,p]=chol(Z);
- if p ~= 0
+% Check that X is positive definite
+if flag_ch==1
+ [C,p]=chol(Z);
+ if p ~= 0
error('Z is not positive definite')
- end
-end
+ end
+end
diff --git a/matlab/partial_information/disclyap_fast.m b/matlab/partial_information/disclyap_fast.m
index 3e101a7a6..5dfcfe4b5 100644
--- a/matlab/partial_information/disclyap_fast.m
+++ b/matlab/partial_information/disclyap_fast.m
@@ -3,23 +3,23 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag)
% Inputs:
% - G [double] first input matrix
% - V [double] second input matrix
-% - tol [scalar] tolerance criterion
+% - tol [scalar] tolerance criterion
% - check_flag empty of non-empty if non-empty: check positive-definiteness
% Outputs:
% - X [double] solution matrix
% - exitflag [scalar] 0 if solution is found, 1 otherwise
%
-% Solve the discrete Lyapunov Equation
-% X=G*X*G'+V
-% Using the Doubling Algorithm
+% Solve the discrete Lyapunov Equation
+% X=G*X*G'+V
+% Using the Doubling Algorithm
%
-% If check_flag is defined then the code will check if the resulting X
-% is positive definite and generate an error message if it is not
-%
-% Joe Pearlman and Alejandro Justiniano
-% 3/5/2005
+% If check_flag is defined then the code will check if the resulting X
+% is positive definite and generate an error message if it is not
+%
+% Joe Pearlman and Alejandro Justiniano
+% 3/5/2005
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -36,40 +36,40 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin <= 3 || isempty( check_flag ) == 1
- flag_ch = 0;
-else
- flag_ch = 1;
-end
+if nargin <= 3 || isempty( check_flag ) == 1
+ flag_ch = 0;
+else
+ flag_ch = 1;
+end
exitflag=0;
-P0=V;
-A0=G;
+P0=V;
+A0=G;
-matd=1;
+matd=1;
iter=1;
-while matd > tol && iter< 2000
- P1=P0+A0*P0*A0';
- A1=A0*A0;
- matd=max( max( abs( P1 - P0 ) ) );
- P0=P1;
- A0=A1;
+while matd > tol && iter< 2000
+ P1=P0+A0*P0*A0';
+ A1=A0*A0;
+ matd=max( max( abs( P1 - P0 ) ) );
+ P0=P1;
+ A0=A1;
iter=iter+1;
-end
+end
if iter==5000
X=NaN(P0);
exitflag=1;
return
end
-clear A0 A1 P1;
+clear A0 A1 P1;
-X=(P0+P0')/2;
+X=(P0+P0')/2;
-% Check that X is positive definite
-if flag_ch==1
- [C,p]=chol(X);
- if p ~= 0
+% Check that X is positive definite
+if flag_ch==1
+ [C,p]=chol(X);
+ if p ~= 0
exitflag=1;
error('X is not positive definite')
- end
-end
\ No newline at end of file
+ end
+end
\ No newline at end of file
diff --git a/matlab/partial_information/dr1_PI.m b/matlab/partial_information/dr1_PI.m
index 0475d4bef..04fe8d926 100644
--- a/matlab/partial_information/dr1_PI.m
+++ b/matlab/partial_information/dr1_PI.m
@@ -6,7 +6,7 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_)
% Prepares System as
% A0*E_t[y(t+1])+A1*y(t)=A2*y(t-1)+c+psi*eps(t)
% with z an exogenous variable process.
-% and calls PI_Gensys.m solver
+% and calls PI_Gensys.m solver
% based on Pearlman et al 1986 paper and derived from
% C.Sims' gensys linear solver.
% to return solution in format
@@ -16,31 +16,31 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_)
% dr [matlab structure] Decision rules for stochastic simulations.
% task [integer] if task = 0 then dr1 computes decision rules.
% if task = 1 then dr1 computes eigenvalues.
-% M_ [matlab structure] Definition of the model.
+% M_ [matlab structure] Definition of the model.
% options_ [matlab structure] Global options.
-% oo_ [matlab structure] Results
-%
+% oo_ [matlab structure] Results
+%
% OUTPUTS
% dr [matlab structure] Decision rules for stochastic simulations.
% info [integer] info=1: the model doesn't define current variables uniquely
-% info=2: problem in mjdgges.dll info(2) contains error code.
+% info=2: problem in mjdgges.dll info(2) contains error code.
% info=3: BK order condition not satisfied info(2) contains "distance"
% absence of stable trajectory.
% info=4: BK order condition not satisfied info(2) contains "distance"
% indeterminacy.
% info=5: BK rank condition not satisfied.
-% M_ [matlab structure]
+% M_ [matlab structure]
% options_ [matlab structure]
% oo_ [matlab structure]
-%
+%
% ALGORITHM
% ...
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
+%
-% Copyright (C) 1996-2012 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -66,9 +66,9 @@ xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
if (options_.aim_solver == 1)
options_.aim_solver == 0;
- warning('You can not use AIM with Part Info solver. AIM ignored');
+ warning('You can not use AIM with Part Info solver. AIM ignored');
end
-if (options_.order > 1)
+if (options_.order > 1)
warning('You can not use order higher than 1 with Part Info solver. Order 1 assumed');
options_.order =1;
end
@@ -101,11 +101,11 @@ else
iyv = iyv(:);
iyr0 = find(iyv) ;
it_ = M_.maximum_lag + 1 ;
-
+
if M_.exo_nbr == 0
oo_.exo_steady_state = [] ;
end
-
+
if options_.ACES_solver == 1
sim_ruleids=[];
@@ -172,15 +172,15 @@ sdyn = M_.endo_nbr - nstatic;
k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var);
k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
-if (options_.aim_solver == 1)
+if (options_.aim_solver == 1)
error('Anderson and Moore AIM solver is not compatible with Partial Information models');
end % end if useAIM and...
% If required, try PCL86 solver, that is, if not the check being
- % performed only and if it is 1st order
+ % performed only and if it is 1st order
% create sparse, extended jacobia AA:
nendo=M_.endo_nbr; % = size(aa,1)
-
+
if(options_.ACES_solver==1)
%if ~isfield(lq_instruments,'names')
@@ -239,8 +239,8 @@ end % end if useAIM and...
% E_t z(t)
% E_t z(t+1)
% E_t z(t+2)
- % E_t z(t+3)
-
+ % E_t z(t+3)
+
% partition jacobian:
jlen=M_.nspred+M_.nsfwrd+M_.endo_nbr+M_.exo_nbr; % length of jacobian
PSI=-jacobia_(:, jlen-M_.exo_nbr+1:end); % exog
@@ -253,12 +253,12 @@ end % end if useAIM and...
AA2=AA0; % empty A2 and A3
AA3=AA0;
if xlen==nendo % && M_.maximum_lag <=1 && M_.maximum_lead <=1 % apply a shortcut
- AA1=jacobia_(:,nspred+1:nspred+nendo);
+ AA1=jacobia_(:,nspred+1:nspred+nendo);
if M_.maximum_lead ==1
fnd = find(lead_lag(:,M_.maximum_lag+2));
AA0(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,M_.maximum_lag+2))); %forwd jacobian
end
- if nspred>0 && M_.maximum_lag ==1
+ if nspred>0 && M_.maximum_lag ==1
fnd = find(lead_lag(:,1));
AA2(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward
end
@@ -266,7 +266,7 @@ end % end if useAIM and...
if nendo-xlen==num_inst
PSI=[PSI;zeros(num_inst, M_.exo_nbr)];
% AA1 contemporary
- AA_all=jacobia_(:,nspred+1:nspred+nendo);
+ AA_all=jacobia_(:,nspred+1:nspred+nendo);
AA1=AA_all(:,lq_instruments.m_var); % endo without instruments
lq_instruments.ij1=AA_all(:,lq_instruments.inst_var_indices); % instruments only
lq_instruments.B1=-[lq_instruments.ij1; eye(num_inst)];
@@ -281,7 +281,7 @@ end % end if useAIM and...
lq_instruments.B0=[lq_instruments.ij0; eye(num_inst)];
AA0=[AA0, zeros(xlen,num_inst); zeros(num_inst,xlen+num_inst)];
end
- if nspred>0 && M_.maximum_lag ==1
+ if nspred>0 && M_.maximum_lag ==1
AA_all(:,:)=0.0;
fnd = find(lead_lag(:,1));
AA_all(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward
@@ -312,7 +312,7 @@ end % end if useAIM and...
NX=M_.exo_nbr; % no of exogenous varexo shock variables.
NETA=nfwrd+nboth; % total no of exp. errors set to no of forward looking equations
FL_RANK=rank(AA0); % nfwrd+nboth; % min total no of forward looking equations and vars
-
+
try
% call [G1pi,C,impact,nmat,TT1,TT2,gev,eu]=PI_gensys(a0,a1,a2,c,PSI,NX,NETA,NO_FL_EQS)
% System given as
@@ -348,13 +348,13 @@ end % end if useAIM and...
[G1pi,CC,impact,nmat,TT1,TT2,gev,eu, DD, E2,E5, GAMMA, FL_RANK]=PI_gensys(AA0,AA1,-AA2,AA3,cc,PSI,NX,NETA,FL_RANK, M_, options_);
end
- % reuse some of the bypassed code and tests that may be needed
+ % reuse some of the bypassed code and tests that may be needed
if (eu(1) ~= 1 || eu(2) ~= 1) && options_.ACES_solver==0
info(1) = abs(eu(1)+eu(2));
info(2) = 1.0e+8;
% return
end
-
+
dr.PI_ghx=G1pi;
dr.PI_ghu=impact;
dr.PI_TT1=TT1;
@@ -369,7 +369,7 @@ end % end if useAIM and...
dr.ghu=impact;
dr.eigval = eig(G1pi);
dr.rank=FL_RANK;
-
+
if options_.ACES_solver==1
betap=options_.planner_discount;
sigma_cov=M_.Sigma_e;
@@ -390,8 +390,8 @@ end % end if useAIM and...
ACES.Q=DYN_Q;
ACES.W=W;
NY=nendo-num_inst;
-
- % save the followings in a subdirectory - BY
+
+ % save the followings in a subdirectory - BY
save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_Matrices'], 'ACES');
save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_GAMMA'], 'GAMMA');
save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_A.txt'], 'G1pi', '-ascii', '-double', '-tabs');
@@ -449,8 +449,6 @@ end % end if useAIM and...
end
end
- % TODO:
+ % TODO:
% if options_.loglinear == 1
- % if exogenous deterministic variables
-
- return;
+ % if exogenous deterministic variables
\ No newline at end of file
diff --git a/matlab/particles b/matlab/particles
index 823d94748..84d213ea3 160000
--- a/matlab/particles
+++ b/matlab/particles
@@ -1 +1 @@
-Subproject commit 823d947484675c8d409a4eb2377a57dc59bdf713
+Subproject commit 84d213ea3e705f36871bc8f960d175a330fd71de
diff --git a/matlab/perfect-foresight-models/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m
index df64df222..ee177d830 100644
--- a/matlab/perfect-foresight-models/det_cond_forecast.m
+++ b/matlab/perfect-foresight-models/det_cond_forecast.m
@@ -12,7 +12,7 @@ function data_set = det_cond_forecast(varargin)
% dataset [dseries] Returns a dseries containing the forecasted endgenous variables and shocks
%
%
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -35,8 +35,8 @@ initial_conditions = oo_.steady_state;
verbosity = options_.verbosity;
if options_.periods == 0
options_.periods = 25;
-end;
-%We have to get an initial guess for the conditional forecast
+end
+%We have to get an initial guess for the conditional forecast
% and terminal conditions for the non-stationary variables, we
% use the first order approximation of the rational expectation solution.
if ~isfield(oo_,'dr') || (isempty(oo_.dr))
@@ -64,7 +64,7 @@ if length(varargin) > 3
nvars = length(constrained_vars);
for i = 1:max_periods_simulation
constraint_index{i} = 1:nvars;
- end;
+ end
direct_mode = 0;
shocks_present = 0;
controlled_varexo = options_cond_fcst.controlled_varexo;
@@ -82,7 +82,7 @@ if length(varargin) > 3
error(['Unknown exogenous variable ' controlled_varexo(i,:)]);
end
end
-
+
else
% alternative way to call: plan, dset, dates_of_frcst
plan = varargin{1};
@@ -102,7 +102,7 @@ else
s2 = strings(range(range.ndat));
error(['the dseries ' inputname(2) ' finish at time ' s1{1} ' before the last period of forecast ' s2{1}]);
end
-
+
sym_dset = dset(dates(-range(1)):dates(range(range.ndat)));
periods = options_.periods + M_.maximum_lag + M_.maximum_lead;
total_periods = periods + range.ndat;
@@ -113,9 +113,9 @@ else
else
oo_.exo_simul = repmat(oo_.exo_steady_state',total_periods,1);
end
-
+
oo_.endo_simul = repmat(oo_.steady_state, 1, total_periods);
-
+
for i = 1:sym_dset.vobs
iy = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.endo_names)));
if ~isempty(iy)
@@ -123,7 +123,7 @@ else
initial_conditions(iy) = sym_dset.data(1, i);
else
ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names)));
- if ~isempty(ix)
+ if ~isempty(ix)
oo_.exo_simul(1, ix) = sym_dset.data(1, i)';
else
%warning(['The variable ' sym_dset.name{i} ' in the dataset ' inputname(2) ' is not a endogenous neither an exogenous variable!!']);
@@ -147,7 +147,7 @@ else
% steady-state
%for jj = 2 : (options_.periods + 2)
for jj = 2 : (range.ndat + 2)
- oo_.endo_simul(:, jj) = oo_.steady_state;
+ oo_.endo_simul(:, jj) = oo_.steady_state;
end
missings = isnan(oo_.endo_simul(:,1));
if any(missings)
@@ -169,7 +169,7 @@ else
oo_.exo_simul = exo;
end
endo = endo';
- endo_l = size(endo(1+M_.maximum_lag:end,:),1);
+ endo_l = size(endo(1+M_.maximum_lag:end,:),1);
jrng = dates(plan.date(1)):dates(plan.date(1)+endo_l);
data_set = dseries(nan(endo_l, dset.vobs), plan.date(1), dset.name);
for i = 1:length(dset.name)
@@ -193,30 +193,30 @@ else
end
end
data_set = merge(dset(dset.dates(1):(plan.date(1)-1)), data_set);
- return;
+ return
union_names = union(data_set.name, dset.name);
dif = setdiff(union_names, data_set.name);
data_set_nobs = data_set.nobs;
for i = 1:length(dif)
data_set{dif{i}} = dseries(nan(data_set_nobs,1),plan.date(1), dif(i), dif(i));
- end;
+ end
dif = setdiff(union_names, dset.name);
dset_nobs = dset.nobs;
for i = 1:length(dif)
dset{dif{i}} = dseries(nan(dset_nobs,1),dset.dates(1), dif(i), dif(i));
- end;
+ end
data_set = [dset(dset.dates(1):(plan.date(1)-1)) ; data_set];
- return;
- end;
+ return
+ end
else
- error('impossible case');
- end;
-
+ error('impossible case');
+ end
+
else
oo_.exo_simul = repmat(oo_.exo_steady_state',options_.periods+2,1);
oo_.endo_simul = repmat(oo_.steady_state, 1, options_.periods+2);
end
-
+
direct_mode = 1;
constrained_paths = plan.constrained_paths_;
constrained_vars = plan.constrained_vars_;
@@ -232,16 +232,16 @@ else
else
shocks_present = 0;
end
-
+
total_periods = plan.date;
-
-end;
+
+end
if ~isfield(options_cond_fcst,'periods') || isempty(options_cond_fcst.periods)
options_cond_fcst.periods = 100;
end
-options_.periods = 10;
+options_.periods = 10;
if direct_mode == 1
n_periods = length(constrained_periods);
@@ -260,7 +260,7 @@ if direct_mode == 1
else
init_periods = period_i;
tp_end = period_i;
- end;
+ end
tp0 = tp;
while tp < init_periods
tp = tp + 1;
@@ -271,18 +271,18 @@ if direct_mode == 1
constrained_paths(i, tp - tp0 + 1) = constrained_paths_cell{i}(j + 1);
tp = tp + 1;
j = j + 1;
- end;
- if tp - tp0 > max_periods_simulation
+ end
+ if tp - tp0 > max_periods_simulation
max_periods_simulation = tp - tp0;
- end;
+ end
end
n_nnz = length(sum(is_constraint,2));
if n_nnz > 0
constraint_index = cell(n_nnz,1);
for i= 1:n_nnz
constraint_index{i} = find(is_constraint(i,:));
- end;
- end;
+ end
+ end
if shocks_present
n_periods = length(shock_periods);
shock_paths_cell = shock_paths;
@@ -299,7 +299,7 @@ if direct_mode == 1
else
init_periods = period_i;
tp_end = period_i;
- end;
+ end
tp0 = tp;
while tp < init_periods
tp = tp + 1;
@@ -310,17 +310,17 @@ if direct_mode == 1
shock_paths(i, tp - tp0 + 1) = shock_paths_cell{i}(j + 1);
tp = tp + 1;
j = j + 1;
- end;
- if tp - tp0 > max_periods_simulation
+ end
+ if tp - tp0 > max_periods_simulation
max_periods_simulation = tp - tp0;
- end;
- end;
+ end
+ end
n_nnz = length(sum(is_shock,2));
if n_nnz > 0
shock_index = cell(n_nnz, 1);
for i= 1:n_nnz
shock_index{i} = find(is_shock(i,:));
- end;
+ end
end
end
else
@@ -336,16 +336,16 @@ ny = size(ys,1);
xs = [oo_.exo_steady_state ; oo_.exo_det_steady_state];
nx = size(xs,1);
-constrained_periods = max_periods_simulation;
+constrained_periods = max_periods_simulation;
n_endo_constrained = size(constrained_vars,1);
if isfield(options_cond_fcst,'controlled_varexo')
n_control_exo = size(options_cond_fcst.controlled_varexo, 1);
if n_control_exo ~= n_endo_constrained
error(['det_cond_forecast: the number of exogenous controlled variables (' int2str(n_control_exo) ') has to be equal to the number of constrained endogenous variabes (' int2str(n_endo_constrained) ')'])
- end;
+ end
else
error('det_cond_forecast: to run a deterministic conditional forecast you have to specified the exogenous variables controlled using the option controlled_varexo in forecast command');
-end;
+end
% if n_endo_constrained == 0
% options_.ep.use_bytecode = options_.bytecode;
@@ -377,14 +377,14 @@ if isempty(indx_endo_solve_pf)
pf = 0;
else
pf = length(indx_endo_solve_pf);
-end;
+end
indx_endo_solve_surprise = setdiff(constrained_vars, indx_endo_solve_pf);
if isempty(indx_endo_solve_surprise)
surprise = 0;
else
surprise = length(indx_endo_solve_surprise);
-end;
+end
eps = options_.solve_tolf;
@@ -414,7 +414,7 @@ if pf && ~surprise
for j = 1:length(constrained_vars)
indx_endo(col_count : col_count + constrained_periods - 1) = constrained_vars(j) + (time_index_constraint - 1) * ny;
col_count = col_count + constrained_periods;
- end;
+ end
oo_=make_ex_(M_,options_,oo_);
oo_=make_y_(M_,options_,oo_);
it = 1;
@@ -436,9 +436,9 @@ if pf && ~surprise
y = oo_.endo_simul(constrained_vars(j), time_index_constraint);
r(col_count:col_count+constrained_periods - 1) = (y - constrained_paths(j,1:constrained_periods))';
col_count = col_count + constrained_periods;
- end;
+ end
normr = norm(r, 1);
- end;
+ end
if (~oo_.deterministic_simulation.status || ~result || normr > normra) && it > 1
not_achieved = 1;
alpha = alpha / 2;
@@ -446,14 +446,14 @@ if pf && ~surprise
for j = controlled_varexo'
oo_.exo_simul(time_index_constraint,j) = (old_exo(:,j) + alpha * D_exo(col_count: (col_count + constrained_periods - 1)));
col_count = col_count + constrained_periods;
- end;
+ end
disp(['Divergence in Newton: reducing the path length alpha=' num2str(alpha)]);
oo_.endo_simul = repmat(oo_.steady_state, 1, options_cond_fcst.periods + 2);
else
not_achieved = 0;
- end;
- end;
-
+ end
+ end
+
per = 30;
z = oo_.endo_simul(:, 1 : per + 2 );
zx = oo_.exo_simul(1: per + 2,:);
@@ -473,7 +473,7 @@ if pf && ~surprise
else
data1 = M_;
Size = 1;
- end;
+ end
data1 = M_;
if (options_.bytecode)
[chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1);
@@ -482,16 +482,16 @@ if pf && ~surprise
data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end);
data1.g1 = g1b(:,1 : end - M_.exo_nbr);
chck = 0;
- end;
+ end
mexErrCheck('bytecode', chck);
- end;
- if k == 1
+ end
+ if k == 1
g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end);
elseif k == per
g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr);
else
g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k, M_.endo_nbr * (k -2) + [lag_indx cur_indx lead_indx]) = data1.g1;
- end;
+ end
l2 = 1;
pf_c = 1;
if k <= constrained_periods
@@ -504,17 +504,17 @@ if pf && ~surprise
for ii = 2:constrained_periods
indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c);
l2 = l2 + 1;
- end;
+ end
pf_c = pf_c + 1;
cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l)];
else
cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l) + (k - 1) * M_.endo_nbr];
end
cum_l1 = cum_l1 + length(l1);
- end;
- end;
- end;
-
+ end
+ end
+ end
+
d_y_x = - g1 \ g1_x;
cum_l1 = 0;
@@ -533,9 +533,9 @@ if pf && ~surprise
cum_l1 = cum_l1 + length(l1);
end
cum_l1 = cum_l1 + length(constrained_vars(j1));
- end;
-
-
+ end
+
+
% col_count = 1;
% for j = controlled_varexo'
% for time = time_index_constraint
@@ -545,13 +545,13 @@ if pf && ~surprise
% J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
% oo_.exo_simul(time,j) = saved;
% col_count = col_count + 1;
- % end;
- % end;
+ % end
+ % end
% J1
% sdfmlksdf;
-
+
disp(['iteration ' int2str(it) ' error = ' num2str(normr)]);
-
+
if normr <= eps
convg = 1;
disp('convergence achieved');
@@ -564,25 +564,25 @@ if pf && ~surprise
for j = controlled_varexo'
oo_.exo_simul(time_index_constraint,j) = oo_.exo_simul(time_index_constraint,j) + D_exo(col_count: (col_count + constrained_periods - 1));
col_count = col_count + constrained_periods - 1;
- end;
- end;
+ end
+ end
it = it + 1;
normra = normr;
- end;
+ end
endo = oo_.endo_simul';
exo = oo_.exo_simul;
else
for t = 1:constrained_periods
-
- if direct_mode && ~isempty(is_constraint)
+
+ if direct_mode && ~isempty(is_constraint)
[pos_constrained_pf, junk] = find(constrained_perfect_foresight .* is_constraint(t, :)');
indx_endo_solve_pf = constrained_vars(pos_constrained_pf);
if isempty(indx_endo_solve_pf)
pf = 0;
else
pf = length(indx_endo_solve_pf);
- end;
-
+ end
+
[pos_constrained_surprise, junk] = find((1-constrained_perfect_foresight) .* is_constraint(t, :)');
indx_endo_solve_surprise = constrained_vars(pos_constrained_surprise);
@@ -590,18 +590,18 @@ else
surprise = 0;
else
surprise = length(indx_endo_solve_surprise);
- end;
- end;
-
- if direct_mode && ~isempty(is_shock)
+ end
+ end
+
+ if direct_mode && ~isempty(is_shock)
[pos_shock_pf, junk] = find(shock_perfect_foresight .* is_shock(t, :)');
indx_endo_solve_pf = shock_vars(pos_shock_pf);
if isempty(indx_endo_solve_pf)
b_pf = 0;
else
b_pf = length(indx_endo_solve_pf);
- end;
-
+ end
+
[pos_shock_surprise, junk] = find((1-shock_perfect_foresight) .* is_shock(t, :)');
indx_endo_solve_surprise = shock_vars(pos_shock_surprise);
@@ -609,9 +609,9 @@ else
b_surprise = 0;
else
b_surprise = length(indx_endo_solve_surprise);
- end;
- end;
-
+ end
+ end
+
disp('===============================================================================================');
disp(['t=' int2str(t) ' conditional (surprise=' int2str(surprise) ' perfect foresight=' int2str(pf) ') unconditional (surprise=' int2str(b_surprise) ' perfect foresight=' int2str(b_pf) ')']);
disp('===============================================================================================');
@@ -623,20 +623,20 @@ else
exo_init = zeros(size(oo_.exo_simul));
end
oo_=make_y_(M_,options_,oo_);
- end;
+ end
%exo_init
oo_.exo_simul = exo_init;
oo_.endo_simul(:,1) = initial_conditions;
-
+
time_index_constraint = maximum_lag + 1:maximum_lag + constrained_periods - t + 1;
-
+
if direct_mode
nb_shocks = length(plan.shock_vars_);
if nb_shocks > 0
shock_index_t = shock_index{t};
shock_vars_t = shock_vars(shock_index_t);
for shock_indx = shock_index_t
- if shock_perfect_foresight(shock_indx)
+ if shock_perfect_foresight(shock_indx)
oo_.exo_simul(time_index_constraint,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t:constrained_periods);
else
oo_.exo_simul(maximum_lag + 1,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t);
@@ -653,11 +653,11 @@ else
for jj = 1 : (options_.periods + 2)
oo_.endo_simul(:,jj) = oo_.steady_state + oo_.endo_simul(:,jj);
end
-
+
constraint_index_t = constraint_index{t};
controlled_varexo_t = controlled_varexo(constraint_index_t);
constrained_vars_t = constrained_vars(constraint_index_t);
-
+
second_system_size = surprise + pf * (constrained_periods - t + 1);
indx_endo = zeros(second_system_size,1);
col_count = 1;
@@ -668,11 +668,11 @@ else
else
indx_endo(col_count) = constrained_vars(j) + maximum_lag * ny;
col_count = col_count + 1;
- end;
- end;
-
+ end
+ end
+
r = zeros(second_system_size,1);
-
+
convg = 0;
it = 1;
while ~convg && it <= maxit
@@ -696,20 +696,20 @@ else
else
oo_.exo_simul(maximum_lag + 1,j) = old_exo(maximum_lag + 1,j) + alpha * D_exo(col_count);
col_count = col_count + 1;
- end;
- end;
+ end
+ end
disp(['Divergence in Newton: reducing the path length alpha=' num2str(alpha) ' result=' num2str(result) ' sum(sum)=' num2str(sum(sum(isfinite(oo_.endo_simul(:,time_index_constraint))))) ' ny * length(time_index_constraint)=' num2str(ny * length(time_index_constraint)) ' oo_.deterministic_simulation.status=' num2str(oo_.deterministic_simulation.status)]);
oo_.endo_simul = [initial_conditions repmat(oo_.steady_state, 1, options_cond_fcst.periods + 1)];
else
not_achieved = 0;
- end;
- end;
+ end
+ end
if t==constrained_periods
ycc = oo_.endo_simul;
- end;
+ end
yc = oo_.endo_simul(:,maximum_lag + 1);
ys = oo_.endo_simul(indx_endo);
-
+
col_count = 1;
for j = constraint_index_t
if constrained_perfect_foresight(j)
@@ -720,9 +720,9 @@ else
y = yc(constrained_vars(j));
r(col_count) = y - constrained_paths(j,t);
col_count = col_count + 1;
- end;
+ end
end
-
+
disp('computation of derivatives w.r. to exogenous shocks');
per = 30;
@@ -745,7 +745,7 @@ else
else
data1 = M_;
Size = 1;
- end;
+ end
data1 = M_;
if (options_.bytecode)
[chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1);
@@ -754,17 +754,17 @@ else
data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end);
data1.g1 = g1b(:,1 : end - M_.exo_nbr);
chck = 0;
- end;
+ end
mexErrCheck('bytecode', chck);
- end;
- if k == 1
+ end
+ if k == 1
g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end);
elseif k == per
g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr);
else
g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k, M_.endo_nbr * (k -2) + [lag_indx cur_indx lead_indx]) = data1.g1;
- end;
-
+ end
+
l2 = 1;
pf_c = 1;
if t + k - 1 <= constrained_periods
@@ -779,25 +779,25 @@ else
for ii = 2:constrained_periods - t + 1
indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c);
l2 = l2 + 1;
- end;
+ end
pf_c = pf_c + 1;
else
indx_x(l2) = l;
l2 = l2 + 1;
- end;
+ end
cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l)];
else
cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l) + (k - 1) * M_.endo_nbr];
end
cum_l1 = cum_l1 + length(l1);
- end;
- end;
- end;
- end;
-
+ end
+ end
+ end
+ end
+
d_y_x = - g1 \ g1_x;
-
+
cum_l1 = 0;
count_col = 1;
cum_index_J = 1:length(cum_index_d_y_x(indx_x));
@@ -819,10 +819,10 @@ else
count_col = count_col + 1;
end
cum_l1 = cum_l1 + length(constrained_vars_t(j1));
- end;
+ end
-
- % % Numerical computation of the derivatives in the second systme
+
+ % % Numerical computation of the derivatives in the second systme
% J1 = [];
% col_count = 1;
% for j = constraint_index_t
@@ -835,7 +835,7 @@ else
% J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
% oo_.exo_simul(time,j_pos) = saved;
% col_count = col_count + 1;
- % end;
+ % end
% else
% saved = oo_.exo_simul(maximum_lag+1,j_pos);
% oo_.exo_simul(maximum_lag+1,j_pos) = oo_.exo_simul(maximum_lag+1,j_pos) + eps1;
@@ -845,15 +845,15 @@ else
% % J(:,col_count) = (oo_.endo_simul((pp - 1) * M_.endo_nbr + 1: pp * M_.endo_nbr) - ys) / eps1;
% oo_.exo_simul(maximum_lag+1,j_pos) = saved;
% col_count = col_count + 1;
- % end;
- % end;
+ % end
+ % end
% disp('J1');
% disp(full(J1));
% sdfmlk;
-
+
normr = norm(r, 1);
-
+
disp(['iteration ' int2str(it) ' error = ' num2str(normr) ' at time ' int2str(t)]);
if normr <= eps
@@ -870,7 +870,7 @@ else
z_root = find(abs(ev) < 1e-4);
z_root
disp(V(:,z_root));
- end;
+ end
old_exo = oo_.exo_simul;
col_count = 1;
for j = constraint_index_t
@@ -881,14 +881,14 @@ else
else
oo_.exo_simul(maximum_lag + 1,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos) + D_exo(col_count);
col_count = col_count + 1;
- end;
- end;
- end;
+ end
+ end
+ end
it = it + 1;
- end;
+ end
if ~convg
error(['convergence not achived at time ' int2str(t) ' after ' int2str(it) ' iterations']);
- end;
+ end
for j = constraint_index_t
j_pos=controlled_varexo(j);
if constrained_perfect_foresight(j)
@@ -900,20 +900,20 @@ else
end
else
exo(maximum_lag + t,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos);
- end;
- end;
+ end
+ end
past_val = past_val + length(time_index_constraint);
if t < constrained_periods
endo(maximum_lag + t,:) = yc;
else
endo(maximum_lag + t :maximum_lag + options_cond_fcst.periods ,:) = ycc(:,maximum_lag + 1:maximum_lag + options_cond_fcst.periods - constrained_periods + 1)';
- end;
+ end
initial_conditions = yc;
if maximum_lag > 0
exo_init(1,:) = exo(maximum_lag + t,:);
- end;
- end;
-end;
+ end
+ end
+end
options_.periods = save_options_periods;
options_.dynatol.f = save_options_dynatol_f;
options_.initval_file = save_options_initval_file;
@@ -922,4 +922,4 @@ oo_.endo_simul = endo';
oo_.exo_simul = exo;
if direct_mode
data_set = dseries([endo(2:end,1:M_.orig_endo_nbr) exo(2:end,:)], total_periods(1), {plan.endo_names{:} plan.exo_names{:}}, {plan.endo_names{:} plan.exo_names{:}});
-end;
+end
diff --git a/matlab/perfect-foresight-models/linear_approximation_accuracy.m b/matlab/perfect-foresight-models/linear_approximation_accuracy.m
index e3f9eb521..289997176 100644
--- a/matlab/perfect-foresight-models/linear_approximation_accuracy.m
+++ b/matlab/perfect-foresight-models/linear_approximation_accuracy.m
@@ -2,15 +2,15 @@ function err = linear_approximation_accuracy(options_, M_, oo_)
% Evaluates the accuracy of the linear approximation when solving perfect foresight models, by
% reporting the max absolute value of the dynamic residuals.
%
-% INPUTS
+% INPUTS
% - options_ [struct] contains various options.
% - M_ [struct] contains a description of the model.
% - oo_ [struct] contains results.
%
-% OUTPUTS
+% OUTPUTS
% - err [double] n*1 vector, evaluation of the accuracy (n is the number of equations).
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
index b8f710bd4..78d9fed41 100644
--- a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
+++ b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
@@ -5,7 +5,7 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjaco
i_cols_j,nnzJ,jendo,jexog)
% function [residuals,JJacobian] = perfect_foresight_problem(x, model_dynamic, Y0, YT,exo_simul,
% params, steady_state, maximum_lag, periods, ny, i_cols,i_cols_J1, i_cols_1,
-% i_cols_T, i_cols_j, nnzA)
+% i_cols_T, i_cols_j, nnzA)
% computes the residuals and th Jacobian matrix
% for a perfect foresight problem over T periods.
%
@@ -19,7 +19,7 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjaco
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m
index 73ab28f43..4f7259048 100644
--- a/matlab/perfect-foresight-models/make_ex_.m
+++ b/matlab/perfect-foresight-models/make_ex_.m
@@ -5,16 +5,16 @@ function oo_=make_ex_(M_,options_,oo_)
% M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
-%
+%
% OUTPUTS
% oo_: Dynare results structure
%
% ALGORITHM
-%
+%
% SPECIAL REQUIREMENTS
-%
+%
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -53,7 +53,7 @@ else
else
error('histval and endval cannot be used simultaneously')
end
-end
+end
% Initialize oo_.exo_det_simul
if M_.exo_det_nbr > 0
diff --git a/matlab/perfect-foresight-models/make_y_.m b/matlab/perfect-foresight-models/make_y_.m
index f3c8f686f..e96333825 100644
--- a/matlab/perfect-foresight-models/make_y_.m
+++ b/matlab/perfect-foresight-models/make_y_.m
@@ -1,22 +1,22 @@
function oo_=make_y_(M_,options_,oo_)
% function oo_=make_y_(M_,options_,oo_)
% forms oo_.endo_simul as guess values for deterministic simulations
-%
+%
% INPUTS
% M_: Dynare model structure
% options_: Dynare options structure
% oo_: Dynare results structure
-%
+%
% OUTPUTS
% oo_: Dynare results structure
-%
+%
% ALGORITHM
% ...
% SPECIAL REQUIREMENTS
% none
-%
+%
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -33,7 +33,7 @@ function oo_=make_y_(M_,options_,oo_)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-global ys0_
+global ys0_
if options_.steadystate_flag
[oo_.steady_state,M_.params,check] = ...
diff --git a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
index ed6553201..eb898322d 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
@@ -17,7 +17,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
% Y0 [double] N*1 array, initial conditions for the endogenous variables
% YT [double] N*1 array, terminal conditions for the endogenous variables
% exo_simul [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order)
-% for all simulation periods
+% for all simulation periods
% params [double] nparams*1 array, parameter values
% steady_state [double] endo_nbr*1 vector of steady state values
% maximum_lag [scalar] maximum lag present in the model
@@ -25,7 +25,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
% ny [scalar] number of endogenous variables
% i_cols [double] indices of variables appearing in M.lead_lag_incidence
% and that need to be passed to _dynamic-file
-% i_cols_J1 [double] indices of contemporaneous and forward looking variables
+% i_cols_J1 [double] indices of contemporaneous and forward looking variables
% appearing in M.lead_lag_incidence
% i_cols_1 [double] indices of contemporaneous and forward looking variables in
% M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
@@ -33,8 +33,8 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
% variables (relevant in last period)
% i_cols_j [double] indices of variables in M.lead_lag_incidence
% in dynamic Jacobian (relevant in intermediate periods)
-% nnzJ [scalar] number of non-zero elements in Jacobian
-% eq_index [double] N*1 array, index vector describing residual mapping resulting
+% nnzJ [scalar] number of non-zero elements in Jacobian
+% eq_index [double] N*1 array, index vector describing residual mapping resulting
% from complementarity setup
% OUTPUTS
% residuals [double] (N*T)*1 array, residuals of the stacked problem
@@ -45,7 +45,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -96,7 +96,7 @@ for it = 2:(T+1)
end
offset = offset + ny;
end
-
+
i_rows = i_rows + ny;
i_cols = i_cols + ny;
end
diff --git a/matlab/perfect-foresight-models/perfect_foresight_problem.m b/matlab/perfect-foresight-models/perfect_foresight_problem.m
index 2f4cee6fd..a4df03f80 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_problem.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_problem.m
@@ -16,7 +16,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
% Y0 [double] N*1 array, initial conditions for the endogenous variables
% YT [double] N*1 array, terminal conditions for the endogenous variables
% exo_simul [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order)
-% for all simulation periods
+% for all simulation periods
% params [double] nparams*1 array, parameter values
% steady_state [double] endo_nbr*1 vector of steady state values
% maximum_lag [scalar] maximum lag present in the model
@@ -24,7 +24,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
% ny [scalar] number of endogenous variables
% i_cols [double] indices of variables appearing in M.lead_lag_incidence
% and that need to be passed to _dynamic-file
-% i_cols_J1 [double] indices of contemporaneous and forward looking variables
+% i_cols_J1 [double] indices of contemporaneous and forward looking variables
% appearing in M.lead_lag_incidence
% i_cols_1 [double] indices of contemporaneous and forward looking variables in
% M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
@@ -32,7 +32,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
% variables (relevant in last period)
% i_cols_j [double] indices of variables in M.lead_lag_incidence
% in dynamic Jacobian (relevant in intermediate periods)
-% nnzJ [scalar] number of non-zero elements in Jacobian
+% nnzJ [scalar] number of non-zero elements in Jacobian
% OUTPUTS
% residuals [double] (N*T)*1 array, residuals of the stacked problem
% JJacobian [double] (N*T)*(N*T) array, Jacobian of the stacked problem
@@ -42,7 +42,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m
index 7d7312fc0..341d70aad 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_setup.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m
@@ -1,18 +1,18 @@
function perfect_foresight_setup()
% Prepares a deterministic simulation, by filling oo_.exo_simul and oo_.endo_simul
-%
+%
% INPUTS
% None
-%
+%
% OUTPUTS
% none
-%
+%
% ALGORITHM
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/perfect_foresight_simulation.m b/matlab/perfect-foresight-models/perfect_foresight_simulation.m
index ffef743ed..15f1b8b76 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_simulation.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_simulation.m
@@ -18,7 +18,7 @@ function info = perfect_foresight_simulation(compute_linear_solution,steady_stat
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver.m b/matlab/perfect-foresight-models/perfect_foresight_solver.m
index b159f2aea..8e7c3bcbc 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_solver.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver.m
@@ -12,7 +12,7 @@ function perfect_foresight_solver()
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -192,12 +192,12 @@ if ~isreal(oo_.endo_simul(:)) %can only happen without bytecode
oo_.deterministic_simulation.status = 1;
oo_.endo_simul=real(oo_.endo_simul);
else
- oo_.deterministic_simulation.status = 0;
+ oo_.deterministic_simulation.status = 0;
disp('Simulation terminated with imaginary parts in the residuals or endogenous variables.')
- end
+ end
end
-if oo_.deterministic_simulation.status == 1
+if oo_.deterministic_simulation.status == 1
disp('Perfect foresight solution found.')
else
disp('Failed to solve perfect foresight model')
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
index c01333f0b..272cd3833 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
@@ -2,16 +2,16 @@ function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_)
%function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_)
% Core function calling solvers for perfect foresight model
%
-% INPUTS
+% INPUTS
% - M_ [struct] contains a description of the model.
% - options_ [struct] contains various options.
% - oo_ [struct] contains results
%
-% OUTPUTS
+% OUTPUTS
% - oo_ [struct] contains results
% - maxerror [double] contains the maximum absolute error
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -143,5 +143,3 @@ if nargout>1
maxerror = max(max(abs(residuals)));
end
end
-
-
diff --git a/matlab/perfect-foresight-models/private/check_input_arguments.m b/matlab/perfect-foresight-models/private/check_input_arguments.m
index affb808e0..fc50114d0 100644
--- a/matlab/perfect-foresight-models/private/check_input_arguments.m
+++ b/matlab/perfect-foresight-models/private/check_input_arguments.m
@@ -3,7 +3,7 @@ function check_input_arguments(DynareOptions, DynareModel, DynareResults)
%Conducts checks for inconsistent/missing inputs to deterministic
%simulations
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -43,7 +43,7 @@ end
if isempty(DynareResults.endo_simul) || any(size(DynareResults.endo_simul) ~= [ DynareModel.endo_nbr, DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead ])
-
+
if DynareOptions.initval_file
fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead)
error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
diff --git a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
index 3f4ead4d1..014bb9acb 100644
--- a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
+++ b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
@@ -4,19 +4,19 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, .
% dynamicmodel] = initialize_stacked_problem(endogenousvariables, options, M, steadystate_y)
% Sets up the stacked perfect foresight problem for use with dynare_solve.m
%
-% INPUTS
+% INPUTS
% - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
% - options [struct] contains various options.
% - M [struct] contains a description of the model.
% - steadystate_y [double] N*1 array, steady state for the endogenous variables.
-% OUTPUTS
+% OUTPUTS
% - options [struct] contains various options.
% - y0 [double] N*1 array, initial conditions for the endogenous variables
% - yT [double] N*1 array, terminal conditions for the endogenous variables
% - z [double] T*M array, paths for the exogenous variables.
% - i_cols [double] indices of variables appearing in M.lead_lag_incidence
% and that need to be passed to _dynamic-file
-% - i_cols_J1 [double] indices of contemporaneous and forward looking variables
+% - i_cols_J1 [double] indices of contemporaneous and forward looking variables
% appearing in M.lead_lag_incidence
% - i_cols_T [double] columns of dynamic Jacobian related to
% contemporaneous and backward-looking
@@ -27,7 +27,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, .
% M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
% - dynamicmodel [handle] function handle to _dynamic-file
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/private/simulation_core.m b/matlab/perfect-foresight-models/private/simulation_core.m
index 1b8b1d51e..0c944c2a6 100644
--- a/matlab/perfect-foresight-models/private/simulation_core.m
+++ b/matlab/perfect-foresight-models/private/simulation_core.m
@@ -1,7 +1,7 @@
function [oo_, maxerror] = simulation_core(options_, M_, oo_)
%function [oo_, maxerror] = simulation_core(options_, M_, oo_)
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/sim1.m b/matlab/perfect-foresight-models/sim1.m
index f00bb43f8..28a777eb9 100644
--- a/matlab/perfect-foresight-models/sim1.m
+++ b/matlab/perfect-foresight-models/sim1.m
@@ -154,13 +154,13 @@ for iter = 1:options.simul.maxit
if endogenous_terminal_period && iter>1
dy = ZERO;
if options.simul.robust_lin_solve
- dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose );
+ dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose );
else
dy(1:i_rows(end)) = -lin_solve( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)), verbose );
end
else
if options.simul.robust_lin_solve
- dy = -lin_solve_robust( A, res, verbose );
+ dy = -lin_solve_robust( A, res, verbose );
else
dy = -lin_solve( A, res, verbose );
end
@@ -329,6 +329,5 @@ if any(~isreal(dyy))
endo_names=cellstr(M.endo_names(indx,:));
disp('Last iteration provided complex number for the following variables:')
fprintf('%s, ',endo_names{:}),
- fprintf('\n'),
-end
-
+ fprintf('\n'),
+end
\ No newline at end of file
diff --git a/matlab/perfect-foresight-models/sim1_lbj.m b/matlab/perfect-foresight-models/sim1_lbj.m
index d4d8c24f2..a9b585907 100644
--- a/matlab/perfect-foresight-models/sim1_lbj.m
+++ b/matlab/perfect-foresight-models/sim1_lbj.m
@@ -15,7 +15,7 @@ function [endogenousvariables, info] = sim1_lbj(endogenousvariables, exogenousva
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 1996-2015 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -122,7 +122,7 @@ if ~stop
end
info.status = 0;% more iterations are needed.
info.error = err;
- info.errors = c/abs(err);
+ info.errors = c/abs(err);
info.iterations = options.simul.maxit;
end
diff --git a/matlab/perfect-foresight-models/sim1_linear.m b/matlab/perfect-foresight-models/sim1_linear.m
index 6820c92bc..85dc38405 100644
--- a/matlab/perfect-foresight-models/sim1_linear.m
+++ b/matlab/perfect-foresight-models/sim1_linear.m
@@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
% Solves a linear approximation of a perfect foresight model using sparse matrix.
%
-% INPUTS
+% INPUTS
% - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
% - exogenousvariables [double] T*M array, paths for the exogenous variables.
% - steadystate_y [double] N*1 array, steady state for the endogenous variables.
@@ -10,16 +10,16 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
% - M [struct] contains a description of the model.
% - options [struct] contains various options.
%
-% OUTPUTS
+% OUTPUTS
% - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model).
% - info [struct] contains informations about the results.
%
-% NOTATIONS
+% NOTATIONS
% - N is the number of endogenous variables.
% - M is the number of innovations.
% - T is the number of periods (including initial and/or terminal conditions).
%
-% REMARKS
+% REMARKS
% - The structure `M` describing the structure of the model, must contain the
% following informations:
% + lead_lag_incidence, incidence matrix (given by the preprocessor).
@@ -38,7 +38,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
% to center the variables around the deterministic steady state to solve the
% perfect foresight model.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/sim1_purely_backward.m b/matlab/perfect-foresight-models/sim1_purely_backward.m
index b4f1decd4..a2ec8db13 100644
--- a/matlab/perfect-foresight-models/sim1_purely_backward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_backward.m
@@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_purely_backward(endogenousvariables,
% Performs deterministic simulation of a purely backward model
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/sim1_purely_forward.m b/matlab/perfect-foresight-models/sim1_purely_forward.m
index 5032e0498..31cd12b77 100644
--- a/matlab/perfect-foresight-models/sim1_purely_forward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_forward.m
@@ -1,7 +1,7 @@
function [endogenousvariables, info] = sim1_purely_forward(endogenousvariables, exogenousvariables, steadystate, M, options)
% Performs deterministic simulation of a purely forward model
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
index cd50c1cbe..5464c9e06 100644
--- a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
+++ b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
@@ -1,6 +1,6 @@
function [endogenousvariables, info] = solve_stacked_linear_problem(endogenousvariables, exogenousvariables, steadystate_y, steadystate_x, M, options)
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/perfect-foresight-models/solve_stacked_problem.m b/matlab/perfect-foresight-models/solve_stacked_problem.m
index 1c29f565e..dd3bc6363 100644
--- a/matlab/perfect-foresight-models/solve_stacked_problem.m
+++ b/matlab/perfect-foresight-models/solve_stacked_problem.m
@@ -1,19 +1,19 @@
-function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options);
+function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options)
% [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options);
% Solves the perfect foresight model using dynare_solve
%
-% INPUTS
+% INPUTS
% - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
% - exogenousvariables [double] T*M array, paths for the exogenous variables.
% - steadystate [double] N*1 array, steady state for the endogenous variables.
% - M [struct] contains a description of the model.
% - options [struct] contains various options.
%
-% OUTPUTS
+% OUTPUTS
% - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model).
% - info [struct] contains informations about the results.
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -74,6 +74,6 @@ endogenousvariables = [y0 reshape(y, M.endo_nbr, options.periods) yT];
if check
info.status = false;
else
-
+
info.status = true;
end
\ No newline at end of file
diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m
index 1d4b61eb7..c4e3c2b2b 100644
--- a/matlab/plot_icforecast.m
+++ b/matlab/plot_icforecast.m
@@ -1,12 +1,12 @@
function plot_icforecast(Variables,periods,options_)
% Build plots for the conditional forecasts.
%
-% INPUTS
-% o Variables [char] m*x array holding the names of the endogenous variables to be plotted.
+% INPUTS
+% o Variables [char] m*x array holding the names of the endogenous variables to be plotted.
%
% OUTPUTS
% None.
-%
+%
% SPECIAL REQUIREMENTS
% This routine has to be called after imcforecast.m.
diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m
index 0c1f48b2c..12da56804 100644
--- a/matlab/plot_identification.m
+++ b/matlab/plot_identification.m
@@ -8,14 +8,14 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance
% o idemodel [structure] identification results for the reduced form solution
% o idelre [structure] identification results for the LRE model
% o advanced [integer] flag for advanced identification checks
-% o tittxt [char] name of the results to plot
+% o tittxt [char] name of the results to plot
% o name [char] list of names
% o IdentifDirectoryName [char] directory name
-% o tittxt [char] TeX-name of the results to plot
+% o tittxt [char] TeX-name of the results to plot
% o name_tex [char] TeX-names of the parameters
% OUTPUTS
% None
-%
+%
% SPECIAL REQUIREMENTS
% None
@@ -42,7 +42,7 @@ if nargin <10 || isempty(tit_TeX)
tit_TeX=tittxt;
end
-if nargin <11
+if nargin <11
name_TeX=name;
end
@@ -58,7 +58,7 @@ siLREnorm = idelre.siLREnorm;
% end
tittxt1=regexprep(tittxt, ' ', '_');
tittxt1=strrep(tittxt1, '.', '');
-if SampleSize == 1,
+if SampleSize == 1
siJ = idemoments.siJ;
hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Identification using info from observables']);
subplot(211)
@@ -72,7 +72,7 @@ if SampleSize == 1,
set(gca,'xlim',[0 nparam+1])
set(gca,'xticklabel','')
dy = get(gca,'ylim');
- for ip=1:nparam,
+ for ip=1:nparam
text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
if ~all(isnan(idehess.ide_strength_J_prior))
@@ -80,12 +80,12 @@ if SampleSize == 1,
else
legend('relative to param value','Location','Best')
end
- if idehess.flag_score,
+ if idehess.flag_score
title('Identification strength with asymptotic Information matrix (log-scale)')
else
title('Identification strength with moments Information matrix (log-scale)')
end
-
+
subplot(212)
if ~all(isnan(idehess.deltaM_prior))
bar(log([idehess.deltaM(is) idehess.deltaM_prior(is)]))
@@ -96,7 +96,7 @@ if SampleSize == 1,
set(gca,'xlim',[0 nparam+1])
set(gca,'xticklabel','')
dy = get(gca,'ylim');
- for ip=1:nparam,
+ for ip=1:nparam
text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
if ~all(isnan(idehess.deltaM_prior))
@@ -104,7 +104,7 @@ if SampleSize == 1,
else
legend('relative to param value','Location','Best')
end
- if idehess.flag_score,
+ if idehess.flag_score
title('Sensitivity component with asymptotic Information matrix (log-scale)')
else
title('Sensitivity component with moments Information matrix (log-scale)')
@@ -123,9 +123,9 @@ if SampleSize == 1,
fclose(fidTeX);
end
dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_.nodisplay,options_.graph_format);
-
- if advanced,
- if ~options_.nodisplay,
+
+ if advanced
+ if ~options_.nodisplay
skipline()
disp('Press ENTER to plot advanced diagnostics'), pause(5),
end
@@ -146,7 +146,7 @@ if SampleSize == 1,
set(gca,'xlim',[0 nparam+1])
set(gca,'xticklabel','')
dy = get(gca,'ylim');
- for ip=1:nparam,
+ for ip=1:nparam
text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
legend('Moments','Model','LRE model','Location','Best')
@@ -167,16 +167,16 @@ if SampleSize == 1,
end
end
% identificaton patterns
- for j=1:size(idemoments.cosnJ,2),
+ for j=1:size(idemoments.cosnJ,2)
pax=NaN(nparam,nparam);
% fprintf('\n')
% disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
% fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
- for i=1:nparam,
+ for i=1:nparam
namx='';
- for in=1:j,
+ for in=1:j
dumpindx = idemoments.pars{i,j}(in);
- if isnan(dumpindx),
+ if isnan(dumpindx)
namx=[namx ' ' sprintf('%-15s','--')];
else
namx=[namx ' ' sprintf('%-15s',name{dumpindx})];
@@ -189,7 +189,7 @@ if SampleSize == 1,
imagesc(pax,[0 1]);
set(gca,'xticklabel','')
set(gca,'yticklabel','')
- for ip=1:nparam,
+ for ip=1:nparam
text(ip,(0.5),name{ip},'rotation',90,'HorizontalAlignment','left','interpreter','none')
text(0.5,ip,name{ip},'rotation',0,'HorizontalAlignment','right','interpreter','none')
end
@@ -198,7 +198,7 @@ if SampleSize == 1,
ax=colormap;
ax(1,:)=[0.9 0.9 0.9];
colormap(ax);
- if nparam>10,
+ if nparam>10
set(gca,'xtick',(5:5:nparam))
set(gca,'ytick',(5:5:nparam))
end
@@ -223,8 +223,8 @@ if SampleSize == 1,
skipline()
[U,S,V]=svd(idehess.AHess,0);
S=diag(S);
- if idehess.flag_score,
- if nparam<5,
+ if idehess.flag_score
+ if nparam<5
f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (Information matrix)'];
else
@@ -236,7 +236,7 @@ if SampleSize == 1,
else
% S = idemoments.S;
% V = idemoments.V;
- if nparam<5,
+ if nparam<5
f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix)']);
tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)'];
else
@@ -246,25 +246,25 @@ if SampleSize == 1,
tex_tit_2=[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV'];
end
end
- for j=1:min(nparam,8),
- if j<5,
+ for j=1:min(nparam,8)
+ if j<5
set(0,'CurrentFigure',f1),
jj=j;
else
set(0,'CurrentFigure',f2),
jj=j-4;
end
- subplot(4,1,jj),
+ subplot(4,1,jj)
if j<5
- bar(abs(V(:,end-j+1))),
+ bar(abs(V(:,end-j+1)))
Stit = S(end-j+1);
else
bar(abs(V(:,jj))),
Stit = S(jj);
end
set(gca,'xticklabel','')
- if j==4 || j==nparam || j==8,
- for ip=1:nparam,
+ if j==4 || j==nparam || j==8
+ for ip=1:nparam
text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
@@ -284,7 +284,7 @@ if SampleSize == 1,
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
- if nparam>4,
+ if nparam>4
dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2.tex'],'w');
@@ -301,7 +301,7 @@ if SampleSize == 1,
end
end
end
-
+
else
hh = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']);
subplot(211)
@@ -309,23 +309,23 @@ else
[ss, is] = sort(mmm);
mmm = mean(siJnorm)';
mmm = mmm./max(mmm);
- if advanced,
+ if advanced
mmm1 = mean(siHnorm)';
mmm=[mmm mmm1./max(mmm1)];
mmm1 = mean(siLREnorm)';
offset=size(siHnorm,2)-size(siLREnorm,2);
mmm1 = [NaN(offset,1); mmm1./max(mmm1)];
mmm=[mmm mmm1];
- end
-
+ end
+
bar(mmm(is,:))
set(gca,'xlim',[0 nparam+1])
set(gca,'xticklabel','')
dy = get(gca,'ylim');
- for ip=1:nparam,
+ for ip=1:nparam
text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
- if advanced,
+ if advanced
legend('Moments','Model','LRE model','Location','Best')
end
title('MC mean of sensitivity measures')
@@ -343,8 +343,8 @@ else
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
-
- if advanced,
+
+ if advanced
if ~options_.nodisplay,
skipline()
disp('Press ENTER to display advanced diagnostics'), pause(5),
@@ -397,7 +397,7 @@ else
% [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), ['MC_HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName, 0.15);
% end
- if nparam<5,
+ if nparam<5
f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
tex_tit_1=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
else
@@ -407,13 +407,13 @@ else
tex_tit_2=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
end
nplots=min(nparam,8);
- if nplots>4,
+ if nplots>4
nsubplo=ceil(nplots/2);
else
nsubplo=nplots;
end
- for j=1:nplots,
- if (nparam>4 && j<=ceil(nplots/2)) || nparam<5,
+ for j=1:nplots
+ if (nparam>4 && j<=ceil(nplots/2)) || nparam<5
set(0,'CurrentFigure',f1),
jj=j;
VVV=squeeze(abs(idemoments.V(:,:,end-j+1)));
@@ -424,8 +424,8 @@ else
VVV=squeeze(abs(idemoments.V(:,:,jj)));
SSS = idemoments.S(:,jj);
end
- subplot(nsubplo,1,jj),
- for i=1:nparam,
+ subplot(nsubplo,1,jj)
+ for i=1:nparam
[post_mean, post_median(:,i), post_var, hpd_interval(i,:), post_deciles] = posterior_moments(VVV(:,i),0,0.9);
end
bar(post_median)
@@ -433,8 +433,8 @@ else
Stit=mean(SSS);
set(gca,'xticklabel','')
- if j==4 || j==nparam || j==8,
- for ip=1:nparam,
+ if j==4 || j==nparam || j==8
+ for ip=1:nparam
text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
@@ -454,7 +454,7 @@ else
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
- if nparam>4,
+ if nparam>4
dyn_saveas(f2,[ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_.nodisplay,options_.graph_format);
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2.tex'],'w');
diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m
index 04f371566..2b2fc83f6 100644
--- a/matlab/plot_priors.m
+++ b/matlab/plot_priors.m
@@ -42,7 +42,7 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
-for plt = 1:nbplt,
+for plt = 1:nbplt
hplt = dyn_figure(options_.nodisplay,'Name',figurename);
if TeX
TeXNAMES = [];
@@ -73,7 +73,7 @@ for plt = 1:nbplt,
dyn_saveas(hplt,[M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format);
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'\\begin{figure}[H]\n');
- for jj = 1:nstar0,
+ for jj = 1:nstar0
fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
end
fprintf(fidTeX,'\\centering\n');
diff --git a/matlab/plot_shock_decomposition.m b/matlab/plot_shock_decomposition.m
index 81602d059..78488d6c6 100644
--- a/matlab/plot_shock_decomposition.m
+++ b/matlab/plot_shock_decomposition.m
@@ -38,7 +38,8 @@ if size(varlist,1) == 0
varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
end
-[i_var,nvar] = varlist_indices(varlist,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
% number of variables
endo_nbr = M_.endo_nbr;
@@ -54,7 +55,7 @@ fig_name='';
% steadystate=0;
% write_xls=0;
-if isfield(options_.plot_shock_decomp,'expand'), % private trap for uimenu calls
+if isfield(options_.plot_shock_decomp,'expand') % private trap for uimenu calls
expand=options_.plot_shock_decomp.expand;
else
expand=0;
@@ -71,15 +72,15 @@ forecast_ = options_.shock_decomp.forecast;
steadystate = options_.plot_shock_decomp.steadystate;
write_xls = options_.plot_shock_decomp.write_xls;
-if vintage_,
+if vintage_
forecast_ = min(forecast_,options_.nobs-vintage_);
end
initial_date = options_.initial_date;
-if isfield(options_.plot_shock_decomp,'q2a'), % private trap for aoa calls
+if isfield(options_.plot_shock_decomp,'q2a') % private trap for aoa calls
q2a=options_.plot_shock_decomp.q2a;
- if isstruct(q2a) && isempty(fieldnames(q2a)),
+ if isstruct(q2a) && isempty(fieldnames(q2a))
q2a=0;
end
else
@@ -87,11 +88,11 @@ else
end
switch realtime_
-
+
case 0
z = oo_.shock_decomposition;
fig_name1=fig_name;
-
+
case 1 % realtime
if vintage_
z = oo_.realtime_shock_decomposition.(['time_' int2str(vintage_)]);
@@ -100,7 +101,7 @@ switch realtime_
z = oo_.realtime_shock_decomposition.pool;
fig_name1=[fig_name ' realtime (rolling)'];
end
-
+
case 2 % conditional
if vintage_
z = oo_.realtime_conditional_shock_decomposition.(['time_' int2str(vintage_)]);
@@ -110,7 +111,7 @@ switch realtime_
z = oo_.conditional_shock_decomposition.pool;
fig_name1=[fig_name ' 1-step ahead conditional forecast (rolling)'];
end
-
+
case 3 % forecast
if vintage_
z = oo_.realtime_forecast_shock_decomposition.(['time_' int2str(vintage_)]);
@@ -125,12 +126,12 @@ end
steady_state = oo_.steady_state;
if isequal(type,'aoa') && isstruct(q2a) && realtime_
- if isempty(initial_date),
+ if isempty(initial_date)
t0=1;
initial_date = dates('1Y');
else
initial_date0 = dates([int2str(initial_date.time(1)) 'Y']);
- if initial_date.time(2)==1,
+ if initial_date.time(2)==1
t0=1;
initial_date1=initial_date0;
else
@@ -141,25 +142,25 @@ if isequal(type,'aoa') && isstruct(q2a) && realtime_
t0=min(options_.plot_shock_decomp.save_realtime);
ini1 = initial_date+t0-1;
t0=t0+(4-ini1.time(2));
- if ~isfield(q2a,'var_type'), % private trap for aoa calls
+ if ~isfield(q2a,'var_type') % private trap for aoa calls
q2a.var_type=1;
end
- if ~isfield(q2a,'islog'), % private trap for aoa calls
+ if ~isfield(q2a,'islog') % private trap for aoa calls
q2a.islog=0;
end
- if ~isfield(q2a,'GYTREND0'), % private trap for aoa calls
+ if ~isfield(q2a,'GYTREND0') % private trap for aoa calls
q2a.GYTREND0=0;
end
- if ~isfield(q2a,'aux'), % private trap for aoa calls
+ if ~isfield(q2a,'aux') % private trap for aoa calls
q2a.aux=0;
end
- if ~isfield(q2a,'cumfix'), % private trap for aoa calls
+ if ~isfield(q2a,'cumfix') % private trap for aoa calls
q2a.cumfix=1;
end
- if ~isfield(q2a,'plot'), % private trap for aoa calls
+ if ~isfield(q2a,'plot') % private trap for aoa calls
q2a.plot=1; % growth rate
end
-
+
% if isstruct(q2a.aux) && ischar(q2a.aux.y)
% opts=options_;
% opts.plot_shock_decomp.type='qoq';
@@ -188,7 +189,7 @@ if options_.plot_shock_decomp.use_shock_groups
ngroups = length(shock_ind);
fig_name=[fig_name ' group ' options_.plot_shock_decomp.use_shock_groups];
shock_names = shock_ind;
- for i=1:ngroups,
+ for i=1:ngroups
shock_names{i} = (shock_groups.(shock_ind{i}).label);
end
zz = zeros(endo_nbr,ngroups+2,gend);
@@ -205,9 +206,9 @@ if options_.plot_shock_decomp.use_shock_groups
shock_groups.(['group' int2str(ngroups+1)]).label = 'Others';
shock_groups.(['group' int2str(ngroups+1)]).shocks = cellstr(M_.exo_names(find(~ismember([1:M_.exo_nbr],kcum)),:))';
M_.shock_groups.(options_.plot_shock_decomp.use_shock_groups)=shock_groups;
- if any(any(zothers)),
+ if any(any(zothers))
shock_names = [shock_names; {'Others + Initial Values'}];
- end
+ end
zz(:,ngroups+1,:) = sum(z(:,1:nshocks+1,:),2);
zz(:,ngroups+2,:) = z(:,nshocks+2,:);
z = zz;
@@ -221,7 +222,7 @@ MAP = distinguishable_colors(size(z,2)-1,'w',func);
MAP(end,:) = [0.7 0.7 0.7];
% MAP = [MAP; [0.7 0.7 0.7]; [0.3 0.3 0.3]];
-if isempty(options_.plot_shock_decomp.colormap),
+if isempty(options_.plot_shock_decomp.colormap)
options_.plot_shock_decomp.colormap = MAP;
end
@@ -229,7 +230,7 @@ switch type
case '' % default
- case 'qoq'
+ case 'qoq'
case 'yoy'
z=z(:,:,1:end-3)+z(:,:,2:end-2)+z(:,:,3:end-1)+z(:,:,4:end);
@@ -239,15 +240,15 @@ switch type
initial_date = dates('1Q4');
end
steady_state = 4*steady_state;
-
+
case 'aoa'
- if isempty(initial_date),
+ if isempty(initial_date)
t0=4;
initial_date = dates('1Y');
else
initial_date0 = dates([int2str(initial_date.time(1)) 'Y']);
- if initial_date.time(2)==1,
+ if initial_date.time(2)==1
t0=1;
initial_date1=initial_date0;
else
@@ -255,27 +256,27 @@ switch type
initial_date1=initial_date0+1;
end
end
- if isstruct(q2a)
+ if isstruct(q2a)
if realtime_ == 0
- if ~isfield(q2a,'var_type'), % private trap for aoa calls
+ if ~isfield(q2a,'var_type') % private trap for aoa calls
q2a.var_type=1;
end
- if ~isfield(q2a,'islog'), % private trap for aoa calls
+ if ~isfield(q2a,'islog') % private trap for aoa calls
q2a.islog=0;
end
- if ~isfield(q2a,'GYTREND0'), % private trap for aoa calls
+ if ~isfield(q2a,'GYTREND0') % private trap for aoa calls
q2a.GYTREND0=0;
end
- if ~isfield(q2a,'aux'), % private trap for aoa calls
+ if ~isfield(q2a,'aux') % private trap for aoa calls
q2a.aux=0;
end
- if ~isfield(q2a,'cumfix'), % private trap for aoa calls
+ if ~isfield(q2a,'cumfix') % private trap for aoa calls
q2a.cumfix=1;
end
- if ~isfield(q2a,'plot'), % private trap for aoa calls
+ if ~isfield(q2a,'plot') % private trap for aoa calls
q2a.plot=1; % growth rate
end
-
+
if isstruct(q2a.aux) && ischar(q2a.aux.y)
opts=options_;
opts.plot_shock_decomp.type='qoq';
@@ -300,15 +301,15 @@ switch type
initial_date = initial_date0;
z=z(:,:,t0:4:end);
end
-
+
if ~isempty(options_.plot_shock_decomp.plot_init_date)
options_.plot_shock_decomp.plot_init_date = dates([int2str(options_.plot_shock_decomp.plot_init_date.time(1)) 'Y']);
end
if ~isempty(options_.plot_shock_decomp.plot_end_date)
options_.plot_shock_decomp.plot_end_date = dates([int2str(options_.plot_shock_decomp.plot_end_date.time(1)) 'Y']);
end
-
-
+
+
otherwise
error('plot_shock_decomposition:: Wrong type')
@@ -340,7 +341,7 @@ z = z(:,:,a:b);
options_.plot_shock_decomp.fig_name=fig_name;
options_.plot_shock_decomp.orig_varlist = varlist;
-if detail_plot,
+if detail_plot
graph_decomp_detail(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_)
else
graph_decomp(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_);
diff --git a/matlab/pltorg.m b/matlab/pltorg.m
index 7f100e4b2..e7f680772 100644
--- a/matlab/pltorg.m
+++ b/matlab/pltorg.m
@@ -1,6 +1,6 @@
function [nbplt,nr,nc,lr,lc,nstar] = pltorg(number)
-% Copyright (C) 2004-2008 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -48,11 +48,11 @@ elseif number == 5
elseif number == 6
nbplt = 1;
nr = 3;
- nc = 2;
+ nc = 2;
elseif number == 7
nbplt = 1;
nr = 3;
- nc = 3;
+ nc = 3;
elseif number == 8
nbplt = 1;
nr = 3;
@@ -67,7 +67,7 @@ else
nr = nrstar;
nc = ncstar;
lr = nr;
- lc = nc;
+ lc = nc;
else
nbplt = ceil(number/nstar);
nr = nrstar;
@@ -90,10 +90,10 @@ else
lc = 2;
elseif reste == 6
lr = 3;
- lc = 2;
+ lc = 2;
elseif reste == 7
lr = 3;
- lc = 3;
+ lc = 3;
elseif reste == 8
lr = 3;
lc = 3;
diff --git a/matlab/pm3.m b/matlab/pm3.m
index d5502d29b..695b641d8 100644
--- a/matlab/pm3.m
+++ b/matlab/pm3.m
@@ -7,7 +7,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
% n2 [scalar] size of second dimension of moment matrix
% ifil [scalar] number of moment files to load
% B [scalar] number of subdraws
-% tit1 [string] Figure title
+% tit1 [string] Figure title
% tit2 [string] not used
% tit3 [string] Save name for figure
% tit_tex [cell array] TeX-Names for Variables
@@ -24,7 +24,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
% See also the comment in posterior_sampler.m funtion.
-% Copyright (C) 2007-2016 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -60,10 +60,10 @@ else
end
end
if options_.TeX
- if isempty(tit_tex),
+ if isempty(tit_tex)
tit_tex=names1;
end
-
+
varlist_TeX = [];
for i=1:nvar
if i==1
@@ -92,7 +92,7 @@ for file = 1:ifil
stock=loaded_file.stock;
if strcmp(var_type,'_filter_step_ahead')
if file==1 %on first run, initialize variable for storing filter_step_ahead
- stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead));
+ stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead));
stock1 = zeros(n1,n2,B);
end
filter_step_ahead_indicator=1;
@@ -321,13 +321,13 @@ if ~options_.nograph && ~options_.no_graph.posterior
if ~isoctave
% Commenting for testing!
- if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4,
+ if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4
fout = pm3_core(localVars,1,nvar,0);
-
+
% Parallel execution!
else
isRemoteOctave = 0;
- for indPC=1:length(options_.parallel),
+ for indPC=1:length(options_.parallel)
isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
end
if isRemoteOctave
@@ -342,7 +342,7 @@ if ~options_.nograph && ~options_.no_graph.posterior
else
% For the time being in Octave enviroment the pm3.m is executed only in
% serial modality, to avoid problem with the plots.
-
+
fout = pm3_core(localVars,1,nvar,0);
end
@@ -355,13 +355,12 @@ if ~options_.nograph && ~options_.no_graph.posterior
fprintf(fidTeX,' \n');
nvar0=cumsum(nvar0);
- i=0;
- for j=1:length(nvar0),
-
+ i=0;
+ for j=1:length(nvar0)
NAMES = [];
TEXNAMES = [];
nvar=nvar0(j);
- while i 10^(-6)
subplotnum = subplotnum+1;
diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m
index 2f925e5e3..881c4b423 100644
--- a/matlab/pm3_core.m
+++ b/matlab/pm3_core.m
@@ -3,7 +3,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
% PARALLEL CONTEXT
% Core functionality for pm3.m function, which can be parallelized.
-% INPUTS
+% INPUTS
% See the comment in posterior_sampler_core.m funtion.
% OUTPUTS
@@ -30,7 +30,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin<4,
+if nargin<4
whoiam=0;
end
@@ -66,7 +66,7 @@ figunumber = 0;
subplotnum = 0;
hh = dyn_figure(options_.nodisplay,'Name',[tit1 ' ' int2str(figunumber+1)]);
RemoteFlag = 0;
-if whoiam,
+if whoiam
if Parallel(ThisMatlab).Local ==0
RemoteFlag=1;
end
@@ -100,16 +100,16 @@ for i=fpar:nvar
set(gca,'yticklabel',yticklabels_new)
end
end
-
- if whoiam,
+
+ if whoiam
if Parallel(ThisMatlab).Local==0
DirectoryName = CheckPath('Output',M_.dname);
end
end
-
+
if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar
dyn_saveas(hh,[M_.dname '/Output/' M_.fname '_' name3 '_' deblank(tit3(i,:))],options_.nodisplay,options_.graph_format);
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName = [OutputFileName; {[M_.dname, filesep, 'Output',filesep], [M_.fname '_' name3 '_' deblank(tit3(i,:)) '.*']}];
end
subplotnum = 0;
@@ -118,17 +118,17 @@ for i=fpar:nvar
hh = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]);
end
end
-
- if whoiam,
+
+ if whoiam
% waitbarString = [ 'Variable ' int2str(i) '/' int2str(nvar) ' done.'];
% fMessageStatus((i-fpar+1)/(nvar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
dyn_waitbar((i-fpar+1)/(nvar-fpar+1),h);
end
-
-
+
+
end
-if whoiam,
+if whoiam
dyn_waitbar_close(h);
end
myoutput.OutputFileName=OutputFileName;
diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m
index faa117c03..fa365b607 100644
--- a/matlab/posterior_analysis.m
+++ b/matlab/posterior_analysis.m
@@ -1,5 +1,5 @@
-function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)
-% Copyright (C) 2008-2012 Dynare Team
+function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -55,14 +55,14 @@ switch type
dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'posterior');
end
oo_ = covariance_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
- vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
+ vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
case 'decomposition'
if nargin==narg1
[nvar,vartan,NumberOfFiles] = ...
dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'posterior');
end
oo_ = variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
- M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
+ M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
case 'correlation'
if nargin==narg1
[nvar,vartan,NumberOfFiles] = ...
@@ -76,7 +76,7 @@ switch type
dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'posterior');
end
oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
- arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
+ arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
otherwise
disp('Not yet implemented')
end
\ No newline at end of file
diff --git a/matlab/posterior_moments.m b/matlab/posterior_moments.m
index beb1b0a41..915827328 100644
--- a/matlab/posterior_moments.m
+++ b/matlab/posterior_moments.m
@@ -11,17 +11,17 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density]
% post_mean [double] Scalar, posterior mean.
% post_median [double] Scalar, posterior median.
% post_var [double] Scalar, posterior variance.
-% hpd_interval [double] Vector (1*2), Highest Probability Density interval
+% hpd_interval [double] Vector (1*2), Highest Probability Density interval
% post_deciles [double] Vector (9*1), deciles of the posterior distribution.
-% density [double] Matrix (n*2), non parametric estimate of the posterior density. First and second
-% columns are respectively abscissa and ordinate coordinates.
-%
+% density [double] Matrix (n*2), non parametric estimate of the posterior density. First and second
+% columns are respectively abscissa and ordinate coordinates.
+%
% SPECIAL REQUIREMENTS
-% Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m
+% Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m
% kernel_density_estimate.m.
%
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -41,7 +41,7 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density]
if nargin<4
number_of_grid_points = 2^9; % 2^9 = 512 !... Must be a power of two.
bandwidth = 0; % Rule of thumb optimal bandwidth parameter.
- kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton.
+ kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton.
else
number_of_grid_points = kernel_options.gridpoints;
bandwidth = kernel_options.bandwidth;
@@ -69,7 +69,7 @@ if hpd_draws>2
[kmin,idx] = min(kk);
hpd_interval = [xx(idx) xx(idx)+kmin];
else
- hpd_interval=NaN(1,2);
+ hpd_interval=NaN(1,2);
end
if length(xx)>9
post_deciles = xx([round(0.1*number_of_draws) ...
diff --git a/matlab/posterior_sampler.m b/matlab/posterior_sampler.m
index be512d140..70f7b5de9 100644
--- a/matlab/posterior_sampler.m
+++ b/matlab/posterior_sampler.m
@@ -1,8 +1,8 @@
function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
% function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
-% Random Walk Metropolis-Hastings algorithm.
-%
-% INPUTS
+% Random Walk Metropolis-Hastings algorithm.
+%
+% INPUTS
% o TargetFun [char] string specifying the name of the objective
% function (posterior kernel).
% o ProposalFun [char] string specifying the name of the proposal
@@ -10,7 +10,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
% o xparam1 [double] (p*1) vector of parameters to be estimated (initial values).
% o sampler_options structure
% .invhess [double] (p*p) matrix, posterior covariance matrix (at the mode).
-% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
+% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
% o dataset_ data structure
% o dataset_info dataset info structure
% o options_ options structure
@@ -27,7 +27,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
% in parallel. The code suitable to be executed in
% parallel on multi core or cluster machine (in general a 'for' cycle)
% has been removed from this function and been placed in the posterior_sampler_core.m funtion.
-%
+%
% The DYNARE parallel packages comprise a i) set of pairs of Matlab functions that can be executed in
% parallel and called name_function.m and name_function_core.m and ii) a second set of functions used
% to manage the parallel computations.
@@ -37,7 +37,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
% Then the comments write here can be used for all the other pairs of
% parallel functions and also for management functions.
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -107,7 +107,7 @@ localVars = struct('TargetFun', TargetFun, ...
'oo_', oo_,...
'varargin',[]);
-if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings');
+if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings')
localVars.options_.silent_optimizer=1; %locally set optimizer to silent mode
if ~isempty(sampler_options.optim_opt)
localVars.options_.optim_opt=sampler_options.optim_opt; %locally set options for optimizer
@@ -117,31 +117,31 @@ end
% User doesn't want to use parallel computing, or wants to compute a
% single chain compute sequentially.
-if isnumeric(options_.parallel) || (nblck-fblck)==0,
+if isnumeric(options_.parallel) || (nblck-fblck)==0
fout = posterior_sampler_core(localVars, fblck, nblck, 0);
record = fout.record;
- % Parallel in Local or remote machine.
-else
+ % Parallel in Local or remote machine.
+else
% Global variables for parallel routines.
globalVars = struct();
% which files have to be copied to run remotely
NamFileInput(1,:) = {'',[ModelName '_static.m']};
NamFileInput(2,:) = {'',[ModelName '_dynamic.m']};
NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']};
- if options_.steadystate_flag,
- if options_.steadystate_flag == 1,
+ if options_.steadystate_flag
+ if options_.steadystate_flag == 1
NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
else
NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']};
end
end
- if (options_.load_mh_file~=0) && any(fline>1) ,
+ if (options_.load_mh_file~=0) && any(fline>1)
NamFileInput(length(NamFileInput)+1,:)={[M_.dname '/metropolis/'],[ModelName '_mh' int2str(NewFile(1)) '_blck*.mat']};
end
% from where to get back results
% NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'};
[fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, fblck, nblck,NamFileInput,'posterior_sampler_core', localVars, globalVars, options_.parallel_info);
- for j=1:totCPU,
+ for j=1:totCPU
offset = sum(nBlockPerCPU(1:j-1))+fblck-1;
record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j)));
record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:);
diff --git a/matlab/posterior_sampler_core.m b/matlab/posterior_sampler_core.m
index d88ae742a..b753391b4 100644
--- a/matlab/posterior_sampler_core.m
+++ b/matlab/posterior_sampler_core.m
@@ -31,12 +31,12 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl
%
% SPECIAL REQUIREMENTS.
% None.
-%
+%
% PARALLEL CONTEXT
% See the comments in the posterior_sampler.m funtion.
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -53,7 +53,7 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin<4,
+if nargin<4
whoiam=0;
end
@@ -108,7 +108,7 @@ end
%
sampler_options.xparam1 = xparam1;
-if ~isempty(d),
+if ~isempty(d)
sampler_options.proposal_covariance_Cholesky_decomposition = d*diag(bayestopt_.jscale);
%store information for load_mh_file
record.ProposalCovariance=d;
@@ -117,7 +117,7 @@ end
block_iter=0;
-for curr_block = fblck:nblck,
+for curr_block = fblck:nblck
LastSeeds=[];
block_iter=block_iter+1;
try
@@ -132,9 +132,9 @@ for curr_block = fblck:nblck,
set_dynare_seed(options_.DynareRandomStreams.seed+curr_block);
end
% Set the state of the RNG
- set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal);
+ set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal);
catch
- % If the state set by master is incompatible with the slave, we only reseed
+ % If the state set by master is incompatible with the slave, we only reseed
set_dynare_seed(options_.DynareRandomStreams.seed+curr_block);
end
if (options_.load_mh_file~=0) && (fline(curr_block)>1) && OpenOldFile(curr_block) %load previous draws and likelihood
@@ -164,9 +164,9 @@ for curr_block = fblck:nblck,
feval_this_file = 0;
draw_index_current_file = fline(curr_block); %get location of first draw in current block
draw_iter = 1;
-
+
while draw_iter <= nruns(curr_block)
-
+
[par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun, last_draw(curr_block,:), last_posterior(curr_block), sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
x2(draw_index_current_file,:) = par;
@@ -192,7 +192,7 @@ for curr_block = fblck:nblck,
end
if (draw_index_current_file == InitSizeArray(curr_block)) || (draw_iter == nruns(curr_block)) % Now I save the simulations, either because the current file is full or the chain is done
[LastSeeds.(['file' int2str(NewFile(curr_block))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_block))]).Normal] = get_dynare_random_generator_state();
- if save_tmp_file,
+ if save_tmp_file
delete([BaseName '_mh_tmp_blck' int2str(curr_block) '.mat']);
end
save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2','LastSeeds');
diff --git a/matlab/posterior_sampler_initialization.m b/matlab/posterior_sampler_initialization.m
index 0292b010d..b8b65e8b8 100644
--- a/matlab/posterior_sampler_initialization.m
+++ b/matlab/posterior_sampler_initialization.m
@@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d, bayestopt_] = ...
% metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
% Metropolis-Hastings initialization.
-%
-% INPUTS
+%
+% INPUTS
% o TargetFun [char] string specifying the name of the objective
% function (posterior kernel).
% o xparam1 [double] (p*1) vector of parameters to be estimated (initial values).
% o vv [double] (p*p) matrix, posterior covariance matrix (at the mode).
-% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
+% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
% o dataset_ data structure
% o dataset_info dataset info structure
% o options_ options structure
@@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% o estim_params_ estimated parameters structure
% o bayestopt_ estimation options structure
% o oo_ outputs structure
-%
-% OUTPUTS
+%
+% OUTPUTS
% o ix2 [double] (NumberOfBlocks*npar) vector of starting points for different chains
% o ilogpo2 [double] (NumberOfBlocks*1) vector of initial posterior values for different chains
% o ModelName [string] name of the mod-file
% o MetropolisFolder [string] path to the Metropolis subfolder
-% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
-% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
+% o FirstBlock [scalar] number of the first MH chain to be run (not equal to 1 in case of recovery)
+% o FirstLine [double] (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
% o npar [scalar] number of parameters estimated
-% o NumberOfBlocks [scalar] Number of MCM chains requested
-% o nruns [double] (NumberOfBlocks*1) number of draws in each chain
+% o NumberOfBlocks [scalar] Number of MCM chains requested
+% o nruns [double] (NumberOfBlocks*1) number of draws in each chain
% o NewFile [scalar] (NumberOfBlocks*1) vector storing the number
% of the first MH-file to created for each chain when saving additional
% draws
@@ -38,7 +38,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -58,7 +58,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
%Initialize outputs
ix2 = [];
ilogpo2 = [];
-ModelName = [];
+ModelName = [];
MetropolisFolder = [];
FirstBlock = [];
FirstLine = [];
@@ -112,7 +112,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,[' Number of blocks...............: ' int2str(NumberOfBlocks) '\n']);
fprintf(fidlog,[' Number of simulations per block: ' int2str(nruns(1)) '\n']);
fprintf(fidlog,' \n');
- if isempty(d),
+ if isempty(d)
prior_draw(bayestopt_,options_.prior_trunc);
end
% Find initial values for the NumberOfBlocks chains...
@@ -127,12 +127,12 @@ if ~options_.load_mh_file && ~options_.mh_recover
init_iter = 0;
trial = 1;
while validate == 0 && trial <= 10
- if isempty(d),
+ if isempty(d)
candidate = prior_draw();
else
candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar);
end
- if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
+ if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
ix2(j,:) = candidate;
ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
if ~isfinite(ilogpo2(j)) % if returned log-density is
@@ -175,7 +175,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
else% Case 2: one chain (we start from the posterior mode)
fprintf(fidlog,[' Initial values of the parameters:\n']);
candidate = transpose(xparam1(:));%
- if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
+ if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
ix2 = candidate;
ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
disp('Estimation::mcmc: Initialization at the posterior mode.')
@@ -234,7 +234,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
fprintf(fidlog,[' Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']);
fprintf(fidlog,[' Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']);
fprintf(fidlog,['\n']);
- for j = 1:NumberOfBlocks,
+ for j = 1:NumberOfBlocks
fprintf(fidlog,[' Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']);
for i=1:length(record.InitialSeeds(j).Normal)
fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Normal(i)') '\n']);
@@ -243,7 +243,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
for i=1:length(record.InitialSeeds(j).Unifor)
fprintf(fidlog,[' ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']);
end
- end,
+ end
fprintf(fidlog,' \n');
fclose(fidlog);
elseif options_.load_mh_file && ~options_.mh_recover
@@ -293,7 +293,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns);
- AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
+ AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles;
record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
record.MhDraws(end,1) = nruns(1);
@@ -312,15 +312,15 @@ elseif options_.mh_recover
load_last_mh_history_file(MetropolisFolder, ModelName);
NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
options_.mh_nblck = NumberOfBlocks;
-
+
%% check consistency of options
if record.MhDraws(end,1)~=options_.mh_replic
fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n')
fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1))
options_.mh_replic=record.MhDraws(end,1);
nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
- end
-
+ end
+
if ~isnan(record.MAX_nruns(end,1)) %field exists
if record.MAX_nruns(end,1)~=MAX_nruns
fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n')
@@ -347,8 +347,8 @@ elseif options_.mh_recover
if OldMhExists
LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session.
LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions.
- %Test if the last mh files of the previous session were not full yet
- if LastLineNumberInThePreviousMh < MAX_nruns%not full
+ %Test if the last mh files of the previous session were not full yet
+ if LastLineNumberInThePreviousMh < MAX_nruns%not full
%store starting point if whole chain needs to be redone
NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1);
@@ -368,7 +368,7 @@ elseif options_.mh_recover
end
[d,bayestopt_]=set_proposal_density_to_previous_value(record,options_,bayestopt_);
%% Now find out what exactly needs to be redone
- % 1. Check if really something needs to be done
+ % 1. Check if really something needs to be done
% How many mh files should we have ?
ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
@@ -378,7 +378,7 @@ elseif options_.mh_recover
% Quit if no crashed mcmc chain can be found as there are as many files as expected
if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles)
disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!')
- disp(' You have to edit the mod file and remove the mh_recover option')
+ disp(' You have to edit the mod file and remove the mh_recover option')
disp(' in the estimation command')
error('Estimation::mcmc: mh_recover option not required!')
end
@@ -401,15 +401,15 @@ elseif options_.mh_recover
end
FirstBlock = FirstBlock+1;
end
-
- %% 3. Overwrite default settings for
+
+ %% 3. Overwrite default settings for
% How many mh-files are saved in this block?
NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
% Check whether last present file is a file included in the last MCMC run
- if ~LastFileFullIndicator
+ if ~LastFileFullIndicator
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
- loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
+ loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
%check whether that last file was filled
if size(loaded_results.x2,1)==MAX_nruns %file is full
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
@@ -419,20 +419,20 @@ elseif options_.mh_recover
ExistingDrawsInLastMCFile=0;
end
end
- elseif LastFileFullIndicator
+ elseif LastFileFullIndicator
ExistingDrawsInLastMCFile=0;
if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC
NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
end
end
% % Correct the number of saved mh files if the crashed Metropolis was not the first session (so
- % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
- % % of the current session).
+ % % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain
+ % % of the current session).
% if OldMhExists
% NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
% end
% NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
-
+
% Correct initial conditions.
if NumberOfSavedMhFilesInTheCrashedBlck mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) )
@@ -136,7 +136,7 @@ switch posterior_sampling_method
current_draw(indices(blocks==block_iter,1))=proposed_par;
last_posterior=logpost;
accepted_draws_counter =accepted_draws_counter +1;
- else %no updating
+ else %no updating
%do nothing, keep old value
end
end
diff --git a/matlab/print_bytecode_dynamic_model.m b/matlab/print_bytecode_dynamic_model.m
index f4e381ed1..af5eb0115 100644
--- a/matlab/print_bytecode_dynamic_model.m
+++ b/matlab/print_bytecode_dynamic_model.m
@@ -1,17 +1,17 @@
function print_bytecode_dynamic_model()
% function print_bytecode_dynamic_model()
% print the model and jacobian from the bytecode format for the dynamic model
-%
+%
% INPUTS
% none
-%
+%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/print_bytecode_static_model.m b/matlab/print_bytecode_static_model.m
index bc216c70d..ece12428b 100644
--- a/matlab/print_bytecode_static_model.m
+++ b/matlab/print_bytecode_static_model.m
@@ -1,17 +1,17 @@
function print_bytecode_static_model()
% function print_bytecode_static_model()
% print the model and jacobian from the bytecode format for the static model
-%
+%
% INPUTS
% none
-%
+%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/print_info.m b/matlab/print_info.m
index 3185e16bf..76ec1d115 100644
--- a/matlab/print_info.m
+++ b/matlab/print_info.m
@@ -2,7 +2,7 @@ function print_info(info, noprint, DynareOptions)
% Prints error messages
%
% INPUTS
-% info [double] vector returned by resol.m
+% info [double] vector returned by resol.m
% noprint [integer] equal to 0 if the error message has to be printed.
% DynareOptions [structure] --> options_
% OUTPUTS
@@ -11,7 +11,7 @@ function print_info(info, noprint, DynareOptions)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2005-2013 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -78,7 +78,7 @@ if ~noprint
if DynareOptions.linear
error(['Impossible to find the steady state. Either the model' ...
' doesn''t have a steady state or there are an infinity of steady states.' ...
- ' Check whether your model is truly linear or whether there is a mistake in linearization.'])
+ ' Check whether your model is truly linear or whether there is a mistake in linearization.'])
else
error(['Impossible to find the steady state. Either the model' ...
' doesn''t have a steady state, there are an infinity of steady states,' ...
@@ -117,7 +117,7 @@ if ~noprint
case 49
error('The model violates one (many) endogenous prior restriction(s)')
case 50
- error('Likelihood is Inf')
+ error('Likelihood is Inf')
case 51
fprintf('\n The dsge_prior_weight is dsge_var=%5.4f, but must be at least %5.4f for the prior to be proper.\n',info(2),info(3));
error('You are estimating a DSGE-VAR model, but the value of the dsge prior weight is too low!')
diff --git a/matlab/print_moments_implied_prior.m b/matlab/print_moments_implied_prior.m
index 496e3bf86..94d14cb02 100644
--- a/matlab/print_moments_implied_prior.m
+++ b/matlab/print_moments_implied_prior.m
@@ -1,9 +1,9 @@
function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv)
% This routine prints in the command window some descriptive statistics
-% about the endogenous variables implied prior moments.
+% about the endogenous variables implied prior moments.
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m
index d84e69a9c..b1f1a13bc 100644
--- a/matlab/print_table_prior.m
+++ b/matlab/print_table_prior.m
@@ -1,8 +1,8 @@
function print_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo)
-% This routine prints in the command window some descriptive statistics about the prior distribution.
+% This routine prints in the command window some descriptive statistics about the prior distribution.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -111,7 +111,7 @@ for i=1:size(BayesInfo.name,1)
UpperBound, ...
PriorIntervals.lb(i), ...
PriorIntervals.ub(i) );
- T2 = strvcat(T2, str);
+ T2 = strvcat(T2, str);
end
T1 = strvcat(T1, l1);
diff --git a/matlab/printline.m b/matlab/printline.m
index c60d0906a..29d4ec1c3 100644
--- a/matlab/printline.m
+++ b/matlab/printline.m
@@ -1,16 +1,16 @@
function varargout = printline(n, s, fid)
% This function print a line formed by replicating a symbol s.
%
-% INPUTS
+% INPUTS
%
% n [integer] Length of the printed line
% s [char] Symbol used to draw the line (+, -, =, ...)
% f [integer] file id returned by fopen
-%
-% OUTPUTS
+%
+% OUTPUTS
% None
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -25,7 +25,7 @@ function varargout = printline(n, s, fid)
% 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 .
+% along with Dynare. If not, see .
if nargin<3
f = 1;
diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m
index fd79414e5..5820f69c3 100644
--- a/matlab/prior_analysis.m
+++ b/matlab/prior_analysis.m
@@ -1,5 +1,5 @@
function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_,estim_params_)
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -56,7 +56,7 @@ switch type
dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'prior');
end
oo_ = covariance_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,...
- vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
+ vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
case 'decomposition'
if nargin==narg1
[nvar,vartan,NumberOfFiles] = ...
diff --git a/matlab/prior_bounds.m b/matlab/prior_bounds.m
index 2bf1173ed..56ef1eb32 100644
--- a/matlab/prior_bounds.m
+++ b/matlab/prior_bounds.m
@@ -40,14 +40,14 @@ function bounds = prior_bounds(bayestopt, prior_trunc)
%
% INPUTS
% bayestopt [structure] characterizing priors (shape, mean, p1..p4)
-%
+%
% OUTPUTS
% bounds [double] structure specifying prior bounds (lb and ub fields)
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m
index 4eb628df9..c97eaeefd 100644
--- a/matlab/prior_draw.m
+++ b/matlab/prior_draw.m
@@ -2,10 +2,10 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
% This function generate one draw from the joint prior distribution and
% allows sampling uniformly from the prior support (uniform==1 when called with init==1)
-%
-% INPUTS
-% o init [integer] scalar equal to:
-% 1: first call to set up persistent variables
+%
+% INPUTS
+% o init [integer] scalar equal to:
+% 1: first call to set up persistent variables
% describing the prior
% 0: subsequent call to get prior
% draw
@@ -13,8 +13,8 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
% 1: sample uniformly from prior
% support (overwrites prior shape used for sampling within this function)
% 0: sample from joint prior distribution
-%
-% OUTPUTS
+%
+% OUTPUTS
% o pdraw [double] 1*npar vector, draws from the joint prior density.
%
%
@@ -25,8 +25,8 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
% NOTE 2. A given draw from the joint prior distribution does not satisfy BK conditions a priori.
% NOTE 3. This code relies on bayestopt_ as created in the base workspace
% by the preprocessor (or as updated in subsequent pieces of code and handed to the base workspace)
-%
-% Copyright (C) 2006-2016 Dynare Team
+%
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -108,9 +108,9 @@ if nargin>0
end
if uniform_draws
- pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index);
+ pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index);
out_of_bound = find( (pdraw(uniform_index)'>ub(uniform_index)) | (pdraw(uniform_index)'ub(uniform_index)) | (pdraw(uniform_index)'ub(gaussian_index)) | (pdraw(gaussian_index)'ub(gaussian_index)) | (pdraw(gaussian_index)'ub(gamma_index)) | (pdraw(gamma_index)'ub(gamma_index)) | (pdraw(gamma_index)'ub(beta_index)) | (pdraw(beta_index)'ub(beta_index)) | (pdraw(beta_index)'ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'ub(weibull_index)) | (pdraw(weibull_index)'ub(weibull_index)) | (pdraw(weibull_index)' MAX_nsmoo || b == B),
+ if run_smoother && (irun(1) > MAX_nsmoo || b == B)
stock = stock_smooth(:,:,1:irun(1)-1);
ifil(1) = ifil(1) + 1;
save([DirectoryName '/' M_.fname '_smooth' int2str(ifil(1)) '.mat'],'stock');
stock = stock_update(:,:,1:irun(1)-1);
save([DirectoryName '/' M_.fname '_update' int2str(ifil(1)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_smooth = [OutputFileName_smooth; {[DirectoryName filesep], [M_.fname '_smooth' int2str(ifil(1)) '.mat']}];
OutputFileName_update = [OutputFileName_update; {[DirectoryName filesep], [M_.fname '_update' int2str(ifil(1)) '.mat']}];
end
@@ -363,7 +363,7 @@ for b=fpar:B
stock = stock_innov(:,:,1:irun(2)-1);
ifil(2) = ifil(2) + 1;
save([DirectoryName '/' M_.fname '_inno' int2str(ifil(2)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_inno = [OutputFileName_inno; {[DirectoryName filesep], [M_.fname '_inno' int2str(ifil(2)) '.mat']}];
end
irun(2) = 1;
@@ -373,7 +373,7 @@ for b=fpar:B
stock = stock_error(:,:,1:irun(3)-1);
ifil(3) = ifil(3) + 1;
save([DirectoryName '/' M_.fname '_error' int2str(ifil(3)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_error = [OutputFileName_error; {[DirectoryName filesep], [M_.fname '_error' int2str(ifil(3)) '.mat']}];
end
irun(3) = 1;
@@ -383,7 +383,7 @@ for b=fpar:B
stock = stock_filter_step_ahead(:,:,:,1:irun(4)-1);
ifil(4) = ifil(4) + 1;
save([DirectoryName '/' M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_filter_step_ahead = [OutputFileName_filter_step_ahead; {[DirectoryName filesep], [M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat']}];
end
irun(4) = 1;
@@ -395,7 +395,7 @@ for b=fpar:B
stock_ys = stock_ys(1:irun(5)-1,:);
ifil(5) = ifil(5) + 1;
save([DirectoryName '/' M_.fname '_param' int2str(ifil(5)) '.mat'],'stock','stock_logpo','stock_ys');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_param = [OutputFileName_param; {[DirectoryName filesep], [M_.fname '_param' int2str(ifil(5)) '.mat']}];
end
irun(5) = 1;
@@ -405,7 +405,7 @@ for b=fpar:B
stock = stock_forcst_mean(:,:,1:irun(6)-1);
ifil(6) = ifil(6) + 1;
save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil(6)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_forc_mean = [OutputFileName_forc_mean; {[DirectoryName filesep], [M_.fname '_forc_mean' int2str(ifil(6)) '.mat']}];
end
irun(6) = 1;
@@ -415,39 +415,39 @@ for b=fpar:B
stock = stock_forcst_point(:,:,1:irun(7)-1);
ifil(7) = ifil(7) + 1;
save([DirectoryName '/' M_.fname '_forc_point' int2str(ifil(7)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_forc_point = [OutputFileName_forc_point; {[DirectoryName filesep], [M_.fname '_forc_point' int2str(ifil(7)) '.mat']}];
end
irun(7) = 1;
end
-
+
if run_smoother && filter_covariance && (irun(8) > MAX_filter_covariance || b == B)
stock = stock_filter_covariance(:,:,:,1:irun(8)-1);
ifil(8) = ifil(8) + 1;
save([DirectoryName '/' M_.fname '_filter_covar' int2str(ifil(8)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_filter_covar = [OutputFileName_filter_covar; {[DirectoryName filesep], [M_.fname '_filter_covar' int2str(ifil(8)) '.mat']}];
end
irun(8) = 1;
end
-
+
irun_index=9;
if run_smoother && (irun(irun_index) > MAX_n_trend_coeff || b == B)
stock = stock_trend_coeff(:,1:irun(irun_index)-1);
ifil(irun_index) = ifil(irun_index) + 1;
save([DirectoryName '/' M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_trend_coeff = [OutputFileName_trend_coeff; {[DirectoryName filesep], [M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat']}];
end
irun(irun_index) = 1;
end
-
+
irun_index=10;
if run_smoother && (irun(irun_index) > MAX_n_smoothed_constant || b == B)
stock = stock_smoothed_constant(:,:,1:irun(irun_index)-1);
ifil(irun_index) = ifil(irun_index) + 1;
save([DirectoryName '/' M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_smoothed_constant = [OutputFileName_smoothed_constant; {[DirectoryName filesep], [M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat']}];
end
irun(irun_index) = 1;
@@ -458,29 +458,29 @@ for b=fpar:B
stock = stock_smoothed_trend(:,:,1:irun(irun_index)-1);
ifil(irun_index) = ifil(irun_index) + 1;
save([DirectoryName '/' M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_smoothed_trend = [OutputFileName_smoothed_trend; {[DirectoryName filesep], [M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat']}];
end
irun(irun_index) = 1;
end
-
+
irun_index=12;
if run_smoother && horizon && ~isequal(M_.H,0) && (irun(irun_index) > MAX_nforc_ME || b == B)
stock = stock_forcst_point_ME(:,:,1:irun(irun_index)-1);
ifil(irun_index) = ifil(irun_index) + 1;
save([DirectoryName '/' M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_forc_point_ME = [OutputFileName_forc_point_ME; {[DirectoryName filesep], [M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat']}];
end
irun(irun_index) = 1;
end
-
+
irun_index=13;
if run_smoother && smoothed_state_uncertainty && (irun(irun_index) > MAX_n_smoothed_state_uncertainty || b == B)
stock = stock_smoothed_uncert(:,:,:,1:irun(irun_index)-1);
ifil(irun_index) = ifil(irun_index) + 1;
save([DirectoryName '/' M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat'],'stock');
- if RemoteFlag==1,
+ if RemoteFlag==1
OutputFileName_state_uncert = [OutputFileName_state_uncert; {[DirectoryName filesep], [M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat']}];
end
irun(irun_index) = 1;
@@ -490,7 +490,7 @@ for b=fpar:B
end
myoutput.ifil=ifil;
-if RemoteFlag==1,
+if RemoteFlag==1
myoutput.OutputFileName = [OutputFileName_smooth;
OutputFileName_update;
OutputFileName_inno;
@@ -508,4 +508,3 @@ if RemoteFlag==1,
end
dyn_waitbar_close(h);
-
diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m
index 267563d8e..b49523634 100644
--- a/matlab/prior_sampler.m
+++ b/matlab/prior_sampler.m
@@ -13,7 +13,7 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2016 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/priordens.m b/matlab/priordens.m
index f760680cf..b988e7ea1 100644
--- a/matlab/priordens.m
+++ b/matlab/priordens.m
@@ -1,7 +1,7 @@
function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4, initialization) % --*-- Unitary tests --*--
% Computes a prior density for the structural parameters of DSGE models
%
-% INPUTS
+% INPUTS
% x [double] vector with n elements.
% pshape [integer] vector with n elements (bayestopt_.pshape).
% p6: [double] vector with n elements, first parameter of the prior distribution (bayestopt_.p6).
@@ -9,13 +9,13 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape,
% p3: [double] vector with n elements, lower bounds of the untruncated standard or generalized distribution
% p4: [double] vector with n elements, upper bound of the untruncated standard or generalized distribution
% initialization [integer] if 1: initialize persistent variables
-%
-% OUTPUTS
+%
+% OUTPUTS
% logged_prior_density [double] scalar, log of the prior density evaluated at x.
% info [double] error code for index of Inf-prior parameter
%
-% Copyright (C) 2003-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -89,12 +89,12 @@ d2lprior = 0.0;
if tt1
logged_prior_density = logged_prior_density + sum(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))) ;
if isinf(logged_prior_density)
- if nargout ==4
+ if nargout ==4
info=id1(isinf(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))));
end
return
end
- if nargout == 2,
+ if nargout == 2
[tmp, dlprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1));
elseif nargout == 3
[tmp, dlprior(id1), d2lprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1));
@@ -104,12 +104,12 @@ end
if tt2
logged_prior_density = logged_prior_density + sum(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))) ;
if isinf(logged_prior_density)
- if nargout ==4
+ if nargout ==4
info=id2(isinf(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))));
end
return
end
- if nargout == 2,
+ if nargout == 2
[tmp, dlprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2));
elseif nargout == 3
[tmp, dlprior(id2), d2lprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2));
@@ -118,7 +118,7 @@ end
if tt3
logged_prior_density = logged_prior_density + sum(lpdfnorm(x(id3),p6(id3),p7(id3))) ;
- if nargout == 2,
+ if nargout == 2
[tmp, dlprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3));
elseif nargout == 3
[tmp, dlprior(id3), d2lprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3));
@@ -128,12 +128,12 @@ end
if tt4
logged_prior_density = logged_prior_density + sum(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))) ;
if isinf(logged_prior_density)
- if nargout ==4
+ if nargout ==4
info=id4(isinf(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))));
end
return
end
- if nargout == 2,
+ if nargout == 2
[tmp, dlprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4));
elseif nargout == 3
[tmp, dlprior(id4), d2lprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4));
@@ -143,13 +143,13 @@ end
if tt5
if any(x(id5)-p3(id5)<0) || any(x(id5)-p4(id5)>0)
logged_prior_density = -Inf ;
- if nargout ==4
+ if nargout ==4
info=id5((x(id5)-p3(id5)<0) || (x(id5)-p4(id5)>0));
end
return
end
logged_prior_density = logged_prior_density + sum(log(1./(p4(id5)-p3(id5)))) ;
- if nargout >1,
+ if nargout >1
dlprior(id5)=zeros(length(id5),1);
end
if nargout == 3
@@ -160,12 +160,12 @@ end
if tt6
logged_prior_density = logged_prior_density + sum(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))) ;
if isinf(logged_prior_density)
- if nargout ==4
+ if nargout ==4
info=id6(isinf(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))));
end
return
end
- if nargout == 2,
+ if nargout == 2
[tmp, dlprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6));
elseif nargout == 3
[tmp, dlprior(id6), d2lprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6));
@@ -175,7 +175,7 @@ end
if tt8
logged_prior_density = logged_prior_density + sum(lpdfgweibull(x(id8),p6(id8),p7(id8)));
if isinf(logged_prior_density)
- if nargout ==4
+ if nargout ==4
info=id8(isinf(log(lpdfgweibull(x(id8),p6(id8),p7(id8)))));
end
return
@@ -187,7 +187,7 @@ if tt8
end
end
-if nargout==3,
+if nargout==3
d2lprior = diag(d2lprior);
end
diff --git a/matlab/qr2.m b/matlab/qr2.m
index 3c84db996..bdd1c0dea 100644
--- a/matlab/qr2.m
+++ b/matlab/qr2.m
@@ -1,23 +1,23 @@
function [Q,R] = qr2(varargin)
% This routine performs a qr decomposition of matrix X such that the
-% diagonal scalars of the upper-triangular matrix R are positive. If X
+% diagonal scalars of the upper-triangular matrix R are positive. If X
% is a full (column) rank matrix, then R is also the cholesky
-% factorization of X'X. This property is needed for the Del Negro
+% factorization of X'X. This property is needed for the Del Negro
% & Schorfheides's identification scheme.
-%
-% INPUTS
+%
+% INPUTS
% See matlab's documentation for QR decomposition.
-%
-% OUTPUTS
+%
+% OUTPUTS
% See matlab's documentation for QR decomposition.
%
% ALGORITHM
-% None.
+% None.
%
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/quadratic_matrix_equation_solver.m b/matlab/quadratic_matrix_equation_solver.m
index d96ea0d9d..40342085e 100644
--- a/matlab/quadratic_matrix_equation_solver.m
+++ b/matlab/quadratic_matrix_equation_solver.m
@@ -47,7 +47,7 @@ function [X,info] = quadratic_matrix_equation_solver(A,B,C,tol,maxit,line_search
%! @end deftypefn
%@eod:
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/qz/mjdgges.m b/matlab/qz/mjdgges.m
index 58e4b6513..12c91d801 100644
--- a/matlab/qz/mjdgges.m
+++ b/matlab/qz/mjdgges.m
@@ -6,16 +6,16 @@ function [err,ss,tt,w,sdim,eigval,info] = mjdgges(e,d,qz_criterium, fake)
% e [double] real square (n*n) matrix.
% d [double] real square (n*n) matrix.
% qz_criterium [double] scalar (1+epsilon).
-%
+%
% OUTPUTS
% err [double] scalar: 1 indicates failure, 0 indicates success
% ss [complex] (n*n) matrix.
% tt [complex] (n*n) matrix.
% w [complex] (n*n) matrix.
-% sdim [integer] scalar.
-% eigval [complex] (n*1) vector.
+% sdim [integer] scalar.
+% eigval [complex] (n*1) vector.
% info [integer] scalar.
-%
+%
% ALGORITHM
% Sims's qzdiv routine is used.
%
@@ -54,7 +54,7 @@ end
% Set default value of qz_criterium.
if nargin <3
- qz_criterium = 1 + 1e-6;
+ qz_criterium = 1 + 1e-6;
end
info = 0;
diff --git a/matlab/qzdiv.m b/matlab/qzdiv.m
index 2c88184f1..ba5206efa 100644
--- a/matlab/qzdiv.m
+++ b/matlab/qzdiv.m
@@ -2,7 +2,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
%function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
%
% Takes U.T. matrices A, B, orthonormal matrices Q,Z, rearranges them
-% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right
+% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right
% corner, while preserving U.T. and orthonormal properties and Q'AZ' and
% Q'BZ'.
@@ -10,7 +10,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
% http://sims.princeton.edu/yftp/gensys/mfiles/qzdiv.m
% Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -27,25 +27,25 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-[n jnk] = size(A);
+[n, jnk] = size(A);
root = abs([diag(A) diag(B)]);
root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2));
root(:,2) = root(:,2)./root(:,1);
for i = n:-1:1
m=0;
for j=i:-1:1
- if (root(j,2) > stake || root(j,2) < -.1)
+ if (root(j,2) > stake || root(j,2) < -.1)
m=j;
break
end
end
- if (m==0)
- return
+ if (m==0)
+ return
end
for k=m:1:i-1
- [A B Q Z] = qzswitch(k,A,B,Q,Z);
+ [A, B, Q, Z] = qzswitch(k,A,B,Q,Z);
tmp = root(k,2);
root(k,2) = root(k+1,2);
root(k+1,2) = tmp;
end
-end
+end
diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m
index ccc50fb04..2ca9079fe 100644
--- a/matlab/ramsey_policy.m
+++ b/matlab/ramsey_policy.m
@@ -1,6 +1,6 @@
function info = ramsey_policy(var_list)
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/read_data_.m b/matlab/read_data_.m
index 7ad6b4228..d7de0843d 100644
--- a/matlab/read_data_.m
+++ b/matlab/read_data_.m
@@ -1,6 +1,6 @@
function read_data_()
% function read_data_
-% reads endogenous and exogenous variables from a text file
+% reads endogenous and exogenous variables from a text file
% Used by datafile option in simulate
%
% INPUT
@@ -12,7 +12,7 @@ function read_data_()
% SPECIAL REQUIREMENT
% none
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/read_key_value_string.m b/matlab/read_key_value_string.m
index d92fb2698..446afd2f5 100644
--- a/matlab/read_key_value_string.m
+++ b/matlab/read_key_value_string.m
@@ -4,7 +4,7 @@ function c = read_key_value_string(s)
% estimation command) into a cell (first column for the option name ans second column for the
% option value).
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/read_variables.m b/matlab/read_variables.m
index a96e8d013..a50501252 100644
--- a/matlab/read_variables.m
+++ b/matlab/read_variables.m
@@ -6,7 +6,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh
% INPUTS
% file_name_01: file name
% var_names_01: variables name
-% dyn_data_01:
+% dyn_data_01:
% xls_sheet: Excel sheet name
% xls_range: Excel range specification
%
@@ -17,7 +17,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh
% all local variables have complicated names in order to avoid name
% conflicts with possible user variable names
-% Copyright (C) 2005-2013 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -65,7 +65,7 @@ fullname = [basename extension];
if ~exist(fullname)
error(['Can''t find datafile: ' fullname ]);
-end
+end
switch (extension)
case '.m'
diff --git a/matlab/realtime_shock_decomposition.m b/matlab/realtime_shock_decomposition.m
index 72b1bde3e..64bf96c6f 100644
--- a/matlab/realtime_shock_decomposition.m
+++ b/matlab/realtime_shock_decomposition.m
@@ -1,11 +1,11 @@
function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
% function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
% Computes shocks contribution to a simulated trajectory. The fields set are
-% oo_.realtime_shock_decomposition, oo_.conditional_shock_decomposition and oo_.realtime_forecast_shock_decomposition.
+% oo_.realtime_shock_decomposition, oo_.conditional_shock_decomposition and oo_.realtime_forecast_shock_decomposition.
% Subfields are arrays n_var by nshock+2 by nperiods. The
% first nshock columns store the respective shock contributions, column n+1
% stores the role of the initial conditions, while column n+2 stores the
-% value of the smoothed variables. Both the variables and shocks are stored
+% value of the smoothed variables. Both the variables and shocks are stored
% in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively.
%
% INPUTS
@@ -22,7 +22,7 @@ function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,e
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -44,7 +44,8 @@ if size(varlist,1) == 0
varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
end
-[i_var,nvar] = varlist_indices(varlist,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
% number of variables
endo_nbr = M_.endo_nbr;
@@ -68,13 +69,13 @@ if isempty(parameter_set)
end
presample = max(1,options_.presample);
-if isfield(options_.shock_decomp,'presample'),
+if isfield(options_.shock_decomp,'presample')
presample = max(presample,options_.shock_decomp.presample);
end
% forecast_=0;
forecast_ = options_.shock_decomp.forecast;
forecast_params=0;
-if forecast_ && isfield(options_.shock_decomp,'forecast_params'),
+if forecast_ && isfield(options_.shock_decomp,'forecast_params')
forecast_params = options_.shock_decomp.forecast_params;
end
@@ -95,32 +96,32 @@ options_.plot_priors=0;
init=1;
nobs = options_.nobs;
-if forecast_ && any(forecast_params),
+if forecast_ && any(forecast_params)
M1=M_;
M1.params = forecast_params;
[junk1,junk2,junk3,junk4,junk5,junk6,oo1] = dynare_resolve(M1,options_,oo_);
clear junk1 junk2 junk3 junk4 junk5 junk6
end
-for j=presample+1:nobs,
+for j=presample+1:nobs
% evalin('base',['options_.nobs=' int2str(j) ';'])
options_.nobs=j;
[oo, M_, junk2, junk3, Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
-
+
% reduced form
dr = oo.dr;
-
+
% data reordering
order_var = dr.order_var;
inv_order_var = dr.inv_order_var;
-
-
+
+
% coefficients
A = dr.ghx;
B = dr.ghu;
-
- if forecast_,
- if any(forecast_params),
+
+ if forecast_
+ if any(forecast_params)
Af = oo1.dr.ghx;
Bf = oo1.dr.ghu;
else
@@ -136,20 +137,20 @@ for j=presample+1:nobs,
epsilon(i,:) = oo.SmoothedShocks.(deblank(M_.exo_names(i,:)));
end
epsilon=[epsilon zeros(nshocks,forecast_)];
-
+
z = zeros(endo_nbr,nshocks+2,gend+forecast_);
-
+
z(:,end,1:gend) = Smoothed_Variables_deviation_from_mean;
-
+
maximum_lag = M_.maximum_lag;
-
+
k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]);
i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr;
- for i=1:gend+forecast_,
+ for i=1:gend+forecast_
if i > 1 && i <= maximum_lag+1
lags = min(i-1,maximum_lag):-1:1;
end
-
+
if i > 1
tempx = permute(z(:,1:nshocks,lags),[1 3 2]);
m = min(i-1,maximum_lag);
@@ -164,30 +165,30 @@ for j=presample+1:nobs,
lags = lags+1;
z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
end
-
+
% z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2);
end
-
+
%% conditional shock decomp 1 step ahead
z1 = zeros(endo_nbr,nshocks+2);
z1(:,end) = Smoothed_Variables_deviation_from_mean(:,gend);
- for i=gend,
-
+ for i=gend
+
z1(:,1:nshocks) = z1(:,1:nshocks) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
z1(:,nshocks+1) = z1(:,nshocks+2) - sum(z1(:,1:nshocks),2);
end
%%
%% conditional shock decomp k step ahead
- if forecast_ && forecast_ 1 && i <= maximum_lag+1
lags = min(i-1,maximum_lag):-1:1;
end
-
+
if i > 1
tempx = permute(zn(:,1:nshocks,lags),[1 3 2]);
m = min(i-1,maximum_lag);
@@ -196,15 +197,15 @@ for j=presample+1:nobs,
lags = lags+1;
zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1);
end
-
+
% zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1);
zn(:,nshocks+1,i) = zn(:,nshocks+2,i) - sum(zn(:,1:nshocks,i),2);
end
oo_.conditional_shock_decomposition.(['time_' int2str(j-forecast_)])=zn;
end
%%
-
- if init,
+
+ if init
zreal(:,:,1:j) = z(:,:,1:j);
else
zreal(:,:,j) = z(:,:,gend);
@@ -213,7 +214,7 @@ for j=presample+1:nobs,
if ismember(j,save_realtime)
oo_.realtime_shock_decomposition.(['time_' int2str(j)])=z;
end
-
+
if forecast_
zfrcst(:,:,j+1) = z(:,:,gend+1);
oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j)])=z(:,:,gend:end);
@@ -226,9 +227,9 @@ for j=presample+1:nobs,
oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:);
oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:) = ...
zreal(:,end,j-forecast_:j);
-
+
if j==nobs
- for my_forecast_=(forecast_-1):-1:1,
+ for my_forecast_=(forecast_-1):-1:1
oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)]) = ...
zreal(:,:,j-my_forecast_:j) - ...
oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,:,1:my_forecast_+1);
@@ -238,10 +239,10 @@ for j=presample+1:nobs,
zreal(:,end,j-my_forecast_:j);
end
end
-
+
end
end
-
+
prctdone=(j-presample)/(nobs-presample);
if isoctave
printf([running_text,' %3.f%% done\r'], prctdone*100);
diff --git a/matlab/recursive_moments.m b/matlab/recursive_moments.m
index 712a4b597..4d38d9b1b 100644
--- a/matlab/recursive_moments.m
+++ b/matlab/recursive_moments.m
@@ -1,25 +1,25 @@
function [mu,sigma,offset] = recursive_moments(m0,s0,data,offset)
% Recursive estimation of order one and two moments (expectation and
-% covariance matrix).
-%
-% INPUTS
+% covariance matrix).
+%
+% INPUTS
% o m0 [double] (n*1) vector, the prior expectation.
% o s0 [double] (n*n) matrix, the prior covariance matrix.
-% o data [double] (T*n) matrix.
+% o data [double] (T*n) matrix.
% o offset [integer] scalar, number of observation previously
% used to compute m0 and s0.
-% OUTPUTS
-% o mu [double] (n*1) vector, the posterior expectation.
+% OUTPUTS
+% o mu [double] (n*1) vector, the posterior expectation.
% o sigma [double] (n*n) matrix, the posterior covariance matrix.
% o offset [integer] = offset + T.
%
-% ALGORITHM
-% None.
+% ALGORITHM
+% None.
%
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2009 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -47,6 +47,6 @@ for t = 1:T
s0 = s1;
end
-mu = m1;
+mu = m1;
sigma = s1;
offset = offset+T;
\ No newline at end of file
diff --git a/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
index 0c6a52d07..522456728 100644
--- a/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
+++ b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
@@ -58,7 +58,7 @@ function [y,y_] = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,gh
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/reduced_rank_cholesky.m b/matlab/reduced_rank_cholesky.m
index f2b6ff74c..fe9edbace 100644
--- a/matlab/reduced_rank_cholesky.m
+++ b/matlab/reduced_rank_cholesky.m
@@ -36,7 +36,7 @@ function T = reduced_rank_cholesky(X)
%! @end deftypefn
%@eod:
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -51,7 +51,7 @@ function T = reduced_rank_cholesky(X)
% 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 .
+% along with Dynare. If not, see .
[T,X_is_not_positive_definite] = chol(X);
@@ -87,7 +87,7 @@ end
%$ catch
%$ t(1) = 0;
%$ T = all(t);
-%$ return;
+%$ return
%$ end
%$
%$
diff --git a/matlab/resid.m b/matlab/resid.m
index 71e0f6619..f124409c1 100644
--- a/matlab/resid.m
+++ b/matlab/resid.m
@@ -2,17 +2,17 @@ function z = resid(junk)
% function z = resid(junk)
%
% Computes static residuals associated with the guess values.
-%
+%
% INPUTS
% junk: dummy value for backward compatibility
-%
+%
% OUTPUTS
% z: residuals
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -58,7 +58,7 @@ if any(imag(oo_.steady_state))
for iter=1:length(imagrow)
fprintf('%s\n',M_.endo_names(imagrow(iter),:));
end
- end
+ end
end
if options_.steadystate_flag
diff --git a/matlab/resol.m b/matlab/resol.m
index 0fae31a9e..ba3d0e647 100644
--- a/matlab/resol.m
+++ b/matlab/resol.m
@@ -76,7 +76,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
%! @end deftypefn
%@eod:
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -93,7 +93,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if isfield(oo,'dr');
+if isfield(oo,'dr')
dr = oo.dr;
end
diff --git a/matlab/rotated_slice_sampler.m b/matlab/rotated_slice_sampler.m
index d5e53e384..79f4b267f 100644
--- a/matlab/rotated_slice_sampler.m
+++ b/matlab/rotated_slice_sampler.m
@@ -4,7 +4,7 @@ function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,
% extension of the orthogonal univarite sampler (slice_sampler.m)
% copyright M. Ratto (European Commission)
%
-% objective_function(theta,varargin): -log of any unnormalized pdf
+% objective_function(theta,varargin): -log of any unnormalized pdf
% with varargin (optional) a vector of auxiliaty parameters
% to be passed to f( ).
% ----------------------------------------------------------
@@ -24,7 +24,7 @@ function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -45,22 +45,22 @@ theta=theta(:);
npar = length(theta);
neval = zeros(npar,1);
W1=[];
-if isfield(sampler_options,'WR'),
+if isfield(sampler_options,'WR')
W1 = sampler_options.WR;
end
-if ~isempty(sampler_options.mode),
+if ~isempty(sampler_options.mode)
mm = sampler_options.mode;
n = length(mm);
- for j=1:n,
+ for j=1:n
distance(j)=sqrt(sum((theta-mm(j).m).^2));
end
[m, im] = min(distance);
-
+
r=im;
V1 = mm(r).m;
jj=0;
- for j=1:n,
- if j~=r,
+ for j=1:n
+ if j~=r
jj=jj+1;
tmp=mm(j).m-mm(r).m;
%tmp=mm(j).m-theta;
@@ -73,7 +73,7 @@ if ~isempty(sampler_options.mode),
%V1 = V1(:, randperm(n-1));
% %d = chol(mm(r).invhess);
% %V1 = transpose(feval(sampler_options.proposal_distribution, transpose(mm(r).m), d, npar));
- %
+ %
% V1=eye(npar);
% V1=V1(:,randperm(npar));
% for j=1:2,
@@ -86,23 +86,23 @@ if ~isempty(sampler_options.mode),
% V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k);
% end
% V1(:,j)=V1(:,j)/norm(V1(:,j));
- % end
+ % end
% for j=1:n,
% distance(j)=sqrt(sum((theta-mm(j).m).^2));
% end
% [m, im] = min(distance);
- % if im==r,
+ % if im==r,
% fxsim=[];
% return,
% else
% theta1=theta;
% end
else
- V1 = sampler_options.V1;
+ V1 = sampler_options.V1;
end
npar=size(V1,2);
-for it=1:npar,
+for it=1:npar
theta0 = theta;
neval(it) = 0;
xold = 0;
@@ -110,18 +110,18 @@ for it=1:npar,
% XUB = thetaprior(4);
tb=sort([(thetaprior(:,1)-theta)./V1(:,it) (thetaprior(:,2)-theta)./V1(:,it)],2);
XLB=max(tb(:,1));
- XUB=min(tb(:,2));
- if isempty(W1),
- W = (XUB-XLB); %*0.8;
+ XUB=min(tb(:,2));
+ if isempty(W1)
+ W = (XUB-XLB); %*0.8;
else
W = W1(it);
end
-
+
% -------------------------------------------------------
% 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
% THIS DEFINES THE SLICE S={x: z < ln(f(x))}
% -------------------------------------------------------
-
+
fxold = -feval(objective_function,theta,varargin{:});
%I have to be sure that the rotation is for L,R or for Fxold, theta(it)
neval(it) = neval(it) + 1;
@@ -133,7 +133,7 @@ for it=1:npar,
u = rand(1,1);
L = max(XLB,xold-W*u);
R = min(XUB,L+W);
-
+
%[L R]=slice_rotation(L, R, alpha);
while(L > XLB)
xsim = L;
@@ -141,7 +141,7 @@ for it=1:npar,
fxl = -feval(objective_function,theta,varargin{:});
neval(it) = neval(it) + 1;
if (fxl <= Z)
- break;
+ break
end
L = max(XLB,L-W);
end
@@ -151,7 +151,7 @@ for it=1:npar,
fxr = -feval(objective_function,theta,varargin{:});
neval(it) = neval(it) + 1;
if (fxr <= Z)
- break;
+ break
end
R = min(XUB,R+W);
end
@@ -180,5 +180,4 @@ end
% fxsim=[];
% end
% end
-end
-
+end
\ No newline at end of file
diff --git a/matlab/row_header_width.m b/matlab/row_header_width.m
index c3132e261..e3a995502 100644
--- a/matlab/row_header_width.m
+++ b/matlab/row_header_width.m
@@ -1,19 +1,19 @@
function w=row_header_width(M_,estim_params_,bayestopt_)
% This function computes the width of the row headers for
% the estimation results
-%
-% INPUTS
-% estim_params_ [structure]
+%
+% INPUTS
+% estim_params_ [structure]
% M_ [structure]
% bayestopt_ [structure]
-%
-% OUTPUTS
+%
+% OUTPUTS
% w integer
%
% SPECIAL REQUIREMENTS
% None.
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -44,13 +44,13 @@ if np
end
if nvx
for i=1:nvx
- k = estim_params_.var_exo(i,1);
+ k = estim_params_.var_exo(i,1);
w = max(w,length(deblank(M_.exo_names(k,:))));
end
end
if nvn
for i=1:nvn
- k = estim_params_.var_endo(i,1);
+ k = estim_params_.var_endo(i,1);
w = max(w,length(deblank(M_.endo_names(k,:))));
end
end
@@ -72,4 +72,3 @@ if ncn
end
end
-
diff --git a/matlab/rplot.m b/matlab/rplot.m
index b77bbdd2f..cc7f30515 100644
--- a/matlab/rplot.m
+++ b/matlab/rplot.m
@@ -52,11 +52,11 @@ ix = [1 - M_.maximum_lag:size(oo_.endo_simul,2)-M_.maximum_lag]' ;
y = [];
for k=1:size(s1,1)
- if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'))
- if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))
+ if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'))
+ if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))
error (['rplot: One of the variables specified does not exist']) ;
else
- y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ;
+ y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ;
end
else
y = [y; oo_.endo_simul(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'),:)] ;
@@ -143,7 +143,7 @@ function []=create_TeX_loader(fidTeX,options,figpath,caption,label_name,label_ty
if nargin<6
scale_factor=1;
end
-fprintf(fidTeX,' \n');
+fprintf(fidTeX,' \n');
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',0.8*scale_factor,strrep(figpath,'\','/'));
diff --git a/matlab/sample_autocovariance.m b/matlab/sample_autocovariance.m
index 12bd34e86..3ae17e1a0 100644
--- a/matlab/sample_autocovariance.m
+++ b/matlab/sample_autocovariance.m
@@ -1,19 +1,19 @@
function [autocov,autocor] = sample_autocovariance(data,q)
% Computes the autocovariance function associated to a time series.
-%
%
-% INPUTS
+%
+% INPUTS
%
% data [double] T*1 vector of data.
-% q [integer] Order of the autocovariance function.
-%
-% OUTPUTS
-% autocov [double] (q+1)*1 vector, autocovariance function (first scalar is the variance).
+% q [integer] Order of the autocovariance function.
+%
+% OUTPUTS
+% autocov [double] (q+1)*1 vector, autocovariance function (first scalar is the variance).
% autocor [double] (q+1)*1 vector, autocorrelation function (first scalar is equal to one).
%
% SPECIAL REQUIREMENTS
-% Copyright (C) 2003-2008 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/sample_hp_filter.m b/matlab/sample_hp_filter.m
index a7b3592cf..381086b3d 100644
--- a/matlab/sample_hp_filter.m
+++ b/matlab/sample_hp_filter.m
@@ -1,18 +1,18 @@
function [hptrend,hpcycle] = sample_hp_filter(y,s)
% HP filters a collection of time series.
-%
-% INPUTS
+%
+% INPUTS
% y [double] T*n matrix of data (n is the number of variables)
% s [double] scalar, smoothing parameter.
-%
-% OUTPUTS
+%
+% OUTPUTS
% hptrend [double] T*n matrix, trend component of y.
-% hpcycle [double] T*n matrix, cycle component of y.
-%
+% hpcycle [double] T*n matrix, cycle component of y.
+%
% SPECIAL REQUIREMENTS
-%
+%
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/save_params_and_steady_state.m b/matlab/save_params_and_steady_state.m
index 0f8dbfe1a..273800fce 100644
--- a/matlab/save_params_and_steady_state.m
+++ b/matlab/save_params_and_steady_state.m
@@ -12,17 +12,17 @@ function save_params_and_steady_state(filename)
% Note that no variable type is stored in the file, so that the values
% can be reloaded (with load_params_and_steady_state) in a setup where
% the variable types are different.
-%
+%
% INPUTS
% filename: where to store the saved values
-%
+%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/score.m b/matlab/score.m
index f9d418bfe..89d4b512b 100644
--- a/matlab/score.m
+++ b/matlab/score.m
@@ -8,7 +8,7 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat
% NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last
% dimension equal to the number of structural parameters
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -40,7 +40,7 @@ Da = zeros(mm,k); % State vector.
Dv = zeros(length(mf),k); % observation vector.
% for ii = 1:k
-% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
+% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
% end
while notsteady & t.
if size(b,2) ~= 1
- error ('The second argument in SELIF must be à column vector') ;
+ error ('The second argument in SELIF must be à column vector') ;
end
x = a(find(b == 1),:) ;
return ;
-
diff --git a/matlab/set_all_parameters.m b/matlab/set_all_parameters.m
index e4daafc37..2f4fcc28e 100644
--- a/matlab/set_all_parameters.m
+++ b/matlab/set_all_parameters.m
@@ -33,7 +33,7 @@ function M = set_all_parameters(xparam1,estim_params,M)
%! @end deftypefn
%@eod:
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -95,7 +95,7 @@ if ncx
end
%build covariance matrix from correlation matrix and variances already on
%diagonal
-Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
+Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
%if calibrated covariances, set them now to their stored value
if isfield(estim_params,'calibrated_covariances')
Sigma_e(estim_params.calibrated_covariances.position)=estim_params.calibrated_covariances.cov_value;
@@ -136,5 +136,5 @@ if nvx || ncx
end
if nvn || ncn
M.H = H;
- M.Correlation_matrix_ME=Correlation_matrix_ME;
+ M.Correlation_matrix_ME=Correlation_matrix_ME;
end
\ No newline at end of file
diff --git a/matlab/set_default_option.m b/matlab/set_default_option.m
index 760d74fa8..44976a15a 100644
--- a/matlab/set_default_option.m
+++ b/matlab/set_default_option.m
@@ -1,20 +1,20 @@
function options=set_default_option(options,field,default)
% function options=set_default_option(options,field,default)
-% Sets the option value
-%
+% Sets the option value
+%
% INPUTS
% options
% field: option name
% default: assigns a value
-%
+%
% OUTPUTS
% options
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/set_dynare_random_generator_state.m b/matlab/set_dynare_random_generator_state.m
index 209965124..a06fdff5d 100644
--- a/matlab/set_dynare_random_generator_state.m
+++ b/matlab/set_dynare_random_generator_state.m
@@ -1,12 +1,12 @@
function [state_u,state_n] = set_dynare_random_generator_state(state_u,state_n)
% Wet state of Matlab/Octave random generator depending on matlab
-% (octave) version.
+% (octave) version.
% In older versions, Matlab kept one generator for uniformly distributed numbers and
-% one for normally distributed numbers.
+% one for normally distributed numbers.
% For backward compatibility, we return two vectors, but, in recent
% versions of Matlab and in Octave, we return two identical vectors.
-%
-% Copyright (C) 2010-2012 Dynare Team
+%
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,7 +34,7 @@ if matlab_random_streams% Use new matlab interface.
if isequal(s.Type,'legacy')
rand('state',state_u);
randn('state',state_n);
- else
+ else
if ~isequal(state_u,state_n)
error(['You are using the new Matlab RandStream mechanism ' ...
'with a single random generator, but the values ' ...
diff --git a/matlab/set_dynare_seed.m b/matlab/set_dynare_seed.m
index 3a71d7236..65c5e0587 100644
--- a/matlab/set_dynare_seed.m
+++ b/matlab/set_dynare_seed.m
@@ -1,8 +1,8 @@
function set_dynare_seed(a,b)
-% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the
+% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the
% user in the mod file.
-%
-% Copyright (C) 2010-2014 Dynare Team
+%
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/set_parameters.m b/matlab/set_parameters.m
index c183bb3d3..15f4175ed 100644
--- a/matlab/set_parameters.m
+++ b/matlab/set_parameters.m
@@ -4,17 +4,17 @@ function set_parameters(xparam1)
% Sets parameters value (except measurement errors)
% This is called for computations such as IRF and forecast
% when measurement errors aren't taken into account
-%
+%
% INPUTS
% xparam1: vector of parameters to be estimated (initial values)
-%
+%
% OUTPUTS
% none
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -66,7 +66,7 @@ if ncx
end
%build covariance matrix from correlation matrix and variances already on
%diagonal
-Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
+Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
if isfield(estim_params_,'calibrated_covariances')
Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value;
end
diff --git a/matlab/set_prior.m b/matlab/set_prior.m
index bb4924c4c..dc7922916 100644
--- a/matlab/set_prior.m
+++ b/matlab/set_prior.m
@@ -4,21 +4,21 @@ function [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params
%
% INPUTS
% o estim_params_ [structure] characterizing parameters to be estimated.
-% o M_ [structure] characterizing the model.
-% o options_ [structure]
-%
+% o M_ [structure] characterizing the model.
+% o options_ [structure]
+%
% OUTPUTS
% o xparam1 [double] vector of parameters to be estimated (initial values)
% o estim_params_ [structure] characterizing parameters to be estimated
% o bayestopt_ [structure] characterizing priors
-% o lb [double] vector of lower bounds for the estimated parameters.
+% o lb [double] vector of lower bounds for the estimated parameters.
% o ub [double] vector of upper bounds for the estimated parameters.
% o M_ [structure] characterizing the model.
-%
+%
% SPECIAL REQUIREMENTS
% None
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -64,7 +64,7 @@ bayestopt_.name = {};
if nvx
xparam1 = estim_params_.var_exo(:,2);
ub = estim_params_.var_exo(:,4);
- lb = estim_params_.var_exo(:,3);
+ lb = estim_params_.var_exo(:,3);
bayestopt_.pshape = estim_params_.var_exo(:,5);
bayestopt_.p1 = estim_params_.var_exo(:,6);
bayestopt_.p2 = estim_params_.var_exo(:,7);
@@ -88,8 +88,8 @@ if nvn
estim_params_.nvn_observable_correspondence(i,1)=obsi_;
end
xparam1 = [xparam1; estim_params_.var_endo(:,2)];
- ub = [ub; estim_params_.var_endo(:,4)];
- lb = [lb; estim_params_.var_endo(:,3)];
+ ub = [ub; estim_params_.var_endo(:,4)];
+ lb = [lb; estim_params_.var_endo(:,3)];
bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.var_endo(:,5)];
bayestopt_.p1 = [ bayestopt_.p1; estim_params_.var_endo(:,6)];
bayestopt_.p2 = [ bayestopt_.p2; estim_params_.var_endo(:,7)];
@@ -170,14 +170,14 @@ bayestopt_.p4(k(k1)) = ones(length(k1),1);
for i=1:length(k)
[bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = beta_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.p4(k(i)), bayestopt_.name{k(i)});
if bayestopt_.p6(k(i))<1 || bayestopt_.p7(k(i))<1
- fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
+ fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
end
m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1);
if length(m)==1
bayestopt_.p5(k(i)) = m;
else
disp(['Prior distribution for parameter ' bayestopt_.name{k(i)} ' has two modes!'])
- bayestopt_.p5(k(i)) = m(1);
+ bayestopt_.p5(k(i)) = m(1);
end
end
@@ -190,7 +190,7 @@ bayestopt_.p4(k(k2)) = Inf(length(k2),1);
for i=1:length(k)
[bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.name{k(i)});
if bayestopt_.p6(k(i))<1
- fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
+ fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
end
bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ;
end
diff --git a/matlab/set_state_space.m b/matlab/set_state_space.m
index a7d108165..de8108f32 100644
--- a/matlab/set_state_space.m
+++ b/matlab/set_state_space.m
@@ -34,7 +34,7 @@ function dr=set_state_space(dr,DynareModel,DynareOptions)
%! @end deftypefn
%@eod:
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -73,7 +73,7 @@ if DynareOptions.block == 1
order_var = DynareModel.block_structure.variable_reordered;
else
order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)];
-end;
+end
inv_order_var(order_var) = (1:endo_nbr);
% building kmask for z state vector in t+1
diff --git a/matlab/shock_decomposition.m b/matlab/shock_decomposition.m
index c63facfe7..1785e8c08 100644
--- a/matlab/shock_decomposition.m
+++ b/matlab/shock_decomposition.m
@@ -4,7 +4,7 @@ function [oo_,M_] = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim
% oo_.shock_decomposition. It is a n_var by nshock+2 by nperiods array. The
% first nshock columns store the respective shock contributions, column n+1
% stores the role of the initial conditions, while column n+2 stores the
-% value of the smoothed variables. Both the variables and shocks are stored
+% value of the smoothed variables. Both the variables and shocks are stored
% in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively.
%
% INPUTS
@@ -23,7 +23,7 @@ function [oo_,M_] = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -45,7 +45,8 @@ if size(varlist,1) == 0
varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
end
-[i_var,nvar] = varlist_indices(varlist,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
% number of variables
endo_nbr = M_.endo_nbr;
@@ -58,9 +59,9 @@ parameter_set = options_.parameter_set;
if isempty(parameter_set)
if isfield(oo_,'posterior_mean')
parameter_set = 'posterior_mean';
- elseif isfield(oo_,'mle_mode')
+ elseif isfield(oo_,'mle_mode')
parameter_set = 'mle_mode';
- elseif isfield(oo_,'posterior')
+ elseif isfield(oo_,'posterior')
parameter_set = 'posterior_mode';
else
error(['shock_decomposition: option parameter_set is not specified ' ...
@@ -104,7 +105,7 @@ for i=1:gend
if i > 1 && i <= maximum_lag+1
lags = min(i-1,maximum_lag):-1:1;
end
-
+
if i > 1
tempx = permute(z(:,1:nshocks,lags),[1 3 2]);
m = min(i-1,maximum_lag);
diff --git a/matlab/simulated_moment_uncertainty.m b/matlab/simulated_moment_uncertainty.m
index 042f9914a..14ca70429 100644
--- a/matlab/simulated_moment_uncertainty.m
+++ b/matlab/simulated_moment_uncertainty.m
@@ -11,7 +11,7 @@ function [cmm, mm] = simulated_moment_uncertainty(indx, periods, replic,options_
% Outputs:
% - cmm: [n_moments by n_moments] covariance matrix of simulated moments
% - mm: [n_moments by replic] matrix of moments
-%
+%
% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
@@ -67,7 +67,7 @@ if options_.logged_steady_state %if steady state was previously logged, undo thi
options_.logged_steady_state=0;
logged_steady_state_indicator=1;
evalin('base','options_.logged_steady_state=0;')
-else
+else
logged_steady_state_indicator=0;
end
@@ -94,17 +94,17 @@ else
end
-for j=1:replic;
+for j=1:replic
[ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_);%do simulation
oo_=disp_moments(ys,char(options_.varobs),M_,options_,oo_); %get moments
dum=[oo_.mean; dyn_vech(oo_.var)];
sd = sqrt(diag(oo_.var));
- for i=1:options_.ar;
+ for i=1:options_.ar
dum=[dum; vec(oo_.autocorr{i}.*(sd*sd'))];
end
mm(:,j)=dum(indx);
dyn_waitbar(j/replic,h,['Simulated moment uncertainty. Replic ',int2str(j),'/',int2str(replic)])
-end;
+end
dyn_waitbar_close(h);
if logged_steady_state_indicator
diff --git a/matlab/simulated_moments_estimation.m b/matlab/simulated_moments_estimation.m
index 0946e3117..b01e5e9d3 100644
--- a/matlab/simulated_moments_estimation.m
+++ b/matlab/simulated_moments_estimation.m
@@ -2,19 +2,19 @@ function [param,sigma] = simulated_moments_estimation(dataset,options,parallel)
% Performs estimation by Simulated Moments Method.
%
% INPUTS:
-% xparam [double] p*1 vector of initial values for the estimated parameters.
+% xparam [double] p*1 vector of initial values for the estimated parameters.
% dataset [ ] Structure describing the data set.
% options [ ] Structure defining options for SMM.
-% parallel [ ] Structure defining the parallel mode settings (optional).
+% parallel [ ] Structure defining the parallel mode settings (optional).
%
-% OUTPUTS:
+% OUTPUTS:
% param [double] p*1 vector of point estimates for the parameters.
% sigma [double] p*p covariance matrix of the SMM estimates.
%
% SPECIAL REQUIREMENTS
% The user has to provide a file where the moment conditions are defined.
-% Copyright (C) 2010-2012 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -87,7 +87,7 @@ options.estimated_parameters.upper_bound = [options.estimated_parameters.upper_b
options.number_of_simulated_sample = 0;
for i=1:length(parallel)
- options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations;
+ options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations;
end
options.observed_variables_idx = dataset.observed_variables_idx;
@@ -97,7 +97,7 @@ if nargin>2
if ~isunix
error('The parallel version of SMM estimation is not implemented for non unix platforms!')
end
- [junk,hostname] = unix('hostname --fqdn');
+ [junk,hostname] = unix('hostname --fqdn');
hostname = deblank(hostname);
master_is_running_a_job = 0;
for i=1:length(parallel)
@@ -204,7 +204,7 @@ end
skipline()
if options.optimization_routine==1
- % Set options for csminwel.
+ % Set options for csminwel.
H0 = 1e-4*eye(options.estimated_parameters.nb);
ct = 1e-4;
it = 1000;
@@ -212,7 +212,7 @@ if options.optimization_routine==1
% Minimization of the objective function.
if nargin==2
[fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
- csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options);
+ csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options);
elseif nargin>2
[fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options,parallel);
@@ -236,7 +236,7 @@ elseif options.optimization_routine==0% Compute the variance of the SMM estimato
V = (1+1/options.number_of_simulated_sample)*G'*long_run_covariance*G;
[param,diag(V)]
elseif options.optimization_routine<0
- T = -options.optimization_routine;% length of the simulated time series.
+ T = -options.optimization_routine;% length of the simulated time series.
time_series = extended_path(oo_.steady_state,T,1);
save time_series.mat;
end
@@ -248,7 +248,7 @@ fid = fopen(['job' int2str(slave_number) '.m'],'w');
fprintf(fid,['% Generated by ' hostname '.\n\n']);
-if ( strcmpi(hostname,remotename) && (job_number>1) ) || ~strcmpi(hostname,remotename)
+if ( strcmpi(hostname,remotename) && (job_number>1) ) || ~strcmpi(hostname,remotename)
fprintf(fid,'load(''master_variables'');\n');
fprintf(fid,'assignin(''base'',''M_'',M_);\n');
fprintf(fid,'assignin(''base'',''oo_'',oo_);\n');
@@ -282,7 +282,7 @@ fprintf(fid,[' time_series = extended_path([],' int2str(sample_size) ',1);\n'
fprintf(fid,[' data = time_series([' int2str(observed_variables_idx) '],' int2str(burn_in_periods) '+1:' int2str(sample_size) ');\n']);
fprintf(fid,[' eval(''tmp = ' moments_file_name '(data);'');\n']);
fprintf(fid,[' simulated_moments = simulated_moments + tmp;\n']);
-fprintf(fid,['end;\n\n']);
+fprintf(fid,['end\n\n']);
fprintf(fid,['simulated_moments = simulated_moments/' int2str(number_of_simulations) ';\n']);
fprintf(fid,['save(''simulated_moments_slave_' int2str(slave_number) '.dat'',''simulated_moments'',''-ascii'');\n']);
@@ -295,7 +295,7 @@ else
fprintf(fid,['unix(''rm simulated_moments_slave_' int2str(slave_number) '.dat'');\n']);
end
-if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename)
+if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename)
fprintf(fid,'exit');
end
diff --git a/matlab/simult_.m b/matlab/simult_.m
index 6113cbb37..381bfaf1b 100644
--- a/matlab/simult_.m
+++ b/matlab/simult_.m
@@ -3,7 +3,7 @@ function y_=simult_(y0,dr,ex_,iorder)
% decision rules.
%
% INPUTS
-% y0 [double] n*1 vector, initial value (n is the number of declared endogenous variables plus the number
+% y0 [double] n*1 vector, initial value (n is the number of declared endogenous variables plus the number
% of auxilliary variables for lags and leads); must be in declaration order, i.e. as in M_.endo_names
% dr [struct] matlab's structure where the reduced form solution of the model is stored.
% ex_ [double] T*q matrix of innovations.
@@ -15,7 +15,7 @@ function y_=simult_(y0,dr,ex_,iorder)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2015 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -77,15 +77,15 @@ else
k2 = dr.state_var;
else
k2 = [];
- end;
+ end
order_var = 1:endo_nbr;
dr.order_var = order_var;
else
k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]);
k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*endo_nbr;
order_var = dr.order_var;
- end;
-
+ end
+
switch iorder
case 1
if isempty(dr.ghu)% For (linearized) deterministic models.
@@ -176,7 +176,7 @@ else
mexErrCheck('A_times_B_kronecker_C', err);
[gy2u, err] = A_times_B_kronecker_C(ghxu,yhat2,u,threads);
mexErrCheck('A_times_B_kronecker_C', err);
- %construct terms of order 3, all based on first order component yhat1
+ %construct terms of order 3, all based on first order component yhat1
y2a = kron(yhat1,yhat1);
[gyyy, err] = A_times_B_kronecker_C(ghxxx,y2a,yhat1,threads);
mexErrCheck('A_times_B_kronecker_C', err);
@@ -199,6 +199,6 @@ else
yhat1 = yhat1(ipred);
yhat2 = yhat2(ipred);
yhat3 = yhat3(ipred);
- end
+ end
end
end
diff --git a/matlab/simultxdet.m b/matlab/simultxdet.m
index 96b1f4c44..21f0421e4 100644
--- a/matlab/simultxdet.m
+++ b/matlab/simultxdet.m
@@ -22,7 +22,7 @@ function [y_,int_width,int_width_ME]=simultxdet(y0,ex,ex_det, iorder,var_list,M_
% The condition size(ex,1)+M_.maximum_lag=size(ex_det,1) must be verified
% for consistency.
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -88,7 +88,7 @@ if iorder == 1
for j=1:min(ykmin+M_.exo_det_length+1-i,M_.exo_det_length)
y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*(ex_det(i+j-1,:)'-exo_det_steady_state);
end
-
+
k1 = k1+1;
end
elseif iorder == 2
diff --git a/matlab/skipline.m b/matlab/skipline.m
index 5b311ab93..f148997b8 100644
--- a/matlab/skipline.m
+++ b/matlab/skipline.m
@@ -1,16 +1,16 @@
function skipline(n, fid)
% This function prints n newlines to fid
%
-% INPUTS
+% INPUTS
%
% n [integer] Number of newlines to print
% fid [integer] file id returned by fopen
-%
-% OUTPUTS
+%
+% OUTPUTS
% None
%
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -25,7 +25,7 @@ function skipline(n, fid)
% 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 .
+% along with Dynare. If not, see .
if nargin < 2
fid = 1;
diff --git a/matlab/slice_sampler.m b/matlab/slice_sampler.m
index 1505a5f28..84ee4a6de 100644
--- a/matlab/slice_sampler.m
+++ b/matlab/slice_sampler.m
@@ -4,7 +4,7 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri
% UNIVARIATE SLICE SAMPLER - stepping out (Neal, 2003)
% W: optimal value in the range (3,10)*std(x)
% - see C.Planas and A.Rossi (2014)
-% objective_function(theta,varargin): -log of any unnormalized pdf
+% objective_function(theta,varargin): -log of any unnormalized pdf
% with varargin (optional) a vector of auxiliaty parameters
% to be passed to f( ).
% ----------------------------------------------------------
@@ -24,7 +24,7 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -43,11 +43,11 @@ function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetapri
if sampler_options.rotated %&& ~isempty(sampler_options.V1),
[theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin{:});
- if isempty(sampler_options.mode), % jumping
- return,
+ if isempty(sampler_options.mode) % jumping
+ return
else
nevalR=sum(neval);
- end
+ end
end
theta=theta(:);
@@ -55,18 +55,18 @@ npar = length(theta);
W1 = sampler_options.W1;
neval = zeros(npar,1);
-for it=1:npar,
+for it=1:npar
neval(it) = 0;
- W = W1(it);
+ W = W1(it);
xold = theta(it);
% XLB = thetaprior(3);
% XUB = thetaprior(4);
XLB = thetaprior(it,1);
XUB = thetaprior(it,2);
-
-
+
+
% -------------------------------------------------------
- % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
+ % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
% THIS DEFINES THE SLICE S={x: z < ln(f(x))}
% -------------------------------------------------------
fxold = -feval(objective_function,theta,varargin{:});
@@ -85,7 +85,7 @@ for it=1:npar,
fxl = -feval(objective_function,theta,varargin{:});
neval(it) = neval(it) + 1;
if (fxl <= Z)
- break;
+ break
end
L = max(XLB,L-W);
end
@@ -95,7 +95,7 @@ for it=1:npar,
fxr = -feval(objective_function,theta,varargin{:});
neval(it) = neval(it) + 1;
if (fxr <= Z)
- break;
+ break
end
R = min(XUB,R+W);
end
@@ -115,9 +115,9 @@ for it=1:npar,
L = xsim;
end
end
-
+
end
-if sampler_options.rotated && ~isempty(sampler_options.mode), % jumping
+if sampler_options.rotated && ~isempty(sampler_options.mode) % jumping
neval=sum(neval)+nevalR;
end
diff --git a/matlab/smm_objective.m b/matlab/smm_objective.m
index 030cb98d9..fc6358205 100644
--- a/matlab/smm_objective.m
+++ b/matlab/smm_objective.m
@@ -2,20 +2,20 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option
% Evaluates the objective of the Simulated Moments Method.
%
% INPUTS:
-% xparams [double] p*1 vector of estimated parameters.
+% xparams [double] p*1 vector of estimated parameters.
% sample_moments [double] n*1 vector of sample moments (n>=p).
% weighting_matrix [double] n*n symetric, positive definite matrix.
% options [ ] Structure defining options for SMM.
% parallel [ ] Structure defining the parallel mode settings (optional).
%
-% OUTPUTS:
+% OUTPUTS:
% r [double] scalar, the value of the objective function.
% junk [ ] empty matrix.
%
% SPECIAL REQUIREMENTS
% The user has to provide a file where the moment conditions are defined.
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -30,7 +30,7 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option
% 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 .
+% along with Dynare. If not, see .
global M_ options_ oo_
persistent mainStream mainState
@@ -67,8 +67,8 @@ end
if penalty>0
flag = 0;
- r = priorObjectiveValue + penalty;
- return;
+ r = priorObjectiveValue + penalty;
+ return
end
save('estimated_parameters.mat','xparams');
@@ -114,7 +114,7 @@ else% parallel mode.
end
end
for j=1:parallel(i).number_of_jobs
- if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
+ if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
job_number = job_number + 1;
unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']);
end
@@ -125,7 +125,7 @@ else% parallel mode.
eval('job1;')
tElapsedMasterJob = etime(clock, tStartMasterJob);
TimeLimit = tElapsedMasterJob*1.2;
- % Master waits for the slaves' output...
+ % Master waits for the slaves' output...
tStart = clock;
tElapsed = 0;
while tElapsed 0
den = max([f;0.5*nn]) ;
if max(abs(g).*max([abs(x(j2)') ones(1,nn)])')/den < tolmin
@@ -147,13 +147,3 @@ disp('SOLVE: maxit has been reached')
% 04/13/01 MJ added test f < tolf !!
% 05/11/01 MJ changed tests for 'check' so as to remove 'continue' which is
% an instruction which appears only in version 6
-
-
-
-
-
-
-
-
-
-
diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m
index 2ce90c7bc..a579ea67e 100644
--- a/matlab/solve_one_boundary.m
+++ b/matlab/solve_one_boundary.m
@@ -1,7 +1,7 @@
function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
y_index_eq, nze, periods, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, forward_backward, is_dynamic, verbose, M, options, oo)
% Computes the deterministic simulation of a block of equation containing
-% lead or lag variables
+% lead or lag variables
%
% INPUTS
% fname [string] name of the file containing the block
@@ -26,7 +26,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
% cutoff [double] cutoff to correct the direction in Newton in case
% of singular jacobian matrix
% stack_solve_algo [integer] linear solver method used in the
-% Newton algorithm :
+% Newton algorithm :
% - 1 sparse LU
% - 2 GMRES
% - 3 BicGStab
@@ -43,19 +43,19 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
% indirect_call [integer] (0) direct call to the fname
% (1) indirect call via the
% local_fname wrapper
-% OUTPUTS
-% y [matrix] All endogenous variables of the model
+% OUTPUTS
+% y [matrix] All endogenous variables of the model
% info [integer] >=0 no error
% <0 error
-%
+%
% ALGORITHM
% Newton with LU or GMRES or BicGstab for dynamic block
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
+%
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -387,7 +387,7 @@ for it_=start:incr:finish
oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed.
oo_.deterministic_simulation.block(Block_Num).error = max_res;
oo_.deterministic_simulation.block(Block_Num).iterations = iter;
- end;
+ end
info = -Block_Num*10;
return
end
diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m
index 89d39fac6..cedf3e060 100644
--- a/matlab/solve_perfect_foresight_model.m
+++ b/matlab/solve_perfect_foresight_model.m
@@ -1,6 +1,6 @@
function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_simul,pfm)
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -34,7 +34,7 @@ end
if pfm.use_bytecode
[flag, endo_simul]=bytecode(Y, exo_simul, pfm.params);
- return;
+ return
end
z = Y(find(pfm.lead_lag_incidence'));
@@ -72,7 +72,7 @@ for iter = 1:pfm.maxit_
end
end
% Stop if Newton residuals are zero.
- err = max(abs(res));
+ err = max(abs(res));
if err < pfm.tolerance
stop = 1 ;
if pfm.verbose
@@ -86,7 +86,7 @@ for iter = 1:pfm.maxit_
endo_simul = reshape(Y,pfm.ny,pfm.periods+2);
break
end
- % Compute the Newton step.
+ % Compute the Newton step.
dy = -A\res;
if any(isnan(dy))
nan_flag = 1;
diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m
index 136d3e1ac..4b5904946 100644
--- a/matlab/solve_two_boundaries.m
+++ b/matlab/solve_two_boundaries.m
@@ -1,6 +1,6 @@
function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo,options,M, oo)
% Computes the deterministic simulation of a block of equation containing
-% both lead and lag variables using relaxation methods
+% both lead and lag variables using relaxation methods
%
% INPUTS
% fname [string] name of the file containing the block
@@ -27,7 +27,7 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
% cutoff [double] cutoff to correct the direction in Newton in case
% of singular jacobian matrix
% stack_solve_algo [integer] linear solver method used in the
-% Newton algorithm :
+% Newton algorithm :
% - 1 sprse LU
% - 2 GMRES
% - 3 BicGStab
@@ -36,17 +36,17 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
% oo [structure] Results
%
% OUTPUTS
-% y [matrix] All endogenous variables of the model
+% y [matrix] All endogenous variables of the model
% oo [structure] Results
%
% ALGORITHM
% Newton with LU or GMRES or BicGstab
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
+%
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -92,7 +92,7 @@ while ~(cvg==1 || iter>maxit_)
[max_res, max_indx]=max(max(abs(r')));
if ~isreal(r)
max_res = (-max_res^2)^0.5;
- end;
+ end
if ~isreal(max_res) || isnan(max_res)
cvg = 0;
elseif(is_linear && iter>0)
@@ -123,7 +123,7 @@ while ~(cvg==1 || iter>maxit_)
end
dx = (g1aa+correcting_factor*speye(periods*Blck_size))\ba- ya;
y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)';
- continue;
+ continue
else
disp('The singularity of the jacobian matrix could not be corrected');
return
@@ -178,7 +178,7 @@ while ~(cvg==1 || iter>maxit_)
B1_inv = inv(g1a(Elem, Elem));
if (t < periods)
S1 = B1_inv * g1a(Elem, Elem_1);
- end;
+ end
g1a(Elem, Elem_1) = S1;
b(Elem) = B1_inv * b(Elem);
g1a(Elem, Elem) = ones(Blck_size, Blck_size);
diff --git a/matlab/steady.m b/matlab/steady.m
index 5f11f73c8..3e0ec0095 100644
--- a/matlab/steady.m
+++ b/matlab/steady.m
@@ -1,17 +1,17 @@
function steady()
% function steady()
% computes and prints the steady state calculations
-%
+%
% INPUTS
% none
-%
+%
% OUTPUTS
% none
%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -28,7 +28,7 @@ function steady()
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-global M_ oo_ options_ ys0_
+global M_ oo_ options_ ys0_
test_for_deep_parameters_calibration(M_);
@@ -70,7 +70,7 @@ if info(1)
disp(sprintf('%12s %12.6f',M_.exo_det_names(hv(ixd(i),2),:), ...
oo_.exo_det_steady_state(hv(ixd(i),2))))
end
-
+
if options_.homotopy_force_continue
disp('Option homotopy_continue is set, so I continue ...')
else
@@ -99,7 +99,7 @@ else
fprintf('\nThe steady state computation failed. It terminated with the following values:\n')
for i=1:M_.orig_endo_nbr
fprintf('%s \t\t %g\n',M_.endo_names(i,:),steady_state(i));
- end
+ end
end
print_info(info,options_.noprint, options_);
end
diff --git a/matlab/steady_.m b/matlab/steady_.m
index 02c7c69ed..46c0e3411 100644
--- a/matlab/steady_.m
+++ b/matlab/steady_.m
@@ -1,12 +1,12 @@
function [steady_state,params,info] = steady_(M_,options_,oo_)
% function [steady_state,params,info] = steady_(M_,options_,oo_)
-% Computes the steady state
-%
+% Computes the steady state
+%
% INPUTS
% M struct model structure
% options struct options
% oo struct output results
-%
+%
% OUTPUTS
% steady_state vector steady state
% params vector parameters (may have been
@@ -18,7 +18,7 @@ function [steady_state,params,info] = steady_(M_,options_,oo_)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/step_length_correction.m b/matlab/step_length_correction.m
index 5af7dcaee..89710637b 100644
--- a/matlab/step_length_correction.m
+++ b/matlab/step_length_correction.m
@@ -1,6 +1,6 @@
function c = step_length_correction(x,scale,i)
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index 5e7decfff..81f8b886a 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -56,7 +56,8 @@ if size(var_list,1) == 0
var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
end
-[i_var,nvar] = varlist_indices(var_list,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(var_list,M_.endo_names);
+var_list=var_list(index_uniques,:);
iter_ = max(options_.periods,1);
if M_.exo_nbr > 0
@@ -83,7 +84,7 @@ else
[oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
end
-if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule
+if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule
oo_.dr.ys=log_variable(1:M_.endo_nbr,oo_.dr.ys,M_);
oo_.steady_state=log_variable(1:M_.endo_nbr,oo_.steady_state,M_);
options_old.logged_steady_state = 1; %make sure option is preserved outside of stoch_simul
@@ -200,7 +201,7 @@ if options_.irf
else
if options_.order>1 && options_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later
y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i)./cs(i,i)/100, options_.irf, options_.drop, ...
- options_.replic, options_.order);
+ options_.replic, options_.order);
else %for linear model, rescaling is done later
y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ...
options_.replic, options_.order);
@@ -323,7 +324,7 @@ if options_.irf
end
hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']);
m = 0;
- for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar;
+ for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar
m = m+1;
subplot(lr,lc,m);
plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1);
diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m
index 1da71109d..a51648a43 100644
--- a/matlab/stochastic_solvers.m
+++ b/matlab/stochastic_solvers.m
@@ -1,35 +1,35 @@
function [dr,info] = stochastic_solvers(dr,task,M_,options_,oo_)
% function [dr,info,M_,options_,oo_] = stochastic_solvers(dr,task,M_,options_,oo_)
-% computes the reduced form solution of a rational expectations model (first, second or third
-% order approximation of the stochastic model around the deterministic steady state).
+% computes the reduced form solution of a rational expectations model (first, second or third
+% order approximation of the stochastic model around the deterministic steady state).
%
% INPUTS
% dr [matlab structure] Decision rules for stochastic simulations.
% task [integer] if task = 0 then dr1 computes decision rules.
% if task = 1 then dr1 computes eigenvalues.
-% M_ [matlab structure] Definition of the model.
+% M_ [matlab structure] Definition of the model.
% options_ [matlab structure] Global options.
-% oo_ [matlab structure] Results
-%
+% oo_ [matlab structure] Results
+%
% OUTPUTS
% dr [matlab structure] Decision rules for stochastic simulations.
% info [integer] info=1: the model doesn't define current variables uniquely
-% info=2: problem in mjdgges.dll info(2) contains error code.
+% info=2: problem in mjdgges.dll info(2) contains error code.
% info=3: BK order condition not satisfied info(2) contains "distance"
% absence of stable trajectory.
% info=4: BK order condition not satisfied info(2) contains "distance"
% indeterminacy.
% info=5: BK rank condition not satisfied.
-% info=6: The jacobian matrix evaluated at the steady state is complex.
-% info=9: k_order_pert was unable to compute the solution
+% info=6: The jacobian matrix evaluated at the steady state is complex.
+% info=9: k_order_pert was unable to compute the solution
% ALGORITHM
% ...
-%
+%
% SPECIAL REQUIREMENTS
% none.
-%
+%
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -62,7 +62,7 @@ if (options_.aim_solver == 1) && (local_order > 1)
error('Option "aim_solver" is incompatible with order >= 2')
end
-if M_.maximum_endo_lag == 0
+if M_.maximum_endo_lag == 0
if local_order >= 2
fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models at higher order.\n')
fprintf('STOCHASTIC_SOLVER: To circumvent this restriction, you can add a backward-looking dummy equation of the form:\n')
@@ -85,7 +85,7 @@ if M_.maximum_endo_lead==0 && M_.exo_det_nbr~=0
error(['var_exo_det not implemented for purely backwards models'])
end
-if options_.k_order_solver;
+if options_.k_order_solver
if options_.risky_steadystate
[dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ...
options_,oo_);
@@ -96,7 +96,7 @@ if options_.k_order_solver;
[dr,info] = k_order_pert(dr,M_,options_);
options_.order = orig_order;
end
- return;
+ return
end
klen = M_.maximum_lag + M_.maximum_lead + 1;
@@ -120,7 +120,7 @@ if local_order == 1
else
[junk,jacobia_] = feval([M_.fname '_dynamic'],z(iyr0),exo_simul, ...
M_.params, dr.ys, it_);
- end;
+ end
elseif local_order == 2
if (options_.bytecode)
[chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
@@ -130,7 +130,7 @@ elseif local_order == 2
[junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z(iyr0),...
exo_simul, ...
M_.params, dr.ys, it_);
- end;
+ end
if options_.use_dll
% In USE_DLL mode, the hessian is in the 3-column sparse representation
hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
@@ -138,7 +138,7 @@ elseif local_order == 2
end
[infrow,infcol]=find(isinf(hessian1));
if options_.debug
- if ~isempty(infrow)
+ if ~isempty(infrow)
fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n')
fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
save([M_.fname '_debug.mat'],'hessian1')
@@ -150,7 +150,7 @@ elseif local_order == 2
end
[nanrow,nancol]=find(isnan(hessian1));
if options_.debug
- if ~isempty(nanrow)
+ if ~isempty(nanrow)
fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains NaN.\n')
fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
save([M_.fname '_debug.mat'],'hessian1')
@@ -159,14 +159,14 @@ elseif local_order == 2
if ~isempty(nanrow)
info(1)=12;
return
- end
+ end
end
[infrow,infcol]=find(isinf(jacobia_));
if options_.debug
- if ~isempty(infrow)
- fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n')
+ if ~isempty(infrow)
+ fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n')
display_problematic_vars_Jacobian(infrow,infcol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
save([M_.fname '_debug.mat'],'jacobia_')
end
@@ -194,8 +194,8 @@ end
[nanrow,nancol]=find(isnan(jacobia_));
if options_.debug
- if ~isempty(nanrow)
- fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n')
+ if ~isempty(nanrow)
+ fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n')
display_problematic_vars_Jacobian(nanrow,nancol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
save([M_.fname '_debug.mat'],'jacobia_')
end
@@ -229,9 +229,9 @@ if M_.maximum_endo_lead == 0
% backward models: simplified code exist only at order == 1
if local_order == 1
[k1,junk,k2] = find(kstate(:,4));
- dr.ghx(:,k1) = -b\jacobia_(:,k2);
+ dr.ghx(:,k1) = -b\jacobia_(:,k2);
if M_.exo_nbr
- dr.ghu = -b\jacobia_(:,nz+1:end);
+ dr.ghu = -b\jacobia_(:,nz+1:end);
end
dr.eigval = eig(kalman_transition_matrix(dr,nstatic+(1:nspred),1:nspred,M_.exo_nbr));
dr.full_rank = 1;
@@ -263,7 +263,7 @@ else
else % use original Dynare solver
[dr,info] = dyn_first_order_solver(jacobia_,M_,dr,options_,task);
if info(1) || task
- return;
+ return
end
end
@@ -272,7 +272,7 @@ else
dr = dyn_second_order_solver(jacobia_,hessian1,dr,M_,...
options_.threads.kronecker.A_times_B_kronecker_C,...
options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
-
+
% reordering second order derivatives, used for deterministic
% variables below
k1 = nonzeros(M_.lead_lag_incidence(:,order_var)');
@@ -381,4 +381,3 @@ if options_.loglinear
end
end
end
-
diff --git a/matlab/store_smoother_results.m b/matlab/store_smoother_results.m
index d8fcbbd06..5ef6e1509 100644
--- a/matlab/store_smoother_results.m
+++ b/matlab/store_smoother_results.m
@@ -1,7 +1,7 @@
function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty)
% oo_=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend)
% Writes the smoother results into respective fields in oo_
-%
+%
% Inputs:
% M_ [structure] storing the model information
% oo_ [structure] storing the results
@@ -42,19 +42,19 @@ function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,da
% oo_.SmoothedMeasurementErrors: structure storing the smoothed measurement errors
% oo_.Smoother.State_uncertainty: smoothed state uncertainty (declaration order)
-% yf [double] (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs)
-%
-% Notes:
+% yf [double] (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs)
+%
+% Notes:
% m: number of endogenous variables (M_.endo_nbr)
% T: number of Time periods (options_.nobs)
% r: number of strucural shocks (M_.exo_nbr)
% n: number of observables (length(options_.varobs))
% K: maximum forecast horizon (max(options_.nk))
-%
+%
% First all smoothed variables are saved without trend and constant.
% Then trend and constant are added for the observed variables.
%
-% Copyright (C) 2014-2016 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -113,7 +113,7 @@ trend_constant_observables=constant_part+Trend;
yf = atT(bayestopt_.mf,:)+trend_constant_observables;
if options_.nk > 0
- %filtered variable E_t(y_t+k) requires to shift trend by k periods
+ %filtered variable E_t(y_t+k) requires to shift trend by k periods
filter_steps_required=union(1,options_.filter_step_ahead); % 1 is required for standard filtered variables
for filter_iter=1:length(filter_steps_required)
filter_step=filter_steps_required(filter_iter);
@@ -172,8 +172,8 @@ end
for pos_iter=1:length(bayestopt_.mf)
oo_.Smoother.Constant.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=constant_part(pos_iter,:)';
if ismember(bayestopt_.mf(pos_iter),bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list))
- oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)';
- if ~isempty(options_.nk) && options_.nk > 0
+ oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)';
+ if ~isempty(options_.nk) && options_.nk > 0
%filtered variable E_t(y_t+1) requires to shift trend by 1 period
oo_.FilteredVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=...
squeeze(aK(1,bayestopt_.mf(pos_iter),2:end-(options_.nk-1)))...
@@ -182,7 +182,7 @@ for pos_iter=1:length(bayestopt_.mf)
filter_step=options_.filter_step_ahead(filter_iter);
oo_.FilteredVariablesKStepAhead(filter_iter,find(i_endo_in_dr_matrices==bayestopt_.mf(pos_iter)),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)) = ...
squeeze(aK(filter_step,bayestopt_.mf(pos_iter),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)))...
- +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)';
+ +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)';
end
end
%updated variables are E_t(y_t) so no trend shift is required
diff --git a/matlab/subset.m b/matlab/subset.m
index 95ad23645..946ebdcc5 100644
--- a/matlab/subset.m
+++ b/matlab/subset.m
@@ -1,6 +1,6 @@
function jndx = subset()
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -63,7 +63,7 @@ else
error
end
tt = [tt;tmp];
- elseif isempty(tmp) && nvn
+ elseif isempty(tmp) && nvn
tmp = strmatch(ExcludedParamNames{i},options_.varobs);
if ~isempty(tmp) && ( strcmpi(info,'All') || strcmpi(info,'MeasurementErrors') || ...
strcmpi(info,'MeasurementErrorsWithoutCorrelations') )
diff --git a/matlab/symmetric_matrix_index.m b/matlab/symmetric_matrix_index.m
index 73cf4a50b..60b2afe70 100644
--- a/matlab/symmetric_matrix_index.m
+++ b/matlab/symmetric_matrix_index.m
@@ -1,9 +1,9 @@
function k = symmetric_matrix_index(i,j,n)
% function k = symmetric_matrix_index(i,j,n)
-% Returns index number of variable combination (i,j) in vech(A) where A is
+% Returns index number of variable combination (i,j) in vech(A) where A is
% an symmetric n by n matrix and vech creates row vector by stacking rows
% of A on and above the diagonal
-%
+%
% Inputs:
% i [scalar] index of first variable
% j [scalar] index of second variable
@@ -11,7 +11,7 @@ function k = symmetric_matrix_index(i,j,n)
% Outputs:
% k [scalar] index of variable combination in vech(A)
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/test_for_deep_parameters_calibration.m b/matlab/test_for_deep_parameters_calibration.m
index 4dbfca7cd..3cdc831b9 100644
--- a/matlab/test_for_deep_parameters_calibration.m
+++ b/matlab/test_for_deep_parameters_calibration.m
@@ -3,17 +3,17 @@ function info=test_for_deep_parameters_calibration(M_)
%
% INPUTS
% M_ [structure] Description of the (simulated or estimated) model.
-%
+%
% OUTPUTS
-% info [scalar] 0 if no problems detected, 1 otherwise
-%
+% info [scalar] 0 if no problems detected, 1 otherwise
+%
% ALGORITHM
% none
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2010-2014 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -28,7 +28,7 @@ function info=test_for_deep_parameters_calibration(M_)
% 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 .
+% along with Dynare. If not, see .
plist = list_of_parameters_calibrated_as_NaN(M_);
if ~isempty(plist)
info=1;
diff --git a/matlab/th_autocovariances.m b/matlab/th_autocovariances.m
index 0f08c18ce..78e6fff4b 100644
--- a/matlab/th_autocovariances.m
+++ b/matlab/th_autocovariances.m
@@ -1,28 +1,28 @@
function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition)
-% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process
+% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process
% with coefficients dr.ghx and dr.ghu and shock variances Sigma_e
% for a subset of variables ivar.
% Theoretical HP-filtering and band-pass filtering is available as an option
-%
+%
% INPUTS
% dr: [structure] Reduced form solution of the DSGE model (decisions rules)
% ivar: [integer] Vector of indices for a subset of variables.
% M_ [structure] Global dynare's structure, description of the DSGE model.
% options_ [structure] Global dynare's structure.
-% nodecomposition [integer] Scalar, if different from zero the variance decomposition is not triggered.
-%
+% nodecomposition [integer] Scalar, if different from zero the variance decomposition is not triggered.
+%
% OUTPUTS
-% Gamma_y [cell] Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays,
+% Gamma_y [cell] Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays,
% where nar is the order of the autocorrelation function.
% Gamma_y{1} [double] Covariance matrix.
% Gamma_y{i+1} [double] Autocorrelation function (for i=1,...,options_.nar).
-% Gamma_y{nar+2} [double] Variance decomposition.
-% Gamma_y{nar+3} [double] Expectation of the endogenous variables associated with a second
-% order approximation.
+% Gamma_y{nar+2} [double] Variance decomposition.
+% Gamma_y{nar+3} [double] Expectation of the endogenous variables associated with a second
+% order approximation.
% stationary_vars [integer] Vector of indices of stationary variables (as a subset of 1:length(ivar))
%
% SPECIAL REQUIREMENTS
-%
+%
% Algorithms
% The means at order=2 are based on the pruned state space as
% in Kim, Kim, Schaumburg, Sims (2008): Calculating and using second-order accurate
@@ -34,15 +34,15 @@ function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,node
% Taking expectations on both sides requires to compute E(x^2)=Var(x), which
% can be obtained up to second order from the first order solution
% \[
-% \hat x_t = g_x \hat x_{t - 1} + g_u u_t
+% \hat x_t = g_x \hat x_{t - 1} + g_u u_t
% \]
-% by solving the corresponding Lyapunov equation.
+% by solving the corresponding Lyapunov equation.
% Given Var(x), the above equation can be solved for E(x_t) as
% \[
% E(x_t) = (I - {g_x}\right)^{- 1} 0.5\left( g_{\sigma\sigma} \sigma^2 + g_{xx} Var(\hat x_t) + g_{uu} Var(u_t) \right)
% \]
-%
-% Copyright (C) 2001-2014 Dynare Team
+%
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -114,7 +114,7 @@ else
trend = 1:M_.endo_nbr;
inv_order_var = trend(M_.block_structure.variable_reordered);
ghu1(1:length(dr.state_var),:) = ghu(dr.state_var,:);
-end;
+end
b = ghu1*M_.Sigma_e*ghu1';
@@ -122,7 +122,7 @@ if options_.block == 0
ipred = nstatic+(1:nspred)';
else
ipred = dr.state_var;
-end;
+end
% state space representation for state variables only
[A,B] = kalman_transition_matrix(dr,ipred,1:nx,M_.exo_nbr);
% Compute stationary variables (before HP filtering),
@@ -134,7 +134,7 @@ if options_.order == 2 || options_.hp_filter == 0
iky = inv_order_var(ivar);
else
iky = ivar;
- end;
+ end
stationary_vars = (1:length(ivar))';
if ~isempty(u)
x = abs(ghx*u);
@@ -144,7 +144,7 @@ if options_.order == 2 || options_.hp_filter == 0
aa = ghx(iky,:);
bb = ghu(iky,:);
if options_.order == 2 % mean correction for 2nd order
- if ~isempty(ikx)
+ if ~isempty(ikx)
Ex = (dr.ghs2(ikx)+dr.ghxx(ikx,:)*vx(:)+dr.ghuu(ikx,:)*M_.Sigma_e(:))/2;
Ex = (eye(n0)-AS(ikx,:))\Ex;
Gamma_y{nar+3} = NaN*ones(nvar, 1);
@@ -164,7 +164,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator
Gamma_y{1} = v;
% autocorrelations
if nar > 0
- vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
+ vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
sy = sqrt(diag(Gamma_y{1}));
sy = sy(stationary_vars);
sy = sy *sy';
@@ -209,7 +209,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator
end
else% ==> Theoretical filters.
% By construction, all variables are stationary when HP filtered
- iky = inv_order_var(ivar);
+ iky = inv_order_var(ivar);
stationary_vars = (1:length(ivar))';
aa = ghx(iky,:); %R in Uhlig (2001)
bb = ghu(iky,:); %S in Uhlig (2001)
@@ -227,22 +227,22 @@ else% ==> Theoretical filters.
filter_gain(freqs>=2*pi/lowest_periodicity & freqs<=2*pi/highest_periodicity)=1;
filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1;
else
- filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); %HP transfer function
+ filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2); %HP transfer function
end
mathp_col = NaN(ngrid,length(ivar)^2);
IA = eye(size(A,1));
IE = eye(M_.exo_nbr);
for ig = 1:ngrid
- if filter_gain(ig)==0,
+ if filter_gain(ig)==0
f_hp = zeros(length(ivar),length(ivar));
else
f_omega =(1/(2*pi))*([(IA-A*tneg(ig))\ghu1;IE]...
*M_.Sigma_e*[ghu1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
- g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
+ g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
end
mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft
- end;
+ end
% Covariance of filtered series
imathp_col = real(ifft(mathp_col))*(2*pi); % Inverse Fast Fourier Transformation; middle formula Uhlig (2001), p. 21;
Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar);
@@ -269,32 +269,32 @@ else% ==> Theoretical filters.
IA = eye(size(A,1));
IE = eye(M_.exo_nbr);
for ig = 1:ngrid
- if filter_gain(ig)==0,
+ if filter_gain(ig)==0
f_hp = zeros(length(ivar),length(ivar));
else
f_omega =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]...
*SS*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
- g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
+ g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
end
mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft
- end;
+ end
imathp_col = real(ifft(mathp_col))*(2*pi);
vv = diag(reshape(imathp_col(1,:),nvar,nvar));
for i=1:M_.exo_nbr
mathp_col = NaN(ngrid,length(ivar)^2);
SSi = cs(:,i)*cs(:,i)';
for ig = 1:ngrid
- if filter_gain(ig)==0,
+ if filter_gain(ig)==0
f_hp = zeros(length(ivar),length(ivar));
else
f_omega =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]...
*SSi*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
- g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
+ g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
end
mathp_col(ig,:) = (f_hp(:))'; % store as matrix row for ifft
- end;
+ end
imathp_col = real(ifft(mathp_col))*(2*pi);
Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv;
end
diff --git a/matlab/thet2tau.m b/matlab/thet2tau.m
index 54673e542..965934e3d 100644
--- a/matlab/thet2tau.m
+++ b/matlab/thet2tau.m
@@ -1,7 +1,7 @@
function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoments,mf,nlags,useautocorr,iv)
%
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -20,22 +20,22 @@ function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoment
global options_
-if nargin==1,
+if nargin==1
indx = [1:M_.param_nbr];
indexo = [];
end
-if nargin<7,
+if nargin<7
flagmoments=0;
end
-if nargin<10 || isempty(useautocorr),
+if nargin<10 || isempty(useautocorr)
useautocorr=0;
end
-if nargin<11 || isempty(iv),
+if nargin<11 || isempty(iv)
iv=[1:M_.endo_nbr];
end
-if length(params)>length(indx),
+if length(params)>length(indx)
M_ = set_all_parameters(params,estim_params_,M_);
else
M_.params(indx) = params;
@@ -44,7 +44,7 @@ end
% M_.Sigma_e(indexo,indexo) = diag(params(1:length(indexo)).^2);
% end
[A,B,tele,tubbies,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
-if flagmoments==0,
+if flagmoments==0
ys=oo_.dr.ys(oo_.dr.order_var);
tau = [ys(iv); vec(A(iv,iv)); dyn_vech(B(iv,:)*M_.Sigma_e*B(iv,:)')];
elseif flagmoments==-1
@@ -58,7 +58,7 @@ else
GAM = lyapunov_symm(A,B*M_.Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
k = find(abs(GAM) < 1e-12);
GAM(k) = 0;
- if useautocorr,
+ if useautocorr
sy = sqrt(diag(GAM));
sy = sy*sy';
sy0 = sy-diag(diag(sy))+eye(length(sy));
@@ -69,7 +69,7 @@ else
end
for ii = 1:nlags
dum = A^(ii)*GAM;
- if useautocorr,
+ if useautocorr
dum = dum./sy;
end
tau = [tau;vec(dum(mf,mf))];
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index c07e4707b..9fbf38358 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -135,7 +135,7 @@ dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],opt
if options_.TeX
fid=fopen([M_.fname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+');
-
+
if strcmpi(type,'DeepParameter')
tex_names=M_.param_names_tex;
base_names=M_.param_names;
@@ -146,7 +146,7 @@ if options_.TeX
tex_names=M_.endo_names_tex;
base_names=M_.endo_names;
end
-
+
if strcmpi(type,'PosteriorDensity')
FigureName = ['Trace plot for ' TYPE name1];
else
@@ -159,7 +159,7 @@ if options_.TeX
if options_.mh_nblck>1
FigureName = [ FigureName , ' (block number ' int2str(blck) ').'];
end
-
+
fprintf(fid,'%-s\n','\begin{figure}[H]');
fprintf(fid,'%-s\n','\centering');
fprintf(fid,'%-s\n',[' \includegraphics[width=0.8\textwidth]{',[M_.fname, '/graphs/TracePlot_' plot_name],'}\\']);
@@ -167,4 +167,3 @@ if options_.TeX
fprintf(fid,'%-s\n','\end{figure}');
fclose(fid);
end
-
diff --git a/matlab/trust_region.m b/matlab/trust_region.m
index 02acae0c5..13f11bd3d 100644
--- a/matlab/trust_region.m
+++ b/matlab/trust_region.m
@@ -25,7 +25,7 @@ function [x,check,info] = trust_region(fcn,x0,j1,j2,jacobian_flag,gstep,tolf,tol
% none
% Copyright (C) 2008-2012 VZLU Prague, a.s.
-% Copyright (C) 2014-2016 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -150,7 +150,7 @@ while (niter < maxiter && ~info)
else
info = -3;
end
- break;
+ break
end
elseif (abs (1-ratio) <= 0.1)
delta = 1.4142*sn;
@@ -229,4 +229,3 @@ if (xn > delta)
x = alpha * x + ((1-alpha) * min (snm, delta)) * s;
end
end
-
diff --git a/matlab/uniform_specification.m b/matlab/uniform_specification.m
index 5af782162..6baceb82f 100644
--- a/matlab/uniform_specification.m
+++ b/matlab/uniform_specification.m
@@ -3,20 +3,20 @@ function [m,s,p6,p7] = uniform_specification(m,s,p3,p4)
%
% INPUTS
% m: mean
-% s: standard deviation
-% p3: lower bound
-% p4: upper bound
+% s: standard deviation
+% p3: lower bound
+% p4: upper bound
% OUTPUTS
% m: mean
-% s: standard deviation
-% p1: lower bound
-% p2: upper bound
-%
+% s: standard deviation
+% p1: lower bound
+% p2: upper bound
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/update_last_mh_history_file.m b/matlab/update_last_mh_history_file.m
index d0c4e9ca5..a0e2d4a96 100644
--- a/matlab/update_last_mh_history_file.m
+++ b/matlab/update_last_mh_history_file.m
@@ -5,9 +5,9 @@ function update_last_mh_history_file(MetropolisFolder, ModelName, record)
% MetropolisFolder [char] Name of the metropolis subfolder
% ModelName [char] Name of the mod-file
% record [structure] structure storing the MH history
-% Outputs: none
+% Outputs: none
-% Copyright (C) 2013-2015 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/user_has_matlab_license.m b/matlab/user_has_matlab_license.m
index 51d7cf0b6..c8c681283 100644
--- a/matlab/user_has_matlab_license.m
+++ b/matlab/user_has_matlab_license.m
@@ -11,7 +11,7 @@ function [hasLicense] = user_has_matlab_license(toolbox)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -31,7 +31,7 @@ function [hasLicense] = user_has_matlab_license(toolbox)
if matlab_ver_less_than('7.12')
hasLicense = license('test', toolbox);
else
- [hasLicense junk] = license('checkout',toolbox);
+ [hasLicense, junk] = license('checkout',toolbox);
end
if ~hasLicense
return
@@ -50,7 +50,7 @@ end
hasInstallation=check_toolbox_installation(n);
if ~hasInstallation
hasLicense=0;
- return;
+ return
end
end
@@ -64,7 +64,7 @@ else
a=ver(ver_string);
if isempty(a)
hasInstallation=0;
- else
+ else
hasInstallation=1;
end
end
diff --git a/matlab/utilities/dataset/descriptive_statistics.m b/matlab/utilities/dataset/descriptive_statistics.m
index d2b52292d..79d324141 100644
--- a/matlab/utilities/dataset/descriptive_statistics.m
+++ b/matlab/utilities/dataset/descriptive_statistics.m
@@ -3,7 +3,7 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
%@info:
%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic})
-%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags)
+%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags)
%! @anchor{compute_corr}
%! This function computes various descriptive statistics on the sample (possibly with missing observations).
%!
@@ -14,15 +14,15 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
%! @item statistic
%! String. The name of the statistic to be computed. Admissible values are:
%! @table @var
-%! @item 'stdv'
+%! @item 'stdv'
%! Computes the standard deviation of each observed variable.
-%! @item 'cova'
-%! Computes the covariance matrix of the sample.
+%! @item 'cova'
+%! Computes the covariance matrix of the sample.
%! @item 'corr'
%! Computes the correlation matrix of the sample.
%! @item 'acov'
%! Computes the (multivariate) auto-covariance function of the sample. In this case a third argument (@code{nlags}) defining the
-%! maximum number of lags is mandatory.
+%! maximum number of lags is mandatory.
%! @end table
%! @item nlags
%! Integer scalar. The maximum number of lags when computing the autocovariance function.
@@ -33,20 +33,20 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
%! @item dataset_
%! Dynare structure describing the dataset, built by @ref{initialize_dataset}
%! @end table
-%!
-%! @strong{This function is called by:}
+%!
+%! @strong{This function is called by:}
%! none.
-%!
+%!
%! @strong{This function calls:}
%! @ref{compute_stdv}, @ref{compute_cova}, @ref{compute_corr}, @ref{compute_acov}.
-%!
+%!
%! @strong{Remark 1.} On exit, a new field containing the computed statistics is appended to the structure.
-%!
+%!
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/dataset/initialize_dataset.m b/matlab/utilities/dataset/initialize_dataset.m
index 0b00df4dc..d7e3ed384 100644
--- a/matlab/utilities/dataset/initialize_dataset.m
+++ b/matlab/utilities/dataset/initialize_dataset.m
@@ -1,7 +1,7 @@
function dataset_ = initialize_dataset(datafile,varobs,first,nobs,logged_data_flag,prefilter,xls)
% Initializes a structure describing the dataset.
-% Copyright (C) 2011-2013 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/dataset/lagged.m b/matlab/utilities/dataset/lagged.m
index 87a7c64a4..4f17d7eeb 100644
--- a/matlab/utilities/dataset/lagged.m
+++ b/matlab/utilities/dataset/lagged.m
@@ -1,16 +1,16 @@
-function xlag = lagged(x, n);
+function xlag = lagged(x, n)
% xlag = lagged(x, n);
% applies n-lags backward shift operator to x
-%
+%
% INPUTS
-% x = time series
+% x = time series
% n = number of backward shifts [DEFAULT=1]
-%
+%
% OUTPUT
% xlag = backward shifted series
% Copyright (C) 2017 Dynare Team
-%
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
@@ -26,7 +26,9 @@ function xlag = lagged(x, n);
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin==1, n=1; end
+if nargin==1
+ n=1;
+end
x=x(:);
-xlag=[NaN(n,1); x(1:end-n)];
+xlag=[NaN(n,1); x(1:end-n)];
\ No newline at end of file
diff --git a/matlab/utilities/dataset/makedataset.m b/matlab/utilities/dataset/makedataset.m
index e46f7aa76..85d86d841 100644
--- a/matlab/utilities/dataset/makedataset.m
+++ b/matlab/utilities/dataset/makedataset.m
@@ -23,6 +23,24 @@ function [DynareDataset, DatasetInfo, newdatainterface] = makedataset(DynareOpti
%
% See also dynare_estimation_init
+% Copyright (C) 2014-2017 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 .
+
+
if nargin<3
gsa_flag = 0;
end
@@ -107,7 +125,7 @@ if ~isempty(datafile)
DynareDataset = load_m_file_data_legacy(datafile, DynareOptions.varobs);
elseif strcmp(datafile(end-3:end),'.mat')
% Load a mat file with the old interface.
- DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs);
+ DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs);
end
end
else
diff --git a/matlab/utilities/dataset/nanvariance.m b/matlab/utilities/dataset/nanvariance.m
index d4894e8e9..121fb2dda 100644
--- a/matlab/utilities/dataset/nanvariance.m
+++ b/matlab/utilities/dataset/nanvariance.m
@@ -1,4 +1,4 @@
-function variances = nanvariance(data)
+function variances = nanvariance(data)
% Compute the standard deviation for each observed variable (possibly with missing observations).
%@info:
@@ -17,21 +17,21 @@ function variances = nanvariance(data)
%! @item variances
%! A N*1 vector of real numbers
%! @end table
-%!
-%! @strong{This function is called by:}
+%!
+%! @strong{This function is called by:}
%! @ref{descriptive_statistics}.
-%!
+%!
%! @strong{This function calls:}
%! @ref{ndim}, @ref{demean}, @ref{nandemean}.
-%!
-%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a
+%!
+%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a
%! @tex{n\times 1} vector (where @tex{n} is the number of observed variables as defined by @code{dataset_.info.nvobs}).
-%!
+%!
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2014 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/dataset/quarterly2annual.m b/matlab/utilities/dataset/quarterly2annual.m
index 4a01941bd..c5c776724 100644
--- a/matlab/utilities/dataset/quarterly2annual.m
+++ b/matlab/utilities/dataset/quarterly2annual.m
@@ -18,16 +18,16 @@ function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux
% 1 log-level
% 2 growth rate Q frequency
% aux optional input used when type>4
-%
+%
%
% OUTPUTS
% ya annual (log-)level
-% yass annual steadystate (log-)level
+% yass annual steadystate (log-)level
% gya annual growth rate
% gyass annual growth rate steadystate
% Copyright (C) 2017 Dynare Team
-%
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
@@ -43,32 +43,32 @@ function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-if nargin ==0,
+if nargin ==0
disp('[ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog);')
return
end
-if nargin<4 || isempty(type),
+if nargin<4 || isempty(type)
type=1;
end
-if nargin<5 || isempty(islog),
+if nargin<5 || isempty(islog)
islog=0;
end
-if isstruct(aux),
+if isstruct(aux)
yaux=aux.y;
yauxss=aux.yss;
islogaux=aux.islog;
GYTREND0aux=aux.GYTREND0;
- typeaux=aux.type;
+ typeaux=aux.type;
if islogaux
yaux=exp(yaux+yauxss);
yauxss=exp(yauxss);
yaux=yaux-yauxss;
end
-elseif type > 4,
+elseif type > 4
error('TYPE>4 requires auxiliary variable!')
end
-if islog == 2,
+if islog == 2
% construct loglevel out of growth rate
y = cumsum(y);
yss=0;
@@ -80,28 +80,23 @@ if islog == 1
y=y-yss;
end
switch type
-
case 1
yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1);
tmp = lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y; % annualized level
ya = tmp(4:4:end);
-
case 2
yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1)/4;
tmp = (lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y)/4; % annualized level
ya = tmp(4:4:end);
-
case 3
yass=yss;
tmp = y;
ya = tmp(4:4:end);
-
case 4
yass = yss*(exp(-GYTREND0*3/2));
- tmp = (lagged(y+yss,3)*exp(-GYTREND0*3).*lagged(y+yss,2)*exp(-GYTREND0*2).*lagged(y+yss,1)*exp(-GYTREND0).*(y+yss)).^(1/4); % annualized level
+ tmp = (lagged(y+yss,3)*exp(-GYTREND0*3).*lagged(y+yss,2)*exp(-GYTREND0*2).*lagged(y+yss,1)*exp(-GYTREND0).*(y+yss)).^(1/4); % annualized level
tmp = tmp - yass;
ya = tmp(4:4:end);
-
case 5
% nominal series
yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
@@ -110,8 +105,7 @@ switch type
[yra, yrass] = quarterly2annual(yaux,yauxss,GYTREND0aux,typeaux,0,0);
% deflator
yass = ynass/yrass;
- ya = (yna+ynass)./(yr+yrass)-yass;
-
+ ya = (yna+ynass)./(yr+yrass)-yass;
case 6
% nominal series
yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
@@ -120,14 +114,12 @@ switch type
[pa, pass] = quarterly2annual(yaux,yauxss,GYTREND0aux,2,0,0);
% real series
yass = ynass/pass;
- ya = (yna+ynass)./(pa+pass)-yass;
-
+ ya = (yna+ynass)./(pa+pass)-yass;
case 7
% nominal series
yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
[ya, yass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0);
GYTREND0=GYTREND0+GYTREND0aux;
-
otherwise
error('Wrong type input')
end
@@ -140,5 +132,4 @@ if islog
ya=log(ya+yass);
yass=log(yass);
ya=ya-yass;
-end
-
+end
\ No newline at end of file
diff --git a/matlab/utilities/doc/dynInfo.m b/matlab/utilities/doc/dynInfo.m
index 952c5bbe1..85c964974 100644
--- a/matlab/utilities/doc/dynInfo.m
+++ b/matlab/utilities/doc/dynInfo.m
@@ -31,7 +31,7 @@ function dynInfo(fun)
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/doc/get_internal_doc_block.m b/matlab/utilities/doc/get_internal_doc_block.m
index 77e4f6625..96dda6d6f 100644
--- a/matlab/utilities/doc/get_internal_doc_block.m
+++ b/matlab/utilities/doc/get_internal_doc_block.m
@@ -1,8 +1,8 @@
function block = get_internal_doc_block(fname,fpath)
% Extract doc sections from matlab's routine.
-% Copyright (C) 2011-2012 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
@@ -50,7 +50,7 @@ else
(~isempty(b1) && ~isempty(b2) && isempty(b)) )
error('get_internal_doc_block:: There is a problem with the internal block definition!')
end
- if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) )
+ if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) )
error('get_internal_doc_block:: There is a problem with the internal block definition!')
end
end
diff --git a/matlab/utilities/general/clean_current_folder.m b/matlab/utilities/general/clean_current_folder.m
index 8375c5607..6c302927e 100644
--- a/matlab/utilities/general/clean_current_folder.m
+++ b/matlab/utilities/general/clean_current_folder.m
@@ -1,6 +1,6 @@
function clean_current_folder()
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/compare_vectors.m b/matlab/utilities/general/compare_vectors.m
index e0ec681a2..00ea0c11e 100644
--- a/matlab/utilities/general/compare_vectors.m
+++ b/matlab/utilities/general/compare_vectors.m
@@ -7,13 +7,13 @@ function C = compare_vectors(f, A, B) % --*-- Unitary tests --*--
% o A vector of real numbers.
% o B vector of real numbers.
%
-% OUTPUTS
+% OUTPUTS
% o C integer scalar, 1 or 0.
%
-% REMARKS
+% REMARKS
% o It is assumed that vectors A and B have the same number of elements.
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/delete_stale_file.m b/matlab/utilities/general/delete_stale_file.m
index 8ac8b7996..d5e9951e4 100644
--- a/matlab/utilities/general/delete_stale_file.m
+++ b/matlab/utilities/general/delete_stale_file.m
@@ -2,7 +2,7 @@ function delete_stale_file(fname)
% function delete_old_files(fname)
% Checks for presence of files and deletes them if necessary
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -23,4 +23,3 @@ Files_info = dir(fname);
if length(Files_info)>0
delete(fname)
end
-
diff --git a/matlab/utilities/general/demean.m b/matlab/utilities/general/demean.m
index aed9eb4b1..741a2f107 100644
--- a/matlab/utilities/general/demean.m
+++ b/matlab/utilities/general/demean.m
@@ -17,18 +17,18 @@ function c = demean(x)
%! @item c
%! Matlab matrix (T-by-N). The demeaned x matrix.
%! @end table
-%!
-%! @strong{This function is called by:}
+%!
+%! @strong{This function is called by:}
%! @ref{compute_cova}, @ref{compute_acov}, @ref{compute_std}.
-%!
-%! @strong{This function calls:}
+%!
+%! @strong{This function calls:}
%! @ref{ndim},
-%!
+%!
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/disp_verbose.m b/matlab/utilities/general/disp_verbose.m
index 09c09e4d7..6ea4e702e 100644
--- a/matlab/utilities/general/disp_verbose.m
+++ b/matlab/utilities/general/disp_verbose.m
@@ -1,8 +1,8 @@
function disp_verbose(input_string,Verbose)
% function disp_verbose(input_string,Verbose)
% Prints input_string unless Verbose=0 is requested
-%
-% Copyright (C) 2015 Dynare Team
+%
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/dyn_mex.m b/matlab/utilities/general/dyn_mex.m
index d4fd7336f..ec682aebb 100644
--- a/matlab/utilities/general/dyn_mex.m
+++ b/matlab/utilities/general/dyn_mex.m
@@ -1,21 +1,21 @@
function dyn_mex(win_compiler,basename,force)
% Compile Dynare model dlls when model option use_dll is used
-% if C file is fresher than mex file
+% if C file is fresher than mex file
%
% INPUTS
-% o win_compiler str compiler used under Windows (unused under Linux or OSX):
+% o win_compiler str compiler used under Windows (unused under Linux or OSX):
% 'msvc' (MS Visual C)
% 'cygwin'
% o basename str filenames base
-% o force bool recompile if 1
-%
-% OUTPUTS
+% o force bool recompile if 1
+%
+% OUTPUTS
% none
%
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
index 37697e723..1e092e0ac 100644
--- a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
+++ b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
@@ -9,8 +9,8 @@ function k = get_all_variables_but_lagged_leaded_exogenous(M)
% k: vector of variable indices
%
-% Copyright (C) 2011-2016 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
@@ -31,5 +31,5 @@ if isempty(M.aux_vars)
else
type = [M.aux_vars.type];
k = [1:M.orig_endo_nbr, M.orig_endo_nbr ...
- + find((type ~= 2) & (type ~= 3))];
+ + find((type ~= 2) & (type ~= 3))];
end
\ No newline at end of file
diff --git a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
index 6b3f0b416..a199b4b0f 100644
--- a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
+++ b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
@@ -12,8 +12,8 @@ function [il,l1,ik,k1] = indices_lagged_leaded_exogenous_variables(k,M)
% ik: indices of non lagged or leaded variable in vector k
% k1: value of non lagged or leaded variable in vector k
-% Copyright (C) 2011-2016 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/isaletter.m b/matlab/utilities/general/isaletter.m
index 054ced91d..f562a320a 100644
--- a/matlab/utilities/general/isaletter.m
+++ b/matlab/utilities/general/isaletter.m
@@ -1,7 +1,7 @@
function info = isaletter(str)
% Returns 1 if the string str has at least one letter, 0 otherwise.
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/isconst.m b/matlab/utilities/general/isconst.m
index 37ee23532..28001ce4e 100644
--- a/matlab/utilities/general/isconst.m
+++ b/matlab/utilities/general/isconst.m
@@ -1,6 +1,6 @@
function aa = isconst(y)
% Returns 1 if vector y is constant, 0 otherwise.
-%
+%
% INPUTS:
% yy [double] n*1 vector.
%
@@ -10,7 +10,7 @@ function aa = isconst(y)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/isdiagonal.m b/matlab/utilities/general/isdiagonal.m
index f76e43797..a8c1a4cf8 100644
--- a/matlab/utilities/general/isdiagonal.m
+++ b/matlab/utilities/general/isdiagonal.m
@@ -1,6 +1,6 @@
function b = isdiagonal(A) % --*-- Unitary tests --*--
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -60,5 +60,3 @@ end
%$ t = isdiagonal(A);
%$ T = all(t);
%@eof:5
-
-
diff --git a/matlab/utilities/general/isint.m b/matlab/utilities/general/isint.m
index e80a79cdf..01f403d5d 100644
--- a/matlab/utilities/general/isint.m
+++ b/matlab/utilities/general/isint.m
@@ -1,21 +1,21 @@
function [l,c,d] = isint(a)
% This function tests if the input argument is an integer.
%
-% INPUT
+% INPUT
% a [double] m*n matrix.
%
-% OUTPUT
-% b [integer] m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer.
+% OUTPUT
+% b [integer] m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer.
% c [integer] p*1 vector of indices pointing to the integer elements of a.
% d [integer] q*1 vector of indices pointing to the non integer elements of a.
-%
+%
% SPECIAL REQUIREMENTS
% None.
-%
-% NOTES
+%
+% NOTES
% p+q is equal to the product of m by n.
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/ispd.m b/matlab/utilities/general/ispd.m
index 7fed2d44c..7ddd73e8a 100644
--- a/matlab/utilities/general/ispd.m
+++ b/matlab/utilities/general/ispd.m
@@ -24,7 +24,7 @@ function [test, penalty] = ispd(A)
%! @end deftypefn
%@eod:
-% Copyright (C) 2007-2009, 2013 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/isquare.m b/matlab/utilities/general/isquare.m
index da47ac62e..693417c35 100644
--- a/matlab/utilities/general/isquare.m
+++ b/matlab/utilities/general/isquare.m
@@ -22,7 +22,7 @@ function info = isquare(A)
%! @end deftypefn
%@eod:
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/utilities/general/log_variable.m b/matlab/utilities/general/log_variable.m
index 74a6aa126..98956a77c 100644
--- a/matlab/utilities/general/log_variable.m
+++ b/matlab/utilities/general/log_variable.m
@@ -12,8 +12,8 @@ function y = log_variable(ivar,x,M)
% for lagged/leaded exogenous variables
%
-% Copyright (C) 2011-2016 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/ndim.m b/matlab/utilities/general/ndim.m
index 1c4d003bb..95dda019d 100644
--- a/matlab/utilities/general/ndim.m
+++ b/matlab/utilities/general/ndim.m
@@ -3,7 +3,7 @@ function n = ndim(x)
%@info:
%! @deftypefn {Function File} {@var{n} =} ndim (@var{x})
-%! @anchor{ndim}
+%! @anchor{ndim}
%! This function reports the number of non singleton dimensions of a matlab array.
%!
%! @strong{Inputs}
@@ -17,18 +17,18 @@ function n = ndim(x)
%! @item n
%! Integer scalar. The number of non singleton dimensions of a matlab array.
%! @end table
-%!
-%! @strong{This function is called by:}
+%!
+%! @strong{This function is called by:}
%! @ref{demean}, @ref{nandemean}.
-%!
+%!
%! @strong{This function calls:}
%! none.
-%!
+%!
%! @end deftypefn
%@eod:
-% Copyright (C) 2011-2012 Dynare Team
-%
+% Copyright (C) 2011-2017 Dynare Team
+%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/remove_fractional_xticks.m b/matlab/utilities/general/remove_fractional_xticks.m
index 19eab7a04..5cf6f33fd 100644
--- a/matlab/utilities/general/remove_fractional_xticks.m
+++ b/matlab/utilities/general/remove_fractional_xticks.m
@@ -2,7 +2,7 @@ function remove_fractional_xticks
% function remove_fractional_xticks
% removes non-integer xtick-labels
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -17,7 +17,7 @@ function remove_fractional_xticks
% 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 .
+% along with Dynare. If not, see .
xticks=get(gca,'xtick');
fractional_periods=find(rem(xticks,1)~=0);
diff --git a/matlab/utilities/graphics/colorspace.m b/matlab/utilities/graphics/colorspace.m
index 3cd4f1c23..a83aee2ff 100644
--- a/matlab/utilities/graphics/colorspace.m
+++ b/matlab/utilities/graphics/colorspace.m
@@ -1,18 +1,18 @@
function varargout = colorspace(Conversion,varargin)
%COLORSPACE Transform a color image between color representations.
% B = COLORSPACE(S,A) transforms the color representation of image A
-% where S is a string specifying the conversion. The input array A
-% should be a real full double array of size Mx3 or MxNx3. The output B
+% where S is a string specifying the conversion. The input array A
+% should be a real full double array of size Mx3 or MxNx3. The output B
% is the same size as A.
%
-% S tells the source and destination color spaces, S = 'dest<-src', or
+% S tells the source and destination color spaces, S = 'dest<-src', or
% alternatively, S = 'src->dest'. Supported color spaces are
%
% 'RGB' sRGB IEC 61966-2-1
% 'YCbCr' Luma + Chroma ("digitized" version of Y'PbPr)
% 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG
% 'YDbDr' SECAM Y'DbDr Luma + Chroma
-% 'YPbPr' Luma (ITU-R BT.601) + Chroma
+% 'YPbPr' Luma (ITU-R BT.601) + Chroma
% 'YUV' NTSC PAL Y'UV Luma + Chroma
% 'YIQ' NTSC Y'IQ Luma + Chroma
% 'HSV' or 'HSB' Hue Saturation Value/Brightness
@@ -26,22 +26,22 @@ function varargout = colorspace(Conversion,varargin)
%
% All conversions assume 2 degree observer and D65 illuminant.
%
-% Color space names are case insensitive and spaces are ignored. When
-% sRGB is the source or destination, it can be omitted. For example
+% Color space names are case insensitive and spaces are ignored. When
+% sRGB is the source or destination, it can be omitted. For example
% 'yuv<-' is short for 'yuv<-rgb'.
%
-% For sRGB, the values should be scaled between 0 and 1. Beware that
-% transformations generally do not constrain colors to be "in gamut."
-% Particularly, transforming from another space to sRGB may obtain
-% R'G'B' values outside of the [0,1] range. So the result should be
+% For sRGB, the values should be scaled between 0 and 1. Beware that
+% transformations generally do not constrain colors to be "in gamut."
+% Particularly, transforming from another space to sRGB may obtain
+% R'G'B' values outside of the [0,1] range. So the result should be
% clamped to [0,1] before displaying:
% image(min(max(B,0),1)); % Clamp B to [0,1] and display
%
% sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard
-% red-green-blue representation of colors used in digital imaging. The
-% components should be scaled between 0 and 1. The space can be
+% red-green-blue representation of colors used in digital imaging. The
+% components should be scaled between 0 and 1. The space can be
% visualized geometrically as a cube.
-%
+%
% Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear
% transformations. These spaces separate a color into a grayscale
% luminance component Y and two chroma components. The valid ranges of
@@ -66,7 +66,7 @@ function varargout = colorspace(Conversion,varargin)
% S = 1 - min(R',G',B')/I (0 <= S <= 1),
% I = (R'+G'+B')/3 (0 <= I <= 1).
% Unlike HSV and HSL, the hue angle H is computed on a circle rather than
-% a hexagon.
+% a hexagon.
%
% CIE XYZ is related to sRGB by inverse gamma correction followed by a
% linear transform. Other CIE color spaces are defined relative to XYZ.
@@ -75,36 +75,29 @@ function varargout = colorspace(Conversion,varargin)
% component is designed to match closely with human perception of
% lightness. The other two components describe the chroma.
%
-% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02
-% chromatic adaptation matrix. The space is designed to model the
+% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02
+% chromatic adaptation matrix. The space is designed to model the
% response of the three types of cones in the human eye, where L, M, S,
% correspond respectively to red ("long"), green ("medium"), and blue
% ("short").
-% Pascal Getreuer 2005-2010
-% All rights reserved.
+% Copyright (C) 2005-2010 Pascal Getreuer
+% Copyright (C) 2017 Dynare Team
%
-% Redistribution and use in source and binary forms, with or without
-% modification, are permitted provided that the following conditions are
-% met:
+% This file is part of Dynare.
%
-% * Redistributions of source code must retain the above copyright
-% notice, this list of conditions and the following disclaimer.
-% * Redistributions in binary form must reproduce the above copyright
-% notice, this list of conditions and the following disclaimer in
-% the documentation and/or other materials provided with the distribution
+% 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.
%
-% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-% POSSIBILITY OF SUCH DAMAGE.
+% 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 .
%%% Input parsing %%%
if nargin < 2, error('Not enough input arguments.'); end
@@ -130,7 +123,7 @@ DestT = gettransform(DestSpace);
if ~ischar(SrcT) && ~ischar(DestT)
% Both source and destination transforms are affine, so they
% can be composed into one affine operation
- T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
+ T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
Temp = zeros(size(Image));
Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
@@ -155,7 +148,7 @@ else
varargout = {Image};
end
-return;
+return
function [SrcSpace,DestSpace] = parse(Str)
@@ -164,21 +157,21 @@ function [SrcSpace,DestSpace] = parse(Str)
if ischar(Str)
Str = lower(strrep(strrep(Str,'-',''),'=',''));
k = find(Str == '>');
-
+
if length(k) == 1 % Interpret the form 'src->dest'
SrcSpace = Str(1:k-1);
DestSpace = Str(k+1:end);
else
k = find(Str == '<');
-
+
if length(k) == 1 % Interpret the form 'dest<-src'
DestSpace = Str(1:k-1);
SrcSpace = Str(k+1:end);
else
error(['Invalid conversion, ''',Str,'''.']);
- end
+ end
end
-
+
SrcSpace = alias(SrcSpace);
DestSpace = alias(DestSpace);
else
@@ -186,7 +179,7 @@ else
DestSpace = Conversion;
if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
end
-return;
+return
function Space = alias(Space)
@@ -204,9 +197,9 @@ switch Space
case {'hsl','hsi','hls'}
Space = 'hsl';
case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
- return;
+ return
end
-return;
+return
function T = gettransform(Space)
@@ -240,14 +233,14 @@ switch Space
otherwise
error(['Unknown color space, ''',Space,'''.']);
end
-return;
+return
function Image = rgb(Image,SrcSpace)
% Convert to sRGB from 'SrcSpace'
switch SrcSpace
case 'rgb'
- return;
+ return
case 'hsv'
% Convert HSV to sRGB
Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
@@ -264,7 +257,7 @@ switch SrcSpace
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B
- % Desaturate and rescale to constrain resulting RGB values to [0,1]
+ % Desaturate and rescale to constrain resulting RGB values to [0,1]
AddWhite = -min(min(min(R,G),B),0);
R = R + AddWhite;
G = G + AddWhite;
@@ -287,16 +280,16 @@ end
% Clip to [0,1]
Image = min(max(Image,0),1);
-return;
+return
function Image = xyz(Image,SrcSpace)
% Convert to CIE XYZ from 'SrcSpace'
-WhitePoint = [0.950456,1,1.088754];
+WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'xyz'
- return;
+ return
case 'luv'
% Convert CIE L*uv to XYZ
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
@@ -324,7 +317,7 @@ switch SrcSpace
L = Image(:,:,1);
M = Image(:,:,2);
S = Image(:,:,3);
- Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X
+ Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X
Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y
Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z
otherwise % Convert from some gamma-corrected space
@@ -336,11 +329,11 @@ switch SrcSpace
B = invgammacorrection(Image(:,:,3));
% Convert RGB to XYZ
T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]);
- Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
+ Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y
Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z
end
-return;
+return
function Image = hsv(Image,SrcSpace)
@@ -351,14 +344,14 @@ S = (V - min(Image,[],3))./(V + (V == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = V;
-return;
+return
function Image = hsl(Image,SrcSpace)
-% Convert to HSL
+% Convert to HSL
switch SrcSpace
case 'hsv'
- % Convert HSV to HSL
+ % Convert HSV to HSL
MaxVal = Image(:,:,3);
MinVal = (1 - Image(:,:,2)).*MaxVal;
L = 0.5*(MaxVal + MinVal);
@@ -377,7 +370,7 @@ switch SrcSpace
Image(:,:,2) = S;
Image(:,:,3) = L;
end
-return;
+return
function Image = lab(Image,SrcSpace)
@@ -386,7 +379,7 @@ WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'lab'
- return;
+ return
case 'lch'
% Convert CIE L*CH to CIE L*ab
C = Image(:,:,2);
@@ -405,7 +398,7 @@ switch SrcSpace
Image(:,:,2) = 500*(fX - fY); % a*
Image(:,:,3) = 200*(fY - fZ); % b*
end
-return;
+return
function Image = luv(Image,SrcSpace)
@@ -423,7 +416,7 @@ L = 116*f(Y) - 16;
Image(:,:,1) = L; % L*
Image(:,:,2) = 13*L.*(U - WhitePointU); % u*
Image(:,:,3) = 13*L.*(V - WhitePointV); % v*
-return;
+return
function Image = lch(Image,SrcSpace)
@@ -433,7 +426,7 @@ H = atan2(Image(:,:,3),Image(:,:,2));
H = H*180/pi + 360*(H < 0);
Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C
Image(:,:,3) = H; % H
-return;
+return
function Image = cat02lms(Image,SrcSpace)
@@ -446,7 +439,7 @@ Z = Image(:,:,3);
Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L
Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M
Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S
-return;
+return
function Image = huetorgb(m0,m2,H)
@@ -461,7 +454,7 @@ Num = length(m0);
j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
k = floor(H) + 1;
Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
-return;
+return
function H = rgbtohue(Image)
@@ -482,7 +475,7 @@ k = (i == 3);
H(k) = 4 + (R(k) - G(k))./Delta(k);
H = 60*H + 360*(H < 0);
H(Delta == 0) = nan;
-return;
+return
function Rp = gammacorrection(R)
@@ -490,7 +483,7 @@ Rp = zeros(size(R));
i = (R <= 0.0031306684425005883);
Rp(i) = 12.92*R(i);
Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055);
-return;
+return
function R = invgammacorrection(Rp)
@@ -498,18 +491,18 @@ R = zeros(size(Rp));
i = (Rp <= 0.0404482362771076);
R(i) = Rp(i)/12.92;
R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4);
-return;
+return
function fY = f(Y)
fY = real(Y.^(1/3));
i = (Y < 0.008856);
fY(i) = Y(i)*(841/108) + (4/29);
-return;
+return
function Y = invf(fY)
Y = fY.^3;
i = (Y < 0.008856);
Y(i) = (fY(i) - 4/29)*(108/841);
-return;
+return
diff --git a/matlab/utilities/graphics/distinguishable_colors.m b/matlab/utilities/graphics/distinguishable_colors.m
index f2c66231d..027ad2cb6 100644
--- a/matlab/utilities/graphics/distinguishable_colors.m
+++ b/matlab/utilities/graphics/distinguishable_colors.m
@@ -53,32 +53,24 @@ function colors = distinguishable_colors(n_colors,bg,func)
% Example using the file exchange's 'colorspace':
% func = @(x) colorspace('RGB->Lab',x);
% c = distinguishable_colors(25,'w',func);
-
-% Copyright 2010-2011 by Timothy E. Holy
-% All rights reserved.
+
+% Copyright (C) 2005-2010 2010-2011 by Timothy E. Holy
+% Copyright (C) 2017 Dynare Team
%
-% Redistribution and use in source and binary forms, with or without
-% modification, are permitted provided that the following conditions are
-% met:
+% This file is part of Dynare.
%
-% * Redistributions of source code must retain the above copyright
-% notice, this list of conditions and the following disclaimer.
-% * Redistributions in binary form must reproduce the above copyright
-% notice, this list of conditions and the following disclaimer in
-% the documentation and/or other materials provided with the distribution
+% 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.
%
-% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-% POSSIBILITY OF SUCH DAMAGE.
-
+% 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 .
% Parse the inputs
if (nargin < 2)
@@ -162,9 +154,9 @@ k = find(cspec==c(1));
if isempty(k)
error('MATLAB:InvalidColorString','Unknown color string.');
end
-if k~=3 || length(c)==1,
+if k~=3 || length(c)==1
c = rgbspec(k,:);
-elseif length(c)>2,
+elseif length(c)>2
if strcmpi(c(1:3),'bla')
c = [0 0 0];
elseif strcmpi(c(1:3),'blu')
diff --git a/matlab/utilities/tests b/matlab/utilities/tests
index c548b2a91..fe65c7727 160000
--- a/matlab/utilities/tests
+++ b/matlab/utilities/tests
@@ -1 +1 @@
-Subproject commit c548b2a91ebedde0d625fe53f5c9f86b0911c45d
+Subproject commit fe65c7727f4d1b91355b62b2cc58f5775c287afd
diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m
index cfaf71c9a..4621f25d3 100644
--- a/matlab/variance_decomposition_mc_analysis.m
+++ b/matlab/variance_decomposition_mc_analysis.m
@@ -25,7 +25,7 @@ function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -94,7 +94,7 @@ if options_.estimation.moments_posterior_density.indicator
posterior_moments(tmp,1,mh_conf_sig);
else
[p_mean, p_median, p_var, hpd_interval, p_deciles] = ...
- posterior_moments(tmp,0,mh_conf_sig);
+ posterior_moments(tmp,0,mh_conf_sig);
end
oo_.([TYPE, 'TheoreticalMoments']).dsge.VarianceDecomposition.Mean.(var).(exo) = p_mean;
diff --git a/matlab/varlist_indices.m b/matlab/varlist_indices.m
index 1299e54d5..4347f9af4 100644
--- a/matlab/varlist_indices.m
+++ b/matlab/varlist_indices.m
@@ -1,10 +1,10 @@
function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
-% function [i_var,nvar] = varlist_indices(sublist,list)
+% function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
% returns the indices of a list of endogenous variables
%
% INPUT
% sublist: sublist of variables
-% list: list of variables
+% list: list of variables
%
% OUTPUT
% i_var: variable indices in M_.endo_names
@@ -14,7 +14,7 @@ function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2010-2014 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/ver_greater_than.m b/matlab/ver_greater_than.m
index 1fef34bf2..7bd973f45 100644
--- a/matlab/ver_greater_than.m
+++ b/matlab/ver_greater_than.m
@@ -12,7 +12,7 @@ function tf = ver_greater_than(ver1, ver2)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'});
maj_ver1 = str2double(ver1{1});
maj_ver2 = str2double(ver2{1});
if maj_ver1 > maj_ver2
- return;
+ return
end
min_ver1 = str2double(ver1{2});
min_ver2 = str2double(ver2{2});
if (maj_ver1 == maj_ver2) && (min_ver1 > min_ver2)
- return;
+ return
end
if (length(ver1) == length(ver2) && length(ver1) == 3)
ismaster1 = isnan(str2double(ver1{3}));
ismaster2 = isnan(str2double(ver2{3}));
if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (ismaster1 && ~ismaster2)
- return;
+ return
end
if ~ismaster1 && ~ismaster2
rev_ver1 = str2double(ver1{3});
rev_ver2 = str2double(ver2{3});
if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 > rev_ver2)
- return;
+ return
end
end
end
diff --git a/matlab/ver_less_than.m b/matlab/ver_less_than.m
index e953ed8a2..c71d163be 100644
--- a/matlab/ver_less_than.m
+++ b/matlab/ver_less_than.m
@@ -12,7 +12,7 @@ function tf = ver_less_than(ver1, ver2)
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'});
maj_ver1 = str2double(ver1{1});
maj_ver2 = str2double(ver2{1});
if maj_ver1 < maj_ver2
- return;
+ return
end
min_ver1 = str2double(ver1{2});
min_ver2 = str2double(ver2{2});
if (maj_ver1 == maj_ver2) && (min_ver1 < min_ver2)
- return;
+ return
end
if (length(ver1) == length(ver2) && length(ver1) == 3)
ismaster1 = isnan(str2double(ver1{3}));
ismaster2 = isnan(str2double(ver2{3}));
if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (~ismaster1 && ismaster2)
- return;
+ return
end
if ~ismaster1 && ~ismaster2
rev_ver1 = str2double(ver1{3});
rev_ver2 = str2double(ver2{3});
if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 < rev_ver2)
- return;
+ return
end
end
end
diff --git a/matlab/vnorm.m b/matlab/vnorm.m
index fc9f5850a..5d3cdadd6 100644
--- a/matlab/vnorm.m
+++ b/matlab/vnorm.m
@@ -35,7 +35,7 @@ function y = vnorm(A,varargin)
% vnorm(A,[],inf) % Correct
%
%
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -88,4 +88,3 @@ elseif ntype~=floor(ntype) || ntype<1
else
y = (sum( abs(A).^ntype , dim) ).^(1/ntype);
end
-
diff --git a/matlab/warning_config.m b/matlab/warning_config.m
index 3b9f45d63..a7cbaab92 100644
--- a/matlab/warning_config.m
+++ b/matlab/warning_config.m
@@ -3,14 +3,14 @@ function warning_config()
%
% INPUTS
% none
-%
+%
% OUTPUTS
% none
-%
+%
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2008-2015 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/write_latex_definitions.m b/matlab/write_latex_definitions.m
index 144f6242b..e9345ac6a 100644
--- a/matlab/write_latex_definitions.m
+++ b/matlab/write_latex_definitions.m
@@ -12,7 +12,7 @@ function write_latex_definitions
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m
index 5a753c31c..92374d77c 100644
--- a/matlab/write_latex_parameter_table.m
+++ b/matlab/write_latex_parameter_table.m
@@ -12,7 +12,7 @@ function write_latex_parameter_table
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -29,7 +29,7 @@ function write_latex_parameter_table
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see .
-global M_;
+global M_
if ~isequal(M_.param_names,M_.param_names_long)
Long_names_present=1;
@@ -38,7 +38,7 @@ else
end
fid = fopen([M_.fname '_latex_parameters.tex'], 'w');
fprintf(fid, '\\begin{center}\n');
-if Long_names_present==1;
+if Long_names_present==1
fprintf(fid, '\\begin{longtable}{ccc}\n');
else
fprintf(fid, '\\begin{longtable}{cc}\n');
@@ -48,7 +48,7 @@ fprintf(fid, ['\\caption{Parameter Values}\\\\%%\n']);
fprintf(fid, '\\toprule%%\n');
fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n');
fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} ');
-if Long_names_present==1;
+if Long_names_present==1
fprintf(fid, '&\n \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n');
else
fprintf(fid, ' \\\\%%\n');
@@ -56,7 +56,7 @@ end
fprintf(fid, '\\midrule%%\n');
fprintf(fid, '\\endfirsthead\n');
-if Long_names_present==1;
+if Long_names_present==1
fprintf(fid, '\\multicolumn{3}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n');
else
fprintf(fid, '\\multicolumn{2}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n');
@@ -64,7 +64,7 @@ end
fprintf(fid, '\\midrule%%\n');
fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n');
fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} ');
-if Long_names_present==1;
+if Long_names_present==1
fprintf(fid, '&\n \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n');
else
fprintf(fid, '\\\\%%\n');
@@ -75,7 +75,7 @@ fprintf(fid, '\\endhead\n');
tex = M_.param_names_tex;
long = M_.param_names_long;
for j=1:size(tex,1)
- if Long_names_present==1;
+ if Long_names_present==1
% replace underscores
long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_');
% replace percent
diff --git a/matlab/write_latex_prior_table.m b/matlab/write_latex_prior_table.m
index db9c8bfbc..2fb738bd7 100644
--- a/matlab/write_latex_prior_table.m
+++ b/matlab/write_latex_prior_table.m
@@ -11,7 +11,7 @@ function write_latex_prior_table
% SPECIAL REQUIREMENTS
% none
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/write_mh_history_file.m b/matlab/write_mh_history_file.m
index 00984c26c..72ce6a22e 100644
--- a/matlab/write_mh_history_file.m
+++ b/matlab/write_mh_history_file.m
@@ -5,10 +5,10 @@ function i = write_mh_history_file(MetropolisFolder, ModelName, record)
% MetropolisFolder [char] Name of the metropolis subfolder
% ModelName [char] Name of the mod-file
% record [structure] structure storing the MH history
-% Outputs:
+% Outputs:
% i [scalar] number of the mh_history file
-% Copyright (C) 2013-2015 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/writecellofchar.m b/matlab/writecellofchar.m
index 9ad378cb2..c08f4bb50 100644
--- a/matlab/writecellofchar.m
+++ b/matlab/writecellofchar.m
@@ -2,13 +2,13 @@ function str = writecellofchar(c)
% Writes a two dimensional cell of char in a string.
%
-% INPUTS
+% INPUTS
% - c [cell] cell of char.
%
-% OUTPUTS
+% OUTPUTS
% - str [char]
%
-% EXAMPLES
+% EXAMPLES
% >> writecellofchar({'a', {'b'; 'c'}})
%
% ans =
@@ -19,9 +19,9 @@ function str = writecellofchar(c)
%
% ans =
%
-%{'a', '['b'; 'c']', 'd'}
+%{'a', '['b'; 'c']', 'd'}
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/writedata.m b/matlab/writedata.m
index 112d7f130..c714728fc 100644
--- a/matlab/writedata.m
+++ b/matlab/writedata.m
@@ -1,6 +1,6 @@
function writedata(fname)
% function writedata(fname)
-% store endogenous and exogenous variables in a XLS spreadsheet file
+% store endogenous and exogenous variables in a XLS spreadsheet file
% INPUT
% fname: name of the XLS file
% OUTPUT
@@ -10,7 +10,7 @@ function writedata(fname)
% SPECIAL REQUIREMENT
% none
-% Copyright (C) 2007-2014 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/matlab/writedata_text.m b/matlab/writedata_text.m
index 5af543e9c..0fa0f7ac2 100644
--- a/matlab/writedata_text.m
+++ b/matlab/writedata_text.m
@@ -1,6 +1,6 @@
function writedata_text(fname)
% function writedata(fname)
-% store endogenous and exogenous variables in a text file
+% store endogenous and exogenous variables in a text file
% INPUT
% fname: name of the text file
% OUTPUT
@@ -10,7 +10,7 @@ function writedata_text(fname)
% SPECIAL REQUIREMENT
% none
-% Copyright (C) 2007-2009 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
%
% This file is part of Dynare.
%
@@ -32,7 +32,7 @@ S=[fname '_endo.dat'];
fid = fopen(S,'w');
for i = 1:size(M_.endo_names,1)
fprintf(fid,'%s ',M_.endo_names(i,:)');
-end;
+end
fprintf(fid,'\n');
for i = 1:size(oo_.endo_simul,2)
fprintf(fid,'%15.7f ',oo_.endo_simul(:,i));
@@ -44,11 +44,10 @@ S=[fname '_exo.dat'];
fid = fopen(S,'w');
for i = 1:size(M_.exo_names,1)
fprintf(fid,'%s ',M_.exo_names(i,:));
-end;
+end
fprintf(fid,'\n');
for i = 1:size(oo_.exo_simul,1)
fprintf(fid,'%15.7f ',oo_.exo_simul(i,:));
fprintf(fid,'\n');
end
-fclose(fid);
-return;
\ No newline at end of file
+fclose(fid);
\ No newline at end of file
diff --git a/matlab/writematrixofchar.m b/matlab/writematrixofchar.m
index aca783955..5f3f26359 100644
--- a/matlab/writematrixofchar.m
+++ b/matlab/writematrixofchar.m
@@ -2,13 +2,13 @@ function str = writematrixofchar(m)
% Writes a matrix of char in a string.
%
-% INPUTS
+% INPUTS
% - m [char] matrix of char.
%
-% OUTPUTS
+% OUTPUTS
% - str [char]
%
-% EXAMPLE
+% EXAMPLE
% >> writematrixofchar(['a'; 'b'])
%
% ans =
@@ -17,7 +17,7 @@ function str = writematrixofchar(m)
%
% where the returned argument is a string which can be evaluated or printed.
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac
index 5bc631690..5fd9aa04d 100644
--- a/mex/build/matlab/configure.ac
+++ b/mex/build/matlab/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see .
AC_PREREQ([2.62])
-AC_INIT([dynare], [4.5-unstable])
+AC_INIT([dynare], [4.6-unstable])
AC_CONFIG_SRCDIR([configure.ac])
AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign])
diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac
index fd563e61c..54351c003 100755
--- a/mex/build/octave/configure.ac
+++ b/mex/build/octave/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see .
AC_PREREQ([2.62])
-AC_INIT([dynare], [4.5-unstable])
+AC_INIT([dynare], [4.6-unstable])
AC_CONFIG_SRCDIR([configure.ac])
AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign])
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.cc b/mex/sources/block_kalman_filter/block_kalman_filter.cc
index 6ef1087a6..4da025ce7 100644
--- a/mex/sources/block_kalman_filter/block_kalman_filter.cc
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.h b/mex/sources/block_kalman_filter/block_kalman_filter.h
index 83eac9a44..28cb75396 100644
--- a/mex/sources/block_kalman_filter/block_kalman_filter.h
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2012 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh
index f9a745d54..b03599444 100644
--- a/mex/sources/bytecode/ErrorHandling.hh
+++ b/mex/sources/bytecode/ErrorHandling.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2015 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
@@ -386,7 +386,7 @@ public:
string tmp_n(str.length(), ' ');
string dollar, pound, tilde;
dollar = "$";
- pound = "£";
+ pound = "£";
tilde = "~";
for (unsigned int i = 0; i < str.length(); i++)
{
@@ -1329,7 +1329,7 @@ public:
tmp_out << "$";
tmp_out << " / ";
if (isinf(r))
- tmp_out << "£";
+ tmp_out << "£";
}
else
tmp_out << " / ";
@@ -1492,7 +1492,7 @@ public:
if (compute)
{
if (isnan(r))
- tmp_out << "$ ^ " << "£";
+ tmp_out << "$ ^ " << "£";
else
tmp_out << " ^ ";
}
@@ -1534,7 +1534,7 @@ public:
if (compute)
{
if (isnan(r))
- tmp_out << "$ PowerDeriv " << "£";
+ tmp_out << "$ PowerDeriv " << "£";
else
tmp_out << "PowerDeriv";
}
@@ -1608,7 +1608,7 @@ public:
if (compute)
{
if (isnan(r))
- tmp_out << "$log" << "£" << "(" << v1 << ")";
+ tmp_out << "$log" << "£" << "(" << v1 << ")";
else
tmp_out << "log(" << v1 << ")";
}
@@ -1626,7 +1626,7 @@ public:
if (compute)
{
if (isnan(r))
- tmp_out << "$log10" << "£" << "(" << v1 << ")";
+ tmp_out << "$log10" << "£" << "(" << v1 << ")";
else
tmp_out << "log10(" << v1 << ")";
}
diff --git a/mex/sources/bytecode/Evaluate.cc b/mex/sources/bytecode/Evaluate.cc
index 20e94ba06..c0860b011 100644
--- a/mex/sources/bytecode/Evaluate.cc
+++ b/mex/sources/bytecode/Evaluate.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/Evaluate.hh b/mex/sources/bytecode/Evaluate.hh
index 2ff37e915..bcf62824b 100644
--- a/mex/sources/bytecode/Evaluate.hh
+++ b/mex/sources/bytecode/Evaluate.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc
index a31b5d148..1c36f5a86 100644
--- a/mex/sources/bytecode/Interpreter.cc
+++ b/mex/sources/bytecode/Interpreter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh
index ab1cda491..d41e0c8cd 100644
--- a/mex/sources/bytecode/Interpreter.hh
+++ b/mex/sources/bytecode/Interpreter.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/Mem_Mngr.cc b/mex/sources/bytecode/Mem_Mngr.cc
index 78a713688..52a2ab905 100644
--- a/mex/sources/bytecode/Mem_Mngr.cc
+++ b/mex/sources/bytecode/Mem_Mngr.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/Mem_Mngr.hh b/mex/sources/bytecode/Mem_Mngr.hh
index 3d2140c26..4bde597a0 100644
--- a/mex/sources/bytecode/Mem_Mngr.hh
+++ b/mex/sources/bytecode/Mem_Mngr.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2010 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc
index eb6eefc00..7526bbf4e 100644
--- a/mex/sources/bytecode/SparseMatrix.cc
+++ b/mex/sources/bytecode/SparseMatrix.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/SparseMatrix.hh b/mex/sources/bytecode/SparseMatrix.hh
index 7d40bdd9c..087853755 100644
--- a/mex/sources/bytecode/SparseMatrix.hh
+++ b/mex/sources/bytecode/SparseMatrix.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc
index 3e00913b8..80ba1b450 100644
--- a/mex/sources/bytecode/bytecode.cc
+++ b/mex/sources/bytecode/bytecode.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/bytecode/testing/mex_interface.hh b/mex/sources/bytecode/testing/mex_interface.hh
index d734c8366..aaee45edf 100644
--- a/mex/sources/bytecode/testing/mex_interface.hh
+++ b/mex/sources/bytecode/testing/mex_interface.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/dynumfpack.h b/mex/sources/dynumfpack.h
index d21ed7954..1eb5511d3 100644
--- a/mex/sources/dynumfpack.h
+++ b/mex/sources/dynumfpack.h
@@ -3,7 +3,7 @@
*/
/*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc
index d8e38960f..41c095925 100644
--- a/mex/sources/estimation/DecisionRules.cc
+++ b/mex/sources/estimation/DecisionRules.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/DecisionRules.hh b/mex/sources/estimation/DecisionRules.hh
index 069536e8f..65b965aea 100644
--- a/mex/sources/estimation/DecisionRules.hh
+++ b/mex/sources/estimation/DecisionRules.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/DetrendData.cc b/mex/sources/estimation/DetrendData.cc
index 7a24c89e5..f9fa1b76d 100644
--- a/mex/sources/estimation/DetrendData.cc
+++ b/mex/sources/estimation/DetrendData.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/DetrendData.hh b/mex/sources/estimation/DetrendData.hh
index ce4d185cc..408b14a11 100644
--- a/mex/sources/estimation/DetrendData.hh
+++ b/mex/sources/estimation/DetrendData.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc
index a6810ceb1..5fd2bad2b 100644
--- a/mex/sources/estimation/EstimatedParameter.cc
+++ b/mex/sources/estimation/EstimatedParameter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh
index 69f2e3be8..52cc26187 100644
--- a/mex/sources/estimation/EstimatedParameter.hh
+++ b/mex/sources/estimation/EstimatedParameter.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/EstimatedParametersDescription.hh b/mex/sources/estimation/EstimatedParametersDescription.hh
index 24a210d1c..2fc2ad8ea 100644
--- a/mex/sources/estimation/EstimatedParametersDescription.hh
+++ b/mex/sources/estimation/EstimatedParametersDescription.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/EstimationSubsample.cc b/mex/sources/estimation/EstimationSubsample.cc
index 51d6c556d..a8dba8039 100644
--- a/mex/sources/estimation/EstimationSubsample.cc
+++ b/mex/sources/estimation/EstimationSubsample.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh
index b4e6ad459..d8c90723a 100644
--- a/mex/sources/estimation/EstimationSubsample.hh
+++ b/mex/sources/estimation/EstimationSubsample.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc
index adbd7565d..095032494 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.cc
+++ b/mex/sources/estimation/InitializeKalmanFilter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh
index 7a49f7ad1..a78b5970e 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.hh
+++ b/mex/sources/estimation/InitializeKalmanFilter.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc
index a97a7110b..db9628b81 100644
--- a/mex/sources/estimation/KalmanFilter.cc
+++ b/mex/sources/estimation/KalmanFilter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh
index f199ec87b..4de6e156e 100644
--- a/mex/sources/estimation/KalmanFilter.hh
+++ b/mex/sources/estimation/KalmanFilter.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc
index 42ebd789b..e775dbc3b 100644
--- a/mex/sources/estimation/LogLikelihoodMain.cc
+++ b/mex/sources/estimation/LogLikelihoodMain.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh
index e18c84cb2..33863f336 100644
--- a/mex/sources/estimation/LogLikelihoodMain.hh
+++ b/mex/sources/estimation/LogLikelihoodMain.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc
index 7d53b67fb..6c647c1f8 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.cc
+++ b/mex/sources/estimation/LogLikelihoodSubSample.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh
index e87071ffa..e9f0dbe9a 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.hh
+++ b/mex/sources/estimation/LogLikelihoodSubSample.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc
index b7b94dbbd..c87e6dee7 100644
--- a/mex/sources/estimation/LogPosteriorDensity.cc
+++ b/mex/sources/estimation/LogPosteriorDensity.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh
index c8088bcb7..425eb625a 100644
--- a/mex/sources/estimation/LogPosteriorDensity.hh
+++ b/mex/sources/estimation/LogPosteriorDensity.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh
index b1f424810..c7c57a6bd 100644
--- a/mex/sources/estimation/LogPriorDensity.hh
+++ b/mex/sources/estimation/LogPriorDensity.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2012 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc
index 3a8478dd8..abeb02124 100644
--- a/mex/sources/estimation/ModelSolution.cc
+++ b/mex/sources/estimation/ModelSolution.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh
index 88f312056..8bdc4a66a 100644
--- a/mex/sources/estimation/ModelSolution.hh
+++ b/mex/sources/estimation/ModelSolution.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh
index c3d0ce3e1..f550e2b75 100644
--- a/mex/sources/estimation/Prior.hh
+++ b/mex/sources/estimation/Prior.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/Proposal.cc b/mex/sources/estimation/Proposal.cc
index f632ab2c4..8bf5933d4 100644
--- a/mex/sources/estimation/Proposal.cc
+++ b/mex/sources/estimation/Proposal.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh
index 7d1386cc8..4beb1c9dd 100644
--- a/mex/sources/estimation/Proposal.hh
+++ b/mex/sources/estimation/Proposal.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
index 0a28dbb4e..c09b2c9df 100644
--- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh
+++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/SteadyStateSolver.cc b/mex/sources/estimation/SteadyStateSolver.cc
index 03361cda2..a0bb7cbe0 100644
--- a/mex/sources/estimation/SteadyStateSolver.cc
+++ b/mex/sources/estimation/SteadyStateSolver.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/SteadyStateSolver.hh b/mex/sources/estimation/SteadyStateSolver.hh
index 846543c7d..726d8594b 100644
--- a/mex/sources/estimation/SteadyStateSolver.hh
+++ b/mex/sources/estimation/SteadyStateSolver.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh
index 1acef6dad..b85d73728 100644
--- a/mex/sources/estimation/libmat/DiscLyapFast.hh
+++ b/mex/sources/estimation/libmat/DiscLyapFast.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
index ca6fde75a..47fc2816e 100644
--- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
+++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
index 3d2898f84..e6d939604 100644
--- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
+++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/LUSolver.hh b/mex/sources/estimation/libmat/LUSolver.hh
index 1c0af58c1..16ab45dad 100644
--- a/mex/sources/estimation/libmat/LUSolver.hh
+++ b/mex/sources/estimation/libmat/LUSolver.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh
index 774811f5d..b17e5b3ce 100644
--- a/mex/sources/estimation/libmat/Matrix.hh
+++ b/mex/sources/estimation/libmat/Matrix.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2012 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/QRDecomposition.hh b/mex/sources/estimation/libmat/QRDecomposition.hh
index 0d1f900dc..d77c2baaf 100644
--- a/mex/sources/estimation/libmat/QRDecomposition.hh
+++ b/mex/sources/estimation/libmat/QRDecomposition.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh
index 5deaa4deb..f4c71c404 100644
--- a/mex/sources/estimation/libmat/Vector.hh
+++ b/mex/sources/estimation/libmat/Vector.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc
index ee9dd2f64..6551701d8 100644
--- a/mex/sources/estimation/logMHMCMCposterior.cc
+++ b/mex/sources/estimation/logMHMCMCposterior.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc
index 319d5e517..95e4e3cbe 100644
--- a/mex/sources/estimation/logposterior.cc
+++ b/mex/sources/estimation/logposterior.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc
index 21bd12954..28139ccdb 100644
--- a/mex/sources/estimation/tests/testInitKalman.cc
+++ b/mex/sources/estimation/tests/testInitKalman.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc
index 29e85c600..f75f3459e 100644
--- a/mex/sources/estimation/tests/testKalman.cc
+++ b/mex/sources/estimation/tests/testKalman.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc
index c4eeecc68..e9d126d9e 100644
--- a/mex/sources/estimation/utils/dynamic_dll.cc
+++ b/mex/sources/estimation/utils/dynamic_dll.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh
index ce346d08a..5e19472ee 100644
--- a/mex/sources/estimation/utils/dynamic_dll.hh
+++ b/mex/sources/estimation/utils/dynamic_dll.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/utils/static_dll.hh b/mex/sources/estimation/utils/static_dll.hh
index 3ca5febc3..36b28a9f2 100644
--- a/mex/sources/estimation/utils/static_dll.hh
+++ b/mex/sources/estimation/utils/static_dll.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h
index ba0bfb324..c3d3ea3c7 100644
--- a/mex/sources/estimation/utils/ts_exception.h
+++ b/mex/sources/estimation/utils/ts_exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/k_order_perturbation/dynamic_dll.hh b/mex/sources/k_order_perturbation/dynamic_dll.hh
index 922f1d12d..15b4acfe9 100644
--- a/mex/sources/k_order_perturbation/dynamic_dll.hh
+++ b/mex/sources/k_order_perturbation/dynamic_dll.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2012 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/k_order_perturbation/dynamic_m.hh b/mex/sources/k_order_perturbation/dynamic_m.hh
index 746acdedc..260d07ef8 100644
--- a/mex/sources/k_order_perturbation/dynamic_m.hh
+++ b/mex/sources/k_order_perturbation/dynamic_m.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc
index 5a5e7a1cc..7602b550d 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.cc
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2014 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.hh b/mex/sources/k_order_perturbation/k_ord_dynare.hh
index f0644acbb..b5d942f6b 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.hh
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2012 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc
index 4be824595..1159b810b 100644
--- a/mex/sources/k_order_perturbation/k_order_perturbation.cc
+++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2014 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
index be71632d6..492a18ff6 100644
--- a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
+++ b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/linsolve/linsolve.cc b/mex/sources/linsolve/linsolve.cc
index daec3999f..c8e55eecb 100644
--- a/mex/sources/linsolve/linsolve.cc
+++ b/mex/sources/linsolve/linsolve.cc
@@ -10,7 +10,7 @@
*/
/*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
index 19cc5739e..3b45d193a 100644
--- a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
+++ b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c
index c73165d35..5086dc8d4 100644
--- a/mex/sources/mjdgges/mjdgges.c
+++ b/mex/sources/mjdgges/mjdgges.c
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006-2016 Dynare Team
+ * Copyright (C) 2006-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/ms-sbvar/mex_top_level.cc b/mex/sources/ms-sbvar/mex_top_level.cc
index 4ca78b408..9d982f327 100644
--- a/mex/sources/ms-sbvar/mex_top_level.cc
+++ b/mex/sources/ms-sbvar/mex_top_level.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/ms-sbvar/mex_write_to_matlab.c b/mex/sources/ms-sbvar/mex_write_to_matlab.c
index 8f7a5c580..1d14ffe3e 100644
--- a/mex/sources/ms-sbvar/mex_write_to_matlab.c
+++ b/mex/sources/ms-sbvar/mex_write_to_matlab.c
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2011 Dynare Team
+ * Copyright (C) 2011-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/ms-sbvar/modify_for_mex.h b/mex/sources/ms-sbvar/modify_for_mex.h
index 0dae81f70..0689df90f 100644
--- a/mex/sources/ms-sbvar/modify_for_mex.h
+++ b/mex/sources/ms-sbvar/modify_for_mex.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/qzcomplex/qzcomplex.cc b/mex/sources/qzcomplex/qzcomplex.cc
index 92cf7f7ae..74773fcdc 100644
--- a/mex/sources/qzcomplex/qzcomplex.cc
+++ b/mex/sources/qzcomplex/qzcomplex.cc
@@ -6,7 +6,7 @@
*/
/*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/mex/sources/sobol/gaussian.hh b/mex/sources/sobol/gaussian.hh
index 8692814f4..6dd00ca22 100644
--- a/mex/sources/sobol/gaussian.hh
+++ b/mex/sources/sobol/gaussian.hh
@@ -2,7 +2,7 @@
**
** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm
**
-** Copyright (C) 2010-2016 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
**
** This file is part of Dynare.
**
diff --git a/mex/sources/sobol/initialize_v_array.hh b/mex/sources/sobol/initialize_v_array.hh
index c276701f4..ad172d7a5 100644
--- a/mex/sources/sobol/initialize_v_array.hh
+++ b/mex/sources/sobol/initialize_v_array.hh
@@ -7,7 +7,7 @@ initialize_v_array(int dim_max, int log_max, T **v)
** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
**
** Copyright (C) 2009 John Burkardt
-** Copyright (C) 2010-2011 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
@@ -21,8 +21,6 @@ initialize_v_array(int dim_max, int log_max, T **v)
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program. If not, see .
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
*/
{
#include "initialize_v_array.inc"
diff --git a/mex/sources/sobol/qmc_sequence.cc b/mex/sources/sobol/qmc_sequence.cc
index 6b60d1614..e99d80594 100644
--- a/mex/sources/sobol/qmc_sequence.cc
+++ b/mex/sources/sobol/qmc_sequence.cc
@@ -1,7 +1,7 @@
/*
** Computes Quasi Monte-Carlo sequence.
**
-** Copyright (C) 2010-2012 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
**
** This file is part of Dynare (can be used outside Dynare).
**
@@ -17,8 +17,6 @@
**
** You should have received a copy of the GNU General Public License
** along with Dynare. If not, see .
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
**/
#include
diff --git a/mex/sources/sobol/sobol.hh b/mex/sources/sobol/sobol.hh
index 37c589412..8926daca9 100644
--- a/mex/sources/sobol/sobol.hh
+++ b/mex/sources/sobol/sobol.hh
@@ -3,7 +3,7 @@
** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
**
** Copyright (C) 2009 John Burkardt
-** Copyright (C) 2010-2011 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
@@ -17,8 +17,6 @@
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program. If not, see .
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
*/
#include
diff --git a/preprocessor/ConfigFile.cc b/preprocessor/ConfigFile.cc
index 36a1faa7d..64d899e13 100644
--- a/preprocessor/ConfigFile.cc
+++ b/preprocessor/ConfigFile.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/ConfigFile.hh b/preprocessor/ConfigFile.hh
index e054922f7..e3d9143eb 100644
--- a/preprocessor/ConfigFile.hh
+++ b/preprocessor/ConfigFile.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/DataTree.hh b/preprocessor/DataTree.hh
index 72b12ddbe..486b57441 100644
--- a/preprocessor/DataTree.hh
+++ b/preprocessor/DataTree.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/DynareMain.cc b/preprocessor/DynareMain.cc
index 51fa77672..887cf2818 100644
--- a/preprocessor/DynareMain.cc
+++ b/preprocessor/DynareMain.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/ExtendedPreprocessorTypes.hh b/preprocessor/ExtendedPreprocessorTypes.hh
index 4c6869a38..bf57a19f5 100644
--- a/preprocessor/ExtendedPreprocessorTypes.hh
+++ b/preprocessor/ExtendedPreprocessorTypes.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2014-2015 Dynare Team
+ * Copyright (C) 2014-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/ExternalFunctionsTable.cc b/preprocessor/ExternalFunctionsTable.cc
index 8554d8304..eb4ab00cb 100644
--- a/preprocessor/ExternalFunctionsTable.cc
+++ b/preprocessor/ExternalFunctionsTable.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2015 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/ExternalFunctionsTable.hh b/preprocessor/ExternalFunctionsTable.hh
index aa4b02cdf..42d18391e 100644
--- a/preprocessor/ExternalFunctionsTable.hh
+++ b/preprocessor/ExternalFunctionsTable.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2015 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/MinimumFeedbackSet.cc b/preprocessor/MinimumFeedbackSet.cc
index a84a994ab..d91391c58 100644
--- a/preprocessor/MinimumFeedbackSet.cc
+++ b/preprocessor/MinimumFeedbackSet.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009-2012 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/NumericalInitialization.cc b/preprocessor/NumericalInitialization.cc
index aa7a25021..7d9439764 100644
--- a/preprocessor/NumericalInitialization.cc
+++ b/preprocessor/NumericalInitialization.cc
@@ -213,12 +213,12 @@ InitValStatement::writeOutput(ostream &output, const string &basename, bool mini
void
InitValStatement::writeOutputPostInit(ostream &output) const
{
- output << "if M_.exo_nbr > 0;" << endl
- << "\too_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];" << endl
- <<"end;" << endl
- << "if M_.exo_det_nbr > 0;" << endl
- << "\too_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];" << endl
- <<"end;" << endl;
+ output << "if M_.exo_nbr > 0" << endl
+ << "\too_.exo_simul = ones(M_.maximum_lag,1)*oo_.exo_steady_state';" << endl
+ <<"end" << endl
+ << "if M_.exo_det_nbr > 0" << endl
+ << "\too_.exo_det_simul = ones(M_.maximum_lag,1)*oo_.exo_det_steady_state';" << endl
+ <<"end" << endl;
}
EndValStatement::EndValStatement(const init_values_t &init_values_arg,
diff --git a/preprocessor/Shocks.cc b/preprocessor/Shocks.cc
index 0aa7fdfa6..6f95a7a9a 100644
--- a/preprocessor/Shocks.cc
+++ b/preprocessor/Shocks.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/Shocks.hh b/preprocessor/Shocks.hh
index 1c7abb913..0710e6630 100644
--- a/preprocessor/Shocks.hh
+++ b/preprocessor/Shocks.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/SteadyStateModel.cc b/preprocessor/SteadyStateModel.cc
index 5fc9dc1de..0a6e1536d 100644
--- a/preprocessor/SteadyStateModel.cc
+++ b/preprocessor/SteadyStateModel.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc
index 01a85ae26..fe96c9088 100644
--- a/preprocessor/SymbolTable.cc
+++ b/preprocessor/SymbolTable.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh
index d0e178ecc..8a67d6bdb 100644
--- a/preprocessor/SymbolTable.hh
+++ b/preprocessor/SymbolTable.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/WarningConsolidation.cc b/preprocessor/WarningConsolidation.cc
index f026dea8f..f1c24f4ad 100644
--- a/preprocessor/WarningConsolidation.cc
+++ b/preprocessor/WarningConsolidation.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/WarningConsolidation.hh b/preprocessor/WarningConsolidation.hh
index 582af0f43..ece47995e 100644
--- a/preprocessor/WarningConsolidation.hh
+++ b/preprocessor/WarningConsolidation.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/macro/MacroDriver.cc b/preprocessor/macro/MacroDriver.cc
index c5193cc6b..71d53b9cb 100644
--- a/preprocessor/macro/MacroDriver.cc
+++ b/preprocessor/macro/MacroDriver.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2015 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/macro/MacroDriver.hh b/preprocessor/macro/MacroDriver.hh
index 7b828b028..773a99dcf 100644
--- a/preprocessor/macro/MacroDriver.hh
+++ b/preprocessor/macro/MacroDriver.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2015 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/macro/MacroValue.cc b/preprocessor/macro/MacroValue.cc
index 3dfab3233..b20beb5db 100644
--- a/preprocessor/macro/MacroValue.cc
+++ b/preprocessor/macro/MacroValue.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2013 Dynare Team
+ * Copyright (C) 2008-2014 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/preprocessor/macro/MacroValue.hh b/preprocessor/macro/MacroValue.hh
index 64f0cdef7..1097841d9 100644
--- a/preprocessor/macro/MacroValue.hh
+++ b/preprocessor/macro/MacroValue.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008-2016 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
*
* This file is part of Dynare.
*
diff --git a/scripts/fix-copyright-years b/scripts/fix-copyright-years
index 86eceb7bd..d6f883e27 100755
--- a/scripts/fix-copyright-years
+++ b/scripts/fix-copyright-years
@@ -14,7 +14,7 @@
# Note that the script does not understand some unusual copyright notices: it
# will display a message in that case.
-LAST_UPDATE_COMMIT=61485ab809d9a33484abf6136f05abd84da2be1b
+LAST_UPDATE_COMMIT=1bf81c9f5a79757c23356f16fe015ae4f10bebde
if [ -z "$1" ]; then
echo "Give a filename in argument"
diff --git a/scripts/indent-c++.el b/scripts/indent-c++.el
index 17ab26ba5..ffbfaf68d 100644
--- a/scripts/indent-c++.el
+++ b/scripts/indent-c++.el
@@ -1,5 +1,6 @@
(c++-mode)
(setq indent-tabs-mode nil)
(indent-region (point-min) (point-max))
-(set-buffer-file-coding-system 'unix)
+(set-buffer-file-coding-system 'utf-8-unix)
+(delete-trailing-whitespace)
(save-buffer)
diff --git a/scripts/indent-matlab.el b/scripts/indent-matlab.el
index 76861b258..a0ef3ae76 100644
--- a/scripts/indent-matlab.el
+++ b/scripts/indent-matlab.el
@@ -3,5 +3,6 @@
(setq matlab-indent-function-body nil)
(untabify (point-min) (point-max))
(indent-region (point-min) (point-max))
-(set-buffer-file-coding-system 'unix)
+(set-buffer-file-coding-system 'utf-8-unix)
+(delete-trailing-whitespace)
(save-buffer)
diff --git a/tests/reporting/AnnualTable.m b/tests/reporting/AnnualTable.m
index fb78267f2..304cc3fe9 100644
--- a/tests/reporting/AnnualTable.m
+++ b/tests/reporting/AnnualTable.m
@@ -1,5 +1,5 @@
function rep = AnnualTable(rep, db_a, dc_a, seriesRootName, arange)
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/reporting/CountryGraphPage.m b/tests/reporting/CountryGraphPage.m
index d67bb28a1..c3b03d188 100644
--- a/tests/reporting/CountryGraphPage.m
+++ b/tests/reporting/CountryGraphPage.m
@@ -1,5 +1,5 @@
function rep = CountryGraphPage(rep, countryAbbr, db_q, dc_q, prange, srange)
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/reporting/CountryTablePage.m b/tests/reporting/CountryTablePage.m
index 309d69c9c..bf0087587 100644
--- a/tests/reporting/CountryTablePage.m
+++ b/tests/reporting/CountryTablePage.m
@@ -1,5 +1,5 @@
function rep = CountryTablePage(rep, countryAbbr, countryName, db_q, dc_q, db_a, dc_a, trange, vline_after)
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2016 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/reporting/runDynareReport.m b/tests/reporting/runDynareReport.m
index ba67cec76..f358a5fcc 100644
--- a/tests/reporting/runDynareReport.m
+++ b/tests/reporting/runDynareReport.m
@@ -1,5 +1,5 @@
function runDynareReport(dc_a, dc_q, db_a, db_q)
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2015 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/run_all_unitary_tests.m b/tests/run_all_unitary_tests.m
index 7200f40b3..e01aa2950 100644
--- a/tests/run_all_unitary_tests.m
+++ b/tests/run_all_unitary_tests.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/run_block_byte_tests_matlab.m b/tests/run_block_byte_tests_matlab.m
index 3675c0da7..8d6d14974 100644
--- a/tests/run_block_byte_tests_matlab.m
+++ b/tests/run_block_byte_tests_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2011-2013 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/run_block_byte_tests_octave.m b/tests/run_block_byte_tests_octave.m
index d930e8028..23e615995 100644
--- a/tests/run_block_byte_tests_octave.m
+++ b/tests/run_block_byte_tests_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2009-2013 Dynare Team
+## Copyright (C) 2009-2017 Dynare Team
##
## This file is part of Dynare.
##
diff --git a/tests/run_reporting_test_matlab.m b/tests/run_reporting_test_matlab.m
index bd8a738d4..c716aa414 100644
--- a/tests/run_reporting_test_matlab.m
+++ b/tests/run_reporting_test_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/run_reporting_test_octave.m b/tests/run_reporting_test_octave.m
index d47fb64a6..abcee07a3 100644
--- a/tests/run_reporting_test_octave.m
+++ b/tests/run_reporting_test_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2013-2016 Dynare Team
+## Copyright (C) 2013-2017 Dynare Team
##
## This file is part of Dynare.
##
diff --git a/tests/run_test_matlab.m b/tests/run_test_matlab.m
index c7735dc16..c1922d86e 100644
--- a/tests/run_test_matlab.m
+++ b/tests/run_test_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
%
% This file is part of Dynare.
%
diff --git a/tests/run_test_octave.m b/tests/run_test_octave.m
index 12ff117ad..7a9ce68f4 100644
--- a/tests/run_test_octave.m
+++ b/tests/run_test_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2009-2016 Dynare Team
+## Copyright (C) 2009-2017 Dynare Team
##
## This file is part of Dynare.
##
diff --git a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
index 90dfb7400..500cc137c 100644
--- a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
+++ b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
@@ -53,15 +53,15 @@ T = 5*floor(log(precision)/log(max(rho_x, rho_n)));
oo_ = simul_backward_model(M_.endo_histval, T, options_, M_, oo_, zeros(T+1,2));
if abs(oo_.endo_simul(1,end)-LongRunEfficiency)>1e-10
- error('Wrong long run level!')
+ error('Wrong long run level!')
end
if abs(oo_.endo_simul(3,end)-LongRunPopulation)>1e-10
- error('Wrong long run level!')
+ error('Wrong long run level!')
end
IntensiveCapitalStock = oo_.endo_simul(6,1:end)./(oo_.endo_simul(1,1:end).*oo_.endo_simul(3,1:end));
-if abs(IntensiveCapitalStock-LongRunIntensiveCapitalStock)>1e-6
- error('Wrong long run level!')
+if abs(IntensiveCapitalStock(end)-LongRunIntensiveCapitalStock>1e-10)
+ error('Wrong long run level!')
end
diff --git a/windows/dynare.nsi b/windows/dynare.nsi
index 51d31ef26..60b575149 100644
--- a/windows/dynare.nsi
+++ b/windows/dynare.nsi
@@ -54,7 +54,7 @@ Section "Dynare core (preprocessor and M-files)"
SectionIn RO
!insertmacro DETERMINE_CONTEXT
SetOutPath $INSTDIR
- File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt
+ File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt ..\VERSION
SetOutPath $INSTDIR\matlab
File /r ..\matlab\*.m