Related
I am having some trouble estimating the parameter for the log-linear realized Garch(1,1) model. The parameter values which I get from the optimisation are different from those derived in the paper and I'm not sure where I am going wrong. Any help would be great. The specification of the model from (Hansen et al. (2012)) is:
Realized GARCH specification
And the likelihood function is given by:
Log Likelihood
I am using the same data as used by Hansen and co-authors which can retrieved from the rugarch package with the command data(spyreal).
My matlab code is
function output = loglikRV(param, data)
r = data.SPY_OC;
RV = data.SPY_RK;
logRV = log(RV);
T = numel(RV); % time sample size
alpha0 = param(1);
alpha1 = param(2);
alpha2 = param(3);
omega0 = param(4);
omega1 = param(5);
omega2 = param(6);
omega3 = param(7);
sigmamu2 = param(8);
z = zeros(T,1);
logh = zeros(T,1);
u = zeros(T,1);
llhs = zeros(T,1);
logh(1) = 8.8296e-05;
u(1) = 0.005;
z(1) = 0.005;
llhs(1) = 0.005;
for i = 2:T
logh(i) = alpha0 + alpha1*logh(i-1) + alpha2*logRV(i-1);
z(i) = r(i) / sqrt(exp(logh(i)));
u(i) = logRV(i) - omega0 - omega1*logh(i) - omega2*z(i) - omega3*(z(i)^2 - 1);
llhs(i) = -(1/2)*(log(2*pi) + logh(i) + z(i)^2) - (1/2)*(log(2*pi) + log(sigmamu2) + u(1)^2 / sigmamu2);
end
output = sum(llhs(2:T-1));
return
And I am optimising this using the Matlab fmincon function with the code as shown below:
clear;close all;
RVfinal = readtable('spyreal.xlsx');
objfun = #(param)(-loglikRV(param,RVfinal)); % negative of the log-likelihood function
param0 = [0.07048753,0.43272574,0.52944743,-0.19368728,1.02540217,-0.06100213, 0.07437231, 0.38];
% constraints in the optimization
A = []; b = []; % no inequality constraints
Aeq=[]; beq=[]; % no equality constraints
% -- MLE Optimization using "fmincon" --
optim_options = optimset('Display','off','TolX',1e-4,'TolFun',1e-4);
[mymle,fval] = fmincon(objfun,param0,A,b,Aeq,beq,[],[],[],optim_options);
mymle
Thank You!
I tried to follow the main tutorial of PlatEMO but I failed to compile it. I tried to modify an already existed function but I've got too many errors.
This is the code I already tried:
classdef counster < PROBLEM
%HELP COUNSTER
methods
%% Initialization
function obj = counster()
obj.Global.M = 2;
if isempty(obj.Global.D)
obj.Global.D = 2;
end
obj.Global.lower =[0,zeros(1,obj.Global.D-1)-2];
obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2];
obj.Global.encoding = 'real';
end
%% Calculate objective values
function PopObj = CalObj(obj,X)
PopObj(:,1) = X(1);
PopObj(:,2) = (1 + X(2))/X(1);
end
%% Calculate constraint violations
function PopCon = CalCon(obj,X)
PopCon(:,1)=-9*X(1)-X(2)+6;
PopCon(:,2)= -9*X(1)-X(2)+1;
end
end
end
and this is an example of built-in function which is correctly working:
classdef CF4 < PROBLEM
% <problem> <CF>
% Constrained benchmark MOP
%------------------------------- Reference --------------------------------
% Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari,
% Multiobjective optimization test instances for the CEC 2009 special
% session and competition, School of CS & EE, University of Essex, Working
% Report CES-487, 2009.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
methods
%% Initialization
function obj = CF4()
obj.Global.M = 2;
if isempty(obj.Global.D)
obj.Global.D = 10;
end
obj.Global.lower = [0,zeros(1,obj.Global.D-1)-2];
obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2];
obj.Global.encoding = 'real';
end
%% Calculate objective values
function PopObj = CalObj(obj,X)
D = size(X,2);
J1 = 3 : 2 : D;
J2 = 2 : 2 : D;
Y = X - sin(6*pi*repmat(X(:,1),1,D)+repmat(1:D,size(X,1),1)*pi/D);
h = Y.^2;
temp = Y(:,2) < 3/2*(1-sqrt(1/2));
h(temp,2) = abs(Y(temp,2));
h(~temp,2) = 0.125 + (Y(~temp,2)-1).^2;
PopObj(:,1) = X(:,1) + sum(h(:,J1),2);
PopObj(:,2) = 1-X(:,1) + sum(h(:,J2),2);
end
%% Calculate constraint violations
function PopCon = CalCon(obj,X)
t = X(:,2) - sin(6*pi*X(:,1)+2*pi/size(X,2)) - 0.5*X(:,1) + 0.25;
PopCon = -t./(1+exp(4*abs(t)));
end
%% Sample reference points on Pareto front
function P = PF(obj,N)
P(:,1) = (0:1/(N-1):1)';
P(:,2) = 1 - P(:,1);
temp1 = 0.5<P(:,1) & P(:,1)<=0.75;
temp2 = 0.75<P(:,1);
P(temp1,2) = -0.5*P(temp1,1)+3/4;
P(temp2,2) = 1 - P(temp2,1)+0.125;
end
end
end
>> main('-algorithm',#MOPSO,'-problem',#counster,'-N',200,'-M',10);
It meant to plot a pareto front of counster problem but I have got this:
Index exceeds matrix dimensions.
Error in INDIVIDUAL (line 79)
obj(i).obj = Objs(i,:);
Error in GLOBAL/Initialization (line 151)
Population = INDIVIDUAL(obj.problem.Init(N));
Error in MOPSO (line 23)
Population = Global.Initialization();
Error in GLOBAL/Start (line 120)
obj.algorithm(obj);
Error in main (line 62)
Global.Start();
CODE
% Why?
tstart = 0;
tfinal = 1;
tspan = [tstart tfinal];
options = odeset('Events',#myEventsFcn);
% Initial conditions
y0 = [0,-0.6,0,0,0,0];
yp0 = [0,0,0,0,0,0];
% decic funtion calculates consistent ICs
[y0,yp0] = decic(#StateI,t0,y0,[0 1 0 0 0 0],yp0,[0 0 0 0 0 0]);
% Arrays for plots
tout = tstart;
sout = y0(1:1);
bout = y0(2:2);
zout = y0(3:3);
svout = y0(4:4);
bvout = y0(5:5);
zvout = y0(6:6);
% ode15i solves system of implicit ODEs
[t,y,te,ye,ie] = ode15i(#StateI,tspan,y0,yp0,options);
% system of implicit ODEs defined as StateI function
function res = StateI(t,y,yp)
% Constants
mS = 3*10^(-4); % [kg]
JS = 5*10^(-9); % [kgm]
mB = 4.5*10^(-3); % [kg]
g = 9.81; % [m/s^2]
JB = 7*10^(-7); % [kgm]
lS = 10^(-2); % [m]
lG = 1.5*10^(-2); % [m]
cp = 5.6*10^(-3); % [N/rad]
res = [(mS+mB)*yp(6) + mB*lS*yp(4) + mB*lG*yp(5) + (mS+mB)*g;
mB*lS*yp(6) + (JS+mB*lS^2)*yp(4) + mB*lS*lG*yp(5) - cp*(y(2)-y(1)) + mB*lS*g;
mB*lG*yp(6) + mB*lS*lG*yp(4) + (JB+mB*lG^2)*yp(5) - cp*(y(1)-y(2)) + mB*lG*g;
y(4)-yp(1);
y(5)-yp(2);
y(6)-yp(3)];
end
% my events defined in myEventsFcn
function [value,isterminal,direction] = myEventsFcn(t,y,yp)
% Constants
mS = 3*10^(-4); % [kg]
mB = 4.5*10^(-3); % [kg]
g = 9.81; % [m/s^2]
rS = 3.1*10^(-3); % [m]
lS = 10^(-2); % [m]
r0 = 2.5*10^(-3); % [m]
hS = 2*10^(-2); % [m]
lG = 1.5*10^(-2); % [m]
lB = 2.01*10^(-2); % [m]
hB = 2*10^(-2); % [m]
cp = 5.6*10^(-3); % [N/rad]
Z2 = -(mS+mB)*g-mB*lG*yp(5);
Z1II = (cp*(y(2)+(rS-r0)/hS)-rS*Z2-mB*lS*lG*yp(5)-mB*lS*g)/hS;
value = [y(1)+(rS-r0)/hS, y(1)-(rS-r0)/hS, Z1II, y(2)-(lS+lG-lB- r0)/hB];
isterminal = [1, 1, 1, 1];
direction = [-1, 1, -1, 1];
end
ERROR MESSAGE
Matrix dimensions must agree.
Error in odezero (line 46)
indzc = find((sign(vL) ~= sign(vR)) & (direction .* (vR - vL) >= 0));
Error in ode15i (line 506)
[te,ye,ie,valt,stop] = odezero(#ntrp15i,#events_aux,events_args,valt,...
Error in silly (line 24)
[t,y,te,ye,ie] = ode15i(#StateI,tspan,y0,yp0,options);
So I ran this code before, no problem, then this error started popping up. I cannot see where this error might occur. I tried transposing my vectors y0 and yp0, which is not sucessful, but it does give another error message, which seems strange because I think Matlab's ode solvers can handle transposed initial conditions.
Best regards
You code runs just fine on my version of MATLAB (2018b). Check your version.
I'm trying to make a time stepping code using the 4th order Runge-Kutta method but am running into issues indexing one of my values properly. My code is:
clc;
clear all;
L = 32; M = 32; N = 32; % No. of elements
Lx = 2; Ly = 2; Lz = 2; % Size of each element
dx = Lx/L; dy = Ly/M; dz = Lz/N; % Step size
Tt = 1;
t0 = 0; % Initial condition
T = 50; % Final time
dt = (Tt-t0)/T; % Determining time step interval
% Wave characteristics
H = 2; % Wave height
a = H/2; % Amplitude
Te = 6; % Period
omega = 2*pi/Te; % Wave rotational frequency
d = 25; % Water depth
x = 0; % Location of cylinder axis
u0(1:L,1:M,1:N,1) = 0; % Setting up solution space matrix (u values)
v0(1:L,1:M,1:N,1) = 0; % Setting up solution space matrix (v values)
w0(1:L,1:M,1:N,1) = 0; % Setting up solution space matrix (w values)
[k,L] = disp(d,omega); % Solving for k and wavelength using Newton-Raphson function
%u = zeros(1,50);
%v = zeros(1,50);
%w = zeros(1,50);
time = 1:1:50;
for t = 1:T
for i = 1:L
for j = 1:M
for k = 1:N
eta(i,j,k,t) = a*cos(omega*time(1,t);
u(i,j,k,1) = u0(i,j,k,1);
v(i,j,k,1) = v0(i,j,k,1);
w(i,j,k,1) = w0(i,j,k,1);
umag(i,j,k,t) = a*omega*(cosh(k*(d+eta(i,j,k,t))))/sinh(k*d);
vmag(i,j,k,t) = 0;
wmag(i,j,k,t) = -a*omega*(sinh(k*(d+eta(i,j,k,t))))/sinh(k*d);
uRHS(i,j,k,t) = umag(i,j,k,t)*cos(k*x-omega*t);
vRHS(i,j,k,t) = vmag(i,j,k,t)*sin(k*x-omega*t);
wRHS(i,j,k,t) = wmag(i,j,k,t)*sin(k*x-omega*t);
k1x(i,j,k,t) = dt*uRHS(i,j,k,t);
k2x(i,j,k,t) = dt*(0.5*k1x(i,j,k,t) + dt*uRHS(i,j,k,t));
k3x(i,j,k,t) = dt*(0.5*k2x(i,j,k,t) + dt*uRHS(i,j,k,t));
k4x(i,j,k,t) = dt*(k3x(i,j,k,t) + dt*uRHS(i,j,k,t));
u(i,j,k,t+1) = u(i,j,k,t) + (1/6)*(k1x(i,j,k,t) + 2*k2x(i,j,k,t) + 2*k3x(i,j,k,t) + k4x(i,j,k,t));
k1y(i,j,k,t) = dt*vRHS(i,j,k,t);
k2y(i,j,k,t) = dt*(0.5*k1y(i,j,k,t) + dt*vRHS(i,j,k,t));
k3y(i,j,k,t) = dt*(0.5*k2y(i,j,k,t) + dt*vRHS(i,j,k,t));
k4y(i,j,k,t) = dt*(k3y(i,j,k,t) + dt*vRHS(i,j,k,t));
v(i,j,k,t+1) = v(i,j,k,t) + (1/6)*(k1y(i,j,k,t) + 2*k2y(i,j,k,t) + 2*k3y(i,j,k,t) + k4y(i,j,k,t));
k1z(i,j,k,t) = dt*wRHS(i,j,k,t);
k2z(i,j,k,t) = dt*(0.5*k1z(i,j,k,t) + dt*wRHS(i,j,k,t));
k3z(i,j,k,t) = dt*(0.5*k2z(i,j,k,t) + dt*wRHS(i,j,k,t));
k4z(i,j,k,t) = dt*(k3z(i,j,k,t) + dt*wRHS(i,j,k,t));
w(i,j,k,t+1) = w(i,j,k,t) + (1/6)*(k1z(i,j,k,t) + 2*k2z(i,j,k,t) + 2*k3z(i,j,k,t) + k4z(i,j,k,t));
a(i,j,k,t+1) = ((u(i,j,k,t+1))^2 + (v(i,j,k,t+1))^2 + (w(i,j,k,t+1))^2)^0.5;
end
end
end
end
At the moment, the values seem to be fine for the first iteration but then I have the error Index exceeds matrix dimension in the line calculating eta. I understand that I am not correctly indexing the eta value but am not sure how to correct this.
My goal is to update the value of eta for each loop of t and then use that new eta value for the rest of the calculations.
I'm still quite new to programming and am trying to understand indexing, especially in 3 or 4 dimensional matrices and would really appreciate any advice in correctly calculating this value.
Thanks in advance for any advice!
You declare
time = 1:1:50;
which is just a row vector but access it here
eta(i,j,k,t) = a*cos(omega*time(i,j,k,t));
as if it were an array with 4 dimensions.
To correctly access element x of time you need to use syntax
time(1,x);
(as it is a 1 x 50 array)
I am using subplot function of MATLAB. Surprisingly the last plot in each subplot set becomes over-sized. Can anybody help me to resolve this issue? I have experimented with the parameters a little, but no luck. I am not able to post the plot figure.
function plotFluxVariabilityByGene(cRxn,KeggID,geneName)
load iJO1366; % Load the model iJO1366
%Find 'Gene' associated reactions from 'model'
reactions = rxnNamesFromKeggID(model,KeggID);
nCheck = 0; % Initialize counter
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions));
for n = 1 : numel(reactions)
% Get the name of nth reaction
rxn = reactions{n};
% Define the array for control reaction fluxes
cRxnArray = getCrxnArray(model,cRxn);
% Initialize storage for lower and upper limit-values
L = []; U = []; Avg = [];
% Get the fluxVariability values
for i = 1 : numel(cRxnArray)
modelMod = changeRxnBounds(model,cRxn,cRxnArray(i),'b');
[L(i) U(i)] = fluxVariability(modelMod,100,'max',{rxn});
Avg(i) = (L(i) + U(i))/2;
%fprintf('mthfcFlux = %f; Li = %f; Ui = %f\n',array(i),L(i),U(i));
end
% adjust the subplot number
nCheck = nCheck + 1;
% Determine the range of n to be saved in one file
if nCheck == 1
start = n;
elseif nCheck == setSize;
stop = n;
end
subplot(R,C,nCheck)
plot(cRxnArray,L,'-r','LineWidth',1); hold on;
plot(cRxnArray,L,'^r','MarkerSize',3,'LineWidth',2);
plot(cRxnArray,U,'-.b','LineWidth',1);
plot(cRxnArray,U,'^b','MarkerSize',2,'LineWidth',2);
plot(cRxnArray,Avg,'-','Color',[0.45,0.45,0.45],'LineWidth',2.5);
% Label X and Y axes
%xlabel([cRxn ' Flux']);
%ylabel(['fluxVariability ' char(rxn)]);
xlabel('Flux');
ylabel('fluxVariability');
hold off;
% Adjust X and Y axes limits
%xmn = min(cRxnArray) - ((max(cRxnArray) - min(cRxnArray))*0.05);
%xmx = max(cRxnArray) + ((max(cRxnArray) - min(cRxnArray))*0.05);
%ymn = min([U L]) - ((max([U L]) - min([U L]))*0.05);
%ymx = max([U L]) + ((max([U L]) - min([U L]))*0.05);
%if xmn ~= xmx
% xlim([xmn xmx]);
%end
%if ymn ~= ymx
% ylim([ymn ymx]);
%end
% Print which reactions are done
fprintf('\n......done for %s',char(rxn));
% If 'setSize' subplots are done then save the set in a file
if nCheck == setSize
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions)-n);
% Return nCheck to zero;
nCheck = 0;
end
end
% If nCheck is not equal to 16 then there are subplot that is not saved
% inside the for loop. Let's save it here.
if nCheck ~= setSize
stop = n;
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
end
fprintf('\nAll done\n');
end
%####################################################
%# Other functions ##
%####################################################
function rxnNames = rxnNamesFromKeggID(model,KeggID)
% Find 'Gene' associated reactions from 'model'
associatedRxns = findRxnsFromGenes(model,KeggID);
% Extract the reaction details from the structure to a cell
rxnDetails = eval(sprintf('associatedRxns.%s',KeggID));
% Extract only the reaction names from the cell
rxnNames = rxnDetails(:,1);
end
%####################################################
function cRxnArray = getCrxnArray(model,cRxn)
% Define the solver
changeCobraSolver('glpk');
% Find solution for the model
sol = optimizeCbModel(model);
% Change the objective of the default model to 'cRxn'
tmpModel = changeObjective(model,cRxn);
% Find slution for the changed model. This gives the maximum and
% minimum possible flux through the reaction 'cRxn' when the model is
% still viable
%solMax = optimizeCbModel(tmpModel,'max');
solMin = optimizeCbModel(tmpModel,'min');
% Create an array of 20 euqally spaced flux values between 'solMin' and
% 'sol.x'
%array = linspace(solMin.f,solMax.f,10);
cRxnArray = linspace(solMin.f,sol.x(findRxnIDs(model,cRxn)),20);
end
%####################################################
function [R C setSize] = subplotSize(remainingPlots)
% Sets number of columns and rows to 3 if total subplot >= 9
if remainingPlots > 7
R = 3; C = 3; setSize = 9;
elseif remainingPlots < 7
R = 2; C = 3; setSize = 6;
elseif remainingPlots < 5
R = 2; C = 2; setSize = 4;
elseif remainingPlots < 4
R = 1; C = 3; setSize = 3;
elseif remainingPlots < 3
R = 1; C = 2; setSize = 2;
end
end
%####################################################
My subplot looks like this:
I suspect its because you are calling subplotSize a second time inside your loop. This could be changing your R and C variables.
I would advise to check the R and C variables at the subplot command on each loop.