replace DOS ending with UNIX,
parent
d265fcba2d
commit
bd626b07f9
|
@ -1,117 +1,117 @@
|
|||
//== Flat Independent Markov States and Simple Restrictions ==//
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Read by CreateMarkovStateVariable_File() only if the passed number of --//
|
||||
//-- observations is less than or equal to zero. Can be omitted if the --//
|
||||
//-- passed number of observations is positive. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number Observations ==//
|
||||
200
|
||||
|
||||
//== Number Independent State Variables ==//
|
||||
2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- state_variable[1] (1 <= i <= n_state_variables) --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of states for state_variable[1] ==//
|
||||
3
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Each column contains the parameters for a Dirichlet prior on the --//
|
||||
//-- corresponding column of the transition matrix. Each element must be --//
|
||||
//-- positive. For each column, the relative size of the prior elements --//
|
||||
//-- determine the relative size of the elements of the transition matrix --//
|
||||
//-- and overall larger sizes implies a tighter prior. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Transition matrix prior for state_variable[1]. (n_states x n_states) ==//
|
||||
10 1 1
|
||||
1 10 1
|
||||
1 1 10
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- An array of n_states integers with each entry between 1 and n_states, --//
|
||||
//-- inclusive. Determines the number of quasi-free Dirichlet dimensions --//
|
||||
//-- each column. Since the sum of the elements in a Dirichlet distribution --//
|
||||
//-- must equal to one, the actual number of free dimensions is one less. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Free Dirichet dimensions for state_variable[1] ==//
|
||||
3 3 3
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- The jth restriction matrix is n_states x free[j]. Each row of the --//
|
||||
//-- restriction matrix has at most one non-zero entry and the sum of each --//
|
||||
//-- column of the restriction matrix must be one. If (x(1),...,x(free[j])) --//
|
||||
//-- is the Dirichlet random variable for column j, then the jth column of --//
|
||||
//-- the transition matrix Q is the jth restriction matrix times the --//
|
||||
//-- Dirichlet random random variable. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Column restrictions for state_variable[1] ==//
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Allows for lagged values of the state variable to be encoded --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of lags encoded for state_variable[1] ==//
|
||||
2
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- state_variable[2] --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
|
||||
//== Number of states for state_variable[2] ==//
|
||||
2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Each column contains the parameters for a Dirichlet prior on the --//
|
||||
//-- corresponding column of the transition matrix. Each element must be --//
|
||||
//-- positive. For each column, the relative size of the prior elements --//
|
||||
//-- determine the relative size of the elements of the transition matrix --//
|
||||
//-- and overall larger sizes implies a tighter prior. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Transition matrix prior for state_variable[2]. (n_states x n_states) ==//
|
||||
5 1
|
||||
1 5
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- An array of n_states integers with each entry between 1 and n_states, --//
|
||||
//-- inclusive. Determines the number of quasi-free Dirichlet dimensions --//
|
||||
//-- each column. Since the sum of the elements in a Dirichlet distribution --//
|
||||
//-- must equal to one, the actual number of free dimensions is one less. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Free Dirichet dimensions for state_variable[2] ==//
|
||||
2 2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- The jth restriction matrix is n_states x free[j]. Each row of the --//
|
||||
//-- restriction matrix has at most one non-zero entry and the sum of each --//
|
||||
//-- column of the restriction matrix must be one. If (x(1),...,x(free[j])) --//
|
||||
//-- is the Dirichlet random variable for column j, then the jth column of --//
|
||||
//-- the transition matrix Q is the jth restriction matrix times the --//
|
||||
//-- Dirichlet random random variable. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Column restrictions for state_variable[2] ==//
|
||||
1 0
|
||||
0 1
|
||||
|
||||
1 0
|
||||
0 1
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Allows for lagged values of the state variable to be encoded --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of lags encoded for state_variable[2] ==//
|
||||
0
|
||||
//== Flat Independent Markov States and Simple Restrictions ==//
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Read by CreateMarkovStateVariable_File() only if the passed number of --//
|
||||
//-- observations is less than or equal to zero. Can be omitted if the --//
|
||||
//-- passed number of observations is positive. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number Observations ==//
|
||||
200
|
||||
|
||||
//== Number Independent State Variables ==//
|
||||
2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- state_variable[1] (1 <= i <= n_state_variables) --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of states for state_variable[1] ==//
|
||||
3
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Each column contains the parameters for a Dirichlet prior on the --//
|
||||
//-- corresponding column of the transition matrix. Each element must be --//
|
||||
//-- positive. For each column, the relative size of the prior elements --//
|
||||
//-- determine the relative size of the elements of the transition matrix --//
|
||||
//-- and overall larger sizes implies a tighter prior. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Transition matrix prior for state_variable[1]. (n_states x n_states) ==//
|
||||
10 1 1
|
||||
1 10 1
|
||||
1 1 10
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- An array of n_states integers with each entry between 1 and n_states, --//
|
||||
//-- inclusive. Determines the number of quasi-free Dirichlet dimensions --//
|
||||
//-- each column. Since the sum of the elements in a Dirichlet distribution --//
|
||||
//-- must equal to one, the actual number of free dimensions is one less. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Free Dirichet dimensions for state_variable[1] ==//
|
||||
3 3 3
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- The jth restriction matrix is n_states x free[j]. Each row of the --//
|
||||
//-- restriction matrix has at most one non-zero entry and the sum of each --//
|
||||
//-- column of the restriction matrix must be one. If (x(1),...,x(free[j])) --//
|
||||
//-- is the Dirichlet random variable for column j, then the jth column of --//
|
||||
//-- the transition matrix Q is the jth restriction matrix times the --//
|
||||
//-- Dirichlet random random variable. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Column restrictions for state_variable[1] ==//
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Allows for lagged values of the state variable to be encoded --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of lags encoded for state_variable[1] ==//
|
||||
2
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- state_variable[2] --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
|
||||
//== Number of states for state_variable[2] ==//
|
||||
2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Each column contains the parameters for a Dirichlet prior on the --//
|
||||
//-- corresponding column of the transition matrix. Each element must be --//
|
||||
//-- positive. For each column, the relative size of the prior elements --//
|
||||
//-- determine the relative size of the elements of the transition matrix --//
|
||||
//-- and overall larger sizes implies a tighter prior. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Transition matrix prior for state_variable[2]. (n_states x n_states) ==//
|
||||
5 1
|
||||
1 5
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- An array of n_states integers with each entry between 1 and n_states, --//
|
||||
//-- inclusive. Determines the number of quasi-free Dirichlet dimensions --//
|
||||
//-- each column. Since the sum of the elements in a Dirichlet distribution --//
|
||||
//-- must equal to one, the actual number of free dimensions is one less. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Free Dirichet dimensions for state_variable[2] ==//
|
||||
2 2
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- The jth restriction matrix is n_states x free[j]. Each row of the --//
|
||||
//-- restriction matrix has at most one non-zero entry and the sum of each --//
|
||||
//-- column of the restriction matrix must be one. If (x(1),...,x(free[j])) --//
|
||||
//-- is the Dirichlet random variable for column j, then the jth column of --//
|
||||
//-- the transition matrix Q is the jth restriction matrix times the --//
|
||||
//-- Dirichlet random random variable. --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Column restrictions for state_variable[2] ==//
|
||||
1 0
|
||||
0 1
|
||||
|
||||
1 0
|
||||
0 1
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------//
|
||||
//-- Allows for lagged values of the state variable to be encoded --//
|
||||
//-----------------------------------------------------------------------------//
|
||||
//== Number of lags encoded for state_variable[2] ==//
|
||||
0
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,117 +1,117 @@
|
|||
|
||||
#include "switch_opt.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
//====== Static Global Variables ======
|
||||
static TStateModel *Model=(TStateModel*)NULL;
|
||||
static PRECISION *buffer=(PRECISION*)NULL;
|
||||
static PRECISION *ModifiedFreeParameters=(PRECISION*)NULL;
|
||||
static PRECISION *FreeParameters_Q=(PRECISION*)NULL;
|
||||
static int NumberFreeParameters_Q=0;
|
||||
static PRECISION *FreeParameters_Theta=(PRECISION*)NULL;
|
||||
static int NumberFreeParameters_Theta=0;
|
||||
|
||||
|
||||
void SetupObjectiveFunction(TStateModel *model, PRECISION *Modified, PRECISION *FreeQ, PRECISION *FreeTheta)
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
Model=model;
|
||||
FreeParameters_Q=FreeQ;
|
||||
NumberFreeParameters_Q=NumberFreeParametersQ(model);
|
||||
FreeParameters_Theta=FreeTheta;
|
||||
NumberFreeParameters_Theta=model->routines->pNumberFreeParametersTheta(model);
|
||||
ModifiedFreeParameters=Modified;
|
||||
}
|
||||
|
||||
void SetupObjectiveFunction_new(TStateModel *model, int FreeTheta_Idx, int FreeQ_Idx, int Modified_Idx)
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
Model=model;
|
||||
NumberFreeParameters_Q=NumberFreeParametersQ(model);
|
||||
NumberFreeParameters_Theta=model->routines->pNumberFreeParametersTheta(model);
|
||||
buffer=(PRECISION*)malloc((NumberFreeParameters_Q + NumberFreeParameters_Theta)*sizeof(PRECISION));
|
||||
|
||||
FreeParameters_Q=buffer+FreeQ_Idx;
|
||||
FreeParameters_Theta=buffer+FreeTheta_Idx;
|
||||
ModifiedFreeParameters=buffer+Modified_Idx;
|
||||
}
|
||||
|
||||
PRECISION PosteriorObjectiveFunction(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogPosterior_StatesIntegratedOut(Model);
|
||||
|
||||
//PRECISION lp_Q, lp_Theta, li;
|
||||
//FILE *f_out;
|
||||
//lp_Q=LogPrior_Q(Model);
|
||||
//lp_Theta=LogPrior_Theta(Model);
|
||||
//li=LogLikelihood_StatesIntegratedOut(Model);
|
||||
//if (isnan(lp_Q) || isnan(lp_Theta) || isnan(li))
|
||||
// {
|
||||
// f_out=fopen("tmp.tmp","wt");
|
||||
// Write_VAR_Specification(f_out,(char*)NULL,Model);
|
||||
// WriteTransitionMatrices(f_out,(char*)NULL,"Error: ",Model);
|
||||
// Write_VAR_Parameters(f_out,(char*)NULL,"Error: ",Model);
|
||||
// fprintf(f_out,"LogPrior_Theta(): %le\n",lp_Theta);
|
||||
// fprintf(f_out,"LogPrior_Q(): %le\n",lp_Q);
|
||||
// fprintf(f_out,"LogLikelihood_StatesIntegratedOut(): %le\n",li);
|
||||
// fprintf(f_out,"Posterior: %le\n\n",lp_Q+lp_Theta+li);
|
||||
// fclose(f_out);
|
||||
// exit(0);
|
||||
// }
|
||||
//return -(lp_Q+lp_Theta+li);
|
||||
}
|
||||
|
||||
PRECISION PosteriorObjectiveFunction_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return PosteriorObjectiveFunction(x,n);
|
||||
}
|
||||
|
||||
void PosteriorObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate)
|
||||
{
|
||||
*f=PosteriorObjectiveFunction(x,*n);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogLikelihood_StatesIntegratedOut(Model);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return MLEObjectiveFunction(x,n);
|
||||
}
|
||||
|
||||
void MLEObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate)
|
||||
{
|
||||
*f=MLEObjectiveFunction(x,*n);
|
||||
}
|
||||
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertLogFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogLikelihood_StatesIntegratedOut(Model);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return MLEObjectiveFunction_LogQ(x,n);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#include "switch_opt.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
//====== Static Global Variables ======
|
||||
static TStateModel *Model=(TStateModel*)NULL;
|
||||
static PRECISION *buffer=(PRECISION*)NULL;
|
||||
static PRECISION *ModifiedFreeParameters=(PRECISION*)NULL;
|
||||
static PRECISION *FreeParameters_Q=(PRECISION*)NULL;
|
||||
static int NumberFreeParameters_Q=0;
|
||||
static PRECISION *FreeParameters_Theta=(PRECISION*)NULL;
|
||||
static int NumberFreeParameters_Theta=0;
|
||||
|
||||
|
||||
void SetupObjectiveFunction(TStateModel *model, PRECISION *Modified, PRECISION *FreeQ, PRECISION *FreeTheta)
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
Model=model;
|
||||
FreeParameters_Q=FreeQ;
|
||||
NumberFreeParameters_Q=NumberFreeParametersQ(model);
|
||||
FreeParameters_Theta=FreeTheta;
|
||||
NumberFreeParameters_Theta=model->routines->pNumberFreeParametersTheta(model);
|
||||
ModifiedFreeParameters=Modified;
|
||||
}
|
||||
|
||||
void SetupObjectiveFunction_new(TStateModel *model, int FreeTheta_Idx, int FreeQ_Idx, int Modified_Idx)
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
Model=model;
|
||||
NumberFreeParameters_Q=NumberFreeParametersQ(model);
|
||||
NumberFreeParameters_Theta=model->routines->pNumberFreeParametersTheta(model);
|
||||
buffer=(PRECISION*)malloc((NumberFreeParameters_Q + NumberFreeParameters_Theta)*sizeof(PRECISION));
|
||||
|
||||
FreeParameters_Q=buffer+FreeQ_Idx;
|
||||
FreeParameters_Theta=buffer+FreeTheta_Idx;
|
||||
ModifiedFreeParameters=buffer+Modified_Idx;
|
||||
}
|
||||
|
||||
PRECISION PosteriorObjectiveFunction(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogPosterior_StatesIntegratedOut(Model);
|
||||
|
||||
//PRECISION lp_Q, lp_Theta, li;
|
||||
//FILE *f_out;
|
||||
//lp_Q=LogPrior_Q(Model);
|
||||
//lp_Theta=LogPrior_Theta(Model);
|
||||
//li=LogLikelihood_StatesIntegratedOut(Model);
|
||||
//if (isnan(lp_Q) || isnan(lp_Theta) || isnan(li))
|
||||
// {
|
||||
// f_out=fopen("tmp.tmp","wt");
|
||||
// Write_VAR_Specification(f_out,(char*)NULL,Model);
|
||||
// WriteTransitionMatrices(f_out,(char*)NULL,"Error: ",Model);
|
||||
// Write_VAR_Parameters(f_out,(char*)NULL,"Error: ",Model);
|
||||
// fprintf(f_out,"LogPrior_Theta(): %le\n",lp_Theta);
|
||||
// fprintf(f_out,"LogPrior_Q(): %le\n",lp_Q);
|
||||
// fprintf(f_out,"LogLikelihood_StatesIntegratedOut(): %le\n",li);
|
||||
// fprintf(f_out,"Posterior: %le\n\n",lp_Q+lp_Theta+li);
|
||||
// fclose(f_out);
|
||||
// exit(0);
|
||||
// }
|
||||
//return -(lp_Q+lp_Theta+li);
|
||||
}
|
||||
|
||||
PRECISION PosteriorObjectiveFunction_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return PosteriorObjectiveFunction(x,n);
|
||||
}
|
||||
|
||||
void PosteriorObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate)
|
||||
{
|
||||
*f=PosteriorObjectiveFunction(x,*n);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogLikelihood_StatesIntegratedOut(Model);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return MLEObjectiveFunction(x,n);
|
||||
}
|
||||
|
||||
void MLEObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate)
|
||||
{
|
||||
*f=MLEObjectiveFunction(x,*n);
|
||||
}
|
||||
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ(PRECISION *x, int n)
|
||||
{
|
||||
if (x != ModifiedFreeParameters) memmove(ModifiedFreeParameters,x,n*sizeof(PRECISION));
|
||||
ConvertLogFreeParametersToQ(Model,FreeParameters_Q);
|
||||
ConvertFreeParametersToTheta(Model,FreeParameters_Theta);
|
||||
return -LogLikelihood_StatesIntegratedOut(Model);
|
||||
}
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ_csminwel(double *x, int n, double **args, int *dims)
|
||||
{
|
||||
return MLEObjectiveFunction_LogQ(x,n);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,21 +1,21 @@
|
|||
|
||||
|
||||
#ifndef __MARKOV_SWITCHING_OPTIMIZATION__
|
||||
#define __MARKOV_SWITCHING_OPTIMIZATION__
|
||||
|
||||
#include "switch.h"
|
||||
|
||||
void SetupObjectiveFunction(TStateModel *model, PRECISION *MFPparms, PRECISION *FTMparms, PRECISION *FMSparms);
|
||||
|
||||
PRECISION PosteriorObjectiveFunction(PRECISION *x, int n);
|
||||
PRECISION PosteriorObjectiveFunction_csminwel(double *x, int n, double **args, int *dims);
|
||||
void PosteriorObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate);
|
||||
|
||||
PRECISION MLEObjectiveFunction(PRECISION *x, int n);
|
||||
PRECISION MLEObjectiveFunction_csminwel(double *x, int n, double **args, int *dims);
|
||||
void MLEObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate);
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ(PRECISION *x, int n);
|
||||
PRECISION MLEObjectiveFunction_LogQ_csminwel(double *x, int n, double **args, int *dims);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef __MARKOV_SWITCHING_OPTIMIZATION__
|
||||
#define __MARKOV_SWITCHING_OPTIMIZATION__
|
||||
|
||||
#include "switch.h"
|
||||
|
||||
void SetupObjectiveFunction(TStateModel *model, PRECISION *MFPparms, PRECISION *FTMparms, PRECISION *FMSparms);
|
||||
|
||||
PRECISION PosteriorObjectiveFunction(PRECISION *x, int n);
|
||||
PRECISION PosteriorObjectiveFunction_csminwel(double *x, int n, double **args, int *dims);
|
||||
void PosteriorObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate);
|
||||
|
||||
PRECISION MLEObjectiveFunction(PRECISION *x, int n);
|
||||
PRECISION MLEObjectiveFunction_csminwel(double *x, int n, double **args, int *dims);
|
||||
void MLEObjectiveFunction_npsol(int *mode, int *n, double *x, double *f, double *g, int *nstate);
|
||||
|
||||
PRECISION MLEObjectiveFunction_LogQ(PRECISION *x, int n);
|
||||
PRECISION MLEObjectiveFunction_LogQ_csminwel(double *x, int n, double **args, int *dims);
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,36 +1,36 @@
|
|||
|
||||
#include "switch.h"
|
||||
|
||||
/*
|
||||
Base routines for reading/writing Markov state variables and transition
|
||||
matrices in native ascii format.
|
||||
*/
|
||||
TMarkovStateVariable* ReadMarkovSpecification_SV(FILE *f_in, char *idstring, int nobs);
|
||||
int WriteMarkovSpecification_SV(FILE *f_out, TMarkovStateVariable *sv, char *idstring);
|
||||
int ReadTransitionMatrices_SV(FILE *f_in, TMarkovStateVariable* sv, char *header, char *idstring);
|
||||
int WriteTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable* sv, char *header, char *idstring);
|
||||
int ReadBaseTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable *sv, char *header, char *idstring);
|
||||
int WriteBaseTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable *sv, char *header, char *idstring);
|
||||
|
||||
int WriteBaseTransitionMatricesFlat_SV(FILE *f_out, TMarkovStateVariable *sv, char *fmt);
|
||||
void WriteBaseTransitionMatricesFlat_Headers_SV(FILE *f_out, TMarkovStateVariable* sv, char *idstring);
|
||||
|
||||
/*
|
||||
Routines for reading/writing Markov state variables and transition matrices
|
||||
from TStateModel. Calls base routines.
|
||||
*/
|
||||
TMarkovStateVariable* ReadMarkovSpecification(FILE *f, char *filename);
|
||||
int WriteMarkovSpecification(FILE *f, char *filename, TStateModel *model);
|
||||
int ReadTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int ReadStates(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteStates(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int ReadBaseTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteBaseTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
|
||||
int WriteBaseTransitionMatricesFlat(FILE *f, TStateModel *model, char *fmt);
|
||||
|
||||
/*
|
||||
Read flat markov state variable specification from file.
|
||||
*/
|
||||
TMarkovStateVariable* CreateMarkovStateVariable_File(FILE *f, char *filename, int nobs);
|
||||
|
||||
#include "switch.h"
|
||||
|
||||
/*
|
||||
Base routines for reading/writing Markov state variables and transition
|
||||
matrices in native ascii format.
|
||||
*/
|
||||
TMarkovStateVariable* ReadMarkovSpecification_SV(FILE *f_in, char *idstring, int nobs);
|
||||
int WriteMarkovSpecification_SV(FILE *f_out, TMarkovStateVariable *sv, char *idstring);
|
||||
int ReadTransitionMatrices_SV(FILE *f_in, TMarkovStateVariable* sv, char *header, char *idstring);
|
||||
int WriteTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable* sv, char *header, char *idstring);
|
||||
int ReadBaseTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable *sv, char *header, char *idstring);
|
||||
int WriteBaseTransitionMatrices_SV(FILE *f_out, TMarkovStateVariable *sv, char *header, char *idstring);
|
||||
|
||||
int WriteBaseTransitionMatricesFlat_SV(FILE *f_out, TMarkovStateVariable *sv, char *fmt);
|
||||
void WriteBaseTransitionMatricesFlat_Headers_SV(FILE *f_out, TMarkovStateVariable* sv, char *idstring);
|
||||
|
||||
/*
|
||||
Routines for reading/writing Markov state variables and transition matrices
|
||||
from TStateModel. Calls base routines.
|
||||
*/
|
||||
TMarkovStateVariable* ReadMarkovSpecification(FILE *f, char *filename);
|
||||
int WriteMarkovSpecification(FILE *f, char *filename, TStateModel *model);
|
||||
int ReadTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int ReadStates(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteStates(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int ReadBaseTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
int WriteBaseTransitionMatrices(FILE *f, char *filename, char *header, TStateModel *model);
|
||||
|
||||
int WriteBaseTransitionMatricesFlat(FILE *f, TStateModel *model, char *fmt);
|
||||
|
||||
/*
|
||||
Read flat markov state variable specification from file.
|
||||
*/
|
||||
TMarkovStateVariable* CreateMarkovStateVariable_File(FILE *f, char *filename, int nobs);
|
||||
|
|
|
@ -1,149 +1,149 @@
|
|||
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_parse_cmd.h"
|
||||
#include "dw_ascii.h"
|
||||
#include "VARbase.h"
|
||||
#include "VARio.h"
|
||||
#include "switch.h"
|
||||
#include "switchio.h"
|
||||
#include "command_line_VAR.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
int main(int nargs, char **args)
|
||||
{
|
||||
TStateModel *model;
|
||||
T_VAR_Parameters *p;
|
||||
FILE *f_out;
|
||||
char *filename;
|
||||
int count, begin_time, end_time, tuning, burn_in, iterations, check, period=1000, seed, output, thinning,
|
||||
nd1;
|
||||
TVARCommandLine *cmd=(TVARCommandLine*)NULL;
|
||||
char *include_help[]={"-di","-do","-fs","-fp","-ph","-MLE",(char*)NULL},
|
||||
*additional_help[]={
|
||||
"-ft <tag>",
|
||||
"Tag for input file. Input file name is est_final_<tag>.dat.",
|
||||
"-fto <tag>",
|
||||
"Tag for output file. Output file names are draws_<tag>.dat and headers_<tag>.dat. Default is -ft <tag>.",
|
||||
"-mh <integer>",
|
||||
"Tuning period for Metropolis-Hasting draws (default value = 30000)",
|
||||
"-b <integer>",
|
||||
"Burn-in period (default value = 0.1 * (number of iterations))",
|
||||
"-i <integer>",
|
||||
"Number of draw (default value = 1000), number saved is (-i)/(-t)",
|
||||
"-t <integer>",
|
||||
"Thinning factor. Only one in t draws are written to file.",
|
||||
"-nd1",
|
||||
"Normalize diagonal of A0 to one (flat output only)",
|
||||
"-gs <integer>",
|
||||
"Seed value for generator - 0 gets seed from clock (default value = 0)",
|
||||
(char*)NULL,
|
||||
(char*)NULL};
|
||||
|
||||
//=== Help Screen ===
|
||||
if (dw_FindArgument_String(nargs,args,"h") != -1)
|
||||
{
|
||||
printf("print_draws <options>\n");
|
||||
PrintHelpMessages(stdout,include_help,additional_help);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//=== Get seed, tuning peroid, burn-in period, number of iterations, and thinning factor
|
||||
seed=dw_ParseInteger_String(nargs,args,"gs",0);
|
||||
tuning=dw_ParseInteger_String(nargs,args,"mh",30000);
|
||||
iterations=dw_ParseInteger_String(nargs,args,"i",1000);
|
||||
burn_in=dw_ParseInteger_String(nargs,args,"b",iterations/10);
|
||||
thinning=dw_ParseInteger_String(nargs,args,"t",1);
|
||||
nd1=(dw_FindArgument_String(nargs,args,"nd1") >= 0) ? 1 : 0;
|
||||
|
||||
//=== Initialize random number generator
|
||||
dw_initialize_generator(seed);
|
||||
|
||||
//=== Setup model and initial parameters
|
||||
printf("Reading data...\n");
|
||||
if (!(model=CreateTStateModelFromEstimateFinal(nargs,args,&cmd)))
|
||||
{
|
||||
swz_fprintf_err("Unable to read model or parameters\n");
|
||||
exit(1);
|
||||
}
|
||||
p=(T_VAR_Parameters*)(model->theta);
|
||||
|
||||
//=== Open header file and print headers
|
||||
filename=CreateFilenameFromTag("%sheader_%s.dat",cmd->out_tag,cmd->out_directory);
|
||||
f_out=fopen(filename,"wt");
|
||||
free(filename);
|
||||
WriteBaseTransitionMatricesFlat_Headers_SV(f_out,model->sv,"");
|
||||
Write_VAR_ParametersFlat_Headers(f_out,model);
|
||||
fprintf(f_out,"\n");
|
||||
fclose(f_out);
|
||||
|
||||
//=== Open output file
|
||||
filename=CreateFilenameFromTag("%sdraws_%s.dat",cmd->out_tag,cmd->out_directory);
|
||||
f_out=fopen(filename,"wt");
|
||||
free(filename);
|
||||
|
||||
// Burn-in period with calibration of jumping parameters
|
||||
printf("Calibrating jumping parameters - %d draws\n",tuning);
|
||||
begin_time=(int)time((time_t*)NULL);
|
||||
AdaptiveMetropolisScale(model,tuning,1000,1,(FILE*)NULL); // tuning iterations - 1000 iterations before updating - verbose
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
|
||||
// Reset parametrers
|
||||
if (!ReadTransitionMatrices((FILE*)NULL,cmd->parameters_filename_actual,cmd->parameters_header_actual,model)
|
||||
|| !Read_VAR_Parameters((FILE*)NULL,cmd->parameters_filename_actual,cmd->parameters_header_actual,model))
|
||||
printf("Unable to reset parameters after tuning\n");
|
||||
|
||||
// Burn-in period
|
||||
printf("Burn-in period - %d draws\n",burn_in);
|
||||
for (check=period, count=1; count <= burn_in; count++)
|
||||
{
|
||||
DrawAll(model);
|
||||
|
||||
if (count == check)
|
||||
{
|
||||
check+=period;
|
||||
printf("%d iterations completed out of %d\n",count,burn_in);
|
||||
}
|
||||
}
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
ResetMetropolisInformation(p);
|
||||
|
||||
// Simulation
|
||||
printf("Simulating - %d draws\n",iterations);
|
||||
for (check=period, output=thinning, count=1; count <= iterations; count++)
|
||||
{
|
||||
DrawAll(model);
|
||||
|
||||
if (count == output)
|
||||
{
|
||||
WriteBaseTransitionMatricesFlat(f_out,model,"%lf ");
|
||||
if (nd1)
|
||||
Write_VAR_ParametersFlat_A0_Diagonal_One(f_out,model,"%lf ");
|
||||
else
|
||||
Write_VAR_ParametersFlat(f_out,model,"%lf ");
|
||||
fprintf(f_out,"\n");
|
||||
output+=thinning;
|
||||
}
|
||||
|
||||
if (count == check)
|
||||
{
|
||||
check+=period;
|
||||
printf("%d(%d) iterations completed out of %d(%d)\n",count,thinning,iterations,thinning);
|
||||
}
|
||||
}
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
|
||||
// clean up
|
||||
fclose(f_out);
|
||||
FreeStateModel(model);
|
||||
Free_VARCommandLine(cmd);
|
||||
}
|
||||
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_parse_cmd.h"
|
||||
#include "dw_ascii.h"
|
||||
#include "VARbase.h"
|
||||
#include "VARio.h"
|
||||
#include "switch.h"
|
||||
#include "switchio.h"
|
||||
#include "command_line_VAR.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
int main(int nargs, char **args)
|
||||
{
|
||||
TStateModel *model;
|
||||
T_VAR_Parameters *p;
|
||||
FILE *f_out;
|
||||
char *filename;
|
||||
int count, begin_time, end_time, tuning, burn_in, iterations, check, period=1000, seed, output, thinning,
|
||||
nd1;
|
||||
TVARCommandLine *cmd=(TVARCommandLine*)NULL;
|
||||
char *include_help[]={"-di","-do","-fs","-fp","-ph","-MLE",(char*)NULL},
|
||||
*additional_help[]={
|
||||
"-ft <tag>",
|
||||
"Tag for input file. Input file name is est_final_<tag>.dat.",
|
||||
"-fto <tag>",
|
||||
"Tag for output file. Output file names are draws_<tag>.dat and headers_<tag>.dat. Default is -ft <tag>.",
|
||||
"-mh <integer>",
|
||||
"Tuning period for Metropolis-Hasting draws (default value = 30000)",
|
||||
"-b <integer>",
|
||||
"Burn-in period (default value = 0.1 * (number of iterations))",
|
||||
"-i <integer>",
|
||||
"Number of draw (default value = 1000), number saved is (-i)/(-t)",
|
||||
"-t <integer>",
|
||||
"Thinning factor. Only one in t draws are written to file.",
|
||||
"-nd1",
|
||||
"Normalize diagonal of A0 to one (flat output only)",
|
||||
"-gs <integer>",
|
||||
"Seed value for generator - 0 gets seed from clock (default value = 0)",
|
||||
(char*)NULL,
|
||||
(char*)NULL};
|
||||
|
||||
//=== Help Screen ===
|
||||
if (dw_FindArgument_String(nargs,args,"h") != -1)
|
||||
{
|
||||
printf("print_draws <options>\n");
|
||||
PrintHelpMessages(stdout,include_help,additional_help);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//=== Get seed, tuning peroid, burn-in period, number of iterations, and thinning factor
|
||||
seed=dw_ParseInteger_String(nargs,args,"gs",0);
|
||||
tuning=dw_ParseInteger_String(nargs,args,"mh",30000);
|
||||
iterations=dw_ParseInteger_String(nargs,args,"i",1000);
|
||||
burn_in=dw_ParseInteger_String(nargs,args,"b",iterations/10);
|
||||
thinning=dw_ParseInteger_String(nargs,args,"t",1);
|
||||
nd1=(dw_FindArgument_String(nargs,args,"nd1") >= 0) ? 1 : 0;
|
||||
|
||||
//=== Initialize random number generator
|
||||
dw_initialize_generator(seed);
|
||||
|
||||
//=== Setup model and initial parameters
|
||||
printf("Reading data...\n");
|
||||
if (!(model=CreateTStateModelFromEstimateFinal(nargs,args,&cmd)))
|
||||
{
|
||||
swz_fprintf_err("Unable to read model or parameters\n");
|
||||
exit(1);
|
||||
}
|
||||
p=(T_VAR_Parameters*)(model->theta);
|
||||
|
||||
//=== Open header file and print headers
|
||||
filename=CreateFilenameFromTag("%sheader_%s.dat",cmd->out_tag,cmd->out_directory);
|
||||
f_out=fopen(filename,"wt");
|
||||
free(filename);
|
||||
WriteBaseTransitionMatricesFlat_Headers_SV(f_out,model->sv,"");
|
||||
Write_VAR_ParametersFlat_Headers(f_out,model);
|
||||
fprintf(f_out,"\n");
|
||||
fclose(f_out);
|
||||
|
||||
//=== Open output file
|
||||
filename=CreateFilenameFromTag("%sdraws_%s.dat",cmd->out_tag,cmd->out_directory);
|
||||
f_out=fopen(filename,"wt");
|
||||
free(filename);
|
||||
|
||||
// Burn-in period with calibration of jumping parameters
|
||||
printf("Calibrating jumping parameters - %d draws\n",tuning);
|
||||
begin_time=(int)time((time_t*)NULL);
|
||||
AdaptiveMetropolisScale(model,tuning,1000,1,(FILE*)NULL); // tuning iterations - 1000 iterations before updating - verbose
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
|
||||
// Reset parametrers
|
||||
if (!ReadTransitionMatrices((FILE*)NULL,cmd->parameters_filename_actual,cmd->parameters_header_actual,model)
|
||||
|| !Read_VAR_Parameters((FILE*)NULL,cmd->parameters_filename_actual,cmd->parameters_header_actual,model))
|
||||
printf("Unable to reset parameters after tuning\n");
|
||||
|
||||
// Burn-in period
|
||||
printf("Burn-in period - %d draws\n",burn_in);
|
||||
for (check=period, count=1; count <= burn_in; count++)
|
||||
{
|
||||
DrawAll(model);
|
||||
|
||||
if (count == check)
|
||||
{
|
||||
check+=period;
|
||||
printf("%d iterations completed out of %d\n",count,burn_in);
|
||||
}
|
||||
}
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
ResetMetropolisInformation(p);
|
||||
|
||||
// Simulation
|
||||
printf("Simulating - %d draws\n",iterations);
|
||||
for (check=period, output=thinning, count=1; count <= iterations; count++)
|
||||
{
|
||||
DrawAll(model);
|
||||
|
||||
if (count == output)
|
||||
{
|
||||
WriteBaseTransitionMatricesFlat(f_out,model,"%lf ");
|
||||
if (nd1)
|
||||
Write_VAR_ParametersFlat_A0_Diagonal_One(f_out,model,"%lf ");
|
||||
else
|
||||
Write_VAR_ParametersFlat(f_out,model,"%lf ");
|
||||
fprintf(f_out,"\n");
|
||||
output+=thinning;
|
||||
}
|
||||
|
||||
if (count == check)
|
||||
{
|
||||
check+=period;
|
||||
printf("%d(%d) iterations completed out of %d(%d)\n",count,thinning,iterations,thinning);
|
||||
}
|
||||
}
|
||||
end_time=(int)time((time_t*)NULL);
|
||||
printf("Elapsed Time: %d seconds\n",end_time - begin_time);
|
||||
|
||||
// clean up
|
||||
fclose(f_out);
|
||||
FreeStateModel(model);
|
||||
Free_VARCommandLine(cmd);
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,433 +1,433 @@
|
|||
|
||||
#ifndef __VAR_BASE_MODEL__
|
||||
#define __VAR_BASE_MODEL__
|
||||
|
||||
#include "switch.h"
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_matrix_array.h"
|
||||
|
||||
#define standard_ordering 1 // for future implementation
|
||||
#define SPEC_RANDOM_WALK 0x00000001
|
||||
#define SPEC_SIMS_ZHA 0x00000002
|
||||
|
||||
//=== Normalization types (must be mutually exclusive) ===//
|
||||
#define VAR_NORMALIZATION_NONE 0x00000000
|
||||
#define VAR_NORMALIZATION_WZ 0x00000001
|
||||
|
||||
typedef struct
|
||||
{
|
||||
//====== Model specification ======
|
||||
int Specification;
|
||||
int *IsIdentity_V;
|
||||
|
||||
//====== Free parameter specification (for future implementation) ======
|
||||
int FreeParameterType;
|
||||
|
||||
//====== Sizes ======
|
||||
int nvars;
|
||||
int nlags;
|
||||
int npre;
|
||||
int nobs;
|
||||
int nstates;
|
||||
|
||||
//====== State variable translation ======
|
||||
int* n_var_states; // nvars n_var_states[j] is the number of variance states for column j
|
||||
int** var_states; // nvars x n_states translation table for variance states
|
||||
int* n_coef_states; // nvars n_coef_states[j] is the number of coefficients states for column j
|
||||
int** coef_states; // nvars x n_states translation table for coefficient states
|
||||
int n_A0_states; // number of states for the matrix A0
|
||||
int* A0_states; // n_states translation table for the matrix A0
|
||||
int** A0_column_states; // nvars x n_A0_states translation table from determinant of A0 states to coefficient states
|
||||
|
||||
//====== Parameters ======
|
||||
PRECISION** Zeta; // nvars x n_var_states[j]
|
||||
TVector** A0; // nvars x n_coef_states[j] x nvars
|
||||
TVector** Aplus; // nvars x n_coef_states[j] x npre
|
||||
|
||||
//====== Free parameters ======
|
||||
int* dim_b0;
|
||||
TVector** b0;
|
||||
int* dim_bplus;
|
||||
TVector** bplus;
|
||||
|
||||
//====== Priors ======
|
||||
TVector zeta_a_prior; //
|
||||
TVector zeta_b_prior; //
|
||||
TMatrix* A0_prior; // A0_prior[j] = constant parameter variance of the normal prior on the jth column of A0
|
||||
TMatrix* Aplus_prior; // Aplus_prior[j] = constant parameter variance of the normal prior on the jth column of Aplus
|
||||
|
||||
//====== Identifying restrictions ======
|
||||
TMatrix *U;
|
||||
TMatrix *V;
|
||||
TMatrix *W;
|
||||
|
||||
//====== Sims-Zha specification parameters and workspace ======
|
||||
TVector** lambda; // nvars x n_coef_states[j] array of nvars-dimensional vectors
|
||||
TVector* constant; // nvars x n_coef_states[j] -- constant[j][k] == psi[j][npre - 1 + k]
|
||||
TVector* psi; // nvars x (npre - 1 + n_coef_states[j])
|
||||
PRECISION lambda_prior; // prior variance of each element of lambda
|
||||
PRECISION inverse_lambda_prior;
|
||||
TMatrix* inverse_psi_prior;
|
||||
|
||||
//====== Normalization ======
|
||||
int normalization_type; // type of normalization used
|
||||
int normalized; // type of normalization actually used to normalize current draw
|
||||
TVector** Target; // nvar x n_coef_states[j] array of nvars-dimensional vectors
|
||||
int** flipped; // nvar x n_coef_states[j] array of integers
|
||||
int WZ_inconsistancies;
|
||||
|
||||
//====== Workspace ======
|
||||
PRECISION log_prior_constant; // Constant of integrate for the log prior
|
||||
PRECISION minus_half_nvars_times_log2pi; // Constant used in LogConditionalProbability functions
|
||||
TVector inverse_zeta_b_prior; // inverse_zeta_b_prior = 1.0/zeta_b_prior
|
||||
TMatrix* inverse_b0_prior; // inverse_b0_prior = U'[j]*Inverse(A0_prior[j])*U[j]
|
||||
TMatrix* inverse_bplus_prior; // inverse_bplus_prior = V'[j]*Inverse(Aplus_prior[j])*V[j]
|
||||
|
||||
TVector log_abs_det_A0; // log(abs(det(A0[k])))
|
||||
|
||||
PRECISION*** A0_dot_products; // A0_dot_products[t][j][k] = Y'[t] * A0[j][k]
|
||||
PRECISION*** Aplus_dot_products; // Aplus_dot_products[t][j][k] = X'[t] * Aplus[j][k]
|
||||
|
||||
// A0 Metropolis Info
|
||||
PRECISION** A0_Metropolis_Scale;
|
||||
int Total_A0_Metropolis_Draws;
|
||||
int** A0_Metropolis_Jumps;
|
||||
|
||||
// State dependent fields
|
||||
TMatrix* YY; // YY[k] = sum(Y[t]*Y'[t], 1 <= t <= nobs and S[t] == k)
|
||||
TMatrix* XY; // YX[k] = sum(X[t]*Y'[t], 1 <= t <= nobs and S[t] == k)
|
||||
TMatrix* XX; // XX[k] = sum(X[t]*X'[t], 1 <= t <= nobs and S[t] == k)
|
||||
int* T; // T[k] = number of t with 1 <= t <= nobs and S[t] == k
|
||||
int *S; // S[t] = state variable used to compute YY, XY, XX, and T
|
||||
TMatrix* yy; // yy[t] = Y[t]*Y'[t]
|
||||
TMatrix* xy; // xy[t] = X[t]*Y'[t]
|
||||
TMatrix* xx; // xx[t] = X[t]*X'[t]
|
||||
|
||||
// Flags for validity of workspace fields
|
||||
int valid_log_abs_det_A0; // Invalid after A0 changes
|
||||
int valid_dot_products; // Invalid after A0 or Aplus changes
|
||||
int valid_state_dependent_fields; // Invalid after states change
|
||||
int valid_state_dependent_fields_previous; // Initially invalid.
|
||||
int valid_parameters; // Initially invalid. Valid after successful read or draw of parameters.
|
||||
// Parametes are invalid if Zeta is negative or if they do not satisfy
|
||||
// the normalization.
|
||||
|
||||
//=== Data ===
|
||||
TVector* Y; // Y[t] nvar vector of time t data for 1 <= t <= T
|
||||
TVector* X; // X[t] npre vector of time t predetermined variables for 1 <= t <= T
|
||||
|
||||
} T_VAR_Parameters;
|
||||
|
||||
// Constructors-Destructors
|
||||
void FreeTheta_VAR(T_VAR_Parameters *p);
|
||||
ThetaRoutines* CreateRoutines_VAR(void);
|
||||
T_VAR_Parameters* CreateTheta_VAR(int flag, int nvars, int nlags, int nexg, int nstates, int nobs, // Specification and Sizes
|
||||
int **coef_states, int **var_states, // Translation Tables
|
||||
TMatrix *U, TMatrix *V, TMatrix *W, // Restrictions
|
||||
TMatrix Y, TMatrix X); // Data
|
||||
int** CreateTranslationMatrix_Flat(int **states, TMarkovStateVariable *sv);
|
||||
|
||||
void SetPriors_VAR(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior, TVector zeta_b_prior);
|
||||
void SetPriors_VAR_SimsZha(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior,
|
||||
TVector zeta_b_prior, PRECISION lambda_prior);
|
||||
|
||||
|
||||
TStateModel* CreateConstantModel(TStateModel *model);
|
||||
TStateModel* ExpandModel_VAR(TStateModel *model, TStateModel *restricted_model, int s);
|
||||
|
||||
|
||||
void SetupSimsZhaSpecification(T_VAR_Parameters *p, PRECISION lambda_prior);
|
||||
|
||||
PRECISION LogConditionalProbability_VAR(int i, int t, TStateModel *model);
|
||||
TVector ExpectationSingleStep_VAR(TVector y, int s, int t, TStateModel *model);
|
||||
|
||||
|
||||
void DrawParameters_VAR(TStateModel *model);
|
||||
void InitializeParameters_VAR(T_VAR_Parameters *p);
|
||||
|
||||
// Priors
|
||||
void SetLogPriorConstant_VAR(T_VAR_Parameters *p);
|
||||
PRECISION LogPrior_VAR(TStateModel *model);
|
||||
|
||||
// Normalization
|
||||
int IsNormalized_VAR(T_VAR_Parameters *p);
|
||||
int Normalize_VAR(T_VAR_Parameters *p);
|
||||
void Setup_No_Normalization(T_VAR_Parameters *p);
|
||||
void Setup_WZ_Normalization(T_VAR_Parameters *p, TVector **A0);
|
||||
int WZ_Normalize(T_VAR_Parameters *p);
|
||||
|
||||
// Notification
|
||||
void StatesChanged_VAR(TStateModel *model);
|
||||
void ThetaChanged_VAR(TStateModel *model);
|
||||
void InitializeForwardRecursion_VAR(TStateModel *model);
|
||||
|
||||
// Utility Routines
|
||||
int Reset_VAR_Improper_Distribution_Counter(void);
|
||||
int Get_VAR_Improper_Distribution_Counter(void);
|
||||
void Increment_Verbose(void);
|
||||
void SetVerboseFile(FILE *f);
|
||||
|
||||
// Optimization
|
||||
int NumberFreeParametersVAR(TStateModel *model);
|
||||
void FreeParametersToVAR(TStateModel *model, PRECISION *f);
|
||||
void VARToFreeParameters(TStateModel *model, PRECISION *f);
|
||||
int ZetaIndex(T_VAR_Parameters *p);
|
||||
int ZetaLength(T_VAR_Parameters *p);
|
||||
|
||||
//PRECISION ComputeConstantSimsZha(TStateModel *model);
|
||||
|
||||
//
|
||||
void PsiDeltaToAplus(TStateModel *model);
|
||||
|
||||
// Impulse Response
|
||||
TMatrix ComputeImpulseResponseReducedForm(TMatrix R, int h, TMatrix A0_Xi_inv, TMatrix B, int nlags);
|
||||
TMatrix ComputeImpulseResponseStructural(TMatrix R, int h, TMatrix A0, TMatrix Aplus, TVector Xi, int nlags);
|
||||
TMatrix ComputeImpulseResponse(TMatrix R, int h, int k, TStateModel *model);
|
||||
TMatrix ComputeVarianceDecomposition(TMatrix X, TMatrix IR, int nvars);
|
||||
|
||||
// Simulation
|
||||
void DrawZeta_Aplus(TStateModel *model);
|
||||
void DrawZeta_DotProducts(TStateModel *model);
|
||||
void AdaptiveMetropolisScale(TStateModel *model, int iterations, int period, int verbose, FILE *f_posterior);
|
||||
void SetupMetropolisInformation(PRECISION **Scale, T_VAR_Parameters *p);
|
||||
void ResetMetropolisInformation(T_VAR_Parameters *p);
|
||||
PRECISION LogKernel_A0_DotProducts(int j, int k, TStateModel *model);
|
||||
PRECISION LogKernel_A0(int j, int k, TStateModel *model);
|
||||
void DrawA0_Metropolis(TStateModel *model);
|
||||
void DrawAplus(TStateModel *model);
|
||||
void Draw_psi(TStateModel *model);
|
||||
void Draw_lambda(TStateModel *model);
|
||||
|
||||
/* Utilities */
|
||||
void ComputeDotProducts_All(T_VAR_Parameters *p);
|
||||
void ComputeLogAbsDetA0_All(T_VAR_Parameters *p);
|
||||
void ComputeLogAbsDetA0(int j, int k, T_VAR_Parameters *p);
|
||||
|
||||
TMatrix MakeA0(TMatrix A0, int k, T_VAR_Parameters *p);
|
||||
TMatrix MakeAplus(TMatrix Aplus, int k, T_VAR_Parameters *p);
|
||||
TMatrix MakeZeta(TMatrix Zeta, int k, T_VAR_Parameters *p);
|
||||
TMatrix ConstructMatrixFromColumns(TMatrix X, TVector **, int k);
|
||||
|
||||
void UpdateStateDependentFields(T_VAR_Parameters *p, int *S);
|
||||
void Update_aplus_from_bplus_a0(int j, int k, T_VAR_Parameters *p);
|
||||
void Update_A0_from_b0(T_VAR_Parameters *p);
|
||||
void Update_Aplus_from_bplus_A0(T_VAR_Parameters *p);
|
||||
void Update_bplus_from_lambda_psi(T_VAR_Parameters *p);
|
||||
void Update_b0_bplus_from_A0_Aplus(T_VAR_Parameters *p);
|
||||
void Update_lambda_psi_from_bplus(T_VAR_Parameters *p);
|
||||
|
||||
int GetNumberStatesFromTranslationMatrix(int j, int **states);
|
||||
int **CreateTranslationMatrix(TMarkovStateVariable ***list, TMarkovStateVariable *sv);
|
||||
|
||||
//PRECISION InnerProductSymmetric(TVector x, TMatrix S);
|
||||
//PRECISION InnerProductNonSymmetric(TVector x, TVector y, TMatrix S);
|
||||
|
||||
void update_psi_quadratic_form(TMatrix S, int n, int m, int k, TVector lambda, TMatrix XX);
|
||||
TMatrix MatrixInnerProductSymmetric(TMatrix X, TMatrix Y, TMatrix S);
|
||||
PRECISION InnerProductSymmetric(TVector x, TMatrix S);
|
||||
PRECISION InnerProductNonSymmetric(TVector x, TVector y, TMatrix S);
|
||||
TVector DrawNormal_InverseVariance(TVector x, TVector b, TMatrix S);
|
||||
TVector DrawNormal_InverseVariance_SVD(TVector x, TVector b, TMatrix S);
|
||||
TVector DrawNormal_InverseUpperTriangular(TVector x, TVector b, TMatrix T);
|
||||
|
||||
|
||||
// Obsolete routines
|
||||
|
||||
|
||||
#endif // __VAR_BASE_MODEL__
|
||||
|
||||
|
||||
/********************************************************************************
|
||||
Notes:
|
||||
|
||||
The model:
|
||||
|
||||
y(t)' * A0(s(t)) = x(t)' * Aplus(s(t)) + epsilon(t)' * Inverse(Xi(s(t)))
|
||||
|
||||
where
|
||||
y(t) is nvars x 1
|
||||
x(t) is npre x 1
|
||||
x(t)=[y(t-1),...,y(t-p),z(t)], where z(t) is exogenous
|
||||
epsilon(t) is nvars x 1
|
||||
A0(k) is nvars x nvars
|
||||
Aplus(k) is npre x nvars
|
||||
Xi(k) is an nvars x nvars diagonal matrix
|
||||
s(t) is an integer with 0 <= s(t) < nstates
|
||||
|
||||
Furthermore
|
||||
|
||||
A0(j,k) = U(j) * b0(j,k)
|
||||
|
||||
Aplus(j,k) = V(j) * bplus(j,k) - W(j) * A0(j,k)
|
||||
|
||||
and
|
||||
|
||||
Zeta(j,k) = Xi(j,k)*Xi(j,k)
|
||||
where
|
||||
|
||||
A0(j,k) is the jth column of A0(k)
|
||||
Aplus(j,k) is the jth column of A0(k)
|
||||
Xi(j,k) is the jth diagonal element of Xi(k)
|
||||
b0(j,k) is q(j) x 1
|
||||
bplus(j,k) is r(j) x 1
|
||||
U(j) is nvars x q(j) with orthonormal columns
|
||||
V(j) is npre x r(j) with orthonormal columns
|
||||
W(j) is npre x nvar
|
||||
e(j) is the jth column of an identity matrix
|
||||
|
||||
Sims-Zha Specification:
|
||||
This specification imposes that r(j) == npre, V(j) is the identity matrix, and
|
||||
W(j) is equal to a npre x nvars diagonal matrix with minus ones along the
|
||||
diagonal. Further restrictions are imposed of the form.
|
||||
|
||||
bplus(j,k) = f(psi(j),lambda(j,k))
|
||||
|
||||
where
|
||||
|
||||
psi(j) is npre x 1
|
||||
lambda(j,k) is nvars x 1
|
||||
|
||||
and f is the function
|
||||
|
||||
f(a,b) = diag(vec(a))
|
||||
|
||||
Random Walk Specification:
|
||||
This specification imposes that W(j) is equal to a npre x nvars diagonal
|
||||
matrix with minus ones along the diagonal. Though it is not imposed, we
|
||||
usually want Aplus(j,k) to satisfy linear restrictions implicit in the
|
||||
matrix V(j). This means that W(j) must be in the span of V(j) and hence
|
||||
(I - V(j)*V'(j))*W(j) = 0.
|
||||
|
||||
|
||||
Normalization:
|
||||
We normalize by requiring Xi(0) to be the identity matrix and
|
||||
delta(j,0) to be a vector of ones.
|
||||
|
||||
Prior:
|
||||
A0(j,k) - The prior on A0(j,k) is normal with mean zero and covariance matrix
|
||||
A0_Prior(j). This implies that the prior on b0(j,k) is normal with mean zero
|
||||
and covariance matrix Inverse(U'[j]*Inverse(A0_prior[j])*U[j]).
|
||||
|
||||
Aplus(j,k) - The prior on Aplus(j,k) conditional on A0(j,k) is normal with mean
|
||||
-W(j) * A0(j,k) and covariance Aplus_Prior(j). This implies that the prior on
|
||||
bplus(j,k) is normal with mean zero and covariance matrix
|
||||
Inverse(V'[j]*Inverse(Aplus_prior[j])*V[j])
|
||||
|
||||
Zeta(j,k) - The prior on Zeta(j,k) is Gamma(zeta_a_prior(j),zeta_b_prior(j)).
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
TVector** A0
|
||||
The length of A0 is nvars. The vector A0[j][k] is the jth column of A0 when
|
||||
the jth coefficient state variable is equal to k. Note that when the Markov
|
||||
state variable is equal to s, the jth coefficient state variable is equal to
|
||||
coef_states[j][s]. The number of distinct values for the jth coefficient state
|
||||
variable is equal to the dimension of A0[j]. This field is created with
|
||||
dw_CreateArray_array() and freed with dw_FreeArray().
|
||||
|
||||
TVector** b0
|
||||
The length of b0 is nvars. The vector b0[j][k] consists of the free parameters
|
||||
in the jth column of A0 when the jth coefficient state variable is equal to k.
|
||||
The dimension of b0[j][k] does not vary across k. Note that when the Markov
|
||||
state variable is equal to s, the jth coefficient state variable is equal to
|
||||
coef_states[j][s]. The dimension of b0[j] is equal to the dimension of A0[j].
|
||||
This field is created with dw_CreateArray_array() and freed with
|
||||
dw_FreeArray().
|
||||
|
||||
TVector** Aplus
|
||||
The length of Aplus is nvars. The vector Aplus[j][k] is the jth column of
|
||||
Aplus when the jth coefficient state variable is equal to k. Note that when
|
||||
the Markov state variable is equal to s, the jth coefficient state variable is
|
||||
equal to coef_states[j][s]. The dimension of Aplus[j] is equal to the
|
||||
dimension of A0[j]. This field is created with dw_CreateArray_array() and
|
||||
freed with dw_FreeArray().
|
||||
|
||||
TVector** bplus
|
||||
The length of bplus is nvars. The vector bplus[j][k] consists of the free
|
||||
parameters in the jth column of Aplus when the jth coefficient state variable
|
||||
is equal to k. The dimension of bplus[j][k] does not vary across k. Note that
|
||||
when the Markov state variable is equal to s, the jth coefficient state
|
||||
variable is equal to coef_states[j][s]. The dimension of bplus[j] is equal to
|
||||
the dimension of A0[j]. This field is created with dw_CreateArray_array() and
|
||||
freed with dw_FreeArray().
|
||||
|
||||
PRECISION** Zeta
|
||||
The length of Zeta is nvars. The value of Zeta[j][k] is the square of the
|
||||
value of the jth diagonal element of Xi when the jth variance state variable is
|
||||
equal to k. Note that the the Markov state variable is equal to s, the jth
|
||||
variance state variable is equal to var_states[j][s]. The number of distinct
|
||||
values for the jth variance state variable is equal to the dimension of
|
||||
Zeta[j]. This field is created with dw_CreateArray_array() and freed with
|
||||
dw_FreeArray().
|
||||
|
||||
TVector** delta
|
||||
The length of delta is nvars. The vector bplus[j][k] is a non-linear function
|
||||
of delta[j][k] and psi[k]. The length of delta[j][k] is nvars. This field is
|
||||
non-null only when using the Sims-Zha specification.
|
||||
|
||||
TVector* psi
|
||||
The length of psi is nvars. The vector bplus[j][k] is a non-linear function
|
||||
of psi[k] and delta[j][k]. The length of psi[k] is npre. This field is non-
|
||||
null only when using the Sims-Zha specification.
|
||||
|
||||
|
||||
=============================== State Translation ===============================
|
||||
|
||||
int* n_var_states
|
||||
An integer array of dimension nvars. The value of n_var_states[j] is the
|
||||
number of variance states for column j.
|
||||
|
||||
int** var_states
|
||||
An integer array of dimension nvars by nstates. The value of var_states[j][k]
|
||||
is the value of the variance state for column j when the overall Markov state
|
||||
variable is equal to k. It is used as an index into Xi[j]. It must be the
|
||||
case that
|
||||
|
||||
0 <= var_states[j][k] < n_var_states[j].
|
||||
|
||||
int* n_coef_states
|
||||
An integer arrary of dimension nvars. The value of n_coef_states[j] is the
|
||||
number of coefficient states for column j.
|
||||
|
||||
int** coef_states
|
||||
An integer array of dimension nvar by nstates. The value of coef_states[j][k]
|
||||
is the value of the coefficient state for column j when the overall Markov
|
||||
state variable is equal to k. It is used as an index into A0[j], b0[j],
|
||||
Aplus[j] or bplus[j]. It must be the case that
|
||||
|
||||
0 <= coef_states[j][k] < n_coef_states[j].
|
||||
|
||||
int n_A0_states
|
||||
The number of distinct values for the matrix A0.
|
||||
|
||||
int* A0_states
|
||||
An integer array of dimension nstates. The value of A0_states[k] is the value
|
||||
of the state variable controlling A0 when the value of the overall Markov state
|
||||
variable is k. It is used as an index into the vector log_abs_det_A0. It must
|
||||
be the case that
|
||||
|
||||
0 <= A0_states[k] < n_A0_states.
|
||||
|
||||
int** A0_column_states
|
||||
An integer array of dimension nvars by n_A0_states. The value of
|
||||
A0_column_states[j][k] is the value of the coefficient state for column j when
|
||||
value of the state variable controlling the matrix A0 is k. It is used as an
|
||||
index into A0[j]. It must be the case that
|
||||
|
||||
0 <= A0_column_states[j][k] < n_coef_states[j].
|
||||
|
||||
|
||||
================================= Normalization =================================
|
||||
For 0 <= k < n_A0_states, the contemporaneous coefficient matrix A[k] is formed.
|
||||
For 0 <= j < nvars and 0 <= k < n_A0_states, the number
|
||||
|
||||
e[j]*Inverse(A[k])*Target[j][A0_column_states[j][k]]
|
||||
|
||||
is computed. If this number is negative, then the sign of
|
||||
|
||||
A0[j][A0_column_states[j][k]]
|
||||
|
||||
is flipped. If the sign of any element of A0[j][.] is flipped more than once,
|
||||
this event is recorded.
|
||||
|
||||
********************************************************************************/
|
||||
|
||||
#ifndef __VAR_BASE_MODEL__
|
||||
#define __VAR_BASE_MODEL__
|
||||
|
||||
#include "switch.h"
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_matrix_array.h"
|
||||
|
||||
#define standard_ordering 1 // for future implementation
|
||||
#define SPEC_RANDOM_WALK 0x00000001
|
||||
#define SPEC_SIMS_ZHA 0x00000002
|
||||
|
||||
//=== Normalization types (must be mutually exclusive) ===//
|
||||
#define VAR_NORMALIZATION_NONE 0x00000000
|
||||
#define VAR_NORMALIZATION_WZ 0x00000001
|
||||
|
||||
typedef struct
|
||||
{
|
||||
//====== Model specification ======
|
||||
int Specification;
|
||||
int *IsIdentity_V;
|
||||
|
||||
//====== Free parameter specification (for future implementation) ======
|
||||
int FreeParameterType;
|
||||
|
||||
//====== Sizes ======
|
||||
int nvars;
|
||||
int nlags;
|
||||
int npre;
|
||||
int nobs;
|
||||
int nstates;
|
||||
|
||||
//====== State variable translation ======
|
||||
int* n_var_states; // nvars n_var_states[j] is the number of variance states for column j
|
||||
int** var_states; // nvars x n_states translation table for variance states
|
||||
int* n_coef_states; // nvars n_coef_states[j] is the number of coefficients states for column j
|
||||
int** coef_states; // nvars x n_states translation table for coefficient states
|
||||
int n_A0_states; // number of states for the matrix A0
|
||||
int* A0_states; // n_states translation table for the matrix A0
|
||||
int** A0_column_states; // nvars x n_A0_states translation table from determinant of A0 states to coefficient states
|
||||
|
||||
//====== Parameters ======
|
||||
PRECISION** Zeta; // nvars x n_var_states[j]
|
||||
TVector** A0; // nvars x n_coef_states[j] x nvars
|
||||
TVector** Aplus; // nvars x n_coef_states[j] x npre
|
||||
|
||||
//====== Free parameters ======
|
||||
int* dim_b0;
|
||||
TVector** b0;
|
||||
int* dim_bplus;
|
||||
TVector** bplus;
|
||||
|
||||
//====== Priors ======
|
||||
TVector zeta_a_prior; //
|
||||
TVector zeta_b_prior; //
|
||||
TMatrix* A0_prior; // A0_prior[j] = constant parameter variance of the normal prior on the jth column of A0
|
||||
TMatrix* Aplus_prior; // Aplus_prior[j] = constant parameter variance of the normal prior on the jth column of Aplus
|
||||
|
||||
//====== Identifying restrictions ======
|
||||
TMatrix *U;
|
||||
TMatrix *V;
|
||||
TMatrix *W;
|
||||
|
||||
//====== Sims-Zha specification parameters and workspace ======
|
||||
TVector** lambda; // nvars x n_coef_states[j] array of nvars-dimensional vectors
|
||||
TVector* constant; // nvars x n_coef_states[j] -- constant[j][k] == psi[j][npre - 1 + k]
|
||||
TVector* psi; // nvars x (npre - 1 + n_coef_states[j])
|
||||
PRECISION lambda_prior; // prior variance of each element of lambda
|
||||
PRECISION inverse_lambda_prior;
|
||||
TMatrix* inverse_psi_prior;
|
||||
|
||||
//====== Normalization ======
|
||||
int normalization_type; // type of normalization used
|
||||
int normalized; // type of normalization actually used to normalize current draw
|
||||
TVector** Target; // nvar x n_coef_states[j] array of nvars-dimensional vectors
|
||||
int** flipped; // nvar x n_coef_states[j] array of integers
|
||||
int WZ_inconsistancies;
|
||||
|
||||
//====== Workspace ======
|
||||
PRECISION log_prior_constant; // Constant of integrate for the log prior
|
||||
PRECISION minus_half_nvars_times_log2pi; // Constant used in LogConditionalProbability functions
|
||||
TVector inverse_zeta_b_prior; // inverse_zeta_b_prior = 1.0/zeta_b_prior
|
||||
TMatrix* inverse_b0_prior; // inverse_b0_prior = U'[j]*Inverse(A0_prior[j])*U[j]
|
||||
TMatrix* inverse_bplus_prior; // inverse_bplus_prior = V'[j]*Inverse(Aplus_prior[j])*V[j]
|
||||
|
||||
TVector log_abs_det_A0; // log(abs(det(A0[k])))
|
||||
|
||||
PRECISION*** A0_dot_products; // A0_dot_products[t][j][k] = Y'[t] * A0[j][k]
|
||||
PRECISION*** Aplus_dot_products; // Aplus_dot_products[t][j][k] = X'[t] * Aplus[j][k]
|
||||
|
||||
// A0 Metropolis Info
|
||||
PRECISION** A0_Metropolis_Scale;
|
||||
int Total_A0_Metropolis_Draws;
|
||||
int** A0_Metropolis_Jumps;
|
||||
|
||||
// State dependent fields
|
||||
TMatrix* YY; // YY[k] = sum(Y[t]*Y'[t], 1 <= t <= nobs and S[t] == k)
|
||||
TMatrix* XY; // YX[k] = sum(X[t]*Y'[t], 1 <= t <= nobs and S[t] == k)
|
||||
TMatrix* XX; // XX[k] = sum(X[t]*X'[t], 1 <= t <= nobs and S[t] == k)
|
||||
int* T; // T[k] = number of t with 1 <= t <= nobs and S[t] == k
|
||||
int *S; // S[t] = state variable used to compute YY, XY, XX, and T
|
||||
TMatrix* yy; // yy[t] = Y[t]*Y'[t]
|
||||
TMatrix* xy; // xy[t] = X[t]*Y'[t]
|
||||
TMatrix* xx; // xx[t] = X[t]*X'[t]
|
||||
|
||||
// Flags for validity of workspace fields
|
||||
int valid_log_abs_det_A0; // Invalid after A0 changes
|
||||
int valid_dot_products; // Invalid after A0 or Aplus changes
|
||||
int valid_state_dependent_fields; // Invalid after states change
|
||||
int valid_state_dependent_fields_previous; // Initially invalid.
|
||||
int valid_parameters; // Initially invalid. Valid after successful read or draw of parameters.
|
||||
// Parametes are invalid if Zeta is negative or if they do not satisfy
|
||||
// the normalization.
|
||||
|
||||
//=== Data ===
|
||||
TVector* Y; // Y[t] nvar vector of time t data for 1 <= t <= T
|
||||
TVector* X; // X[t] npre vector of time t predetermined variables for 1 <= t <= T
|
||||
|
||||
} T_VAR_Parameters;
|
||||
|
||||
// Constructors-Destructors
|
||||
void FreeTheta_VAR(T_VAR_Parameters *p);
|
||||
ThetaRoutines* CreateRoutines_VAR(void);
|
||||
T_VAR_Parameters* CreateTheta_VAR(int flag, int nvars, int nlags, int nexg, int nstates, int nobs, // Specification and Sizes
|
||||
int **coef_states, int **var_states, // Translation Tables
|
||||
TMatrix *U, TMatrix *V, TMatrix *W, // Restrictions
|
||||
TMatrix Y, TMatrix X); // Data
|
||||
int** CreateTranslationMatrix_Flat(int **states, TMarkovStateVariable *sv);
|
||||
|
||||
void SetPriors_VAR(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior, TVector zeta_b_prior);
|
||||
void SetPriors_VAR_SimsZha(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior,
|
||||
TVector zeta_b_prior, PRECISION lambda_prior);
|
||||
|
||||
|
||||
TStateModel* CreateConstantModel(TStateModel *model);
|
||||
TStateModel* ExpandModel_VAR(TStateModel *model, TStateModel *restricted_model, int s);
|
||||
|
||||
|
||||
void SetupSimsZhaSpecification(T_VAR_Parameters *p, PRECISION lambda_prior);
|
||||
|
||||
PRECISION LogConditionalProbability_VAR(int i, int t, TStateModel *model);
|
||||
TVector ExpectationSingleStep_VAR(TVector y, int s, int t, TStateModel *model);
|
||||
|
||||
|
||||
void DrawParameters_VAR(TStateModel *model);
|
||||
void InitializeParameters_VAR(T_VAR_Parameters *p);
|
||||
|
||||
// Priors
|
||||
void SetLogPriorConstant_VAR(T_VAR_Parameters *p);
|
||||
PRECISION LogPrior_VAR(TStateModel *model);
|
||||
|
||||
// Normalization
|
||||
int IsNormalized_VAR(T_VAR_Parameters *p);
|
||||
int Normalize_VAR(T_VAR_Parameters *p);
|
||||
void Setup_No_Normalization(T_VAR_Parameters *p);
|
||||
void Setup_WZ_Normalization(T_VAR_Parameters *p, TVector **A0);
|
||||
int WZ_Normalize(T_VAR_Parameters *p);
|
||||
|
||||
// Notification
|
||||
void StatesChanged_VAR(TStateModel *model);
|
||||
void ThetaChanged_VAR(TStateModel *model);
|
||||
void InitializeForwardRecursion_VAR(TStateModel *model);
|
||||
|
||||
// Utility Routines
|
||||
int Reset_VAR_Improper_Distribution_Counter(void);
|
||||
int Get_VAR_Improper_Distribution_Counter(void);
|
||||
void Increment_Verbose(void);
|
||||
void SetVerboseFile(FILE *f);
|
||||
|
||||
// Optimization
|
||||
int NumberFreeParametersVAR(TStateModel *model);
|
||||
void FreeParametersToVAR(TStateModel *model, PRECISION *f);
|
||||
void VARToFreeParameters(TStateModel *model, PRECISION *f);
|
||||
int ZetaIndex(T_VAR_Parameters *p);
|
||||
int ZetaLength(T_VAR_Parameters *p);
|
||||
|
||||
//PRECISION ComputeConstantSimsZha(TStateModel *model);
|
||||
|
||||
//
|
||||
void PsiDeltaToAplus(TStateModel *model);
|
||||
|
||||
// Impulse Response
|
||||
TMatrix ComputeImpulseResponseReducedForm(TMatrix R, int h, TMatrix A0_Xi_inv, TMatrix B, int nlags);
|
||||
TMatrix ComputeImpulseResponseStructural(TMatrix R, int h, TMatrix A0, TMatrix Aplus, TVector Xi, int nlags);
|
||||
TMatrix ComputeImpulseResponse(TMatrix R, int h, int k, TStateModel *model);
|
||||
TMatrix ComputeVarianceDecomposition(TMatrix X, TMatrix IR, int nvars);
|
||||
|
||||
// Simulation
|
||||
void DrawZeta_Aplus(TStateModel *model);
|
||||
void DrawZeta_DotProducts(TStateModel *model);
|
||||
void AdaptiveMetropolisScale(TStateModel *model, int iterations, int period, int verbose, FILE *f_posterior);
|
||||
void SetupMetropolisInformation(PRECISION **Scale, T_VAR_Parameters *p);
|
||||
void ResetMetropolisInformation(T_VAR_Parameters *p);
|
||||
PRECISION LogKernel_A0_DotProducts(int j, int k, TStateModel *model);
|
||||
PRECISION LogKernel_A0(int j, int k, TStateModel *model);
|
||||
void DrawA0_Metropolis(TStateModel *model);
|
||||
void DrawAplus(TStateModel *model);
|
||||
void Draw_psi(TStateModel *model);
|
||||
void Draw_lambda(TStateModel *model);
|
||||
|
||||
/* Utilities */
|
||||
void ComputeDotProducts_All(T_VAR_Parameters *p);
|
||||
void ComputeLogAbsDetA0_All(T_VAR_Parameters *p);
|
||||
void ComputeLogAbsDetA0(int j, int k, T_VAR_Parameters *p);
|
||||
|
||||
TMatrix MakeA0(TMatrix A0, int k, T_VAR_Parameters *p);
|
||||
TMatrix MakeAplus(TMatrix Aplus, int k, T_VAR_Parameters *p);
|
||||
TMatrix MakeZeta(TMatrix Zeta, int k, T_VAR_Parameters *p);
|
||||
TMatrix ConstructMatrixFromColumns(TMatrix X, TVector **, int k);
|
||||
|
||||
void UpdateStateDependentFields(T_VAR_Parameters *p, int *S);
|
||||
void Update_aplus_from_bplus_a0(int j, int k, T_VAR_Parameters *p);
|
||||
void Update_A0_from_b0(T_VAR_Parameters *p);
|
||||
void Update_Aplus_from_bplus_A0(T_VAR_Parameters *p);
|
||||
void Update_bplus_from_lambda_psi(T_VAR_Parameters *p);
|
||||
void Update_b0_bplus_from_A0_Aplus(T_VAR_Parameters *p);
|
||||
void Update_lambda_psi_from_bplus(T_VAR_Parameters *p);
|
||||
|
||||
int GetNumberStatesFromTranslationMatrix(int j, int **states);
|
||||
int **CreateTranslationMatrix(TMarkovStateVariable ***list, TMarkovStateVariable *sv);
|
||||
|
||||
//PRECISION InnerProductSymmetric(TVector x, TMatrix S);
|
||||
//PRECISION InnerProductNonSymmetric(TVector x, TVector y, TMatrix S);
|
||||
|
||||
void update_psi_quadratic_form(TMatrix S, int n, int m, int k, TVector lambda, TMatrix XX);
|
||||
TMatrix MatrixInnerProductSymmetric(TMatrix X, TMatrix Y, TMatrix S);
|
||||
PRECISION InnerProductSymmetric(TVector x, TMatrix S);
|
||||
PRECISION InnerProductNonSymmetric(TVector x, TVector y, TMatrix S);
|
||||
TVector DrawNormal_InverseVariance(TVector x, TVector b, TMatrix S);
|
||||
TVector DrawNormal_InverseVariance_SVD(TVector x, TVector b, TMatrix S);
|
||||
TVector DrawNormal_InverseUpperTriangular(TVector x, TVector b, TMatrix T);
|
||||
|
||||
|
||||
// Obsolete routines
|
||||
|
||||
|
||||
#endif // __VAR_BASE_MODEL__
|
||||
|
||||
|
||||
/********************************************************************************
|
||||
Notes:
|
||||
|
||||
The model:
|
||||
|
||||
y(t)' * A0(s(t)) = x(t)' * Aplus(s(t)) + epsilon(t)' * Inverse(Xi(s(t)))
|
||||
|
||||
where
|
||||
y(t) is nvars x 1
|
||||
x(t) is npre x 1
|
||||
x(t)=[y(t-1),...,y(t-p),z(t)], where z(t) is exogenous
|
||||
epsilon(t) is nvars x 1
|
||||
A0(k) is nvars x nvars
|
||||
Aplus(k) is npre x nvars
|
||||
Xi(k) is an nvars x nvars diagonal matrix
|
||||
s(t) is an integer with 0 <= s(t) < nstates
|
||||
|
||||
Furthermore
|
||||
|
||||
A0(j,k) = U(j) * b0(j,k)
|
||||
|
||||
Aplus(j,k) = V(j) * bplus(j,k) - W(j) * A0(j,k)
|
||||
|
||||
and
|
||||
|
||||
Zeta(j,k) = Xi(j,k)*Xi(j,k)
|
||||
where
|
||||
|
||||
A0(j,k) is the jth column of A0(k)
|
||||
Aplus(j,k) is the jth column of A0(k)
|
||||
Xi(j,k) is the jth diagonal element of Xi(k)
|
||||
b0(j,k) is q(j) x 1
|
||||
bplus(j,k) is r(j) x 1
|
||||
U(j) is nvars x q(j) with orthonormal columns
|
||||
V(j) is npre x r(j) with orthonormal columns
|
||||
W(j) is npre x nvar
|
||||
e(j) is the jth column of an identity matrix
|
||||
|
||||
Sims-Zha Specification:
|
||||
This specification imposes that r(j) == npre, V(j) is the identity matrix, and
|
||||
W(j) is equal to a npre x nvars diagonal matrix with minus ones along the
|
||||
diagonal. Further restrictions are imposed of the form.
|
||||
|
||||
bplus(j,k) = f(psi(j),lambda(j,k))
|
||||
|
||||
where
|
||||
|
||||
psi(j) is npre x 1
|
||||
lambda(j,k) is nvars x 1
|
||||
|
||||
and f is the function
|
||||
|
||||
f(a,b) = diag(vec(a))
|
||||
|
||||
Random Walk Specification:
|
||||
This specification imposes that W(j) is equal to a npre x nvars diagonal
|
||||
matrix with minus ones along the diagonal. Though it is not imposed, we
|
||||
usually want Aplus(j,k) to satisfy linear restrictions implicit in the
|
||||
matrix V(j). This means that W(j) must be in the span of V(j) and hence
|
||||
(I - V(j)*V'(j))*W(j) = 0.
|
||||
|
||||
|
||||
Normalization:
|
||||
We normalize by requiring Xi(0) to be the identity matrix and
|
||||
delta(j,0) to be a vector of ones.
|
||||
|
||||
Prior:
|
||||
A0(j,k) - The prior on A0(j,k) is normal with mean zero and covariance matrix
|
||||
A0_Prior(j). This implies that the prior on b0(j,k) is normal with mean zero
|
||||
and covariance matrix Inverse(U'[j]*Inverse(A0_prior[j])*U[j]).
|
||||
|
||||
Aplus(j,k) - The prior on Aplus(j,k) conditional on A0(j,k) is normal with mean
|
||||
-W(j) * A0(j,k) and covariance Aplus_Prior(j). This implies that the prior on
|
||||
bplus(j,k) is normal with mean zero and covariance matrix
|
||||
Inverse(V'[j]*Inverse(Aplus_prior[j])*V[j])
|
||||
|
||||
Zeta(j,k) - The prior on Zeta(j,k) is Gamma(zeta_a_prior(j),zeta_b_prior(j)).
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
TVector** A0
|
||||
The length of A0 is nvars. The vector A0[j][k] is the jth column of A0 when
|
||||
the jth coefficient state variable is equal to k. Note that when the Markov
|
||||
state variable is equal to s, the jth coefficient state variable is equal to
|
||||
coef_states[j][s]. The number of distinct values for the jth coefficient state
|
||||
variable is equal to the dimension of A0[j]. This field is created with
|
||||
dw_CreateArray_array() and freed with dw_FreeArray().
|
||||
|
||||
TVector** b0
|
||||
The length of b0 is nvars. The vector b0[j][k] consists of the free parameters
|
||||
in the jth column of A0 when the jth coefficient state variable is equal to k.
|
||||
The dimension of b0[j][k] does not vary across k. Note that when the Markov
|
||||
state variable is equal to s, the jth coefficient state variable is equal to
|
||||
coef_states[j][s]. The dimension of b0[j] is equal to the dimension of A0[j].
|
||||
This field is created with dw_CreateArray_array() and freed with
|
||||
dw_FreeArray().
|
||||
|
||||
TVector** Aplus
|
||||
The length of Aplus is nvars. The vector Aplus[j][k] is the jth column of
|
||||
Aplus when the jth coefficient state variable is equal to k. Note that when
|
||||
the Markov state variable is equal to s, the jth coefficient state variable is
|
||||
equal to coef_states[j][s]. The dimension of Aplus[j] is equal to the
|
||||
dimension of A0[j]. This field is created with dw_CreateArray_array() and
|
||||
freed with dw_FreeArray().
|
||||
|
||||
TVector** bplus
|
||||
The length of bplus is nvars. The vector bplus[j][k] consists of the free
|
||||
parameters in the jth column of Aplus when the jth coefficient state variable
|
||||
is equal to k. The dimension of bplus[j][k] does not vary across k. Note that
|
||||
when the Markov state variable is equal to s, the jth coefficient state
|
||||
variable is equal to coef_states[j][s]. The dimension of bplus[j] is equal to
|
||||
the dimension of A0[j]. This field is created with dw_CreateArray_array() and
|
||||
freed with dw_FreeArray().
|
||||
|
||||
PRECISION** Zeta
|
||||
The length of Zeta is nvars. The value of Zeta[j][k] is the square of the
|
||||
value of the jth diagonal element of Xi when the jth variance state variable is
|
||||
equal to k. Note that the the Markov state variable is equal to s, the jth
|
||||
variance state variable is equal to var_states[j][s]. The number of distinct
|
||||
values for the jth variance state variable is equal to the dimension of
|
||||
Zeta[j]. This field is created with dw_CreateArray_array() and freed with
|
||||
dw_FreeArray().
|
||||
|
||||
TVector** delta
|
||||
The length of delta is nvars. The vector bplus[j][k] is a non-linear function
|
||||
of delta[j][k] and psi[k]. The length of delta[j][k] is nvars. This field is
|
||||
non-null only when using the Sims-Zha specification.
|
||||
|
||||
TVector* psi
|
||||
The length of psi is nvars. The vector bplus[j][k] is a non-linear function
|
||||
of psi[k] and delta[j][k]. The length of psi[k] is npre. This field is non-
|
||||
null only when using the Sims-Zha specification.
|
||||
|
||||
|
||||
=============================== State Translation ===============================
|
||||
|
||||
int* n_var_states
|
||||
An integer array of dimension nvars. The value of n_var_states[j] is the
|
||||
number of variance states for column j.
|
||||
|
||||
int** var_states
|
||||
An integer array of dimension nvars by nstates. The value of var_states[j][k]
|
||||
is the value of the variance state for column j when the overall Markov state
|
||||
variable is equal to k. It is used as an index into Xi[j]. It must be the
|
||||
case that
|
||||
|
||||
0 <= var_states[j][k] < n_var_states[j].
|
||||
|
||||
int* n_coef_states
|
||||
An integer arrary of dimension nvars. The value of n_coef_states[j] is the
|
||||
number of coefficient states for column j.
|
||||
|
||||
int** coef_states
|
||||
An integer array of dimension nvar by nstates. The value of coef_states[j][k]
|
||||
is the value of the coefficient state for column j when the overall Markov
|
||||
state variable is equal to k. It is used as an index into A0[j], b0[j],
|
||||
Aplus[j] or bplus[j]. It must be the case that
|
||||
|
||||
0 <= coef_states[j][k] < n_coef_states[j].
|
||||
|
||||
int n_A0_states
|
||||
The number of distinct values for the matrix A0.
|
||||
|
||||
int* A0_states
|
||||
An integer array of dimension nstates. The value of A0_states[k] is the value
|
||||
of the state variable controlling A0 when the value of the overall Markov state
|
||||
variable is k. It is used as an index into the vector log_abs_det_A0. It must
|
||||
be the case that
|
||||
|
||||
0 <= A0_states[k] < n_A0_states.
|
||||
|
||||
int** A0_column_states
|
||||
An integer array of dimension nvars by n_A0_states. The value of
|
||||
A0_column_states[j][k] is the value of the coefficient state for column j when
|
||||
value of the state variable controlling the matrix A0 is k. It is used as an
|
||||
index into A0[j]. It must be the case that
|
||||
|
||||
0 <= A0_column_states[j][k] < n_coef_states[j].
|
||||
|
||||
|
||||
================================= Normalization =================================
|
||||
For 0 <= k < n_A0_states, the contemporaneous coefficient matrix A[k] is formed.
|
||||
For 0 <= j < nvars and 0 <= k < n_A0_states, the number
|
||||
|
||||
e[j]*Inverse(A[k])*Target[j][A0_column_states[j][k]]
|
||||
|
||||
is computed. If this number is negative, then the sign of
|
||||
|
||||
A0[j][A0_column_states[j][k]]
|
||||
|
||||
is flipped. If the sign of any element of A0[j][.] is flipped more than once,
|
||||
this event is recorded.
|
||||
|
||||
********************************************************************************/
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,26 +1,26 @@
|
|||
|
||||
#ifndef __VAR_INPUT_OUTPUT__
|
||||
#define __VAR_INPUT_OUTPUT__
|
||||
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
void Write_VAR_Specification(FILE *f, char *filename, TStateModel *model);
|
||||
TStateModel* Read_VAR_Specification(FILE *f, char *filename);
|
||||
|
||||
int Write_VAR_Parameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
int Read_VAR_Parameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
int Write_VAR_ParametersFlat(FILE *f, TStateModel *model, char *fmt);
|
||||
int Write_VAR_ParametersFlat_Headers(FILE *f_out, TStateModel *model);
|
||||
int Write_VAR_ParametersFlat_A0_Diagonal_One(FILE *f, TStateModel *model, char *fmt);
|
||||
|
||||
void ReadAllParameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
void WriteAllParameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
|
||||
//T_VAR_Parameters* Create_VAR_Parameters_File(FILE *f, char *filename, TMarkovStateVariable *sv);
|
||||
//TStateModel* CreateStateModel_VAR_File(FILE *f, char *filename);
|
||||
|
||||
//void PrintParametersVAR(FILE *f_out, TStateModel *model);
|
||||
//void Write_VAR_Info(FILE *f, char *filename, T_VAR_Parameters *p);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __VAR_INPUT_OUTPUT__
|
||||
#define __VAR_INPUT_OUTPUT__
|
||||
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
void Write_VAR_Specification(FILE *f, char *filename, TStateModel *model);
|
||||
TStateModel* Read_VAR_Specification(FILE *f, char *filename);
|
||||
|
||||
int Write_VAR_Parameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
int Read_VAR_Parameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
int Write_VAR_ParametersFlat(FILE *f, TStateModel *model, char *fmt);
|
||||
int Write_VAR_ParametersFlat_Headers(FILE *f_out, TStateModel *model);
|
||||
int Write_VAR_ParametersFlat_A0_Diagonal_One(FILE *f, TStateModel *model, char *fmt);
|
||||
|
||||
void ReadAllParameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
void WriteAllParameters(FILE *f, char *filename, char *id, TStateModel *model);
|
||||
|
||||
//T_VAR_Parameters* Create_VAR_Parameters_File(FILE *f, char *filename, TMarkovStateVariable *sv);
|
||||
//TStateModel* CreateStateModel_VAR_File(FILE *f, char *filename);
|
||||
|
||||
//void PrintParametersVAR(FILE *f_out, TStateModel *model);
|
||||
//void Write_VAR_Info(FILE *f, char *filename, T_VAR_Parameters *p);
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,12 +1,12 @@
|
|||
|
||||
#ifndef __VAR_INPUT_OUTPUT_MATLAB__
|
||||
#define __VAR_INPUT_OUTPUT_MATLAB__
|
||||
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
TStateModel* Combine_matlab_standard(char *inmatlab, char *instandard);
|
||||
void ReadConstantParameters(char *filename, TStateModel *model);
|
||||
TStateModel* CreateStateModel_VAR_matlab(char *filename);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __VAR_INPUT_OUTPUT_MATLAB__
|
||||
#define __VAR_INPUT_OUTPUT_MATLAB__
|
||||
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
TStateModel* Combine_matlab_standard(char *inmatlab, char *instandard);
|
||||
void ReadConstantParameters(char *filename, TStateModel *model);
|
||||
TStateModel* CreateStateModel_VAR_matlab(char *filename);
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,37 +1,37 @@
|
|||
#ifndef __command_line_VAR
|
||||
#define __command_line_VAR
|
||||
|
||||
#include "switch.h"
|
||||
#include <stdio.h>
|
||||
|
||||
char* CreateFilenameFromTag(char *fmt, char *tag, char *dir);
|
||||
char* CreatePath(char *path);
|
||||
void PrintHelpMessages(FILE *f, char **include, char **additional);
|
||||
|
||||
typedef struct
|
||||
{
|
||||
char *in_directory; // -di
|
||||
char *in_tag; // -ft
|
||||
char *specification_filename; // -fs
|
||||
char *parameters_filename; // -fp
|
||||
char *parameters_header; // -ph
|
||||
|
||||
char *specification_filename_actual;
|
||||
char *parameters_filename_actual;
|
||||
char *parameters_header_actual;
|
||||
|
||||
char *out_directory; // -do
|
||||
char *out_tag; // -fto (default from -ft)
|
||||
char *out_header; // -pho (default from -ph)
|
||||
} TVARCommandLine;
|
||||
|
||||
TVARCommandLine* Create_VARCommandLine(void);
|
||||
void Free_VARCommandLine(TVARCommandLine *cmd);
|
||||
TVARCommandLine* Base_VARCommandLine(int nargs, char **args, TVARCommandLine *cmd);
|
||||
|
||||
void EstimateFinal_VARCommandLine_Help(FILE *f);
|
||||
TStateModel* CreateTStateModelFromEstimateFinal(int nargs, char **args, TVARCommandLine **p_cmd);
|
||||
|
||||
TStateModel* CreateTStateModelForEstimate(int nargs, char **args, TVARCommandLine **p_cmd);
|
||||
|
||||
#endif
|
||||
#ifndef __command_line_VAR
|
||||
#define __command_line_VAR
|
||||
|
||||
#include "switch.h"
|
||||
#include <stdio.h>
|
||||
|
||||
char* CreateFilenameFromTag(char *fmt, char *tag, char *dir);
|
||||
char* CreatePath(char *path);
|
||||
void PrintHelpMessages(FILE *f, char **include, char **additional);
|
||||
|
||||
typedef struct
|
||||
{
|
||||
char *in_directory; // -di
|
||||
char *in_tag; // -ft
|
||||
char *specification_filename; // -fs
|
||||
char *parameters_filename; // -fp
|
||||
char *parameters_header; // -ph
|
||||
|
||||
char *specification_filename_actual;
|
||||
char *parameters_filename_actual;
|
||||
char *parameters_header_actual;
|
||||
|
||||
char *out_directory; // -do
|
||||
char *out_tag; // -fto (default from -ft)
|
||||
char *out_header; // -pho (default from -ph)
|
||||
} TVARCommandLine;
|
||||
|
||||
TVARCommandLine* Create_VARCommandLine(void);
|
||||
void Free_VARCommandLine(TVARCommandLine *cmd);
|
||||
TVARCommandLine* Base_VARCommandLine(int nargs, char **args, TVARCommandLine *cmd);
|
||||
|
||||
void EstimateFinal_VARCommandLine_Help(FILE *f);
|
||||
TStateModel* CreateTStateModelFromEstimateFinal(int nargs, char **args, TVARCommandLine **p_cmd);
|
||||
|
||||
TStateModel* CreateTStateModelForEstimate(int nargs, char **args, TVARCommandLine **p_cmd);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,44 +1,44 @@
|
|||
|
||||
#include "switch.h"
|
||||
#include "switchio.h"
|
||||
#include "VARbase.h"
|
||||
#include "VARio.h"
|
||||
#include "VARio_matlab.h"
|
||||
#include "dw_error.h"
|
||||
#include "dw_ascii.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/*
|
||||
Creates a standard initialization file from the matlab and specification file.
|
||||
*/
|
||||
int main(int nargs, char **args)
|
||||
{
|
||||
TStateModel *model;
|
||||
FILE *f_out;
|
||||
char *filename, *fmt="init_%s.dat", *header="Initial: ";
|
||||
|
||||
dw_SetTerminalErrors(ALL_ERRORS);
|
||||
dw_SetVerboseErrors(ALL_ERRORS);
|
||||
|
||||
if (nargs != 4)
|
||||
{
|
||||
swz_fprintf_err("Syntax:\n create_init_file <matlab filename> <specs filename> <file tag>\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
model=Combine_matlab_standard(args[1],args[2]);
|
||||
ReadConstantParameters(args[1],model);
|
||||
sprintf(filename=(char*)malloc(strlen(fmt) + strlen(args[3]) - 1),fmt,args[3]);
|
||||
f_out=dw_CreateTextFile(filename);
|
||||
Write_VAR_Specification(f_out,(char*)NULL,model);
|
||||
WriteTransitionMatrices(f_out,(char*)NULL,header,model);
|
||||
Write_VAR_Parameters(f_out,(char*)NULL,header,model);
|
||||
fclose(f_out);
|
||||
FreeStateModel(model);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#include "switch.h"
|
||||
#include "switchio.h"
|
||||
#include "VARbase.h"
|
||||
#include "VARio.h"
|
||||
#include "VARio_matlab.h"
|
||||
#include "dw_error.h"
|
||||
#include "dw_ascii.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/*
|
||||
Creates a standard initialization file from the matlab and specification file.
|
||||
*/
|
||||
int main(int nargs, char **args)
|
||||
{
|
||||
TStateModel *model;
|
||||
FILE *f_out;
|
||||
char *filename, *fmt="init_%s.dat", *header="Initial: ";
|
||||
|
||||
dw_SetTerminalErrors(ALL_ERRORS);
|
||||
dw_SetVerboseErrors(ALL_ERRORS);
|
||||
|
||||
if (nargs != 4)
|
||||
{
|
||||
swz_fprintf_err("Syntax:\n create_init_file <matlab filename> <specs filename> <file tag>\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
model=Combine_matlab_standard(args[1],args[2]);
|
||||
ReadConstantParameters(args[1],model);
|
||||
sprintf(filename=(char*)malloc(strlen(fmt) + strlen(args[3]) - 1),fmt,args[3]);
|
||||
f_out=dw_CreateTextFile(filename);
|
||||
Write_VAR_Specification(f_out,(char*)NULL,model);
|
||||
WriteTransitionMatrices(f_out,(char*)NULL,header,model);
|
||||
Write_VAR_Parameters(f_out,(char*)NULL,header,model);
|
||||
fclose(f_out);
|
||||
FreeStateModel(model);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,88 +1,88 @@
|
|||
|
||||
#ifndef __MODIFIED_HARMONIC_MEAN_
|
||||
#define __MODIFIED_HARMONIC_MEAN_
|
||||
|
||||
#include "swzmatrix.h"
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
typedef struct
|
||||
{
|
||||
// Sample sizes to use in computations
|
||||
int n_burn1; // set to negative of actual value if first burn-in has been completed
|
||||
int n_burn2; // set to negative of actual value if second burn-in has been completed
|
||||
int n_mean_variance; // set to negative of actual value if mean and variance have been computed
|
||||
int n_mhm; // number of draws for computing the modified harmonic mean
|
||||
int n_thin; // thinning factor
|
||||
|
||||
// Accumulation fields
|
||||
int N; // Total number observations
|
||||
|
||||
PRECISION old_log_posterior;
|
||||
PRECISION sum;
|
||||
PRECISION sum_square;
|
||||
PRECISION max_log_posterior;
|
||||
PRECISION max_log_likelihood;
|
||||
|
||||
// mhm info
|
||||
TVector mean; // Gaussian mean
|
||||
TMatrix variance; // Gaussian variance
|
||||
TMatrix inverse_variance; // Inverse of Gaussian variance
|
||||
TVector center; // Used to center gaussian. Must be equal to posterior_mode_VAR or mean.
|
||||
|
||||
TVector alpha_scales; // scaling values for base dirichlet pdf parameters
|
||||
TVector* BaseAlpha; // base dirichlet pdf parameters
|
||||
TVector** Alpha; // base dirichlet pdf parameters times the scale factors
|
||||
|
||||
// Model info
|
||||
TStateModel *model;
|
||||
TVector posterior_mode_VAR;
|
||||
PRECISION log_likelihood_at_mode;
|
||||
PRECISION log_posterior_at_mode;
|
||||
PRECISION log_prior_at_mode;
|
||||
|
||||
// Workspace
|
||||
TVector free_parameters_VAR; // workspace for free parameters for VAR
|
||||
|
||||
// Workspace for states
|
||||
int *states;
|
||||
|
||||
// Files
|
||||
FILE *f_out;
|
||||
FILE *f_out_regime_counts;
|
||||
char *regime_counts_filename;
|
||||
char *intermediate_output_filename;
|
||||
char *final_output_filename;
|
||||
char *intermediate_draws_output_filename;
|
||||
char *draws_output_filename;
|
||||
char *spec_filename;
|
||||
char *parameter_filename;
|
||||
char *parameter_header;
|
||||
char *mhm_filename;
|
||||
|
||||
} T_MHM;
|
||||
|
||||
// Constructors
|
||||
void FreeMHM(T_MHM *mhm);
|
||||
T_MHM* CreateMHM(void);
|
||||
T_MHM* AddDirichletScales(TVector alpha_scales, T_MHM *mhm);
|
||||
T_MHM* AddStateModel(TStateModel *model, T_MHM *mhm);
|
||||
|
||||
void ResetMHM(T_MHM *mhm);
|
||||
void BurnIn(T_MHM *mhm, int iterations, int period);
|
||||
void BurnIn_AdaptiveMetropolisScale(T_MHM *mhm, int iterations, int period);
|
||||
void ComputeMeanVariance_MHM(T_MHM *mhm, int iterations, int period);
|
||||
int IsValidZeta(PRECISION* zeta, int n, PRECISION* gamma_cuts);
|
||||
PRECISION UpdatePosteriorLikelihood(T_MHM *mhm);
|
||||
void UpdateModifiedHarmonicMean(T_MHM *mhm, int n_singular);
|
||||
void ComputeModifiedHarmonicMean(T_MHM *mhm, int period);
|
||||
|
||||
void WriteMHM_Input(FILE *f_out, T_MHM *mhm);
|
||||
T_MHM* ReadMHM_Input(FILE *f_in, char *filename, T_MHM *mhm);
|
||||
void WriteMeanVariance(FILE *f_out, T_MHM *mhm);
|
||||
int ReadMeanVariance(FILE *f_in, T_MHM *mhm);
|
||||
|
||||
void PrintJumps(FILE *f, T_VAR_Parameters *p);
|
||||
void PrintMHM(FILE *f, char *filename, TStateModel *model, T_MHM *mhm);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __MODIFIED_HARMONIC_MEAN_
|
||||
#define __MODIFIED_HARMONIC_MEAN_
|
||||
|
||||
#include "swzmatrix.h"
|
||||
#include "switch.h"
|
||||
#include "VARbase.h"
|
||||
|
||||
typedef struct
|
||||
{
|
||||
// Sample sizes to use in computations
|
||||
int n_burn1; // set to negative of actual value if first burn-in has been completed
|
||||
int n_burn2; // set to negative of actual value if second burn-in has been completed
|
||||
int n_mean_variance; // set to negative of actual value if mean and variance have been computed
|
||||
int n_mhm; // number of draws for computing the modified harmonic mean
|
||||
int n_thin; // thinning factor
|
||||
|
||||
// Accumulation fields
|
||||
int N; // Total number observations
|
||||
|
||||
PRECISION old_log_posterior;
|
||||
PRECISION sum;
|
||||
PRECISION sum_square;
|
||||
PRECISION max_log_posterior;
|
||||
PRECISION max_log_likelihood;
|
||||
|
||||
// mhm info
|
||||
TVector mean; // Gaussian mean
|
||||
TMatrix variance; // Gaussian variance
|
||||
TMatrix inverse_variance; // Inverse of Gaussian variance
|
||||
TVector center; // Used to center gaussian. Must be equal to posterior_mode_VAR or mean.
|
||||
|
||||
TVector alpha_scales; // scaling values for base dirichlet pdf parameters
|
||||
TVector* BaseAlpha; // base dirichlet pdf parameters
|
||||
TVector** Alpha; // base dirichlet pdf parameters times the scale factors
|
||||
|
||||
// Model info
|
||||
TStateModel *model;
|
||||
TVector posterior_mode_VAR;
|
||||
PRECISION log_likelihood_at_mode;
|
||||
PRECISION log_posterior_at_mode;
|
||||
PRECISION log_prior_at_mode;
|
||||
|
||||
// Workspace
|
||||
TVector free_parameters_VAR; // workspace for free parameters for VAR
|
||||
|
||||
// Workspace for states
|
||||
int *states;
|
||||
|
||||
// Files
|
||||
FILE *f_out;
|
||||
FILE *f_out_regime_counts;
|
||||
char *regime_counts_filename;
|
||||
char *intermediate_output_filename;
|
||||
char *final_output_filename;
|
||||
char *intermediate_draws_output_filename;
|
||||
char *draws_output_filename;
|
||||
char *spec_filename;
|
||||
char *parameter_filename;
|
||||
char *parameter_header;
|
||||
char *mhm_filename;
|
||||
|
||||
} T_MHM;
|
||||
|
||||
// Constructors
|
||||
void FreeMHM(T_MHM *mhm);
|
||||
T_MHM* CreateMHM(void);
|
||||
T_MHM* AddDirichletScales(TVector alpha_scales, T_MHM *mhm);
|
||||
T_MHM* AddStateModel(TStateModel *model, T_MHM *mhm);
|
||||
|
||||
void ResetMHM(T_MHM *mhm);
|
||||
void BurnIn(T_MHM *mhm, int iterations, int period);
|
||||
void BurnIn_AdaptiveMetropolisScale(T_MHM *mhm, int iterations, int period);
|
||||
void ComputeMeanVariance_MHM(T_MHM *mhm, int iterations, int period);
|
||||
int IsValidZeta(PRECISION* zeta, int n, PRECISION* gamma_cuts);
|
||||
PRECISION UpdatePosteriorLikelihood(T_MHM *mhm);
|
||||
void UpdateModifiedHarmonicMean(T_MHM *mhm, int n_singular);
|
||||
void ComputeModifiedHarmonicMean(T_MHM *mhm, int period);
|
||||
|
||||
void WriteMHM_Input(FILE *f_out, T_MHM *mhm);
|
||||
T_MHM* ReadMHM_Input(FILE *f_in, char *filename, T_MHM *mhm);
|
||||
void WriteMeanVariance(FILE *f_out, T_MHM *mhm);
|
||||
int ReadMeanVariance(FILE *f_in, T_MHM *mhm);
|
||||
|
||||
void PrintJumps(FILE *f, T_VAR_Parameters *p);
|
||||
void PrintMHM(FILE *f, char *filename, TStateModel *model, T_MHM *mhm);
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,205 +1,205 @@
|
|||
|
||||
#ifndef __TARRAY__
|
||||
#define __TARRAY__
|
||||
|
||||
/******************************** C-style arrays ********************************
|
||||
|
||||
Attempts to implement a C++ class template for multidimensional arrays. The goal
|
||||
is to allow access through the bracket operator (a[i_1][i_2]...[i_n]) but provide
|
||||
mechanisms for creating, destroying, and determining the dimensions of the array.
|
||||
|
||||
In this implementation, an array is a pointer to void. The exact behavior of the
|
||||
implementation is determined by structure TElementSpecification. This, together
|
||||
with the dimension of the array are stored before the first element of the array.
|
||||
The dimension of the array can be obtained with the macro dw_DimA().
|
||||
|
||||
Additionally, mechanisms are provided for copying, initializing, printing, and
|
||||
writing arrays. If the array uses non-standard mechanisms for creating or
|
||||
destroying its elements, the functions dw_CopyArray() and dw_InitializeArray()
|
||||
should not be used.
|
||||
|
||||
=================================================================================
|
||||
Specification of functions avaiable to arrays
|
||||
|
||||
Destructor
|
||||
void Destructor(void*)
|
||||
The destructor is called to destroy each element of the array. It is assumed
|
||||
that each element of the array is in a valid state. If the flag bit
|
||||
dw_ARRAY_POINTER set, the calling syntax from an array is
|
||||
|
||||
Destructor(((void**)a)[i])
|
||||
|
||||
and the destructor should free the passed pointer if it is not null.
|
||||
Otherwise the calling syntax is
|
||||
|
||||
Destructor((void*)(((char*)a) + i*size))
|
||||
|
||||
and the destructor must not free the passed pointer.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Default Constructor
|
||||
void DefaultConstructor(void *)
|
||||
The default constructor is called to initialize each element of the array.
|
||||
The default constructor must not fail in the since that after a call to the
|
||||
default constructor, the element is in a valid state. The calling syntax is
|
||||
|
||||
DefaultConstructor((void*)(((char*)a) + i*size))
|
||||
|
||||
Note that calling syntax is the same for static and pointer arrays. This
|
||||
allows memory to be allocated to pointers.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Pointer Copy Constructor
|
||||
void* PointerCopyConstructor(void*, void*)
|
||||
The pointer copy constructor is called when coping or initializing elements.
|
||||
The calling syntax is
|
||||
|
||||
CopyConstructor(((void**)d)[i],((void**)s)[i])
|
||||
|
||||
The pointer copy constructor returns a pointer to the destination. If the
|
||||
destination was null, an attempt to create it can be made, and if successful
|
||||
a pointer to the newly allocated destination is returned. Upon failure, a
|
||||
null pointer is returned. In the event of failure, the pointer copy
|
||||
constructor should leave the contents of the destination in a valid state.
|
||||
It is assumed that source is in a valid state.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Static Copy Constructor
|
||||
int StaticCopyConstructor(void*, void*)
|
||||
The static copy constructor is called when coping or initializing elements.
|
||||
The calling syntax is
|
||||
|
||||
CopyConstructor((void*)(((char*)d) + i*size),(void*)(((char*)s) + i*size)
|
||||
|
||||
The static copy constrctor should return one upon success and zero upon
|
||||
failure. In the event of failure, the static copy constructor should leave
|
||||
the contents of the destination in a state such that a call to the destructor
|
||||
will behave as expected. The source is assume to be properly initialized.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
Print Routine
|
||||
int Print(FILE*, void*, char*)
|
||||
The print routine prints an element to the file f using the formating
|
||||
information in the character string. If the flag bit dw_ARRAY_POINTER is
|
||||
set, the calling syntax is
|
||||
|
||||
Print(f,((void**)a)[i],format)
|
||||
|
||||
and otherwise is
|
||||
|
||||
Print(f,(void*)(((char*)a) + i*size),format)
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Read Routine
|
||||
int Read(FILE*, void*)
|
||||
The read routine reads an element from the file f. If the flag bit
|
||||
dw_ARRAY_POINTER is set, the calling syntax is
|
||||
|
||||
Read(f,((void**)a)[i])
|
||||
|
||||
and otherwise is
|
||||
|
||||
Read(f,(void*)(((char*)a) + i*size))
|
||||
|
||||
********************************************************************************/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
//=========================== TElementSpecification ===========================//
|
||||
#define dw_ARRAY_USE_MEMCPY 0x00000001
|
||||
#define dw_ARRAY_POINTER 0x00000002
|
||||
#define dw_ARRAY_ARRAY 0x00000004
|
||||
#define dw_ARRAY_DELETE_SPECS 0x00000008
|
||||
|
||||
typedef struct
|
||||
{
|
||||
int flag;
|
||||
|
||||
int size;
|
||||
int offset;
|
||||
|
||||
void (*destructor)(void*);
|
||||
void (*default_constructor)(void *);
|
||||
void* (*pointer_copy_constructor)(void*, void*);
|
||||
int (*static_copy_constructor)(void*, void*);
|
||||
int (*print_routine)(FILE*, void*, char*);
|
||||
int (*read_routine)(FILE*, void*);
|
||||
|
||||
} TElementSpecification;
|
||||
|
||||
TElementSpecification* CreateArraySpecification_pointer(void (*destructor)(void *));
|
||||
|
||||
extern TElementSpecification dw_IntSpecs;
|
||||
extern TElementSpecification dw_DoubleSpecs;
|
||||
extern TElementSpecification dw_FloatSpecs;
|
||||
extern TElementSpecification dw_CharSpecs;
|
||||
extern TElementSpecification dw_StringSpecs;
|
||||
extern TElementSpecification dw_ArraySpecs;
|
||||
extern TElementSpecification dw_PointerSpecs;
|
||||
//=============================================================================//
|
||||
|
||||
//=== Macros ===
|
||||
#define dw_DimA(a) (((int*)(a))[-1])
|
||||
#define dw_SpecsA(a) (*((TElementSpecification**)(((char*)(a))-(sizeof(TElementSpecification*)+sizeof(int)))))
|
||||
#define dw_IsArrayA(a) (dw_SpecsA(a)->flag & dw_ARRAY_ARRAY)
|
||||
|
||||
//=== Destructor ===//
|
||||
void dw_FreeArray(void* a);
|
||||
|
||||
//=== Constructors ===//
|
||||
void* dw_CreateArray(TElementSpecification *specs, int dim);
|
||||
void* dw_CreateMultidimensionalArray(TElementSpecification *specs, int depth, int *dim);
|
||||
void* dw_CreateMultidimensionalArrayList(TElementSpecification *specs, int depth, ...);
|
||||
|
||||
//=== Routines ===//
|
||||
void* dw_CopyArray(void* d, void* s);
|
||||
int dw_PrintArray(FILE* f, void* a, char* format);
|
||||
int dw_ReadArray(FILE* f, void* a);
|
||||
|
||||
// Array arrays
|
||||
#define dw_CreateArray_array(dim) dw_CreateArray(&dw_ArraySpecs,dim)
|
||||
|
||||
// Pointer arrays
|
||||
#define dw_CreateArray_pointer(dim,destructor) dw_CreateArray(CreateArraySpecification_pointer(destructor),dim)
|
||||
void DefaultPointerConstructor(void*);
|
||||
|
||||
// String arrays
|
||||
#define dw_CreateArray_string(dim) (char**)dw_CreateArray(&dw_StringSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_string(depth,dim) dw_CreateMultidimensionalArray(&dw_StringSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_string(int depth, ...);
|
||||
#define dw_CreateRectangularArray_string(row,col) (char***)dw_CreateMultidimensionalArrayList_string(2,row,col)
|
||||
#define dw_InitializeArray_string(a,x) dw_InitializeArray(a,x)
|
||||
|
||||
// Integer arrays
|
||||
#define dw_CreateArray_int(dim) (int*)dw_CreateArray(&dw_IntSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_int(depth,dim) dw_CreateMultidimensionalArray(&dw_IntSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_int(int depth, ...);
|
||||
#define dw_CreateRectangularArray_int(row,col) (int**)dw_CreateMultidimensionalArrayList_int(2,row,col)
|
||||
int dw_InitializeArray_int(void *a, int x);
|
||||
|
||||
// Double arrays
|
||||
#define dw_CreateArray_double(dim) (double*)dw_CreateArray(&dw_DoubleSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_double(depth,dim) dw_CreateMultidimensionalArray(&dw_DoubleSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_double(int depth, ...);
|
||||
#define dw_CreateRectangularArray_double(row,col) (double**)dw_CreateMultidimensionalArrayList_double(2,row,col)
|
||||
int dw_InitializeArray_double(void *a, double x);
|
||||
|
||||
// Float arrays
|
||||
#define dw_CreateArray_float(dim) (float*)dw_CreateArray(&dw_FloatSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_float(depth,dim) dw_CreateMultidimensionalArray(&dw_FloatSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_float(int depth, ...);
|
||||
#define dw_CreateRectangularArray_float(row,col) (float**)dw_CreateMultidimensionalArrayList_float(2,row,col)
|
||||
int dw_InitializeArray_float(void *a, float x);
|
||||
|
||||
// Character arrays
|
||||
#define dw_CreateArray_char(dim) (float*)dw_CreateArray(&dw_CharSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_char(depth,dim) dw_CreateMultidimensionalArray(&dw_CharSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_char(int depth, ...);
|
||||
#define dw_CreateRectangularArray_char(row,col) (char**)dw_CreateMultidimensionalArrayList_char(2,row,col)
|
||||
int dw_InitializeArray_char(void *a, char x);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __TARRAY__
|
||||
#define __TARRAY__
|
||||
|
||||
/******************************** C-style arrays ********************************
|
||||
|
||||
Attempts to implement a C++ class template for multidimensional arrays. The goal
|
||||
is to allow access through the bracket operator (a[i_1][i_2]...[i_n]) but provide
|
||||
mechanisms for creating, destroying, and determining the dimensions of the array.
|
||||
|
||||
In this implementation, an array is a pointer to void. The exact behavior of the
|
||||
implementation is determined by structure TElementSpecification. This, together
|
||||
with the dimension of the array are stored before the first element of the array.
|
||||
The dimension of the array can be obtained with the macro dw_DimA().
|
||||
|
||||
Additionally, mechanisms are provided for copying, initializing, printing, and
|
||||
writing arrays. If the array uses non-standard mechanisms for creating or
|
||||
destroying its elements, the functions dw_CopyArray() and dw_InitializeArray()
|
||||
should not be used.
|
||||
|
||||
=================================================================================
|
||||
Specification of functions avaiable to arrays
|
||||
|
||||
Destructor
|
||||
void Destructor(void*)
|
||||
The destructor is called to destroy each element of the array. It is assumed
|
||||
that each element of the array is in a valid state. If the flag bit
|
||||
dw_ARRAY_POINTER set, the calling syntax from an array is
|
||||
|
||||
Destructor(((void**)a)[i])
|
||||
|
||||
and the destructor should free the passed pointer if it is not null.
|
||||
Otherwise the calling syntax is
|
||||
|
||||
Destructor((void*)(((char*)a) + i*size))
|
||||
|
||||
and the destructor must not free the passed pointer.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Default Constructor
|
||||
void DefaultConstructor(void *)
|
||||
The default constructor is called to initialize each element of the array.
|
||||
The default constructor must not fail in the since that after a call to the
|
||||
default constructor, the element is in a valid state. The calling syntax is
|
||||
|
||||
DefaultConstructor((void*)(((char*)a) + i*size))
|
||||
|
||||
Note that calling syntax is the same for static and pointer arrays. This
|
||||
allows memory to be allocated to pointers.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Pointer Copy Constructor
|
||||
void* PointerCopyConstructor(void*, void*)
|
||||
The pointer copy constructor is called when coping or initializing elements.
|
||||
The calling syntax is
|
||||
|
||||
CopyConstructor(((void**)d)[i],((void**)s)[i])
|
||||
|
||||
The pointer copy constructor returns a pointer to the destination. If the
|
||||
destination was null, an attempt to create it can be made, and if successful
|
||||
a pointer to the newly allocated destination is returned. Upon failure, a
|
||||
null pointer is returned. In the event of failure, the pointer copy
|
||||
constructor should leave the contents of the destination in a valid state.
|
||||
It is assumed that source is in a valid state.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Static Copy Constructor
|
||||
int StaticCopyConstructor(void*, void*)
|
||||
The static copy constructor is called when coping or initializing elements.
|
||||
The calling syntax is
|
||||
|
||||
CopyConstructor((void*)(((char*)d) + i*size),(void*)(((char*)s) + i*size)
|
||||
|
||||
The static copy constrctor should return one upon success and zero upon
|
||||
failure. In the event of failure, the static copy constructor should leave
|
||||
the contents of the destination in a state such that a call to the destructor
|
||||
will behave as expected. The source is assume to be properly initialized.
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
Print Routine
|
||||
int Print(FILE*, void*, char*)
|
||||
The print routine prints an element to the file f using the formating
|
||||
information in the character string. If the flag bit dw_ARRAY_POINTER is
|
||||
set, the calling syntax is
|
||||
|
||||
Print(f,((void**)a)[i],format)
|
||||
|
||||
and otherwise is
|
||||
|
||||
Print(f,(void*)(((char*)a) + i*size),format)
|
||||
|
||||
---------------------------------------------------------------------------------
|
||||
|
||||
Read Routine
|
||||
int Read(FILE*, void*)
|
||||
The read routine reads an element from the file f. If the flag bit
|
||||
dw_ARRAY_POINTER is set, the calling syntax is
|
||||
|
||||
Read(f,((void**)a)[i])
|
||||
|
||||
and otherwise is
|
||||
|
||||
Read(f,(void*)(((char*)a) + i*size))
|
||||
|
||||
********************************************************************************/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
//=========================== TElementSpecification ===========================//
|
||||
#define dw_ARRAY_USE_MEMCPY 0x00000001
|
||||
#define dw_ARRAY_POINTER 0x00000002
|
||||
#define dw_ARRAY_ARRAY 0x00000004
|
||||
#define dw_ARRAY_DELETE_SPECS 0x00000008
|
||||
|
||||
typedef struct
|
||||
{
|
||||
int flag;
|
||||
|
||||
int size;
|
||||
int offset;
|
||||
|
||||
void (*destructor)(void*);
|
||||
void (*default_constructor)(void *);
|
||||
void* (*pointer_copy_constructor)(void*, void*);
|
||||
int (*static_copy_constructor)(void*, void*);
|
||||
int (*print_routine)(FILE*, void*, char*);
|
||||
int (*read_routine)(FILE*, void*);
|
||||
|
||||
} TElementSpecification;
|
||||
|
||||
TElementSpecification* CreateArraySpecification_pointer(void (*destructor)(void *));
|
||||
|
||||
extern TElementSpecification dw_IntSpecs;
|
||||
extern TElementSpecification dw_DoubleSpecs;
|
||||
extern TElementSpecification dw_FloatSpecs;
|
||||
extern TElementSpecification dw_CharSpecs;
|
||||
extern TElementSpecification dw_StringSpecs;
|
||||
extern TElementSpecification dw_ArraySpecs;
|
||||
extern TElementSpecification dw_PointerSpecs;
|
||||
//=============================================================================//
|
||||
|
||||
//=== Macros ===
|
||||
#define dw_DimA(a) (((int*)(a))[-1])
|
||||
#define dw_SpecsA(a) (*((TElementSpecification**)(((char*)(a))-(sizeof(TElementSpecification*)+sizeof(int)))))
|
||||
#define dw_IsArrayA(a) (dw_SpecsA(a)->flag & dw_ARRAY_ARRAY)
|
||||
|
||||
//=== Destructor ===//
|
||||
void dw_FreeArray(void* a);
|
||||
|
||||
//=== Constructors ===//
|
||||
void* dw_CreateArray(TElementSpecification *specs, int dim);
|
||||
void* dw_CreateMultidimensionalArray(TElementSpecification *specs, int depth, int *dim);
|
||||
void* dw_CreateMultidimensionalArrayList(TElementSpecification *specs, int depth, ...);
|
||||
|
||||
//=== Routines ===//
|
||||
void* dw_CopyArray(void* d, void* s);
|
||||
int dw_PrintArray(FILE* f, void* a, char* format);
|
||||
int dw_ReadArray(FILE* f, void* a);
|
||||
|
||||
// Array arrays
|
||||
#define dw_CreateArray_array(dim) dw_CreateArray(&dw_ArraySpecs,dim)
|
||||
|
||||
// Pointer arrays
|
||||
#define dw_CreateArray_pointer(dim,destructor) dw_CreateArray(CreateArraySpecification_pointer(destructor),dim)
|
||||
void DefaultPointerConstructor(void*);
|
||||
|
||||
// String arrays
|
||||
#define dw_CreateArray_string(dim) (char**)dw_CreateArray(&dw_StringSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_string(depth,dim) dw_CreateMultidimensionalArray(&dw_StringSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_string(int depth, ...);
|
||||
#define dw_CreateRectangularArray_string(row,col) (char***)dw_CreateMultidimensionalArrayList_string(2,row,col)
|
||||
#define dw_InitializeArray_string(a,x) dw_InitializeArray(a,x)
|
||||
|
||||
// Integer arrays
|
||||
#define dw_CreateArray_int(dim) (int*)dw_CreateArray(&dw_IntSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_int(depth,dim) dw_CreateMultidimensionalArray(&dw_IntSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_int(int depth, ...);
|
||||
#define dw_CreateRectangularArray_int(row,col) (int**)dw_CreateMultidimensionalArrayList_int(2,row,col)
|
||||
int dw_InitializeArray_int(void *a, int x);
|
||||
|
||||
// Double arrays
|
||||
#define dw_CreateArray_double(dim) (double*)dw_CreateArray(&dw_DoubleSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_double(depth,dim) dw_CreateMultidimensionalArray(&dw_DoubleSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_double(int depth, ...);
|
||||
#define dw_CreateRectangularArray_double(row,col) (double**)dw_CreateMultidimensionalArrayList_double(2,row,col)
|
||||
int dw_InitializeArray_double(void *a, double x);
|
||||
|
||||
// Float arrays
|
||||
#define dw_CreateArray_float(dim) (float*)dw_CreateArray(&dw_FloatSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_float(depth,dim) dw_CreateMultidimensionalArray(&dw_FloatSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_float(int depth, ...);
|
||||
#define dw_CreateRectangularArray_float(row,col) (float**)dw_CreateMultidimensionalArrayList_float(2,row,col)
|
||||
int dw_InitializeArray_float(void *a, float x);
|
||||
|
||||
// Character arrays
|
||||
#define dw_CreateArray_char(dim) (float*)dw_CreateArray(&dw_CharSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_char(depth,dim) dw_CreateMultidimensionalArray(&dw_CharSpecs,depth,dim)
|
||||
void* dw_CreateMultidimensionalArrayList_char(int depth, ...);
|
||||
#define dw_CreateRectangularArray_char(row,col) (char**)dw_CreateMultidimensionalArrayList_char(2,row,col)
|
||||
int dw_InitializeArray_char(void *a, char x);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,253 +1,253 @@
|
|||
|
||||
#include "dw_matrix_array.h"
|
||||
#include "dw_error.h"
|
||||
#include "bmatrix.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
TElementSpecification dw_VectorSpecs =
|
||||
{
|
||||
dw_ARRAY_POINTER,
|
||||
sizeof(TVector),
|
||||
sizeof(int)+sizeof(TElementSpecification*),
|
||||
(void (*)(void*))FreeVector,
|
||||
DefaultPointerConstructor,
|
||||
(void* (*)(void*,void*))EquateVector,
|
||||
NULL,
|
||||
(int (*)(FILE*,void*,char*))dw_PrintVector,
|
||||
(int (*)(FILE*,void*))dw_ReadVector
|
||||
};
|
||||
|
||||
TElementSpecification dw_MatrixSpecs =
|
||||
{
|
||||
dw_ARRAY_POINTER,
|
||||
sizeof(TMatrix),
|
||||
sizeof(int)+sizeof(TElementSpecification*),
|
||||
(void (*)(void*))FreeMatrix,
|
||||
DefaultPointerConstructor,
|
||||
(void* (*)(void*,void*))EquateMatrix,
|
||||
NULL,
|
||||
(int (*)(FILE*,void*,char*))dw_PrintMatrix,
|
||||
(int (*)(FILE*,void*))dw_ReadMatrix
|
||||
};
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************* Initializaton ********************************/
|
||||
/******************************************************************************/
|
||||
void* dw_InitializeArray_vector(void* x, PRECISION y)
|
||||
{
|
||||
int i;
|
||||
if (!x)
|
||||
dw_Error(NULL_ERR);
|
||||
else
|
||||
if (dw_IsArrayA(x))
|
||||
for (i=dw_DimA(x)-1; i >= 0; i--) dw_InitializeArray_vector(((void**)x)[i],y);
|
||||
else
|
||||
for (i=dw_DimA(x)-1; i >= 0; i--) InitializeVector(((void**)x)[i],y);
|
||||
return x;
|
||||
}
|
||||
|
||||
void* dw_InitializeArray_matrix(void* X, PRECISION y)
|
||||
{
|
||||
int i;
|
||||
if (!X)
|
||||
dw_Error(NULL_ERR);
|
||||
else
|
||||
if (dw_IsArrayA(X))
|
||||
for (i=dw_DimA(X)-1; i >= 0; i--) dw_InitializeArray_matrix(((void**)X)[i],y);
|
||||
else
|
||||
for (i=dw_DimA(X)-1; i >= 0; i--) InitializeMatrix(((void**)X)[i],y);
|
||||
return X;
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
/****************************** Tensor Calculus *******************************/
|
||||
/******************************************************************************/
|
||||
/*
|
||||
Assumes:
|
||||
X - r x s matrix or null pointer
|
||||
Y - k dimensional array of matrices
|
||||
|
||||
Returns:
|
||||
The the tensor product
|
||||
|
||||
Y[0] x Y[1] x ... x Y[k-1]
|
||||
|
||||
If X is null, then space for the tensor product is allocated. If X is not
|
||||
null, then the dimensions must match.
|
||||
|
||||
r=RowM(Y[0]) x ... x RowM(Y[k-1])
|
||||
c=ColM(Y[0]) x ... x ColM(Y[k-1])
|
||||
|
||||
Notes:
|
||||
Calls bMatrixTensor().
|
||||
*/
|
||||
TMatrix MatrixTensor(TMatrix X, TMatrix* Y)
|
||||
{
|
||||
int i, r=1, c=1;
|
||||
PRECISION *Z, *U, *V, *W;
|
||||
TMatrix rtrn;
|
||||
if (!Y)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
for (i=dw_DimA(Y)-1; i >= 0; i--)
|
||||
if (!Y[i])
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
r*=RowM(Y[i]);
|
||||
c*=ColM(Y[i]);
|
||||
}
|
||||
if (!X)
|
||||
{
|
||||
if (!(rtrn=CreateMatrix(r,c)))
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
if ((r != RowM(X)) || (c != ColM(X)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
rtrn=X;
|
||||
if (dw_DimA(Y) > 2)
|
||||
{
|
||||
if (!(Z=(PRECISION*)malloc(r*c*sizeof(PRECISION))))
|
||||
{
|
||||
if (!X) FreeMatrix(rtrn);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (dw_DimA(Y) % 2)
|
||||
{
|
||||
U=Z;
|
||||
V=pElementM(rtrn);
|
||||
}
|
||||
else
|
||||
{
|
||||
U=pElementM(rtrn);
|
||||
V=Z;
|
||||
}
|
||||
i=dw_DimA(Y)-2;
|
||||
bMatrixTensor(U,pElementM(Y[i]),pElementM(Y[i+1]),RowM(Y[i]),ColM(Y[i]),RowM(Y[i+1]),
|
||||
ColM(Y[i+1]),MajorForm(rtrn),MajorForm(Y[i]),MajorForm(Y[i+1]));
|
||||
r=RowM(Y[i])*RowM(Y[i+1]);
|
||||
c=ColM(Y[i])*ColM(Y[i+1]);
|
||||
while (--i >= 0)
|
||||
{
|
||||
bMatrixTensor(V,pElementM(Y[i]),U,RowM(Y[i]),ColM(Y[i]),r,c,MajorForm(rtrn),MajorForm(Y[i]),MajorForm(rtrn));
|
||||
r*=RowM(Y[i]);
|
||||
c*=ColM(Y[i]);
|
||||
W=U;
|
||||
U=V;
|
||||
V=W;
|
||||
}
|
||||
free(Z);
|
||||
}
|
||||
else
|
||||
if (dw_DimA(Y) > 1)
|
||||
bMatrixTensor(pElementM(rtrn),pElementM(Y[0]),pElementM(Y[1]),RowM(Y[0]),ColM(Y[0]),RowM(Y[1]),
|
||||
ColM(Y[1]),MajorForm(rtrn),MajorForm(Y[0]),MajorForm(Y[1]));
|
||||
else
|
||||
EquateMatrix(rtrn,Y[0]);
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
X - d dimensional vector or null pointer
|
||||
Y - k dimensional array of vectors
|
||||
|
||||
Returns:
|
||||
The the tensor product
|
||||
|
||||
y[0] x y[1] x ... x y[k-1]
|
||||
|
||||
If x is null, then space for the tensor product is allocated. If x is not
|
||||
null, then the dimensions must match.
|
||||
|
||||
d=DimV(Y[0]) x ... x DimV(Y[k-1])
|
||||
|
||||
Notes:
|
||||
Calls bVectorTensor().
|
||||
*/
|
||||
TVector VectorTensor(TVector x, TVector* y)
|
||||
{
|
||||
int i, d=1;
|
||||
PRECISION *z, *u, *v, *w;
|
||||
TVector rtrn;
|
||||
if (!y)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
for (i=dw_DimA(y)-1; i >= 0; i--)
|
||||
if (!y[i])
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
d*=DimV(y[i]);
|
||||
if (!x)
|
||||
{
|
||||
if (!(rtrn=CreateVector(d)))
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
if (d != DimV(x))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
rtrn=x;
|
||||
if (dw_DimA(y) > 2)
|
||||
{
|
||||
if (!(z=(PRECISION*)malloc(d*sizeof(PRECISION))))
|
||||
{
|
||||
if (!x) FreeVector(rtrn);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
if (dw_DimA(y) % 2)
|
||||
{
|
||||
u=z;
|
||||
v=pElementV(rtrn);
|
||||
}
|
||||
else
|
||||
{
|
||||
u=pElementV(rtrn);
|
||||
v=z;
|
||||
}
|
||||
i=dw_DimA(y)-2;
|
||||
bVectorTensor(u,pElementV(y[i]),pElementV(y[i+1]),DimV(y[i]),DimV(y[i+1]));
|
||||
d=DimV(y[i])*DimV(y[i+1]);
|
||||
while (--i >= 0)
|
||||
{
|
||||
bVectorTensor(v,pElementV(y[i]),u,DimV(y[i]),d);
|
||||
d*=DimV(y[i]);
|
||||
w=u;
|
||||
u=v;
|
||||
v=w;
|
||||
}
|
||||
free(z);
|
||||
}
|
||||
else
|
||||
if (dw_DimA(y) > 1)
|
||||
bVectorTensor(pElementV(rtrn),pElementV(y[0]),pElementV(y[1]),DimV(y[0]),DimV(y[1]));
|
||||
else
|
||||
EquateVector(rtrn,y[0]);
|
||||
return rtrn;
|
||||
}
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
|
||||
|
||||
|
||||
#include "dw_matrix_array.h"
|
||||
#include "dw_error.h"
|
||||
#include "bmatrix.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
TElementSpecification dw_VectorSpecs =
|
||||
{
|
||||
dw_ARRAY_POINTER,
|
||||
sizeof(TVector),
|
||||
sizeof(int)+sizeof(TElementSpecification*),
|
||||
(void (*)(void*))FreeVector,
|
||||
DefaultPointerConstructor,
|
||||
(void* (*)(void*,void*))EquateVector,
|
||||
NULL,
|
||||
(int (*)(FILE*,void*,char*))dw_PrintVector,
|
||||
(int (*)(FILE*,void*))dw_ReadVector
|
||||
};
|
||||
|
||||
TElementSpecification dw_MatrixSpecs =
|
||||
{
|
||||
dw_ARRAY_POINTER,
|
||||
sizeof(TMatrix),
|
||||
sizeof(int)+sizeof(TElementSpecification*),
|
||||
(void (*)(void*))FreeMatrix,
|
||||
DefaultPointerConstructor,
|
||||
(void* (*)(void*,void*))EquateMatrix,
|
||||
NULL,
|
||||
(int (*)(FILE*,void*,char*))dw_PrintMatrix,
|
||||
(int (*)(FILE*,void*))dw_ReadMatrix
|
||||
};
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************* Initializaton ********************************/
|
||||
/******************************************************************************/
|
||||
void* dw_InitializeArray_vector(void* x, PRECISION y)
|
||||
{
|
||||
int i;
|
||||
if (!x)
|
||||
dw_Error(NULL_ERR);
|
||||
else
|
||||
if (dw_IsArrayA(x))
|
||||
for (i=dw_DimA(x)-1; i >= 0; i--) dw_InitializeArray_vector(((void**)x)[i],y);
|
||||
else
|
||||
for (i=dw_DimA(x)-1; i >= 0; i--) InitializeVector(((void**)x)[i],y);
|
||||
return x;
|
||||
}
|
||||
|
||||
void* dw_InitializeArray_matrix(void* X, PRECISION y)
|
||||
{
|
||||
int i;
|
||||
if (!X)
|
||||
dw_Error(NULL_ERR);
|
||||
else
|
||||
if (dw_IsArrayA(X))
|
||||
for (i=dw_DimA(X)-1; i >= 0; i--) dw_InitializeArray_matrix(((void**)X)[i],y);
|
||||
else
|
||||
for (i=dw_DimA(X)-1; i >= 0; i--) InitializeMatrix(((void**)X)[i],y);
|
||||
return X;
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
/****************************** Tensor Calculus *******************************/
|
||||
/******************************************************************************/
|
||||
/*
|
||||
Assumes:
|
||||
X - r x s matrix or null pointer
|
||||
Y - k dimensional array of matrices
|
||||
|
||||
Returns:
|
||||
The the tensor product
|
||||
|
||||
Y[0] x Y[1] x ... x Y[k-1]
|
||||
|
||||
If X is null, then space for the tensor product is allocated. If X is not
|
||||
null, then the dimensions must match.
|
||||
|
||||
r=RowM(Y[0]) x ... x RowM(Y[k-1])
|
||||
c=ColM(Y[0]) x ... x ColM(Y[k-1])
|
||||
|
||||
Notes:
|
||||
Calls bMatrixTensor().
|
||||
*/
|
||||
TMatrix MatrixTensor(TMatrix X, TMatrix* Y)
|
||||
{
|
||||
int i, r=1, c=1;
|
||||
PRECISION *Z, *U, *V, *W;
|
||||
TMatrix rtrn;
|
||||
if (!Y)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
for (i=dw_DimA(Y)-1; i >= 0; i--)
|
||||
if (!Y[i])
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
r*=RowM(Y[i]);
|
||||
c*=ColM(Y[i]);
|
||||
}
|
||||
if (!X)
|
||||
{
|
||||
if (!(rtrn=CreateMatrix(r,c)))
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
if ((r != RowM(X)) || (c != ColM(X)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
rtrn=X;
|
||||
if (dw_DimA(Y) > 2)
|
||||
{
|
||||
if (!(Z=(PRECISION*)malloc(r*c*sizeof(PRECISION))))
|
||||
{
|
||||
if (!X) FreeMatrix(rtrn);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (dw_DimA(Y) % 2)
|
||||
{
|
||||
U=Z;
|
||||
V=pElementM(rtrn);
|
||||
}
|
||||
else
|
||||
{
|
||||
U=pElementM(rtrn);
|
||||
V=Z;
|
||||
}
|
||||
i=dw_DimA(Y)-2;
|
||||
bMatrixTensor(U,pElementM(Y[i]),pElementM(Y[i+1]),RowM(Y[i]),ColM(Y[i]),RowM(Y[i+1]),
|
||||
ColM(Y[i+1]),MajorForm(rtrn),MajorForm(Y[i]),MajorForm(Y[i+1]));
|
||||
r=RowM(Y[i])*RowM(Y[i+1]);
|
||||
c=ColM(Y[i])*ColM(Y[i+1]);
|
||||
while (--i >= 0)
|
||||
{
|
||||
bMatrixTensor(V,pElementM(Y[i]),U,RowM(Y[i]),ColM(Y[i]),r,c,MajorForm(rtrn),MajorForm(Y[i]),MajorForm(rtrn));
|
||||
r*=RowM(Y[i]);
|
||||
c*=ColM(Y[i]);
|
||||
W=U;
|
||||
U=V;
|
||||
V=W;
|
||||
}
|
||||
free(Z);
|
||||
}
|
||||
else
|
||||
if (dw_DimA(Y) > 1)
|
||||
bMatrixTensor(pElementM(rtrn),pElementM(Y[0]),pElementM(Y[1]),RowM(Y[0]),ColM(Y[0]),RowM(Y[1]),
|
||||
ColM(Y[1]),MajorForm(rtrn),MajorForm(Y[0]),MajorForm(Y[1]));
|
||||
else
|
||||
EquateMatrix(rtrn,Y[0]);
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
X - d dimensional vector or null pointer
|
||||
Y - k dimensional array of vectors
|
||||
|
||||
Returns:
|
||||
The the tensor product
|
||||
|
||||
y[0] x y[1] x ... x y[k-1]
|
||||
|
||||
If x is null, then space for the tensor product is allocated. If x is not
|
||||
null, then the dimensions must match.
|
||||
|
||||
d=DimV(Y[0]) x ... x DimV(Y[k-1])
|
||||
|
||||
Notes:
|
||||
Calls bVectorTensor().
|
||||
*/
|
||||
TVector VectorTensor(TVector x, TVector* y)
|
||||
{
|
||||
int i, d=1;
|
||||
PRECISION *z, *u, *v, *w;
|
||||
TVector rtrn;
|
||||
if (!y)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
for (i=dw_DimA(y)-1; i >= 0; i--)
|
||||
if (!y[i])
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
d*=DimV(y[i]);
|
||||
if (!x)
|
||||
{
|
||||
if (!(rtrn=CreateVector(d)))
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
if (d != DimV(x))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
else
|
||||
rtrn=x;
|
||||
if (dw_DimA(y) > 2)
|
||||
{
|
||||
if (!(z=(PRECISION*)malloc(d*sizeof(PRECISION))))
|
||||
{
|
||||
if (!x) FreeVector(rtrn);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
if (dw_DimA(y) % 2)
|
||||
{
|
||||
u=z;
|
||||
v=pElementV(rtrn);
|
||||
}
|
||||
else
|
||||
{
|
||||
u=pElementV(rtrn);
|
||||
v=z;
|
||||
}
|
||||
i=dw_DimA(y)-2;
|
||||
bVectorTensor(u,pElementV(y[i]),pElementV(y[i+1]),DimV(y[i]),DimV(y[i+1]));
|
||||
d=DimV(y[i])*DimV(y[i+1]);
|
||||
while (--i >= 0)
|
||||
{
|
||||
bVectorTensor(v,pElementV(y[i]),u,DimV(y[i]),d);
|
||||
d*=DimV(y[i]);
|
||||
w=u;
|
||||
u=v;
|
||||
v=w;
|
||||
}
|
||||
free(z);
|
||||
}
|
||||
else
|
||||
if (dw_DimA(y) > 1)
|
||||
bVectorTensor(pElementV(rtrn),pElementV(y[0]),pElementV(y[1]),DimV(y[0]),DimV(y[1]));
|
||||
else
|
||||
EquateVector(rtrn,y[0]);
|
||||
return rtrn;
|
||||
}
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
|
||||
|
||||
|
|
|
@ -1,34 +1,34 @@
|
|||
|
||||
#ifndef __MATRIX_ARRAY__
|
||||
#define __MATRIX_ARRAY__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_array.h"
|
||||
|
||||
extern TElementSpecification dw_VectorSpecs;
|
||||
extern TElementSpecification dw_MatrixSpecs;
|
||||
|
||||
#define dw_CreateArray_vector(dim) (TVector*)dw_CreateArray(&dw_VectorSpecs,dim)
|
||||
void* dw_InitializeArray_vector(void* x, PRECISION y);
|
||||
#define dw_CreateArray_matrix(dim) (TMatrix*)dw_CreateArray(&dw_MatrixSpecs,dim)
|
||||
void* dw_InitializeArray_matrix(void* X, PRECISION y);
|
||||
|
||||
#if (PRECISION_SIZE == 8)
|
||||
#define dw_CreateArray_scalar(dim) (double*)dw_CreateArray(&dw_DoubleSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_scalar(depth,dim) dw_CreateMultidimensionalArray(&dw_DoubleSpecs,depth,dim)
|
||||
#define dw_CreateMultidimensionalArrayList_scalar dw_CreateMultidimensionalArrayList_double
|
||||
#define dw_CreateRectangularArray_scalar(row,col) (double**)dw_CreateMultidimensionalArrayList_double(2,row,col)
|
||||
#define dw_InitializeArray_scalar(a,x) dw_InitializeArray_double(a,x)
|
||||
#else
|
||||
#define dw_CreateArray_scalar(dim) (float*)dw_CreateArray(&dw_FloatSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_scalar(depth,dim) dw_CreateMultidimensionalArray(&dw_FloatSpecs,depth,dim)
|
||||
#define dw_CreateMultidimensionalArrayList_scalar dw_CreateMultidimensionalArrayList_float
|
||||
#define dw_CreateRectangularArray_scalar(row,col) (float**)dw_CreateMultidimensionalArrayList_float(2,row,col)
|
||||
#define dw_InitializeArray_scalar(a,x) dw_InitializeArray_float(a,x)
|
||||
#endif
|
||||
|
||||
/* Tensor Calculus */
|
||||
TMatrix MatrixTensor(TMatrix X, TMatrix* Y);
|
||||
TVector VectorTensor(TVector x, TVector* y);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __MATRIX_ARRAY__
|
||||
#define __MATRIX_ARRAY__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
#include "dw_array.h"
|
||||
|
||||
extern TElementSpecification dw_VectorSpecs;
|
||||
extern TElementSpecification dw_MatrixSpecs;
|
||||
|
||||
#define dw_CreateArray_vector(dim) (TVector*)dw_CreateArray(&dw_VectorSpecs,dim)
|
||||
void* dw_InitializeArray_vector(void* x, PRECISION y);
|
||||
#define dw_CreateArray_matrix(dim) (TMatrix*)dw_CreateArray(&dw_MatrixSpecs,dim)
|
||||
void* dw_InitializeArray_matrix(void* X, PRECISION y);
|
||||
|
||||
#if (PRECISION_SIZE == 8)
|
||||
#define dw_CreateArray_scalar(dim) (double*)dw_CreateArray(&dw_DoubleSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_scalar(depth,dim) dw_CreateMultidimensionalArray(&dw_DoubleSpecs,depth,dim)
|
||||
#define dw_CreateMultidimensionalArrayList_scalar dw_CreateMultidimensionalArrayList_double
|
||||
#define dw_CreateRectangularArray_scalar(row,col) (double**)dw_CreateMultidimensionalArrayList_double(2,row,col)
|
||||
#define dw_InitializeArray_scalar(a,x) dw_InitializeArray_double(a,x)
|
||||
#else
|
||||
#define dw_CreateArray_scalar(dim) (float*)dw_CreateArray(&dw_FloatSpecs,dim)
|
||||
#define dw_CreateMultidimensionalArray_scalar(depth,dim) dw_CreateMultidimensionalArray(&dw_FloatSpecs,depth,dim)
|
||||
#define dw_CreateMultidimensionalArrayList_scalar dw_CreateMultidimensionalArrayList_float
|
||||
#define dw_CreateRectangularArray_scalar(row,col) (float**)dw_CreateMultidimensionalArrayList_float(2,row,col)
|
||||
#define dw_InitializeArray_scalar(a,x) dw_InitializeArray_float(a,x)
|
||||
#endif
|
||||
|
||||
/* Tensor Calculus */
|
||||
TMatrix MatrixTensor(TMatrix X, TMatrix* Y);
|
||||
TVector VectorTensor(TVector x, TVector* y);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,448 +1,448 @@
|
|||
|
||||
#include "dw_ascii.h"
|
||||
#include "dw_array.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/*
|
||||
Attempts to open filename for reading. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. The file must exist.
|
||||
*/
|
||||
FILE *dw_OpenTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"rt");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Attempts to create filename for writing. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. If the file exists, it is
|
||||
overwritten.
|
||||
*/
|
||||
FILE *dw_CreateTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"wt");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Attempts to create filename for writing. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. The file is created if it
|
||||
does not exist and is opened with the file pointer positioned at the end of
|
||||
file if it does exist.
|
||||
*/
|
||||
FILE *dw_AppendTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"at");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
f : valid file pointer
|
||||
buffer : pointer to character or null pointer
|
||||
n : pointer to integer containing the length of buffer
|
||||
|
||||
Returns:
|
||||
Pointer to null terminated string containing the characters from the file up
|
||||
to and including the terminating new line character. A null pointer return
|
||||
indicates that there was a memory error or no characters to be read. Call
|
||||
dw_GetError() to determine if a error occured.
|
||||
|
||||
Results:
|
||||
Reads line, beginning at current position from file f Returns a pointer to
|
||||
the buffer containing the file and resets *n if necessary. The if the
|
||||
passed buffer is null or is not large enough to contain the line, buffer is
|
||||
freed and a new buffer is allocated. Because of this, the passed buffer
|
||||
must either null or allocated with malloc(), realloc(), or calloc() and the
|
||||
calling routine is responsible for eventually freeing the memory if the
|
||||
return value is not null.
|
||||
|
||||
Notes:
|
||||
If buffer is null, then value pointed to by the pointer n is not used.
|
||||
*/
|
||||
#define SIZE_INCREMENT 1024
|
||||
char* dw_ReadLine(FILE *f, char *buffer, int *n)
|
||||
{
|
||||
char *ptr, *nbuffer;
|
||||
int i, k=0;
|
||||
if (!buffer && !(buffer=(char*)malloc(*n=SIZE_INCREMENT)))
|
||||
{
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
ptr=buffer;
|
||||
while (fgets(ptr,*n-k,f))
|
||||
if (ptr[(i=(int)strlen(ptr))-1] == '\n')
|
||||
return buffer;
|
||||
else
|
||||
if (!(nbuffer=(char*)realloc(buffer,*n+=SIZE_INCREMENT)))
|
||||
{
|
||||
free(buffer);
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
else
|
||||
ptr=(buffer=nbuffer) + (k+=i);
|
||||
if (ptr != buffer)
|
||||
return buffer;
|
||||
else
|
||||
{
|
||||
free(buffer);
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
}
|
||||
#undef SIZE_INCREMENT
|
||||
|
||||
|
||||
char** dw_ParseDelimitedString(char *buffer, char delimiter, int flag)
|
||||
{
|
||||
struct StringList
|
||||
{
|
||||
struct StringList *next;
|
||||
char *string;
|
||||
int length;
|
||||
} *head, *ptr;
|
||||
int k=0, n, m;
|
||||
char **v;
|
||||
if (!buffer) return (char**)NULL;
|
||||
for (head=ptr=(struct StringList*)NULL; *buffer; buffer+=buffer[n] ? n+1 : n)
|
||||
{
|
||||
if (flag & STRIP_LEADING_WHITESPACE)
|
||||
while (*buffer && (*buffer != delimiter) && isspace(*buffer)) buffer++;
|
||||
for (n=0; buffer[n] && (buffer[n] != delimiter); n++);
|
||||
if (flag & STRIP_TRAILING_WHITESPACE)
|
||||
for (m=n-1; (m >= 0) && isspace(buffer[m]); m--);
|
||||
else
|
||||
m=n-1;
|
||||
if ((m >= 0) || !(flag & REMOVE_EMPTY_FIELDS))
|
||||
{
|
||||
ptr=(struct StringList*)malloc(sizeof(struct StringList));
|
||||
ptr->string=buffer;
|
||||
ptr->length=m+1;
|
||||
ptr->next=head;
|
||||
head=ptr;
|
||||
k++;
|
||||
}
|
||||
}
|
||||
v=dw_CreateArray_string(k);
|
||||
while (--k >= 0)
|
||||
{
|
||||
v[k]=(char*)malloc(head->length+1);
|
||||
if (head->length > 0) memcpy(v[k],head->string,head->length);
|
||||
v[k][head->length]='\0';
|
||||
ptr=head;
|
||||
head=head->next;
|
||||
free(ptr);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
f: valid file pointer
|
||||
delimiter: field deliniter.
|
||||
flag: one of the values defined in dw_ascii.h
|
||||
|
||||
Returns
|
||||
One-dimensional string array of the delimited fields of the current line of
|
||||
the file f or a null pointer.
|
||||
|
||||
Notes
|
||||
The file is read starting from the current file position. If the file
|
||||
contains no fields or there is a memory error, then a null pointer is
|
||||
returned. The delimiter character defines the fields in each row and the
|
||||
new line character defines the rows.
|
||||
*/
|
||||
char** dw_ReadDelimitedLine(FILE *f, char delimiter, int flag)
|
||||
{
|
||||
int n=0;
|
||||
char **v=(char**)NULL, *buffer=dw_ReadLine(f,(char*)NULL,&n);
|
||||
if (buffer)
|
||||
{
|
||||
v=dw_ParseDelimitedString(buffer,delimiter,flag);
|
||||
free(buffer);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
f: valid file pointer or null pointer.
|
||||
filename: pointer to null terminated string or null pointer.
|
||||
delimiter: field deliniter.
|
||||
flag: one of the values defined in dw_ascii.h
|
||||
|
||||
Returns
|
||||
Two-dimensional string array of the deliminted fields of f or a null
|
||||
pointer.
|
||||
|
||||
Notes
|
||||
One of f and filename should be non-null. If f is non-null, the file is
|
||||
read starting from the current file position. If f is null, an attempt is
|
||||
made to open the file. If successful, the file is read from the beginning.
|
||||
If the file does not exist or contains no fields, then a null pointer is
|
||||
returned. The delimiter character defines the fields in each row and the
|
||||
new line character defines the rows.
|
||||
|
||||
*/
|
||||
char*** dw_ReadDelimitedFile(FILE *f, char* filename, char delimiter, int flag)
|
||||
{
|
||||
struct LineList
|
||||
{
|
||||
struct LineList *next;
|
||||
char **line;
|
||||
} *head=(struct LineList*)NULL, *ptr;
|
||||
int n=0;
|
||||
char **v, ***M=(char***)NULL, *buffer=(char*)NULL;
|
||||
FILE *f_in=f ? f : fopen(filename,"rt");
|
||||
if (f_in)
|
||||
{
|
||||
while (buffer=dw_ReadLine(f_in,buffer,&n))
|
||||
if (v=dw_ParseDelimitedString(buffer,delimiter,flag))
|
||||
{
|
||||
ptr=(struct LineList*)malloc(sizeof(struct LineList));
|
||||
ptr->line=v;
|
||||
ptr->next=head;
|
||||
head=ptr;
|
||||
n++;
|
||||
}
|
||||
if (!f) fclose(f_in);
|
||||
if (n > 0)
|
||||
{
|
||||
M=(char***)dw_CreateArray_array(n);
|
||||
while (--n >= 0)
|
||||
{
|
||||
M[n]=head->line;
|
||||
ptr=head;
|
||||
head=head->next;
|
||||
free(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
return M;
|
||||
}
|
||||
|
||||
int dw_PrintDelimitedArray(FILE *f, void* array, char delimiter)
|
||||
{
|
||||
char format[4];
|
||||
format[0]='%';
|
||||
format[1]='s';
|
||||
format[2]=delimiter;
|
||||
format[3]='\0';
|
||||
return dw_PrintArray(f,array,format);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
f : valid file pointer
|
||||
delimiter : field terminator
|
||||
terminal : line terminator
|
||||
flag : determine how characters are processed
|
||||
buffer : pointer to pointer to character or null pointer
|
||||
n : pointer to integer containing the length of buffer
|
||||
|
||||
Returns:
|
||||
0 : memory error occured
|
||||
1 : field read, terminated by delimiter
|
||||
2 : field read, terminated by terminal
|
||||
3 : field read, terminated by EOF
|
||||
|
||||
Results:
|
||||
If necessary, memory ia reallocated. The length of this reallocated memory
|
||||
is stored in n. It is the calling routines responsibility to free the
|
||||
memory pointed to by *buffer.
|
||||
|
||||
Notes:
|
||||
flag values
|
||||
ALLOW_QUOTED_TEXT
|
||||
If set the delimiter and terminal characters do not stop processing when
|
||||
encountered between quotes. To produce a quote in quoted text, use two
|
||||
consectutive quotes. Outside quoted text, a quote always begins quoted
|
||||
text.
|
||||
|
||||
PRINTABLE_ONLY_IN_QUOTES
|
||||
|
||||
PRINTABLE_ONLY
|
||||
|
||||
STRIP_LEADING_WHITESPACE
|
||||
|
||||
STRIP_TRAILING_WHITESPACE
|
||||
|
||||
STRIP_WHITESPACE
|
||||
|
||||
|
||||
*/
|
||||
//#define INCREMENT 1024
|
||||
//int dw_ReadDelimitedField(FILE *f, int delimiter, int terminal, int flag, char **buffer, int *n)
|
||||
//{
|
||||
/* int ch; // next character read */
|
||||
/* int k=0; // position to store next char, always less than *n */
|
||||
/* int quoted=0; */
|
||||
/* int leading=(flag & STRIP_LEADING_WHITESPACE) ? 1 : 0; */
|
||||
/* char *ptr; */
|
||||
|
||||
/* ch=fgetc(f); */
|
||||
|
||||
/* while (ch != EOF) */
|
||||
/* { */
|
||||
/* //=== reallocate memory if necessary */
|
||||
/* if (k+1 > *n) */
|
||||
/* if (!(ptr=(char*)realloc(buffer,*n+=INCREMENT))) */
|
||||
/* { */
|
||||
/* *n-=INCREMENT; */
|
||||
/* return 0; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* buffer=ptr; */
|
||||
|
||||
/* //=== process character */
|
||||
/* if (quoted) */
|
||||
/* { */
|
||||
/* if (ch == '"') */
|
||||
/* if ((ch=fgets(f)) != '"') */
|
||||
/* { */
|
||||
/* quoted=0; */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* if (!(flag & PRINTABLE_ONLY_IN_QUOTES) || isprint(ch)) */
|
||||
/* buffer[k++]=ch; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* if ((ch == delimiter) || (ch == terminal)) */
|
||||
/* break; */
|
||||
/* else */
|
||||
/* if ((ch == '"') && (flag & ALLOW_QUOTED_TEXT)) */
|
||||
/* quoted=1; */
|
||||
/* else */
|
||||
/* if (!(flag & PRINTABLE_ONLY) || isprint(ch)) */
|
||||
/* { */
|
||||
/* if ((ch == "\r") && (terminal == '\n')) */
|
||||
/* { */
|
||||
/* if ((ch=fgetc(f)) == '\n') break; */
|
||||
/* if (!leading) buffer[k++]='\r'; */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* if (leading) */
|
||||
/* if (isspace(ch)) */
|
||||
/* { */
|
||||
/* ch=fgetc(f); */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* leading=0; */
|
||||
/* buffer[k++]=ch; */
|
||||
/* } */
|
||||
|
||||
/* ch=fgets(f); */
|
||||
/* } */
|
||||
|
||||
/* buffer[k]='\0'; */
|
||||
|
||||
/* return (ch == EOF) ? 3 : (ch == terminal) ? 2 : 1; */
|
||||
//}
|
||||
//#undef INCREMENT
|
||||
|
||||
/*
|
||||
Returns 1 if the null terminated string id is found at the beginning of a line
|
||||
in the file and 0 otherwise. The file pointer is set to the line immediately
|
||||
after the line containing id. The search starts at the current position of
|
||||
the file. If id is not found, then the file is rewound and the search is
|
||||
continued until the initial file position is passed.
|
||||
*/
|
||||
int dw_SetFilePosition(FILE *f, char *id)
|
||||
{
|
||||
char *buffer=(char*)NULL;
|
||||
int m, n, pos;
|
||||
if ((n=(int)strlen(id)) > 0)
|
||||
{
|
||||
pos=ftell(f);
|
||||
while (buffer=dw_ReadLine(f,buffer,&m))
|
||||
if (!memcmp(buffer,id,n))
|
||||
{
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
if (pos > 0)
|
||||
{
|
||||
rewind(f);
|
||||
while ((ftell(f) < pos) && (buffer=dw_ReadLine(f,buffer,&m)))
|
||||
if (!memcmp(buffer,id,n))
|
||||
{
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
if (buffer) free(buffer);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns 1 if the null terminated string id is found at the beginning of a line
|
||||
in the file and 0 otherwise. The file pointer is set to the line immediately
|
||||
after the line containing id. Compares a maximum of 1023 characters of id.
|
||||
The file is not rewound so that the search starts at the current position.
|
||||
*/
|
||||
int dw_SetFilePositionNoRewind(FILE *f, char *id)
|
||||
{
|
||||
char buffer[1024], ch;
|
||||
int n=(int)strlen(id);
|
||||
if (n > 1023) n=1023;
|
||||
while (fgets(buffer,1024,f))
|
||||
{
|
||||
if (buffer[strlen(buffer)-1] != '\n')
|
||||
do
|
||||
ch=fgetc(f);
|
||||
while ((ch != '\n') && (ch != EOF));
|
||||
if (!memcmp(buffer,id,n)) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int dw_SetFilePositionBySection(FILE *f, int n, ...)
|
||||
{
|
||||
char *arg;
|
||||
int i;
|
||||
va_list ap;
|
||||
rewind(f);
|
||||
va_start(ap,n);
|
||||
for (i=0; i < n; i++)
|
||||
if (!(arg=va_arg(ap,char*)) || !dw_SetFilePositionNoRewind(f,arg))
|
||||
{
|
||||
va_end(ap);
|
||||
return 0;
|
||||
}
|
||||
va_end(ap);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* dw_DuplicateString(char *buffer)
|
||||
{
|
||||
char *rtrn=(char*)NULL;
|
||||
if (buffer && (rtrn=(char*)malloc(strlen(buffer)+1))) strcpy(rtrn,buffer);
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
#include "dw_ascii.h"
|
||||
#include "dw_array.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/*
|
||||
Attempts to open filename for reading. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. The file must exist.
|
||||
*/
|
||||
FILE *dw_OpenTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"rt");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Attempts to create filename for writing. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. If the file exists, it is
|
||||
overwritten.
|
||||
*/
|
||||
FILE *dw_CreateTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"wt");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Attempts to create filename for writing. Returns pointer to file upon success
|
||||
and prints error message and exits upon failure. The file is created if it
|
||||
does not exist and is opened with the file pointer positioned at the end of
|
||||
file if it does exist.
|
||||
*/
|
||||
FILE *dw_AppendTextFile(char *filename)
|
||||
{
|
||||
FILE *f=fopen(filename,"at");
|
||||
if (!f)
|
||||
{
|
||||
printf("Unable to open %s\n",filename);
|
||||
exit(0);
|
||||
}
|
||||
return (f);
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
f : valid file pointer
|
||||
buffer : pointer to character or null pointer
|
||||
n : pointer to integer containing the length of buffer
|
||||
|
||||
Returns:
|
||||
Pointer to null terminated string containing the characters from the file up
|
||||
to and including the terminating new line character. A null pointer return
|
||||
indicates that there was a memory error or no characters to be read. Call
|
||||
dw_GetError() to determine if a error occured.
|
||||
|
||||
Results:
|
||||
Reads line, beginning at current position from file f Returns a pointer to
|
||||
the buffer containing the file and resets *n if necessary. The if the
|
||||
passed buffer is null or is not large enough to contain the line, buffer is
|
||||
freed and a new buffer is allocated. Because of this, the passed buffer
|
||||
must either null or allocated with malloc(), realloc(), or calloc() and the
|
||||
calling routine is responsible for eventually freeing the memory if the
|
||||
return value is not null.
|
||||
|
||||
Notes:
|
||||
If buffer is null, then value pointed to by the pointer n is not used.
|
||||
*/
|
||||
#define SIZE_INCREMENT 1024
|
||||
char* dw_ReadLine(FILE *f, char *buffer, int *n)
|
||||
{
|
||||
char *ptr, *nbuffer;
|
||||
int i, k=0;
|
||||
if (!buffer && !(buffer=(char*)malloc(*n=SIZE_INCREMENT)))
|
||||
{
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
ptr=buffer;
|
||||
while (fgets(ptr,*n-k,f))
|
||||
if (ptr[(i=(int)strlen(ptr))-1] == '\n')
|
||||
return buffer;
|
||||
else
|
||||
if (!(nbuffer=(char*)realloc(buffer,*n+=SIZE_INCREMENT)))
|
||||
{
|
||||
free(buffer);
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
else
|
||||
ptr=(buffer=nbuffer) + (k+=i);
|
||||
if (ptr != buffer)
|
||||
return buffer;
|
||||
else
|
||||
{
|
||||
free(buffer);
|
||||
*n=0;
|
||||
return (char*)NULL;
|
||||
}
|
||||
}
|
||||
#undef SIZE_INCREMENT
|
||||
|
||||
|
||||
char** dw_ParseDelimitedString(char *buffer, char delimiter, int flag)
|
||||
{
|
||||
struct StringList
|
||||
{
|
||||
struct StringList *next;
|
||||
char *string;
|
||||
int length;
|
||||
} *head, *ptr;
|
||||
int k=0, n, m;
|
||||
char **v;
|
||||
if (!buffer) return (char**)NULL;
|
||||
for (head=ptr=(struct StringList*)NULL; *buffer; buffer+=buffer[n] ? n+1 : n)
|
||||
{
|
||||
if (flag & STRIP_LEADING_WHITESPACE)
|
||||
while (*buffer && (*buffer != delimiter) && isspace(*buffer)) buffer++;
|
||||
for (n=0; buffer[n] && (buffer[n] != delimiter); n++);
|
||||
if (flag & STRIP_TRAILING_WHITESPACE)
|
||||
for (m=n-1; (m >= 0) && isspace(buffer[m]); m--);
|
||||
else
|
||||
m=n-1;
|
||||
if ((m >= 0) || !(flag & REMOVE_EMPTY_FIELDS))
|
||||
{
|
||||
ptr=(struct StringList*)malloc(sizeof(struct StringList));
|
||||
ptr->string=buffer;
|
||||
ptr->length=m+1;
|
||||
ptr->next=head;
|
||||
head=ptr;
|
||||
k++;
|
||||
}
|
||||
}
|
||||
v=dw_CreateArray_string(k);
|
||||
while (--k >= 0)
|
||||
{
|
||||
v[k]=(char*)malloc(head->length+1);
|
||||
if (head->length > 0) memcpy(v[k],head->string,head->length);
|
||||
v[k][head->length]='\0';
|
||||
ptr=head;
|
||||
head=head->next;
|
||||
free(ptr);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
f: valid file pointer
|
||||
delimiter: field deliniter.
|
||||
flag: one of the values defined in dw_ascii.h
|
||||
|
||||
Returns
|
||||
One-dimensional string array of the delimited fields of the current line of
|
||||
the file f or a null pointer.
|
||||
|
||||
Notes
|
||||
The file is read starting from the current file position. If the file
|
||||
contains no fields or there is a memory error, then a null pointer is
|
||||
returned. The delimiter character defines the fields in each row and the
|
||||
new line character defines the rows.
|
||||
*/
|
||||
char** dw_ReadDelimitedLine(FILE *f, char delimiter, int flag)
|
||||
{
|
||||
int n=0;
|
||||
char **v=(char**)NULL, *buffer=dw_ReadLine(f,(char*)NULL,&n);
|
||||
if (buffer)
|
||||
{
|
||||
v=dw_ParseDelimitedString(buffer,delimiter,flag);
|
||||
free(buffer);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
f: valid file pointer or null pointer.
|
||||
filename: pointer to null terminated string or null pointer.
|
||||
delimiter: field deliniter.
|
||||
flag: one of the values defined in dw_ascii.h
|
||||
|
||||
Returns
|
||||
Two-dimensional string array of the deliminted fields of f or a null
|
||||
pointer.
|
||||
|
||||
Notes
|
||||
One of f and filename should be non-null. If f is non-null, the file is
|
||||
read starting from the current file position. If f is null, an attempt is
|
||||
made to open the file. If successful, the file is read from the beginning.
|
||||
If the file does not exist or contains no fields, then a null pointer is
|
||||
returned. The delimiter character defines the fields in each row and the
|
||||
new line character defines the rows.
|
||||
|
||||
*/
|
||||
char*** dw_ReadDelimitedFile(FILE *f, char* filename, char delimiter, int flag)
|
||||
{
|
||||
struct LineList
|
||||
{
|
||||
struct LineList *next;
|
||||
char **line;
|
||||
} *head=(struct LineList*)NULL, *ptr;
|
||||
int n=0;
|
||||
char **v, ***M=(char***)NULL, *buffer=(char*)NULL;
|
||||
FILE *f_in=f ? f : fopen(filename,"rt");
|
||||
if (f_in)
|
||||
{
|
||||
while (buffer=dw_ReadLine(f_in,buffer,&n))
|
||||
if (v=dw_ParseDelimitedString(buffer,delimiter,flag))
|
||||
{
|
||||
ptr=(struct LineList*)malloc(sizeof(struct LineList));
|
||||
ptr->line=v;
|
||||
ptr->next=head;
|
||||
head=ptr;
|
||||
n++;
|
||||
}
|
||||
if (!f) fclose(f_in);
|
||||
if (n > 0)
|
||||
{
|
||||
M=(char***)dw_CreateArray_array(n);
|
||||
while (--n >= 0)
|
||||
{
|
||||
M[n]=head->line;
|
||||
ptr=head;
|
||||
head=head->next;
|
||||
free(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
return M;
|
||||
}
|
||||
|
||||
int dw_PrintDelimitedArray(FILE *f, void* array, char delimiter)
|
||||
{
|
||||
char format[4];
|
||||
format[0]='%';
|
||||
format[1]='s';
|
||||
format[2]=delimiter;
|
||||
format[3]='\0';
|
||||
return dw_PrintArray(f,array,format);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
f : valid file pointer
|
||||
delimiter : field terminator
|
||||
terminal : line terminator
|
||||
flag : determine how characters are processed
|
||||
buffer : pointer to pointer to character or null pointer
|
||||
n : pointer to integer containing the length of buffer
|
||||
|
||||
Returns:
|
||||
0 : memory error occured
|
||||
1 : field read, terminated by delimiter
|
||||
2 : field read, terminated by terminal
|
||||
3 : field read, terminated by EOF
|
||||
|
||||
Results:
|
||||
If necessary, memory ia reallocated. The length of this reallocated memory
|
||||
is stored in n. It is the calling routines responsibility to free the
|
||||
memory pointed to by *buffer.
|
||||
|
||||
Notes:
|
||||
flag values
|
||||
ALLOW_QUOTED_TEXT
|
||||
If set the delimiter and terminal characters do not stop processing when
|
||||
encountered between quotes. To produce a quote in quoted text, use two
|
||||
consectutive quotes. Outside quoted text, a quote always begins quoted
|
||||
text.
|
||||
|
||||
PRINTABLE_ONLY_IN_QUOTES
|
||||
|
||||
PRINTABLE_ONLY
|
||||
|
||||
STRIP_LEADING_WHITESPACE
|
||||
|
||||
STRIP_TRAILING_WHITESPACE
|
||||
|
||||
STRIP_WHITESPACE
|
||||
|
||||
|
||||
*/
|
||||
//#define INCREMENT 1024
|
||||
//int dw_ReadDelimitedField(FILE *f, int delimiter, int terminal, int flag, char **buffer, int *n)
|
||||
//{
|
||||
/* int ch; // next character read */
|
||||
/* int k=0; // position to store next char, always less than *n */
|
||||
/* int quoted=0; */
|
||||
/* int leading=(flag & STRIP_LEADING_WHITESPACE) ? 1 : 0; */
|
||||
/* char *ptr; */
|
||||
|
||||
/* ch=fgetc(f); */
|
||||
|
||||
/* while (ch != EOF) */
|
||||
/* { */
|
||||
/* //=== reallocate memory if necessary */
|
||||
/* if (k+1 > *n) */
|
||||
/* if (!(ptr=(char*)realloc(buffer,*n+=INCREMENT))) */
|
||||
/* { */
|
||||
/* *n-=INCREMENT; */
|
||||
/* return 0; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* buffer=ptr; */
|
||||
|
||||
/* //=== process character */
|
||||
/* if (quoted) */
|
||||
/* { */
|
||||
/* if (ch == '"') */
|
||||
/* if ((ch=fgets(f)) != '"') */
|
||||
/* { */
|
||||
/* quoted=0; */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* if (!(flag & PRINTABLE_ONLY_IN_QUOTES) || isprint(ch)) */
|
||||
/* buffer[k++]=ch; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* if ((ch == delimiter) || (ch == terminal)) */
|
||||
/* break; */
|
||||
/* else */
|
||||
/* if ((ch == '"') && (flag & ALLOW_QUOTED_TEXT)) */
|
||||
/* quoted=1; */
|
||||
/* else */
|
||||
/* if (!(flag & PRINTABLE_ONLY) || isprint(ch)) */
|
||||
/* { */
|
||||
/* if ((ch == "\r") && (terminal == '\n')) */
|
||||
/* { */
|
||||
/* if ((ch=fgetc(f)) == '\n') break; */
|
||||
/* if (!leading) buffer[k++]='\r'; */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* if (leading) */
|
||||
/* if (isspace(ch)) */
|
||||
/* { */
|
||||
/* ch=fgetc(f); */
|
||||
/* continue; */
|
||||
/* } */
|
||||
/* else */
|
||||
/* leading=0; */
|
||||
/* buffer[k++]=ch; */
|
||||
/* } */
|
||||
|
||||
/* ch=fgets(f); */
|
||||
/* } */
|
||||
|
||||
/* buffer[k]='\0'; */
|
||||
|
||||
/* return (ch == EOF) ? 3 : (ch == terminal) ? 2 : 1; */
|
||||
//}
|
||||
//#undef INCREMENT
|
||||
|
||||
/*
|
||||
Returns 1 if the null terminated string id is found at the beginning of a line
|
||||
in the file and 0 otherwise. The file pointer is set to the line immediately
|
||||
after the line containing id. The search starts at the current position of
|
||||
the file. If id is not found, then the file is rewound and the search is
|
||||
continued until the initial file position is passed.
|
||||
*/
|
||||
int dw_SetFilePosition(FILE *f, char *id)
|
||||
{
|
||||
char *buffer=(char*)NULL;
|
||||
int m, n, pos;
|
||||
if ((n=(int)strlen(id)) > 0)
|
||||
{
|
||||
pos=ftell(f);
|
||||
while (buffer=dw_ReadLine(f,buffer,&m))
|
||||
if (!memcmp(buffer,id,n))
|
||||
{
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
if (pos > 0)
|
||||
{
|
||||
rewind(f);
|
||||
while ((ftell(f) < pos) && (buffer=dw_ReadLine(f,buffer,&m)))
|
||||
if (!memcmp(buffer,id,n))
|
||||
{
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
if (buffer) free(buffer);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns 1 if the null terminated string id is found at the beginning of a line
|
||||
in the file and 0 otherwise. The file pointer is set to the line immediately
|
||||
after the line containing id. Compares a maximum of 1023 characters of id.
|
||||
The file is not rewound so that the search starts at the current position.
|
||||
*/
|
||||
int dw_SetFilePositionNoRewind(FILE *f, char *id)
|
||||
{
|
||||
char buffer[1024], ch;
|
||||
int n=(int)strlen(id);
|
||||
if (n > 1023) n=1023;
|
||||
while (fgets(buffer,1024,f))
|
||||
{
|
||||
if (buffer[strlen(buffer)-1] != '\n')
|
||||
do
|
||||
ch=fgetc(f);
|
||||
while ((ch != '\n') && (ch != EOF));
|
||||
if (!memcmp(buffer,id,n)) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int dw_SetFilePositionBySection(FILE *f, int n, ...)
|
||||
{
|
||||
char *arg;
|
||||
int i;
|
||||
va_list ap;
|
||||
rewind(f);
|
||||
va_start(ap,n);
|
||||
for (i=0; i < n; i++)
|
||||
if (!(arg=va_arg(ap,char*)) || !dw_SetFilePositionNoRewind(f,arg))
|
||||
{
|
||||
va_end(ap);
|
||||
return 0;
|
||||
}
|
||||
va_end(ap);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* dw_DuplicateString(char *buffer)
|
||||
{
|
||||
char *rtrn=(char*)NULL;
|
||||
if (buffer && (rtrn=(char*)malloc(strlen(buffer)+1))) strcpy(rtrn,buffer);
|
||||
return rtrn;
|
||||
}
|
||||
|
|
|
@ -1,34 +1,34 @@
|
|||
|
||||
|
||||
#ifndef __DW_ASCII_ROUTINES__
|
||||
#define __DW_ASCII_ROUTINES__
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// Flag codes. See ParseDelimitedString() for explanation.
|
||||
#define REMOVE_EMPTY_FIELDS 0x00000001
|
||||
#define ALLOW_QUOTED_TEXT 0x00000002
|
||||
#define STRIP_LEADING_WHITESPACE 0x00000004
|
||||
#define STRIP_TRAILING_WHITESPACE 0x00000008
|
||||
#define STRIP_WHITESPACE 0x0000000c
|
||||
|
||||
FILE *dw_OpenTextFile(char *filename);
|
||||
FILE *dw_CreateTextFile(char *filename);
|
||||
FILE *dw_AppendTextFile(char *filename);
|
||||
|
||||
int dw_SetFilePosition(FILE *f, char *id);
|
||||
int dw_SetFilePositionNoRewind(FILE *f, char *id);
|
||||
int dw_SetFilePositionBySection(FILE *f, int n, ...);
|
||||
|
||||
char* dw_ReadLine(FILE *f, char *buffer, int *n);
|
||||
char** dw_ParseDelimitedString(char *buffer, char delimiter, int flag);
|
||||
char** dw_ReadDelimitedLine(FILE *f, char delimiter, int flag);
|
||||
char*** dw_ReadDelimitedFile(FILE *f, char* filename, char delimiter, int flag);
|
||||
int dw_PrintDelimitedArray(FILE *f, void* array, char delimiter);
|
||||
|
||||
//int dw_ReadDelimitedField(FILE *f, char **buffer, int *n);
|
||||
int dw_ReadDelimitedField(FILE *f, int delimiter, int terminal, int flag, char **buffer, int *n);
|
||||
|
||||
char* dw_DuplicateString(char *buffer);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef __DW_ASCII_ROUTINES__
|
||||
#define __DW_ASCII_ROUTINES__
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// Flag codes. See ParseDelimitedString() for explanation.
|
||||
#define REMOVE_EMPTY_FIELDS 0x00000001
|
||||
#define ALLOW_QUOTED_TEXT 0x00000002
|
||||
#define STRIP_LEADING_WHITESPACE 0x00000004
|
||||
#define STRIP_TRAILING_WHITESPACE 0x00000008
|
||||
#define STRIP_WHITESPACE 0x0000000c
|
||||
|
||||
FILE *dw_OpenTextFile(char *filename);
|
||||
FILE *dw_CreateTextFile(char *filename);
|
||||
FILE *dw_AppendTextFile(char *filename);
|
||||
|
||||
int dw_SetFilePosition(FILE *f, char *id);
|
||||
int dw_SetFilePositionNoRewind(FILE *f, char *id);
|
||||
int dw_SetFilePositionBySection(FILE *f, int n, ...);
|
||||
|
||||
char* dw_ReadLine(FILE *f, char *buffer, int *n);
|
||||
char** dw_ParseDelimitedString(char *buffer, char delimiter, int flag);
|
||||
char** dw_ReadDelimitedLine(FILE *f, char delimiter, int flag);
|
||||
char*** dw_ReadDelimitedFile(FILE *f, char* filename, char delimiter, int flag);
|
||||
int dw_PrintDelimitedArray(FILE *f, void* array, char delimiter);
|
||||
|
||||
//int dw_ReadDelimitedField(FILE *f, char **buffer, int *n);
|
||||
int dw_ReadDelimitedField(FILE *f, int delimiter, int terminal, int flag, char **buffer, int *n);
|
||||
|
||||
char* dw_DuplicateString(char *buffer);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,258 +1,258 @@
|
|||
|
||||
#include "dw_parse_cmd.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define ARGUMENT_ID '-'
|
||||
|
||||
/*
|
||||
A floating point number is of the form
|
||||
|
||||
[white space][+/-]digits[.[digits]][E/e[+/-]digits]white space/null character
|
||||
|
||||
or
|
||||
|
||||
[white space][+/-].digits[E/e[+/-]digits]white space/null character
|
||||
|
||||
where characters in square brackets are optional.
|
||||
|
||||
Returns one if valid floating point number and zero otherwise.
|
||||
*/
|
||||
int dw_IsFloat(char *buffer)
|
||||
{
|
||||
int i=0;
|
||||
|
||||
if (!buffer) return 0;
|
||||
|
||||
/* Strip leading white space */
|
||||
while (isspace(buffer[i])) i++;
|
||||
|
||||
/* Mantissa OK? */
|
||||
if ((buffer[i] == '+') || (buffer[i] == '-')) i++;
|
||||
if (isdigit(buffer[i]))
|
||||
{
|
||||
while (isdigit(buffer[++i]));
|
||||
if ((buffer[i] == '.'))
|
||||
while (isdigit(buffer[++i]));
|
||||
}
|
||||
else
|
||||
if ((buffer[i] == '.'))
|
||||
if (isdigit(buffer[++i]))
|
||||
while (isdigit(buffer[++i]));
|
||||
else
|
||||
return 0;
|
||||
else
|
||||
return 0;
|
||||
|
||||
/* Is exponent OK? */
|
||||
if ((buffer[i] == 'e') || (buffer[i] == 'E'))
|
||||
{
|
||||
if ((buffer[++i] == '+') || (buffer[i] == '-')) i++;
|
||||
if (isdigit(buffer[i]))
|
||||
while (isdigit(buffer[++i]));
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Is end of string or trailing white space */
|
||||
if (buffer[i] && !isspace(buffer[i])) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Integers are of the form
|
||||
|
||||
[white space][+/-]digits[.]white space/null character
|
||||
|
||||
where characters in square brackets are optional.
|
||||
|
||||
Returns one if valid integer and zero otherwise.
|
||||
*/
|
||||
int dw_IsInteger(char *buffer)
|
||||
{
|
||||
int i=0;
|
||||
|
||||
if (!buffer) return 0;
|
||||
|
||||
/* Strip leading white space */
|
||||
while (isspace(buffer[i])) i++;
|
||||
|
||||
/* Leading sign */
|
||||
if ((buffer[i] == '+') || (buffer[i] == '-')) i++;
|
||||
|
||||
/* At least one digits possibly followed by decimal point */
|
||||
if (isdigit(buffer[i]))
|
||||
{
|
||||
while (isdigit(buffer[++i]));
|
||||
if ((buffer[i] == '.')) i++;
|
||||
}
|
||||
else
|
||||
return 0;
|
||||
|
||||
/* Is end of string or trailing white space */
|
||||
if (buffer[i] && !isspace(buffer[i])) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches args for a leading ARGUMENT_ID followed by the character opt. Returns
|
||||
the index if found and -1 otherwise.
|
||||
*/
|
||||
int dw_FindArgument(int nargs, char **args, char opt)
|
||||
{
|
||||
int i;
|
||||
for (i=nargs-1; i >= 0; i--)
|
||||
if ((args[i][0] == ARGUMENT_ID) && (args[i][1] == opt)) break;
|
||||
return i;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
integer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
If the characters following the second form a valid integer, then this
|
||||
integer is returned. Otherwise the integer def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument and its characters form a valid integer, then
|
||||
this integer is returned. Otherwise the integer def is returned.
|
||||
*/
|
||||
int dw_ParseInteger(int nargs, char **args, char opt, int def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (dw_IsInteger(args[i]+2))
|
||||
return atoi(args[i]+2);
|
||||
else
|
||||
if ((i+1 < nargs) && dw_IsInteger(args[i+1])) return atoi(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
double def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
If the characters following the second form a valid floating point number,
|
||||
then this value is returned. Otherwise def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument and its characters form a valid floating point
|
||||
number, then this value is returned. Otherwise def is returned.
|
||||
*/
|
||||
double dw_ParseFloating(int nargs, char **args, char opt, double def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (dw_IsFloat(args[i]+2))
|
||||
return atof(args[i]+2);
|
||||
else
|
||||
if ((i+1 < nargs) && dw_IsFloat(args[i+1])) return atof(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
pointer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
A pointer to the found argument plus two is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument then a pointer to this argument is returned.
|
||||
Otherwise the integer def is returned.
|
||||
*/
|
||||
char* dw_ParseString(int nargs, char **args, char opt, char *def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (args[i][2])
|
||||
return args[i]+2;
|
||||
else
|
||||
if (i+1 < nargs) return args[i+1];
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches args for a leading ARGUMENT_ID followed by the string opt. Returns
|
||||
the index if found and -1 otherwise.
|
||||
*/
|
||||
int dw_FindArgument_String(int nargs, char **args, char *opt)
|
||||
{
|
||||
int i;
|
||||
for (i=nargs-1; i >= 0; i--)
|
||||
if ((args[i][0] == ARGUMENT_ID) && !strcmp(args[i]+1,opt)) break;
|
||||
return i;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is a ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
integer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
If the characters following the second form a valid integer, then this
|
||||
integer is returned. Otherwise the integer def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument and its characters form a valid integer, then
|
||||
this integer is returned. Otherwise the integer def is returned.
|
||||
*/
|
||||
int dw_ParseInteger_String(int nargs, char **args, char *opt, int def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs) && dw_IsInteger(args[i+1])) return atoi(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
double def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
If the characters following the second form a valid floating point number,
|
||||
then this value is returned. Otherwise def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument and its characters form a valid floating point
|
||||
number, then this value is returned. Otherwise def is returned.
|
||||
*/
|
||||
double dw_ParseFloating_String(int nargs, char **args, char *opt, double def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs) && dw_IsFloat(args[i+1])) return atof(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
pointer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
A pointer to the found argument plus two is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument, then a pointer to this argument is returned.
|
||||
Otherwise the string def is returned.
|
||||
*/
|
||||
char* dw_ParseString_String(int nargs, char **args, char *opt, char *def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs)) return args[i+1];
|
||||
return def;
|
||||
}
|
||||
|
||||
|
||||
#include "dw_parse_cmd.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define ARGUMENT_ID '-'
|
||||
|
||||
/*
|
||||
A floating point number is of the form
|
||||
|
||||
[white space][+/-]digits[.[digits]][E/e[+/-]digits]white space/null character
|
||||
|
||||
or
|
||||
|
||||
[white space][+/-].digits[E/e[+/-]digits]white space/null character
|
||||
|
||||
where characters in square brackets are optional.
|
||||
|
||||
Returns one if valid floating point number and zero otherwise.
|
||||
*/
|
||||
int dw_IsFloat(char *buffer)
|
||||
{
|
||||
int i=0;
|
||||
|
||||
if (!buffer) return 0;
|
||||
|
||||
/* Strip leading white space */
|
||||
while (isspace(buffer[i])) i++;
|
||||
|
||||
/* Mantissa OK? */
|
||||
if ((buffer[i] == '+') || (buffer[i] == '-')) i++;
|
||||
if (isdigit(buffer[i]))
|
||||
{
|
||||
while (isdigit(buffer[++i]));
|
||||
if ((buffer[i] == '.'))
|
||||
while (isdigit(buffer[++i]));
|
||||
}
|
||||
else
|
||||
if ((buffer[i] == '.'))
|
||||
if (isdigit(buffer[++i]))
|
||||
while (isdigit(buffer[++i]));
|
||||
else
|
||||
return 0;
|
||||
else
|
||||
return 0;
|
||||
|
||||
/* Is exponent OK? */
|
||||
if ((buffer[i] == 'e') || (buffer[i] == 'E'))
|
||||
{
|
||||
if ((buffer[++i] == '+') || (buffer[i] == '-')) i++;
|
||||
if (isdigit(buffer[i]))
|
||||
while (isdigit(buffer[++i]));
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Is end of string or trailing white space */
|
||||
if (buffer[i] && !isspace(buffer[i])) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Integers are of the form
|
||||
|
||||
[white space][+/-]digits[.]white space/null character
|
||||
|
||||
where characters in square brackets are optional.
|
||||
|
||||
Returns one if valid integer and zero otherwise.
|
||||
*/
|
||||
int dw_IsInteger(char *buffer)
|
||||
{
|
||||
int i=0;
|
||||
|
||||
if (!buffer) return 0;
|
||||
|
||||
/* Strip leading white space */
|
||||
while (isspace(buffer[i])) i++;
|
||||
|
||||
/* Leading sign */
|
||||
if ((buffer[i] == '+') || (buffer[i] == '-')) i++;
|
||||
|
||||
/* At least one digits possibly followed by decimal point */
|
||||
if (isdigit(buffer[i]))
|
||||
{
|
||||
while (isdigit(buffer[++i]));
|
||||
if ((buffer[i] == '.')) i++;
|
||||
}
|
||||
else
|
||||
return 0;
|
||||
|
||||
/* Is end of string or trailing white space */
|
||||
if (buffer[i] && !isspace(buffer[i])) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches args for a leading ARGUMENT_ID followed by the character opt. Returns
|
||||
the index if found and -1 otherwise.
|
||||
*/
|
||||
int dw_FindArgument(int nargs, char **args, char opt)
|
||||
{
|
||||
int i;
|
||||
for (i=nargs-1; i >= 0; i--)
|
||||
if ((args[i][0] == ARGUMENT_ID) && (args[i][1] == opt)) break;
|
||||
return i;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
integer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
If the characters following the second form a valid integer, then this
|
||||
integer is returned. Otherwise the integer def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument and its characters form a valid integer, then
|
||||
this integer is returned. Otherwise the integer def is returned.
|
||||
*/
|
||||
int dw_ParseInteger(int nargs, char **args, char opt, int def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (dw_IsInteger(args[i]+2))
|
||||
return atoi(args[i]+2);
|
||||
else
|
||||
if ((i+1 < nargs) && dw_IsInteger(args[i+1])) return atoi(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
double def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
If the characters following the second form a valid floating point number,
|
||||
then this value is returned. Otherwise def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument and its characters form a valid floating point
|
||||
number, then this value is returned. Otherwise def is returned.
|
||||
*/
|
||||
double dw_ParseFloating(int nargs, char **args, char opt, double def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (dw_IsFloat(args[i]+2))
|
||||
return atof(args[i]+2);
|
||||
else
|
||||
if ((i+1 < nargs) && dw_IsFloat(args[i+1])) return atof(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the character opt. If such an argument is not found, then the
|
||||
pointer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 2.
|
||||
A pointer to the found argument plus two is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 2.
|
||||
If there is an i+1 argument then a pointer to this argument is returned.
|
||||
Otherwise the integer def is returned.
|
||||
*/
|
||||
char* dw_ParseString(int nargs, char **args, char opt, char *def)
|
||||
{
|
||||
int i=dw_FindArgument(nargs,args,opt);
|
||||
if (i != -1)
|
||||
if (args[i][2])
|
||||
return args[i]+2;
|
||||
else
|
||||
if (i+1 < nargs) return args[i+1];
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches args for a leading ARGUMENT_ID followed by the string opt. Returns
|
||||
the index if found and -1 otherwise.
|
||||
*/
|
||||
int dw_FindArgument_String(int nargs, char **args, char *opt)
|
||||
{
|
||||
int i;
|
||||
for (i=nargs-1; i >= 0; i--)
|
||||
if ((args[i][0] == ARGUMENT_ID) && !strcmp(args[i]+1,opt)) break;
|
||||
return i;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is a ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
integer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
If the characters following the second form a valid integer, then this
|
||||
integer is returned. Otherwise the integer def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument and its characters form a valid integer, then
|
||||
this integer is returned. Otherwise the integer def is returned.
|
||||
*/
|
||||
int dw_ParseInteger_String(int nargs, char **args, char *opt, int def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs) && dw_IsInteger(args[i+1])) return atoi(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
double def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
If the characters following the second form a valid floating point number,
|
||||
then this value is returned. Otherwise def is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument and its characters form a valid floating point
|
||||
number, then this value is returned. Otherwise def is returned.
|
||||
*/
|
||||
double dw_ParseFloating_String(int nargs, char **args, char *opt, double def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs) && dw_IsFloat(args[i+1])) return atof(args[i+1]);
|
||||
return def;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Searches for the last argument whose leading character is ARGUMENT_ID
|
||||
followed by the string opt. If such an argument is not found, then the
|
||||
pointer def is returned. If such an argument is found then:
|
||||
|
||||
Case 1: The string length of the found argument is greater than 1+strlen(opt).
|
||||
A pointer to the found argument plus two is returned.
|
||||
|
||||
Case 2: The string length of the found argument is equal to 1+strlen(opt).
|
||||
If there is an i+1 argument, then a pointer to this argument is returned.
|
||||
Otherwise the string def is returned.
|
||||
*/
|
||||
char* dw_ParseString_String(int nargs, char **args, char *opt, char *def)
|
||||
{
|
||||
int i=dw_FindArgument_String(nargs,args,opt);
|
||||
if ((i != -1) && (i+1 < nargs)) return args[i+1];
|
||||
return def;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,24 +1,24 @@
|
|||
|
||||
#ifndef __PARSE_COMMAND_LINE__
|
||||
#define __PARSE_COMMAND_LINE__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
int dw_FindArgument(int nargs, char **args, char opt);
|
||||
int dw_ParseInteger(int nargs, char **args, char opt, int def);
|
||||
double dw_ParseFloating(int nargs, char **args, char opt, double def);
|
||||
char* dw_ParseString(int nargs, char **args, char opt, char *def);
|
||||
|
||||
int dw_FindArgument_String(int nargs, char **args, char *opt);
|
||||
int dw_ParseInteger_String(int nargs, char **args, char *opt, int def);
|
||||
double dw_ParseFloating_String(int nargs, char **args, char *opt, double def);
|
||||
char* dw_ParseString_String(int nargs, char **args, char *opt, char *def);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __PARSE_COMMAND_LINE__
|
||||
#define __PARSE_COMMAND_LINE__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
int dw_FindArgument(int nargs, char **args, char opt);
|
||||
int dw_ParseInteger(int nargs, char **args, char opt, int def);
|
||||
double dw_ParseFloating(int nargs, char **args, char opt, double def);
|
||||
char* dw_ParseString(int nargs, char **args, char opt, char *def);
|
||||
|
||||
int dw_FindArgument_String(int nargs, char **args, char *opt);
|
||||
int dw_ParseInteger_String(int nargs, char **args, char *opt, int def);
|
||||
double dw_ParseFloating_String(int nargs, char **args, char *opt, double def);
|
||||
char* dw_ParseString_String(int nargs, char **args, char *opt, char *def);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,208 +1,208 @@
|
|||
|
||||
#include "dw_error.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define ERROR_MESSAGE_BUFFER_LENGTH 256
|
||||
static int ERROR=NO_ERR;
|
||||
static char ERROR_MESSAGE[ERROR_MESSAGE_BUFFER_LENGTH]="";
|
||||
static int TerminalErrors=ALL_ERRORS;
|
||||
static int VerboseErrors=ALL_ERRORS;
|
||||
static FILE* f_err=(FILE*)NULL;
|
||||
|
||||
/*
|
||||
Returns the value of the current error flag.
|
||||
*/
|
||||
int dw_GetError(void)
|
||||
{
|
||||
return ERROR;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns pointer to current error message. This buffer should not be modified
|
||||
or freed.
|
||||
*/
|
||||
char* dw_GetErrorMessage(void)
|
||||
{
|
||||
return ERROR_MESSAGE;
|
||||
}
|
||||
|
||||
/*
|
||||
Clears the error flag and returns the value of the previous flag. This is the
|
||||
most efficient way to clear the error flag and message.
|
||||
*/
|
||||
int dw_ClearError(void)
|
||||
{
|
||||
int rtrn=ERROR;
|
||||
ERROR=NO_ERR;
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Sets the error flag to err, the error message to msg and returns the value of
|
||||
the previous flag. If the null terminated string msg is longer than 255
|
||||
characters, only the first 255 characters are used. If msg is null, then a
|
||||
predefined error message is used.
|
||||
*/
|
||||
int dw_SetError(int err, char *msg)
|
||||
{
|
||||
int rtrn=ERROR;
|
||||
if (msg)
|
||||
switch (ERROR=err)
|
||||
{
|
||||
case MEM_ERR:
|
||||
case FILE_ERR:
|
||||
case PARSE_ERR:
|
||||
case FLOAT_ERR:
|
||||
case NULL_ERR:
|
||||
case ARG_ERR:
|
||||
case ITERATION_ERR:
|
||||
case NOT_IMPLEMENTED_ERR:
|
||||
case SIZE_ERR:
|
||||
case SING_ERR:
|
||||
case POSDEF_ERR:
|
||||
case BLAS_LAPACK_ERR:
|
||||
case USER_ERR:
|
||||
strncpy(ERROR_MESSAGE,msg,ERROR_MESSAGE_BUFFER_LENGTH-1);
|
||||
ERROR_MESSAGE[ERROR_MESSAGE_BUFFER_LENGTH-1]='\0';
|
||||
break;
|
||||
case NO_ERR:
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
break;
|
||||
default:
|
||||
ERROR=UNKNOWN_ERR;
|
||||
strcpy(ERROR_MESSAGE,"Unknown error.");
|
||||
break;
|
||||
}
|
||||
else
|
||||
switch (ERROR=err)
|
||||
{
|
||||
case MEM_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Out of memory.");
|
||||
break;
|
||||
case FILE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"File operation error.");
|
||||
break;
|
||||
case PARSE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Error parsing data.");
|
||||
break;
|
||||
case FLOAT_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Floating point error.");
|
||||
break;
|
||||
case NULL_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Unexpected null pointer encountered.");
|
||||
break;
|
||||
case ARG_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Argument error.");
|
||||
break;
|
||||
case ITERATION_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Maximum iteration limit exceeded.");
|
||||
break;
|
||||
case NOT_IMPLEMENTED_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Feature not yet implemented.");
|
||||
break;
|
||||
case SIZE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Matrices/vectors not conformable.");
|
||||
break;
|
||||
case SING_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Singular matrix.");
|
||||
break;
|
||||
case POSDEF_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Matrix not positive definite.");
|
||||
break;
|
||||
case BLAS_LAPACK_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Blas/Lapack error.");
|
||||
break;
|
||||
case USER_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Undocumented error.");
|
||||
break;
|
||||
case NO_ERR:
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
break;
|
||||
default:
|
||||
ERROR=UNKNOWN_ERR;
|
||||
strcpy(ERROR_MESSAGE,"Unknown error.");
|
||||
break;
|
||||
}
|
||||
if (VerboseErrors & ERROR) fprintf(f_err ? f_err : stderr,"%s\n",ERROR_MESSAGE);
|
||||
if (TerminalErrors & ERROR) exit(ERROR);
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the error flag and to err, sets the error message to the predefined error
|
||||
message, and returns the value of the previous error flag.
|
||||
*/
|
||||
int dw_Error(int err)
|
||||
{
|
||||
return dw_SetError(err,(char*)NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the error flag and to USER_ERR, sets the error message to msg, and
|
||||
returns the value of the previous error flag.
|
||||
*/
|
||||
int dw_UserError(char *msg)
|
||||
{
|
||||
return dw_SetError(USER_ERR,msg);
|
||||
}
|
||||
|
||||
/*
|
||||
Sets errors which terminate program. The integer err should be a combination
|
||||
of the error flags defined in dw_error.h.
|
||||
*/
|
||||
int dw_SetTerminalErrors(int err)
|
||||
{
|
||||
int rtrn=TerminalErrors;
|
||||
TerminalErrors=err & ALL_ERRORS;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the current terminal errors.
|
||||
*/
|
||||
int dw_GetTerminalErrors(void)
|
||||
{
|
||||
return TerminalErrors;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets errors which causes program to print a error message to f_err. The
|
||||
integer err should be a combination of the error flags defined in dw_error.h.
|
||||
*/
|
||||
int dw_SetVerboseErrors(int err)
|
||||
{
|
||||
int rtrn=VerboseErrors;
|
||||
VerboseErrors=err & ALL_ERRORS;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the current verbose errors.
|
||||
*/
|
||||
int dw_GetVerboseErrors(void)
|
||||
{
|
||||
return VerboseErrors;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the file to which errors messages will be sent. The file pointer f
|
||||
must either be the null pointer or a valid printer to an open file. Passing a
|
||||
null pointer has the same effect as redirecting output to stderr. To suppress
|
||||
output of error messages, call dw_SetVerboseErrors(). Returns a pointer to
|
||||
current error message file. When redirecting the error message, if is
|
||||
critical that the error message file pointer point to an open file and that
|
||||
this file not be closed as long as it is the current error message file.
|
||||
*/
|
||||
FILE* dw_SetErrorMessageFile(FILE *f)
|
||||
{
|
||||
FILE *rtrn=f_err;
|
||||
f_err=f ? f : stderr;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#include "dw_error.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define ERROR_MESSAGE_BUFFER_LENGTH 256
|
||||
static int ERROR=NO_ERR;
|
||||
static char ERROR_MESSAGE[ERROR_MESSAGE_BUFFER_LENGTH]="";
|
||||
static int TerminalErrors=ALL_ERRORS;
|
||||
static int VerboseErrors=ALL_ERRORS;
|
||||
static FILE* f_err=(FILE*)NULL;
|
||||
|
||||
/*
|
||||
Returns the value of the current error flag.
|
||||
*/
|
||||
int dw_GetError(void)
|
||||
{
|
||||
return ERROR;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns pointer to current error message. This buffer should not be modified
|
||||
or freed.
|
||||
*/
|
||||
char* dw_GetErrorMessage(void)
|
||||
{
|
||||
return ERROR_MESSAGE;
|
||||
}
|
||||
|
||||
/*
|
||||
Clears the error flag and returns the value of the previous flag. This is the
|
||||
most efficient way to clear the error flag and message.
|
||||
*/
|
||||
int dw_ClearError(void)
|
||||
{
|
||||
int rtrn=ERROR;
|
||||
ERROR=NO_ERR;
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Sets the error flag to err, the error message to msg and returns the value of
|
||||
the previous flag. If the null terminated string msg is longer than 255
|
||||
characters, only the first 255 characters are used. If msg is null, then a
|
||||
predefined error message is used.
|
||||
*/
|
||||
int dw_SetError(int err, char *msg)
|
||||
{
|
||||
int rtrn=ERROR;
|
||||
if (msg)
|
||||
switch (ERROR=err)
|
||||
{
|
||||
case MEM_ERR:
|
||||
case FILE_ERR:
|
||||
case PARSE_ERR:
|
||||
case FLOAT_ERR:
|
||||
case NULL_ERR:
|
||||
case ARG_ERR:
|
||||
case ITERATION_ERR:
|
||||
case NOT_IMPLEMENTED_ERR:
|
||||
case SIZE_ERR:
|
||||
case SING_ERR:
|
||||
case POSDEF_ERR:
|
||||
case BLAS_LAPACK_ERR:
|
||||
case USER_ERR:
|
||||
strncpy(ERROR_MESSAGE,msg,ERROR_MESSAGE_BUFFER_LENGTH-1);
|
||||
ERROR_MESSAGE[ERROR_MESSAGE_BUFFER_LENGTH-1]='\0';
|
||||
break;
|
||||
case NO_ERR:
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
break;
|
||||
default:
|
||||
ERROR=UNKNOWN_ERR;
|
||||
strcpy(ERROR_MESSAGE,"Unknown error.");
|
||||
break;
|
||||
}
|
||||
else
|
||||
switch (ERROR=err)
|
||||
{
|
||||
case MEM_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Out of memory.");
|
||||
break;
|
||||
case FILE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"File operation error.");
|
||||
break;
|
||||
case PARSE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Error parsing data.");
|
||||
break;
|
||||
case FLOAT_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Floating point error.");
|
||||
break;
|
||||
case NULL_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Unexpected null pointer encountered.");
|
||||
break;
|
||||
case ARG_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Argument error.");
|
||||
break;
|
||||
case ITERATION_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Maximum iteration limit exceeded.");
|
||||
break;
|
||||
case NOT_IMPLEMENTED_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Feature not yet implemented.");
|
||||
break;
|
||||
case SIZE_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Matrices/vectors not conformable.");
|
||||
break;
|
||||
case SING_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Singular matrix.");
|
||||
break;
|
||||
case POSDEF_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Matrix not positive definite.");
|
||||
break;
|
||||
case BLAS_LAPACK_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Blas/Lapack error.");
|
||||
break;
|
||||
case USER_ERR:
|
||||
strcpy(ERROR_MESSAGE,"Undocumented error.");
|
||||
break;
|
||||
case NO_ERR:
|
||||
ERROR_MESSAGE[0]='\0';
|
||||
break;
|
||||
default:
|
||||
ERROR=UNKNOWN_ERR;
|
||||
strcpy(ERROR_MESSAGE,"Unknown error.");
|
||||
break;
|
||||
}
|
||||
if (VerboseErrors & ERROR) fprintf(f_err ? f_err : stderr,"%s\n",ERROR_MESSAGE);
|
||||
if (TerminalErrors & ERROR) exit(ERROR);
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the error flag and to err, sets the error message to the predefined error
|
||||
message, and returns the value of the previous error flag.
|
||||
*/
|
||||
int dw_Error(int err)
|
||||
{
|
||||
return dw_SetError(err,(char*)NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the error flag and to USER_ERR, sets the error message to msg, and
|
||||
returns the value of the previous error flag.
|
||||
*/
|
||||
int dw_UserError(char *msg)
|
||||
{
|
||||
return dw_SetError(USER_ERR,msg);
|
||||
}
|
||||
|
||||
/*
|
||||
Sets errors which terminate program. The integer err should be a combination
|
||||
of the error flags defined in dw_error.h.
|
||||
*/
|
||||
int dw_SetTerminalErrors(int err)
|
||||
{
|
||||
int rtrn=TerminalErrors;
|
||||
TerminalErrors=err & ALL_ERRORS;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the current terminal errors.
|
||||
*/
|
||||
int dw_GetTerminalErrors(void)
|
||||
{
|
||||
return TerminalErrors;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets errors which causes program to print a error message to f_err. The
|
||||
integer err should be a combination of the error flags defined in dw_error.h.
|
||||
*/
|
||||
int dw_SetVerboseErrors(int err)
|
||||
{
|
||||
int rtrn=VerboseErrors;
|
||||
VerboseErrors=err & ALL_ERRORS;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the current verbose errors.
|
||||
*/
|
||||
int dw_GetVerboseErrors(void)
|
||||
{
|
||||
return VerboseErrors;
|
||||
}
|
||||
|
||||
/*
|
||||
Sets the file to which errors messages will be sent. The file pointer f
|
||||
must either be the null pointer or a valid printer to an open file. Passing a
|
||||
null pointer has the same effect as redirecting output to stderr. To suppress
|
||||
output of error messages, call dw_SetVerboseErrors(). Returns a pointer to
|
||||
current error message file. When redirecting the error message, if is
|
||||
critical that the error message file pointer point to an open file and that
|
||||
this file not be closed as long as it is the current error message file.
|
||||
*/
|
||||
FILE* dw_SetErrorMessageFile(FILE *f)
|
||||
{
|
||||
FILE *rtrn=f_err;
|
||||
f_err=f ? f : stderr;
|
||||
return rtrn;
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -1,42 +1,42 @@
|
|||
|
||||
#ifndef __ERROR_HANDLING__
|
||||
#define __ERROR_HANDLING__
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define NO_ERR 0x00000000
|
||||
#define ALL_ERRORS 0x000F03FF
|
||||
|
||||
//=== General Errors ===
|
||||
#define MEM_ERR 0x00000001
|
||||
#define FILE_ERR 0x00000002
|
||||
#define PARSE_ERR 0x00000004
|
||||
#define FLOAT_ERR 0x00000008
|
||||
#define NULL_ERR 0x00000010
|
||||
#define ARG_ERR 0x00000020
|
||||
#define ITERATION_ERR 0x00000040
|
||||
#define USER_ERR 0x00000080
|
||||
#define NOT_IMPLEMENTED_ERR 0x00000100
|
||||
#define UNKNOWN_ERR 0x00000200
|
||||
|
||||
|
||||
//=== Matrix Errors ===
|
||||
#define SIZE_ERR 0x00010000
|
||||
#define SING_ERR 0x00020000
|
||||
#define POSDEF_ERR 0x00040000
|
||||
#define BLAS_LAPACK_ERR 0x00080000
|
||||
|
||||
//=== Error Routines ===
|
||||
int dw_GetError(void);
|
||||
char* dw_GetErrorMessage(void);
|
||||
int dw_ClearError(void);
|
||||
int dw_SetError(int err, char *msg);
|
||||
int dw_Error(int err);
|
||||
int dw_UserError(char *msg);
|
||||
int dw_SetVerboseErrors(int errors);
|
||||
int dw_GetVerboseErrors(void);
|
||||
int dw_SetTerminalErrors(int errors);
|
||||
int dw_GetTerminalErrors(void);
|
||||
FILE* dw_SetMessageFile(FILE *f);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __ERROR_HANDLING__
|
||||
#define __ERROR_HANDLING__
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define NO_ERR 0x00000000
|
||||
#define ALL_ERRORS 0x000F03FF
|
||||
|
||||
//=== General Errors ===
|
||||
#define MEM_ERR 0x00000001
|
||||
#define FILE_ERR 0x00000002
|
||||
#define PARSE_ERR 0x00000004
|
||||
#define FLOAT_ERR 0x00000008
|
||||
#define NULL_ERR 0x00000010
|
||||
#define ARG_ERR 0x00000020
|
||||
#define ITERATION_ERR 0x00000040
|
||||
#define USER_ERR 0x00000080
|
||||
#define NOT_IMPLEMENTED_ERR 0x00000100
|
||||
#define UNKNOWN_ERR 0x00000200
|
||||
|
||||
|
||||
//=== Matrix Errors ===
|
||||
#define SIZE_ERR 0x00010000
|
||||
#define SING_ERR 0x00020000
|
||||
#define POSDEF_ERR 0x00040000
|
||||
#define BLAS_LAPACK_ERR 0x00080000
|
||||
|
||||
//=== Error Routines ===
|
||||
int dw_GetError(void);
|
||||
char* dw_GetErrorMessage(void);
|
||||
int dw_ClearError(void);
|
||||
int dw_SetError(int err, char *msg);
|
||||
int dw_Error(int err);
|
||||
int dw_UserError(char *msg);
|
||||
int dw_SetVerboseErrors(int errors);
|
||||
int dw_GetVerboseErrors(void);
|
||||
int dw_SetTerminalErrors(int errors);
|
||||
int dw_GetTerminalErrors(void);
|
||||
FILE* dw_SetMessageFile(FILE *f);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,111 +1,111 @@
|
|||
|
||||
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
|
||||
#include <dynmex.h>
|
||||
#include <dynblas.h>
|
||||
#include <dynlapack.h>
|
||||
#else
|
||||
|
||||
#ifndef __BLAS_LAPACK__
|
||||
#define __BLAS_LAPACK__
|
||||
|
||||
typedef int lapack_int;
|
||||
typedef int blas_int;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
/* Linux defines */
|
||||
#define sscal sscal_
|
||||
#define saxpy saxpy_
|
||||
#define sgemm sgemm_
|
||||
#define sgetrf sgetrf_
|
||||
#define sgesdd sgesdd_
|
||||
#define sgesvd sgesvd_
|
||||
#define sgetrf sgetrf_
|
||||
#define sorgqr sorgqr_
|
||||
#define sgelqf sgelqf_
|
||||
#define sorglq sorglq_
|
||||
#define sgges sgges_
|
||||
#define stgsen stgsen_
|
||||
#define stgexc stgexc_
|
||||
|
||||
#define dscal dscal_ // Blas scalar times vector
|
||||
#define daxpy daxpy_ // Blas vector plus scalar times vector
|
||||
#define dgemm dgemm_ // Blas matrix multiplication
|
||||
#define dgetrf dgetrf_
|
||||
#define dgesdd dgesdd_ // SVD decomposition (divide and conquer)
|
||||
#define dgesvd dgesvd_ // SVD decomposition (QR)
|
||||
#define dgetrf dgetrf_ // LU decomposition
|
||||
#define dgeqrf dgeqrf_ // QR decomposition
|
||||
#define dorgqr dorgqr_ // Forms orthogonal matrix from Housholder matrices created by dgeqrf
|
||||
#define dgelqf dgelqf_ // LQ decompostion
|
||||
#define dorglq dorglq_ // Forms orthogonal matrix from Housholder matrices created by dgeqrf
|
||||
#define dgges dgges_ // Generalized Schur decomposition
|
||||
#define dtgsen dtgsen_ // Reorders generalized Schur decomposition
|
||||
#define dtgexc dtgexc_ // Reorders generalized Schur decomposition
|
||||
|
||||
#define dsyev dsyev_
|
||||
#define dgeev dgeev_
|
||||
#define dpotrf dpotrf_
|
||||
#define dpotri dpotri_
|
||||
#define dtrtri dtrtri_
|
||||
#define dgetri dgetri_
|
||||
#define dgeqp3 dgeqp3_
|
||||
#define dormqr dormqr_
|
||||
#define dgesv dgesv_
|
||||
/*******************************************************************************/
|
||||
|
||||
|
||||
/* cblas defines *
|
||||
#define cblas_daxpy daxpy
|
||||
/*******************************************************************************/
|
||||
|
||||
|
||||
/* Window defines */
|
||||
void sscal(int *n, float *alpha, float *x, int *incx);
|
||||
void saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy);
|
||||
void sgemm(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
|
||||
void sgetrf(int *M, int *N, float *A, int *LDA, int *IPIV, int *INFO);
|
||||
void sgesdd(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info);
|
||||
void sgesvd(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info);
|
||||
void sgeqrf(int *M, int *N, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sorgqr(int *M, int *N, int *K, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sgelqf(int *M, int *N, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sorglq(int *M, int *N, int *K, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sgges(char *jobvsl, char *jobvsr, char *sort, void *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, void *bwork, int *info);
|
||||
void stgsen(int *ijob, void *wantq, void *wantz, void *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info);
|
||||
void stgexc(void *wantq, void *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info);
|
||||
|
||||
void dscal(int*,double*,double*,int*);
|
||||
void daxpy(int*,double*,double*,int*,double*,int*);
|
||||
void dgemm(char*,char*,int*,int*,int*,double*,double*,int*,double*,int*,double*,double*,int*);
|
||||
void dgetrf(int*,int*,double*,int*,int*,int*);
|
||||
void dgesdd(char*,int*,int*,double*,int*,double*,double*,int*,double*,int*,double*,int*,int*,int*);
|
||||
void dgesvd(char*,char*,int*,int*,double*,int*,double*,double*,int*,double*,int*,double*,int*,int*);
|
||||
void dgeqrf(int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dorgqr(int*,int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgelqf(int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dorglq(int*,int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgges(char*,char*,char*,void*,int*,double*,int*,double*,int*,int*,double*,double*,double*,double*,int*,double*,int*,double*,int*,void*,int*);
|
||||
void dtgsen(int*,void*,void*,void*,int*,double*,int*,double*,int*,double*,double*,double*,double*,int*,double*,int*,int*,double*,double*,double*,double*,int*,int*,int*,int*);
|
||||
void dtgexc(void*,void*,int*,double*,int*,double*,int*,double*,int*,double*,int*,int*,int*,double*,int*,int*);
|
||||
void dsyev(char*,char*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgeev(char*,char*,int*,double*,int*,double*,double*,double*,int*,double*,int*,double*,int*,int*);
|
||||
void dpotrf(char*,int*,double*,int*,int*);
|
||||
void dpotri(char*,int*,double*,int*,int*);
|
||||
void dgeqp3(int*,int*,double*,int*,int*,double*,double*,int*,int*);
|
||||
void dtrtri(char*,char*,int*,double*,int*,int*);
|
||||
void dgetri(int*,double*,int*,int*,double*,int*,int*);
|
||||
void dormqr(char*,char*,int*,int*,int*,double*,int*,double*,double*,int*,double*,int*,int*);
|
||||
void dgesv(int*,int*,double*,int*,int*,double*,int*,int*);
|
||||
/*******************************************************************************/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
|
||||
#include <dynmex.h>
|
||||
#include <dynblas.h>
|
||||
#include <dynlapack.h>
|
||||
#else
|
||||
|
||||
#ifndef __BLAS_LAPACK__
|
||||
#define __BLAS_LAPACK__
|
||||
|
||||
typedef int lapack_int;
|
||||
typedef int blas_int;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
/* Linux defines */
|
||||
#define sscal sscal_
|
||||
#define saxpy saxpy_
|
||||
#define sgemm sgemm_
|
||||
#define sgetrf sgetrf_
|
||||
#define sgesdd sgesdd_
|
||||
#define sgesvd sgesvd_
|
||||
#define sgetrf sgetrf_
|
||||
#define sorgqr sorgqr_
|
||||
#define sgelqf sgelqf_
|
||||
#define sorglq sorglq_
|
||||
#define sgges sgges_
|
||||
#define stgsen stgsen_
|
||||
#define stgexc stgexc_
|
||||
|
||||
#define dscal dscal_ // Blas scalar times vector
|
||||
#define daxpy daxpy_ // Blas vector plus scalar times vector
|
||||
#define dgemm dgemm_ // Blas matrix multiplication
|
||||
#define dgetrf dgetrf_
|
||||
#define dgesdd dgesdd_ // SVD decomposition (divide and conquer)
|
||||
#define dgesvd dgesvd_ // SVD decomposition (QR)
|
||||
#define dgetrf dgetrf_ // LU decomposition
|
||||
#define dgeqrf dgeqrf_ // QR decomposition
|
||||
#define dorgqr dorgqr_ // Forms orthogonal matrix from Housholder matrices created by dgeqrf
|
||||
#define dgelqf dgelqf_ // LQ decompostion
|
||||
#define dorglq dorglq_ // Forms orthogonal matrix from Housholder matrices created by dgeqrf
|
||||
#define dgges dgges_ // Generalized Schur decomposition
|
||||
#define dtgsen dtgsen_ // Reorders generalized Schur decomposition
|
||||
#define dtgexc dtgexc_ // Reorders generalized Schur decomposition
|
||||
|
||||
#define dsyev dsyev_
|
||||
#define dgeev dgeev_
|
||||
#define dpotrf dpotrf_
|
||||
#define dpotri dpotri_
|
||||
#define dtrtri dtrtri_
|
||||
#define dgetri dgetri_
|
||||
#define dgeqp3 dgeqp3_
|
||||
#define dormqr dormqr_
|
||||
#define dgesv dgesv_
|
||||
/*******************************************************************************/
|
||||
|
||||
|
||||
/* cblas defines *
|
||||
#define cblas_daxpy daxpy
|
||||
/*******************************************************************************/
|
||||
|
||||
|
||||
/* Window defines */
|
||||
void sscal(int *n, float *alpha, float *x, int *incx);
|
||||
void saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy);
|
||||
void sgemm(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
|
||||
void sgetrf(int *M, int *N, float *A, int *LDA, int *IPIV, int *INFO);
|
||||
void sgesdd(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info);
|
||||
void sgesvd(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info);
|
||||
void sgeqrf(int *M, int *N, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sorgqr(int *M, int *N, int *K, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sgelqf(int *M, int *N, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sorglq(int *M, int *N, int *K, float *A, int *LDA, float *TAU, float *WORK, int *LWORK, int *INFO);
|
||||
void sgges(char *jobvsl, char *jobvsr, char *sort, void *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, void *bwork, int *info);
|
||||
void stgsen(int *ijob, void *wantq, void *wantz, void *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info);
|
||||
void stgexc(void *wantq, void *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info);
|
||||
|
||||
void dscal(int*,double*,double*,int*);
|
||||
void daxpy(int*,double*,double*,int*,double*,int*);
|
||||
void dgemm(char*,char*,int*,int*,int*,double*,double*,int*,double*,int*,double*,double*,int*);
|
||||
void dgetrf(int*,int*,double*,int*,int*,int*);
|
||||
void dgesdd(char*,int*,int*,double*,int*,double*,double*,int*,double*,int*,double*,int*,int*,int*);
|
||||
void dgesvd(char*,char*,int*,int*,double*,int*,double*,double*,int*,double*,int*,double*,int*,int*);
|
||||
void dgeqrf(int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dorgqr(int*,int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgelqf(int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dorglq(int*,int*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgges(char*,char*,char*,void*,int*,double*,int*,double*,int*,int*,double*,double*,double*,double*,int*,double*,int*,double*,int*,void*,int*);
|
||||
void dtgsen(int*,void*,void*,void*,int*,double*,int*,double*,int*,double*,double*,double*,double*,int*,double*,int*,int*,double*,double*,double*,double*,int*,int*,int*,int*);
|
||||
void dtgexc(void*,void*,int*,double*,int*,double*,int*,double*,int*,double*,int*,int*,int*,double*,int*,int*);
|
||||
void dsyev(char*,char*,int*,double*,int*,double*,double*,int*,int*);
|
||||
void dgeev(char*,char*,int*,double*,int*,double*,double*,double*,int*,double*,int*,double*,int*,int*);
|
||||
void dpotrf(char*,int*,double*,int*,int*);
|
||||
void dpotri(char*,int*,double*,int*,int*);
|
||||
void dgeqp3(int*,int*,double*,int*,int*,double*,double*,int*,int*);
|
||||
void dtrtri(char*,char*,int*,double*,int*,int*);
|
||||
void dgetri(int*,double*,int*,int*,double*,int*,int*);
|
||||
void dormqr(char*,char*,int*,int*,int*,double*,int*,double*,double*,int*,double*,int*,int*);
|
||||
void dgesv(int*,int*,double*,int*,int*,double*,int*,int*);
|
||||
/*******************************************************************************/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1 +1 @@
|
|||
#include "bmatrix_blas_lapack.c"
|
||||
#include "bmatrix_blas_lapack.c"
|
||||
|
|
|
@ -1,67 +1,67 @@
|
|||
|
||||
#ifndef __BMATRIX__
|
||||
#define __BMATRIX__
|
||||
|
||||
#include "prcsn.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
/* Unary Operators */
|
||||
int bNegative(PRECISION *x, PRECISION *y, int m);
|
||||
int bAbs(PRECISION *x, PRECISION *y, int m);
|
||||
int bTranspose(PRECISION *x, PRECISION *y, int m, int n, int t);
|
||||
int bTransposeInPlace(PRECISION *x, int m);
|
||||
|
||||
/* Addition */
|
||||
int bAdd(PRECISION *x, PRECISION *y, PRECISION *z, int m);
|
||||
int bSubtract(PRECISION *x, PRECISION *y, PRECISION *z, int m);
|
||||
int bLinearUpdateScalar(PRECISION *x, PRECISION *y, PRECISION a, int m);
|
||||
int bLinearCombination(PRECISION *x, PRECISION a, PRECISION *y, PRECISION b, PRECISION *z, int m);
|
||||
int bMatrixAdd(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
int bMatrixSubtract(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
int bMatrixLinearCombination(PRECISION *x, PRECISION a, PRECISION *y, PRECISION b,PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
|
||||
/* Multiplication */
|
||||
int bMultiply(PRECISION *x, PRECISION *y, PRECISION s, int m);
|
||||
int bMatrixMultiply(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int p, int xt, int yt, int zt);
|
||||
|
||||
/* LU Decomposition */
|
||||
int bLU(int *p, PRECISION *x, int m, int n, int xt);
|
||||
int bSolveTriangular(PRECISION *x, PRECISION *b, int m, int n,int u, int xt, int bt);
|
||||
int bSolveUnitTriangular(PRECISION *x, PRECISION *b, int m, int n, int u, int xt, int bt);
|
||||
|
||||
/* QR Decompositions */
|
||||
int bQR(PRECISION *Q, PRECISION *R, PRECISION *X, int m, int n, int q, int qt, int rt, int xt);
|
||||
|
||||
/* Singular Value Decomposition */
|
||||
int bSVD(PRECISION *U, PRECISION *d, PRECISION *V, PRECISION *A, int m, int n, int ut, int vt, int at);
|
||||
int bSVD_new(PRECISION *U, PRECISION *d, PRECISION *V, PRECISION *A, int m, int n, int ut, int vt, int at, int compact);
|
||||
|
||||
/* Generalize Schur Decomposition */
|
||||
int bQZ_real(PRECISION *Q, PRECISION *Z, PRECISION *S, PRECISION *T, PRECISION *A, PRECISION *B, int n, int qt, int zt, int st, int tt, int at, int bt,
|
||||
PRECISION *alpha_r, PRECISION *alpha_i, PRECISION *beta);
|
||||
|
||||
/* Cholesky Decompositions */
|
||||
int bCholesky(PRECISION *X, int m, int u, int t);
|
||||
|
||||
/* Permutation Routines */
|
||||
int bPermutationMultiply(int *p, PRECISION *y, int m, int n, int q, int pt, int yt);
|
||||
int bPermutation(PRECISION *x, int *p, int m, int q, int t);
|
||||
|
||||
/* Tensor Calculus */
|
||||
int bMatrixTensor(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int r, int s, int xt, int yt, int zt);
|
||||
int bVectorTensor(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n);
|
||||
|
||||
//int bQRPivot_R(PRECISION *R, int *p, int m, int n);
|
||||
//int bQRPivot_QR(PRECISION *Q, PRECISION *R, int *p, int m, int n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#ifndef __BMATRIX__
|
||||
#define __BMATRIX__
|
||||
|
||||
#include "prcsn.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
/* Unary Operators */
|
||||
int bNegative(PRECISION *x, PRECISION *y, int m);
|
||||
int bAbs(PRECISION *x, PRECISION *y, int m);
|
||||
int bTranspose(PRECISION *x, PRECISION *y, int m, int n, int t);
|
||||
int bTransposeInPlace(PRECISION *x, int m);
|
||||
|
||||
/* Addition */
|
||||
int bAdd(PRECISION *x, PRECISION *y, PRECISION *z, int m);
|
||||
int bSubtract(PRECISION *x, PRECISION *y, PRECISION *z, int m);
|
||||
int bLinearUpdateScalar(PRECISION *x, PRECISION *y, PRECISION a, int m);
|
||||
int bLinearCombination(PRECISION *x, PRECISION a, PRECISION *y, PRECISION b, PRECISION *z, int m);
|
||||
int bMatrixAdd(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
int bMatrixSubtract(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
int bMatrixLinearCombination(PRECISION *x, PRECISION a, PRECISION *y, PRECISION b,PRECISION *z, int m, int n, int xt, int yt, int zt);
|
||||
|
||||
/* Multiplication */
|
||||
int bMultiply(PRECISION *x, PRECISION *y, PRECISION s, int m);
|
||||
int bMatrixMultiply(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int p, int xt, int yt, int zt);
|
||||
|
||||
/* LU Decomposition */
|
||||
int bLU(int *p, PRECISION *x, int m, int n, int xt);
|
||||
int bSolveTriangular(PRECISION *x, PRECISION *b, int m, int n,int u, int xt, int bt);
|
||||
int bSolveUnitTriangular(PRECISION *x, PRECISION *b, int m, int n, int u, int xt, int bt);
|
||||
|
||||
/* QR Decompositions */
|
||||
int bQR(PRECISION *Q, PRECISION *R, PRECISION *X, int m, int n, int q, int qt, int rt, int xt);
|
||||
|
||||
/* Singular Value Decomposition */
|
||||
int bSVD(PRECISION *U, PRECISION *d, PRECISION *V, PRECISION *A, int m, int n, int ut, int vt, int at);
|
||||
int bSVD_new(PRECISION *U, PRECISION *d, PRECISION *V, PRECISION *A, int m, int n, int ut, int vt, int at, int compact);
|
||||
|
||||
/* Generalize Schur Decomposition */
|
||||
int bQZ_real(PRECISION *Q, PRECISION *Z, PRECISION *S, PRECISION *T, PRECISION *A, PRECISION *B, int n, int qt, int zt, int st, int tt, int at, int bt,
|
||||
PRECISION *alpha_r, PRECISION *alpha_i, PRECISION *beta);
|
||||
|
||||
/* Cholesky Decompositions */
|
||||
int bCholesky(PRECISION *X, int m, int u, int t);
|
||||
|
||||
/* Permutation Routines */
|
||||
int bPermutationMultiply(int *p, PRECISION *y, int m, int n, int q, int pt, int yt);
|
||||
int bPermutation(PRECISION *x, int *p, int m, int q, int t);
|
||||
|
||||
/* Tensor Calculus */
|
||||
int bMatrixTensor(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n, int r, int s, int xt, int yt, int zt);
|
||||
int bVectorTensor(PRECISION *x, PRECISION *y, PRECISION *z, int m, int n);
|
||||
|
||||
//int bQRPivot_R(PRECISION *R, int *p, int m, int n);
|
||||
//int bQRPivot_QR(PRECISION *Q, PRECISION *R, int *p, int m, int n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,18 +1,18 @@
|
|||
|
||||
/* Matrix error constants */
|
||||
|
||||
#define NO_ERR 0x00000000
|
||||
|
||||
#define MEM_ERR 0x00000001
|
||||
#define SIZE_ERR 0x00000002
|
||||
#define NULL_ERR 0x00000004
|
||||
#define SING_ERR 0x00000008
|
||||
#define ITER_ERR 0x00000010
|
||||
#define POSDEF_ERR 0x00000020
|
||||
#define FLOAT_ERR 0x00000040
|
||||
#define ARG_ERR 0x00000080
|
||||
#define NOT_IMPLEMENTED_ERR 0x00000100
|
||||
#define BLAS_LAPACK_ERR 0x00000200
|
||||
|
||||
#define ALL_ERRORS 0x000001FF
|
||||
|
||||
|
||||
/* Matrix error constants */
|
||||
|
||||
#define NO_ERR 0x00000000
|
||||
|
||||
#define MEM_ERR 0x00000001
|
||||
#define SIZE_ERR 0x00000002
|
||||
#define NULL_ERR 0x00000004
|
||||
#define SING_ERR 0x00000008
|
||||
#define ITER_ERR 0x00000010
|
||||
#define POSDEF_ERR 0x00000020
|
||||
#define FLOAT_ERR 0x00000040
|
||||
#define ARG_ERR 0x00000080
|
||||
#define NOT_IMPLEMENTED_ERR 0x00000100
|
||||
#define BLAS_LAPACK_ERR 0x00000200
|
||||
|
||||
#define ALL_ERRORS 0x000001FF
|
||||
|
||||
|
|
|
@ -1,35 +1,35 @@
|
|||
|
||||
/*
|
||||
Defines the precision to be used
|
||||
*/
|
||||
|
||||
#ifndef __PRECISION_H__
|
||||
#define __PRECISION_H__
|
||||
|
||||
#include <float.h>
|
||||
|
||||
/********** double precision **********/
|
||||
#define PRECISION double
|
||||
#define MACHINE_EPSILON 1.11E-16
|
||||
#define SQRT_MACHINE_EPSILON 1.06E-08
|
||||
#define PRECISION_SIZE 8
|
||||
#define PRECISION_SHIFT 3
|
||||
#define PRECISION_WORD qword
|
||||
#define MINUS_INFINITY -1.0E300
|
||||
#define PLUS_INFINITY 1.0E300
|
||||
//#define MINUS_INFINITY -DBL_MAX
|
||||
//#define PLUS_INFINITY DBL_MAX
|
||||
/**************************************/
|
||||
|
||||
/********** single precision **********
|
||||
#define PRECISION float
|
||||
#define MACHINE_EPSILON 5.97E-08
|
||||
#define SQRT_MACHINE_EPSILON 2.45E-04
|
||||
#define PRECISION_SIZE 4
|
||||
#define PRECISION_SHIFT 2
|
||||
#define PRECISION_WORD dword
|
||||
#define MINUS_INFINITY -FLT_MAX
|
||||
#define PLUS_INFINITY FLT_MAX
|
||||
/**************************************/
|
||||
|
||||
#endif
|
||||
|
||||
/*
|
||||
Defines the precision to be used
|
||||
*/
|
||||
|
||||
#ifndef __PRECISION_H__
|
||||
#define __PRECISION_H__
|
||||
|
||||
#include <float.h>
|
||||
|
||||
/********** double precision **********/
|
||||
#define PRECISION double
|
||||
#define MACHINE_EPSILON 1.11E-16
|
||||
#define SQRT_MACHINE_EPSILON 1.06E-08
|
||||
#define PRECISION_SIZE 8
|
||||
#define PRECISION_SHIFT 3
|
||||
#define PRECISION_WORD qword
|
||||
#define MINUS_INFINITY -1.0E300
|
||||
#define PLUS_INFINITY 1.0E300
|
||||
//#define MINUS_INFINITY -DBL_MAX
|
||||
//#define PLUS_INFINITY DBL_MAX
|
||||
/**************************************/
|
||||
|
||||
/********** single precision **********
|
||||
#define PRECISION float
|
||||
#define MACHINE_EPSILON 5.97E-08
|
||||
#define SQRT_MACHINE_EPSILON 2.45E-04
|
||||
#define PRECISION_SIZE 4
|
||||
#define PRECISION_SHIFT 2
|
||||
#define PRECISION_WORD dword
|
||||
#define MINUS_INFINITY -FLT_MAX
|
||||
#define PLUS_INFINITY FLT_MAX
|
||||
/**************************************/
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,45 +1,45 @@
|
|||
|
||||
#ifndef __TZ2DW__
|
||||
#define __TZ2DW__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
// flags and defines
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
#define square(x) ((x)*(x))
|
||||
|
||||
// matrix and vector structures
|
||||
typedef struct
|
||||
{
|
||||
double *M;
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct
|
||||
{
|
||||
double *v;
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
|
||||
|
||||
|
||||
// memory management
|
||||
#define tzMalloc(elt_count,type) (type *)malloc((elt_count)*sizeof(type))
|
||||
#define tzDestroy(x) {if (x) { free((x)); (x) = NULL; }}
|
||||
|
||||
// i/o
|
||||
#define tzFclose(x) {if (x) { fclose(x); (x)=(FILE *)NULL;}}
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __TZ2DW__
|
||||
#define __TZ2DW__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
// flags and defines
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
#define square(x) ((x)*(x))
|
||||
|
||||
// matrix and vector structures
|
||||
typedef struct
|
||||
{
|
||||
double *M;
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct
|
||||
{
|
||||
double *v;
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
|
||||
|
||||
|
||||
// memory management
|
||||
#define tzMalloc(elt_count,type) (type *)malloc((elt_count)*sizeof(type))
|
||||
#define tzDestroy(x) {if (x) { free((x)); (x) = NULL; }}
|
||||
|
||||
// i/o
|
||||
#define tzFclose(x) {if (x) { fclose(x); (x)=(FILE *)NULL;}}
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,14 +1,14 @@
|
|||
|
||||
#ifndef __SORT_MATRICES__
|
||||
#define __SORT_MATRICES__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
TVector SortVectorAscending(TVector x, TVector y);
|
||||
TVector SortVectorDescending(TVector x, TVector y);
|
||||
TMatrix SortMatrixRowsAscending(TMatrix X, TMatrix Y, int j);
|
||||
TMatrix SortMatrixRowsDescending(TMatrix X, TMatrix Y, int j);
|
||||
TMatrix SortMatrixColumnsAscending(TMatrix X, TMatrix Y, int i);
|
||||
TMatrix SortMatrixColumnsDescending(TMatrix X, TMatrix Y, int i);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __SORT_MATRICES__
|
||||
#define __SORT_MATRICES__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
TVector SortVectorAscending(TVector x, TVector y);
|
||||
TVector SortVectorDescending(TVector x, TVector y);
|
||||
TMatrix SortMatrixRowsAscending(TMatrix X, TMatrix Y, int j);
|
||||
TMatrix SortMatrixRowsDescending(TMatrix X, TMatrix Y, int j);
|
||||
TMatrix SortMatrixColumnsAscending(TMatrix X, TMatrix Y, int i);
|
||||
TMatrix SortMatrixColumnsDescending(TMatrix X, TMatrix Y, int i);
|
||||
|
||||
#endif
|
||||
|
|
|
@ -1,418 +1,418 @@
|
|||
|
||||
#include "spherical.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_matrix_rand.h"
|
||||
#include "dw_error.h"
|
||||
#include "dw_ascii.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define SPHERICAL_GAUSSIAN 1
|
||||
#define SPHERICAL_UNIFORM 2
|
||||
#define SPHERICAL_POWER 3
|
||||
#define SPHERICAL_TRUNCATED_POWER 4
|
||||
#define SPHERICAL_TABLE 5
|
||||
#define SPHERICAL_TRUNCATED_GAUSSIAN 6
|
||||
|
||||
#define PI 3.141592653589793
|
||||
|
||||
static int SPHERICAL_TYPE=0;
|
||||
static int SPHERICAL_DIM=0;
|
||||
static PRECISION SPHERICAL_CONSTANT=0.0;
|
||||
|
||||
static PRECISION SPHERICAL_POWER_EXP=0.0;
|
||||
static PRECISION SPHERICAL_LOWER_TRUNCATE=0.0;
|
||||
static PRECISION SPHERICAL_UPPER_TRUNCATE=0.0;
|
||||
|
||||
static PRECISION *SPHERICAL_TABLE_VALUES=(PRECISION*)NULL;
|
||||
static int SPHERICAL_TABLE_LENGTH=0;
|
||||
|
||||
/*
|
||||
Returns ln(exp(a) + exp(b)) computed to avoid overflow. If
|
||||
a = ln(c) and b = ln(d), as is usually the case, then the
|
||||
routine returns ln(c + d).
|
||||
|
||||
*/
|
||||
static PRECISION AddLogs_static(PRECISION a, PRECISION b)
|
||||
{
|
||||
return (a > b) ? a + log(1.0 + exp(b-a)) : b + log(exp(a-b) + 1.0);
|
||||
}
|
||||
|
||||
char* SphericalType(void)
|
||||
{
|
||||
static char buffer[128];
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
return "Gaussian";
|
||||
case SPHERICAL_UNIFORM:
|
||||
return "Uniform";
|
||||
case SPHERICAL_POWER:
|
||||
sprintf(buffer,"Power(%lg)",SPHERICAL_POWER_EXP);
|
||||
return buffer;
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
sprintf(buffer,"TruncatedPower(%lg,%lg)",SPHERICAL_POWER_EXP,SPHERICAL_LOWER_TRUNCATE);
|
||||
return buffer;
|
||||
case SPHERICAL_TABLE:
|
||||
sprintf(buffer,"Table(%d)",SPHERICAL_TABLE_LENGTH);
|
||||
return buffer;
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
sprintf(buffer,"TruncatedGaussian(%lg,%lg)",SPHERICAL_LOWER_TRUNCATE,SPHERICAL_UPPER_TRUNCATE);
|
||||
return buffer;
|
||||
default:
|
||||
return "Spherical type not set";
|
||||
}
|
||||
}
|
||||
|
||||
void SetupSpherical_Gaussian(int n)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_GAUSSIAN;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=-0.5*n*log(2.0*PI);
|
||||
}
|
||||
|
||||
void SetupSpherical_TruncatedGaussian(int n, PRECISION r1, PRECISION r2)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_TRUNCATED_GAUSSIAN;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=-0.5*n*log(2.0*PI) - log(dw_chi_square_cdf(r2*r2,n) - dw_chi_square_cdf(r1*r1,n));
|
||||
SPHERICAL_LOWER_TRUNCATE=r1;
|
||||
SPHERICAL_UPPER_TRUNCATE=r2;
|
||||
}
|
||||
|
||||
void SetupSpherical_Uniform(int n)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_UNIFORM;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*n) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
}
|
||||
|
||||
/*
|
||||
See the function PowerUnitBall() below for the description of the
|
||||
distribution.
|
||||
*/
|
||||
void SetupSpherical_Power(int n, PRECISION k)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_POWER;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*k) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
SPHERICAL_POWER_EXP=k;
|
||||
}
|
||||
|
||||
void SetupSpherical_TruncatedPower(int n, PRECISION k, PRECISION a)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_TRUNCATED_POWER;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*k/(1.0 - pow(a,k))) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
SPHERICAL_POWER_EXP=k;
|
||||
SPHERICAL_LOWER_TRUNCATE=a;
|
||||
}
|
||||
|
||||
void SetupSpherical_Table(int n, PRECISION *table, int m)
|
||||
{
|
||||
int i;
|
||||
SPHERICAL_TYPE=SPHERICAL_TABLE;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
if (SPHERICAL_TABLE_VALUES) free(SPHERICAL_TABLE_VALUES);
|
||||
SPHERICAL_TABLE_VALUES=(PRECISION*)malloc((m+1)*sizeof(PRECISION));
|
||||
SPHERICAL_TABLE_LENGTH=m;
|
||||
memcpy(SPHERICAL_TABLE_VALUES,table,(m+1)*sizeof(PRECISION));
|
||||
|
||||
// Check
|
||||
if (SPHERICAL_TABLE_VALUES[0] != 0.0)
|
||||
{
|
||||
printf("First entry of inverse cumulative spherical table must be zero\n");
|
||||
exit(0);
|
||||
}
|
||||
for (i=1; i < SPHERICAL_TABLE_LENGTH; i++)
|
||||
if (SPHERICAL_TABLE_VALUES[i-1] >= SPHERICAL_TABLE_VALUES[i])
|
||||
{
|
||||
printf("Inverse cumulative spherical table must be strictly increasing\n");
|
||||
for (i=0; i <= m; i++) printf("%lf\n",table[i]);
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
PRECISION DrawSpherical(TVector x)
|
||||
{
|
||||
PRECISION r;
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
dw_NormalVector(x);
|
||||
return Norm(x);
|
||||
case SPHERICAL_UNIFORM:
|
||||
return UniformUnitBall(x);
|
||||
case SPHERICAL_POWER:
|
||||
return PowerUnitBall(x,SPHERICAL_POWER_EXP);
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
return TruncatedPowerUnitBall(x,SPHERICAL_POWER_EXP,SPHERICAL_LOWER_TRUNCATE);
|
||||
case SPHERICAL_TABLE:
|
||||
return SphericalTable(x,SPHERICAL_TABLE_VALUES,SPHERICAL_TABLE_LENGTH);
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
do
|
||||
{
|
||||
dw_NormalVector(x);
|
||||
r=Norm(x);
|
||||
}
|
||||
while ((r < SPHERICAL_LOWER_TRUNCATE) || (SPHERICAL_UPPER_TRUNCATE < r));
|
||||
return r;
|
||||
default:
|
||||
swz_fprintf_err("Unknown spherical type\n");
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
PRECISION LogSphericalDensity(PRECISION r)
|
||||
{
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
return -0.5*r*r + SPHERICAL_CONSTANT;
|
||||
case SPHERICAL_UNIFORM:
|
||||
return (r > 1.0) ? MINUS_INFINITY : SPHERICAL_CONSTANT;
|
||||
case SPHERICAL_POWER:
|
||||
return (r > 1.0) ? MINUS_INFINITY : SPHERICAL_CONSTANT + (SPHERICAL_POWER_EXP - SPHERICAL_DIM)*log(r);
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
return ((r < SPHERICAL_LOWER_TRUNCATE) || (r > 1.0)) ? MINUS_INFINITY
|
||||
: SPHERICAL_CONSTANT + (SPHERICAL_POWER_EXP - SPHERICAL_DIM)*log(r);
|
||||
case SPHERICAL_TABLE:
|
||||
return SPHERICAL_CONSTANT - (SPHERICAL_DIM - 1)*log(r) + LogSphericalTableDensity(r,SPHERICAL_TABLE_VALUES,SPHERICAL_TABLE_LENGTH);
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
return ((r < SPHERICAL_LOWER_TRUNCATE) || (r > SPHERICAL_UPPER_TRUNCATE)) ? MINUS_INFINITY : -0.5*r*r + SPHERICAL_CONSTANT;
|
||||
default:
|
||||
swz_fprintf_err("Unknown spherical type\n");
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
The ith entry of the returned vector is the cumulative density evaluated at
|
||||
(i + 1) * max / bins. The integer cum_bins controls the accuracy of the
|
||||
estimation. The larger the value, the more accuate the estimate.
|
||||
*/
|
||||
TVector SphericalCumulativeDensity(PRECISION max, int bins, int cum_bins)
|
||||
{
|
||||
TVector cumulative=CreateVector(bins);
|
||||
int i, j;
|
||||
PRECISION r, z, inc=max/(PRECISION)bins, cum_inc=inc/(PRECISION)cum_bins;
|
||||
for (i=0; i < bins; i++)
|
||||
{
|
||||
for (r=(PRECISION)i*inc + 0.5*cum_inc, z=MINUS_INFINITY, j=0; j < cum_bins; r+=cum_inc, j++)
|
||||
z=AddLogs_static(z,LogSphericalDensity(r) + (SPHERICAL_DIM - 1)*log(r));
|
||||
ElementV(cumulative,i)=exp(z - log(0.5) + 0.5*SPHERICAL_DIM*log(PI) - dw_log_gamma(0.5*SPHERICAL_DIM) + log(cum_inc));
|
||||
}
|
||||
for (i=1; i < bins; i++)
|
||||
ElementV(cumulative,i)+=ElementV(cumulative,i-1);
|
||||
return cumulative;
|
||||
}
|
||||
|
||||
void TestSpherical(FILE *f, char *filename, PRECISION max)
|
||||
{
|
||||
TMatrix cumulative;
|
||||
TVector x;
|
||||
int i, j, bins=1000, cum_bins=20, ndraws=1000000;
|
||||
PRECISION r, z, inc=max/(PRECISION)bins, cum_inc=inc/(PRECISION)cum_bins, s=1.0/(PRECISION)ndraws;
|
||||
FILE *f_out;
|
||||
|
||||
cumulative=CreateMatrix(bins,3);
|
||||
for (i=0; i < bins; i++)
|
||||
{
|
||||
ElementM(cumulative,i,0)=(PRECISION)(i+1)*inc;
|
||||
for (r=(PRECISION)i*inc + 0.5*cum_inc, z=MINUS_INFINITY, j=0; j < cum_bins; r+=cum_inc, j++)
|
||||
z=AddLogs_static(z,LogSphericalDensity(r) + (SPHERICAL_DIM - 1)*log(r));
|
||||
ElementM(cumulative,i,1)=exp(z - log(0.5) + 0.5*SPHERICAL_DIM*log(PI) - dw_log_gamma(0.5*SPHERICAL_DIM) + log(cum_inc));
|
||||
ElementM(cumulative,i,2)=0.0;
|
||||
}
|
||||
|
||||
x=CreateVector(SPHERICAL_DIM);
|
||||
for (i=ndraws; i > 0; i--)
|
||||
{
|
||||
r=DrawSpherical(x);
|
||||
if ((j=(int)floor(r/inc)) < bins)
|
||||
ElementM(cumulative,j,2)+=s;
|
||||
}
|
||||
FreeVector(x);
|
||||
|
||||
for (i=1; i < bins; i++)
|
||||
{
|
||||
ElementM(cumulative,i,1)+=ElementM(cumulative,i-1,1);
|
||||
ElementM(cumulative,i,2)+=ElementM(cumulative,i-1,2);
|
||||
}
|
||||
|
||||
f_out=!f ? dw_CreateTextFile(filename) : f;
|
||||
dw_PrintMatrix(f_out,cumulative,"%lf,");
|
||||
if (!f) fclose(f_out);
|
||||
FreeMatrix(cumulative);
|
||||
}
|
||||
#undef PI
|
||||
|
||||
#undef SPHERICAL_GAUSSIAN
|
||||
#undef SPHERICAL_UNIFORM
|
||||
#undef SPHERICAL_POWER
|
||||
#undef SPHERICAL_TURNCATED_POWER
|
||||
#undef SPHERICAL_TRUNCATED_GAUSSIAN
|
||||
/*******************************************************************************/
|
||||
/*******************************************************************************/
|
||||
/*******************************************************************************/
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m dimensional solid unit sphere.
|
||||
|
||||
Returns:
|
||||
Upon success, returns the norm of x, upon failure returns negative value.
|
||||
|
||||
Notes:
|
||||
The vector is drawn by drawing a m-vector from the standard normal
|
||||
distribution and a real number u from the uniform distribution on [0,1], and
|
||||
normalizing the vector so its length equal to u^(1/m).
|
||||
*/
|
||||
PRECISION UniformUnitBall(TVector x)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/DimV(x)))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : n-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the distribution
|
||||
|
||||
0.5 * k * Gamma(n/2) * pi^(-n/2) * norm(x)^(k-n)
|
||||
|
||||
Returns:
|
||||
norm(x) upon success and a negative value upon failure.
|
||||
|
||||
Notes:
|
||||
If x is obtained by drawing y from the standard n-dimensional Gaussian
|
||||
distribtuion and r from the distribution on [0,1] with density
|
||||
|
||||
k * r^(k-1)
|
||||
|
||||
Since the cumulative density of r is
|
||||
|
||||
r^k
|
||||
|
||||
a draw of r can be obtained by drawing u from the uniform on [0,1] and
|
||||
defining r = u^(1/k). This assumes that k > 0.
|
||||
*/
|
||||
PRECISION PowerUnitBall(TVector x, PRECISION k)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/k))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : n-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the distribution
|
||||
|
||||
0.5 * k * Gamma(n/2) * pi^(-n/2) * norm(x)^(k-n) / (1 - a^k)
|
||||
|
||||
Returns:
|
||||
norm(x) upon success and a negative value upon failure.
|
||||
|
||||
Notes:
|
||||
If x is obtained by drawing y from the standard n-dimensional Gaussian
|
||||
distribtuion and r from the distribution on [a,1] with density
|
||||
|
||||
k * r^(k-1) / (1 - a^k)
|
||||
|
||||
Since the cumulative density of r is
|
||||
|
||||
(r^k - a^k) / (1 - a^k)
|
||||
|
||||
a draw of r can be obtained by drawing u from the uniform on [0,1] and
|
||||
defining r = (u(1-a^k) + a^k)^(1/k). This assumes that k > 0.
|
||||
*/
|
||||
PRECISION TruncatedPowerUnitBall(TVector x, PRECISION k, PRECISION a)
|
||||
{
|
||||
PRECISION r, s, t;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
t=pow(a,k);
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd()*(1.0 - t) + t,1.0/k))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
PRECISION SphericalTable(TVector x, PRECISION *table, int m)
|
||||
{
|
||||
PRECISION r, s;
|
||||
int i, j;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
j=(int)floor(dw_uniform_rnd()*(PRECISION)m);
|
||||
r=(j < m) ? table[j] + dw_uniform_rnd()*(table[j+1] - table[j]) : table[m];
|
||||
ProductSV(x,r/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
PRECISION LogSphericalTableDensity(PRECISION r, PRECISION *table, int m)
|
||||
{
|
||||
int min=0, max=m, mid;
|
||||
if (r > table[m]) return MINUS_INFINITY;
|
||||
while (max - min > 1)
|
||||
if (r > table[mid=(min + max)/2])
|
||||
min=mid;
|
||||
else
|
||||
max=mid;
|
||||
return -log((PRECISION)m*(table[max] - table[min]));
|
||||
}
|
||||
|
||||
|
||||
#include "spherical.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_matrix_rand.h"
|
||||
#include "dw_error.h"
|
||||
#include "dw_ascii.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define SPHERICAL_GAUSSIAN 1
|
||||
#define SPHERICAL_UNIFORM 2
|
||||
#define SPHERICAL_POWER 3
|
||||
#define SPHERICAL_TRUNCATED_POWER 4
|
||||
#define SPHERICAL_TABLE 5
|
||||
#define SPHERICAL_TRUNCATED_GAUSSIAN 6
|
||||
|
||||
#define PI 3.141592653589793
|
||||
|
||||
static int SPHERICAL_TYPE=0;
|
||||
static int SPHERICAL_DIM=0;
|
||||
static PRECISION SPHERICAL_CONSTANT=0.0;
|
||||
|
||||
static PRECISION SPHERICAL_POWER_EXP=0.0;
|
||||
static PRECISION SPHERICAL_LOWER_TRUNCATE=0.0;
|
||||
static PRECISION SPHERICAL_UPPER_TRUNCATE=0.0;
|
||||
|
||||
static PRECISION *SPHERICAL_TABLE_VALUES=(PRECISION*)NULL;
|
||||
static int SPHERICAL_TABLE_LENGTH=0;
|
||||
|
||||
/*
|
||||
Returns ln(exp(a) + exp(b)) computed to avoid overflow. If
|
||||
a = ln(c) and b = ln(d), as is usually the case, then the
|
||||
routine returns ln(c + d).
|
||||
|
||||
*/
|
||||
static PRECISION AddLogs_static(PRECISION a, PRECISION b)
|
||||
{
|
||||
return (a > b) ? a + log(1.0 + exp(b-a)) : b + log(exp(a-b) + 1.0);
|
||||
}
|
||||
|
||||
char* SphericalType(void)
|
||||
{
|
||||
static char buffer[128];
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
return "Gaussian";
|
||||
case SPHERICAL_UNIFORM:
|
||||
return "Uniform";
|
||||
case SPHERICAL_POWER:
|
||||
sprintf(buffer,"Power(%lg)",SPHERICAL_POWER_EXP);
|
||||
return buffer;
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
sprintf(buffer,"TruncatedPower(%lg,%lg)",SPHERICAL_POWER_EXP,SPHERICAL_LOWER_TRUNCATE);
|
||||
return buffer;
|
||||
case SPHERICAL_TABLE:
|
||||
sprintf(buffer,"Table(%d)",SPHERICAL_TABLE_LENGTH);
|
||||
return buffer;
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
sprintf(buffer,"TruncatedGaussian(%lg,%lg)",SPHERICAL_LOWER_TRUNCATE,SPHERICAL_UPPER_TRUNCATE);
|
||||
return buffer;
|
||||
default:
|
||||
return "Spherical type not set";
|
||||
}
|
||||
}
|
||||
|
||||
void SetupSpherical_Gaussian(int n)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_GAUSSIAN;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=-0.5*n*log(2.0*PI);
|
||||
}
|
||||
|
||||
void SetupSpherical_TruncatedGaussian(int n, PRECISION r1, PRECISION r2)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_TRUNCATED_GAUSSIAN;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=-0.5*n*log(2.0*PI) - log(dw_chi_square_cdf(r2*r2,n) - dw_chi_square_cdf(r1*r1,n));
|
||||
SPHERICAL_LOWER_TRUNCATE=r1;
|
||||
SPHERICAL_UPPER_TRUNCATE=r2;
|
||||
}
|
||||
|
||||
void SetupSpherical_Uniform(int n)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_UNIFORM;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*n) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
}
|
||||
|
||||
/*
|
||||
See the function PowerUnitBall() below for the description of the
|
||||
distribution.
|
||||
*/
|
||||
void SetupSpherical_Power(int n, PRECISION k)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_POWER;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*k) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
SPHERICAL_POWER_EXP=k;
|
||||
}
|
||||
|
||||
void SetupSpherical_TruncatedPower(int n, PRECISION k, PRECISION a)
|
||||
{
|
||||
SPHERICAL_TYPE=SPHERICAL_TRUNCATED_POWER;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5*k/(1.0 - pow(a,k))) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
SPHERICAL_POWER_EXP=k;
|
||||
SPHERICAL_LOWER_TRUNCATE=a;
|
||||
}
|
||||
|
||||
void SetupSpherical_Table(int n, PRECISION *table, int m)
|
||||
{
|
||||
int i;
|
||||
SPHERICAL_TYPE=SPHERICAL_TABLE;
|
||||
SPHERICAL_DIM=n;
|
||||
SPHERICAL_CONSTANT=log(0.5) + dw_log_gamma(0.5*n) - 0.5*n*log(PI);
|
||||
if (SPHERICAL_TABLE_VALUES) free(SPHERICAL_TABLE_VALUES);
|
||||
SPHERICAL_TABLE_VALUES=(PRECISION*)malloc((m+1)*sizeof(PRECISION));
|
||||
SPHERICAL_TABLE_LENGTH=m;
|
||||
memcpy(SPHERICAL_TABLE_VALUES,table,(m+1)*sizeof(PRECISION));
|
||||
|
||||
// Check
|
||||
if (SPHERICAL_TABLE_VALUES[0] != 0.0)
|
||||
{
|
||||
printf("First entry of inverse cumulative spherical table must be zero\n");
|
||||
exit(0);
|
||||
}
|
||||
for (i=1; i < SPHERICAL_TABLE_LENGTH; i++)
|
||||
if (SPHERICAL_TABLE_VALUES[i-1] >= SPHERICAL_TABLE_VALUES[i])
|
||||
{
|
||||
printf("Inverse cumulative spherical table must be strictly increasing\n");
|
||||
for (i=0; i <= m; i++) printf("%lf\n",table[i]);
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
PRECISION DrawSpherical(TVector x)
|
||||
{
|
||||
PRECISION r;
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
dw_NormalVector(x);
|
||||
return Norm(x);
|
||||
case SPHERICAL_UNIFORM:
|
||||
return UniformUnitBall(x);
|
||||
case SPHERICAL_POWER:
|
||||
return PowerUnitBall(x,SPHERICAL_POWER_EXP);
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
return TruncatedPowerUnitBall(x,SPHERICAL_POWER_EXP,SPHERICAL_LOWER_TRUNCATE);
|
||||
case SPHERICAL_TABLE:
|
||||
return SphericalTable(x,SPHERICAL_TABLE_VALUES,SPHERICAL_TABLE_LENGTH);
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
do
|
||||
{
|
||||
dw_NormalVector(x);
|
||||
r=Norm(x);
|
||||
}
|
||||
while ((r < SPHERICAL_LOWER_TRUNCATE) || (SPHERICAL_UPPER_TRUNCATE < r));
|
||||
return r;
|
||||
default:
|
||||
swz_fprintf_err("Unknown spherical type\n");
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
PRECISION LogSphericalDensity(PRECISION r)
|
||||
{
|
||||
switch (SPHERICAL_TYPE)
|
||||
{
|
||||
case SPHERICAL_GAUSSIAN:
|
||||
return -0.5*r*r + SPHERICAL_CONSTANT;
|
||||
case SPHERICAL_UNIFORM:
|
||||
return (r > 1.0) ? MINUS_INFINITY : SPHERICAL_CONSTANT;
|
||||
case SPHERICAL_POWER:
|
||||
return (r > 1.0) ? MINUS_INFINITY : SPHERICAL_CONSTANT + (SPHERICAL_POWER_EXP - SPHERICAL_DIM)*log(r);
|
||||
case SPHERICAL_TRUNCATED_POWER:
|
||||
return ((r < SPHERICAL_LOWER_TRUNCATE) || (r > 1.0)) ? MINUS_INFINITY
|
||||
: SPHERICAL_CONSTANT + (SPHERICAL_POWER_EXP - SPHERICAL_DIM)*log(r);
|
||||
case SPHERICAL_TABLE:
|
||||
return SPHERICAL_CONSTANT - (SPHERICAL_DIM - 1)*log(r) + LogSphericalTableDensity(r,SPHERICAL_TABLE_VALUES,SPHERICAL_TABLE_LENGTH);
|
||||
case SPHERICAL_TRUNCATED_GAUSSIAN:
|
||||
return ((r < SPHERICAL_LOWER_TRUNCATE) || (r > SPHERICAL_UPPER_TRUNCATE)) ? MINUS_INFINITY : -0.5*r*r + SPHERICAL_CONSTANT;
|
||||
default:
|
||||
swz_fprintf_err("Unknown spherical type\n");
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
The ith entry of the returned vector is the cumulative density evaluated at
|
||||
(i + 1) * max / bins. The integer cum_bins controls the accuracy of the
|
||||
estimation. The larger the value, the more accuate the estimate.
|
||||
*/
|
||||
TVector SphericalCumulativeDensity(PRECISION max, int bins, int cum_bins)
|
||||
{
|
||||
TVector cumulative=CreateVector(bins);
|
||||
int i, j;
|
||||
PRECISION r, z, inc=max/(PRECISION)bins, cum_inc=inc/(PRECISION)cum_bins;
|
||||
for (i=0; i < bins; i++)
|
||||
{
|
||||
for (r=(PRECISION)i*inc + 0.5*cum_inc, z=MINUS_INFINITY, j=0; j < cum_bins; r+=cum_inc, j++)
|
||||
z=AddLogs_static(z,LogSphericalDensity(r) + (SPHERICAL_DIM - 1)*log(r));
|
||||
ElementV(cumulative,i)=exp(z - log(0.5) + 0.5*SPHERICAL_DIM*log(PI) - dw_log_gamma(0.5*SPHERICAL_DIM) + log(cum_inc));
|
||||
}
|
||||
for (i=1; i < bins; i++)
|
||||
ElementV(cumulative,i)+=ElementV(cumulative,i-1);
|
||||
return cumulative;
|
||||
}
|
||||
|
||||
void TestSpherical(FILE *f, char *filename, PRECISION max)
|
||||
{
|
||||
TMatrix cumulative;
|
||||
TVector x;
|
||||
int i, j, bins=1000, cum_bins=20, ndraws=1000000;
|
||||
PRECISION r, z, inc=max/(PRECISION)bins, cum_inc=inc/(PRECISION)cum_bins, s=1.0/(PRECISION)ndraws;
|
||||
FILE *f_out;
|
||||
|
||||
cumulative=CreateMatrix(bins,3);
|
||||
for (i=0; i < bins; i++)
|
||||
{
|
||||
ElementM(cumulative,i,0)=(PRECISION)(i+1)*inc;
|
||||
for (r=(PRECISION)i*inc + 0.5*cum_inc, z=MINUS_INFINITY, j=0; j < cum_bins; r+=cum_inc, j++)
|
||||
z=AddLogs_static(z,LogSphericalDensity(r) + (SPHERICAL_DIM - 1)*log(r));
|
||||
ElementM(cumulative,i,1)=exp(z - log(0.5) + 0.5*SPHERICAL_DIM*log(PI) - dw_log_gamma(0.5*SPHERICAL_DIM) + log(cum_inc));
|
||||
ElementM(cumulative,i,2)=0.0;
|
||||
}
|
||||
|
||||
x=CreateVector(SPHERICAL_DIM);
|
||||
for (i=ndraws; i > 0; i--)
|
||||
{
|
||||
r=DrawSpherical(x);
|
||||
if ((j=(int)floor(r/inc)) < bins)
|
||||
ElementM(cumulative,j,2)+=s;
|
||||
}
|
||||
FreeVector(x);
|
||||
|
||||
for (i=1; i < bins; i++)
|
||||
{
|
||||
ElementM(cumulative,i,1)+=ElementM(cumulative,i-1,1);
|
||||
ElementM(cumulative,i,2)+=ElementM(cumulative,i-1,2);
|
||||
}
|
||||
|
||||
f_out=!f ? dw_CreateTextFile(filename) : f;
|
||||
dw_PrintMatrix(f_out,cumulative,"%lf,");
|
||||
if (!f) fclose(f_out);
|
||||
FreeMatrix(cumulative);
|
||||
}
|
||||
#undef PI
|
||||
|
||||
#undef SPHERICAL_GAUSSIAN
|
||||
#undef SPHERICAL_UNIFORM
|
||||
#undef SPHERICAL_POWER
|
||||
#undef SPHERICAL_TURNCATED_POWER
|
||||
#undef SPHERICAL_TRUNCATED_GAUSSIAN
|
||||
/*******************************************************************************/
|
||||
/*******************************************************************************/
|
||||
/*******************************************************************************/
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m dimensional solid unit sphere.
|
||||
|
||||
Returns:
|
||||
Upon success, returns the norm of x, upon failure returns negative value.
|
||||
|
||||
Notes:
|
||||
The vector is drawn by drawing a m-vector from the standard normal
|
||||
distribution and a real number u from the uniform distribution on [0,1], and
|
||||
normalizing the vector so its length equal to u^(1/m).
|
||||
*/
|
||||
PRECISION UniformUnitBall(TVector x)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/DimV(x)))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : n-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the distribution
|
||||
|
||||
0.5 * k * Gamma(n/2) * pi^(-n/2) * norm(x)^(k-n)
|
||||
|
||||
Returns:
|
||||
norm(x) upon success and a negative value upon failure.
|
||||
|
||||
Notes:
|
||||
If x is obtained by drawing y from the standard n-dimensional Gaussian
|
||||
distribtuion and r from the distribution on [0,1] with density
|
||||
|
||||
k * r^(k-1)
|
||||
|
||||
Since the cumulative density of r is
|
||||
|
||||
r^k
|
||||
|
||||
a draw of r can be obtained by drawing u from the uniform on [0,1] and
|
||||
defining r = u^(1/k). This assumes that k > 0.
|
||||
*/
|
||||
PRECISION PowerUnitBall(TVector x, PRECISION k)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/k))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : n-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the distribution
|
||||
|
||||
0.5 * k * Gamma(n/2) * pi^(-n/2) * norm(x)^(k-n) / (1 - a^k)
|
||||
|
||||
Returns:
|
||||
norm(x) upon success and a negative value upon failure.
|
||||
|
||||
Notes:
|
||||
If x is obtained by drawing y from the standard n-dimensional Gaussian
|
||||
distribtuion and r from the distribution on [a,1] with density
|
||||
|
||||
k * r^(k-1) / (1 - a^k)
|
||||
|
||||
Since the cumulative density of r is
|
||||
|
||||
(r^k - a^k) / (1 - a^k)
|
||||
|
||||
a draw of r can be obtained by drawing u from the uniform on [0,1] and
|
||||
defining r = (u(1-a^k) + a^k)^(1/k). This assumes that k > 0.
|
||||
*/
|
||||
PRECISION TruncatedPowerUnitBall(TVector x, PRECISION k, PRECISION a)
|
||||
{
|
||||
PRECISION r, s, t;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
t=pow(a,k);
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd()*(1.0 - t) + t,1.0/k))/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
PRECISION SphericalTable(TVector x, PRECISION *table, int m)
|
||||
{
|
||||
PRECISION r, s;
|
||||
int i, j;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
|
||||
j=(int)floor(dw_uniform_rnd()*(PRECISION)m);
|
||||
r=(j < m) ? table[j] + dw_uniform_rnd()*(table[j+1] - table[j]) : table[m];
|
||||
ProductSV(x,r/s,x);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
PRECISION LogSphericalTableDensity(PRECISION r, PRECISION *table, int m)
|
||||
{
|
||||
int min=0, max=m, mid;
|
||||
if (r > table[m]) return MINUS_INFINITY;
|
||||
while (max - min > 1)
|
||||
if (r > table[mid=(min + max)/2])
|
||||
min=mid;
|
||||
else
|
||||
max=mid;
|
||||
return -log((PRECISION)m*(table[max] - table[min]));
|
||||
}
|
||||
|
||||
|
|
|
@ -1,23 +1,23 @@
|
|||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
char* SphericalType(void);
|
||||
void SetupSpherical_Gaussian(int n);
|
||||
void SetupSpherical_Uniform(int n);
|
||||
void SetupSpherical_Power(int n, PRECISION k);
|
||||
void SetupSpherical_TruncatedPower(int n, PRECISION k, PRECISION a);
|
||||
void SetupSpherical_Table(int n, PRECISION *table, int m);
|
||||
void SetupSpherical_TruncatedGaussian(int n, PRECISION r1, PRECISION r2);
|
||||
|
||||
PRECISION DrawSpherical(TVector x);
|
||||
PRECISION LogSphericalDensity(PRECISION r);
|
||||
TVector SphericalCumulativeDensity(PRECISION max, int bins, int cum_bins);
|
||||
|
||||
void TestSpherical(FILE *f, char *filename, PRECISION max);
|
||||
|
||||
PRECISION UniformUnitBall(TVector x);
|
||||
PRECISION PowerUnitBall(TVector x, PRECISION k);
|
||||
PRECISION TruncatedPowerUnitBall(TVector x, PRECISION k, PRECISION a);
|
||||
PRECISION SphericalTable(TVector x, PRECISION *table, int m);
|
||||
PRECISION LogSphericalTableDensity(PRECISION r, PRECISION *table, int m);
|
||||
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
char* SphericalType(void);
|
||||
void SetupSpherical_Gaussian(int n);
|
||||
void SetupSpherical_Uniform(int n);
|
||||
void SetupSpherical_Power(int n, PRECISION k);
|
||||
void SetupSpherical_TruncatedPower(int n, PRECISION k, PRECISION a);
|
||||
void SetupSpherical_Table(int n, PRECISION *table, int m);
|
||||
void SetupSpherical_TruncatedGaussian(int n, PRECISION r1, PRECISION r2);
|
||||
|
||||
PRECISION DrawSpherical(TVector x);
|
||||
PRECISION LogSphericalDensity(PRECISION r);
|
||||
TVector SphericalCumulativeDensity(PRECISION max, int bins, int cum_bins);
|
||||
|
||||
void TestSpherical(FILE *f, char *filename, PRECISION max);
|
||||
|
||||
PRECISION UniformUnitBall(TVector x);
|
||||
PRECISION PowerUnitBall(TVector x, PRECISION k);
|
||||
PRECISION TruncatedPowerUnitBall(TVector x, PRECISION k, PRECISION a);
|
||||
PRECISION SphericalTable(TVector x, PRECISION *table, int m);
|
||||
PRECISION LogSphericalTableDensity(PRECISION r, PRECISION *table, int m);
|
||||
|
||||
|
|
|
@ -1,284 +1,284 @@
|
|||
|
||||
#include "dw_matrix_rand.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_error.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/******************************************************************************/
|
||||
/************************ Random Matrices and Vectors *************************/
|
||||
/******************************************************************************/
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with deviates drawn from the uniform distribution on [0,1]
|
||||
*/
|
||||
TVector dw_UniformVector(TVector x)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_uniform_rnd();
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x n matrix
|
||||
|
||||
Results
|
||||
Fills X with deviates drawn from the uniform distribution on [0,1]
|
||||
*/
|
||||
TMatrix dw_UniformMatrix(TMatrix X)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX;
|
||||
if (!X) { dw_Error(NULL_ERR); return (TMatrix)NULL; }
|
||||
for (pX=pElementM(X), i=RowM(X)*ColM(X)-1; i >= 0; i--) pX[i]=dw_uniform_rnd();
|
||||
return X;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with independent standard normal deviates
|
||||
*/
|
||||
TVector dw_NormalVector(TVector x)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_gaussian_rnd();
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x n matrix
|
||||
|
||||
Results
|
||||
Fills X with independent standard normal deviates
|
||||
*/
|
||||
TMatrix dw_NormalMatrix(TMatrix X)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX;
|
||||
if (!X) { dw_Error(NULL_ERR); return (TMatrix)NULL; }
|
||||
for (pX=pElementM(X), i=RowM(X)*ColM(X)-1; i >= 0; i--) pX[i]=dw_gaussian_rnd();
|
||||
return X;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with independent log normal deviates. The mean and standard
|
||||
deviation of the underlying normal distribution are passed.
|
||||
*/
|
||||
TVector dw_LogNormalVector(TVector x, PRECISION mean, PRECISION standard_deviation)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_lognormal_rnd(mean,standard_deviation);
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Computes a matrix of gamma deviates. If x, a, and b represent X(i,j),
|
||||
A(i,j), and B(i,j), then density of x is
|
||||
|
||||
x^(a-1) exp(-x/b)
|
||||
------------------
|
||||
gamma(a) b^a
|
||||
|
||||
*/
|
||||
TMatrix dw_GammaMatrix(TMatrix X, TMatrix A, TMatrix B)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX, *pA, *pB;
|
||||
if (!A || !B)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if ((RowM(A) != RowM(B)) || (ColM(A) != ColM(B)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (!X)
|
||||
{
|
||||
if (!(X=CreateMatrix(RowM(A),ColM(A))))
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
if ((RowM(X) != RowM(A)) || (ColM(X) != ColM(A)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
for (pX=pElementM(X), pA=pElementM(A), pB=pElementM(B), i=RowM(X)*ColM(X)-1; i >= 0; i--)
|
||||
pX[i]=pB[i]*dw_gamma_rnd(pA[i]);
|
||||
return X;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x m matrix
|
||||
S : m x m non-singular matrix
|
||||
|
||||
Results
|
||||
X is drawn from the Wishart distribution with parameters sigma, nu, and m,
|
||||
where sigma=Inverse(S'S). The pdf of X is proportional to
|
||||
|
||||
|det(X)|^(0.5*(nu - m - 1))
|
||||
---------------------------- * exp(-0.5*tr(Inverse(sigma*X))
|
||||
|det(sigma)|^(0.5*nu)
|
||||
|
||||
|
||||
= |det(X)|^(0.5*(nu - m - 1)) |det(S)|^(0.5*nu) exp(-0.5*tr(S'*X*S))
|
||||
*/
|
||||
TMatrix dw_Wishart(TMatrix X, TMatrix S, int nu)
|
||||
{
|
||||
int m=RowM(S);
|
||||
TMatrix Z;
|
||||
|
||||
if ((m != ColM(S)) || (m != RowM(X)) || (m != ColM(X))) dw_Error(SIZE_ERR);
|
||||
|
||||
Z=dw_NormalMatrix(CreateMatrix(m,nu));
|
||||
ProductMM(Z,S,Z);
|
||||
ProductTransposeMM(X,Z,Z);
|
||||
FreeMatrix(Z);
|
||||
return X;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : n x n matrix
|
||||
T : n x n upper triangular matrix
|
||||
|
||||
Results
|
||||
x is drawn from the multivariate student-t distribution with parameters.
|
||||
The pdf of x is given by
|
||||
*/
|
||||
TVector dw_StudentT(TVector x, TMatrix T, int nu)
|
||||
{
|
||||
PRECISION r=0.0, s;
|
||||
int i, n=DimV(x);
|
||||
if ((n != ColM(T)) || (n != RowM(T))) dw_Error(SIZE_ERR);
|
||||
dw_NormalVector(x);
|
||||
ProductMV(x,T,x);
|
||||
for (i=nu; i > 0; i--)
|
||||
{
|
||||
s=dw_gaussian_rnd();
|
||||
r+=s*s;
|
||||
}
|
||||
ProductSV(x,sqrt((PRECISION)nu/r),x);
|
||||
return x;
|
||||
}
|
||||
|
||||
TMatrix dw_UniformOrthogonal(TMatrix Q)
|
||||
{
|
||||
TMatrix X;
|
||||
int i, j, err;
|
||||
|
||||
if (!Q)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (RowM(Q) != ColM(Q))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
|
||||
/* Uncomment to use IMSL implementation */
|
||||
//imsls_d_random_orthogonal_matrix(RowM(Q),IMSLS_RETURN_USER,pElementM(Q),0);
|
||||
/**/
|
||||
|
||||
|
||||
/* Uncomment to use C code implementation */
|
||||
X=dw_NormalMatrix(CreateMatrix(RowM(Q),ColM(Q)));
|
||||
if (!(err=QR(Q,X,X)))
|
||||
for (i=RowM(X)-1; i >= 0; i--)
|
||||
if (ElementM(X,i,i) < 0)
|
||||
for (j=RowM(Q)-1; j >= 0; j--) ElementM(Q,j,i)=-ElementM(Q,j,i);
|
||||
FreeMatrix(X);
|
||||
if (err) return (TMatrix)NULL;
|
||||
/**/
|
||||
|
||||
return Q;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m-1 dimensional unit sphere.
|
||||
|
||||
Returns:
|
||||
The vector x.
|
||||
|
||||
Notes:
|
||||
The vector is obtained by drawing a m-vector from the standard normal
|
||||
distribution and then normalizing its length to one.
|
||||
*/
|
||||
TVector dw_UniformUnitSphere(TVector x)
|
||||
{
|
||||
PRECISION r;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((r=Norm(x)) == 0.0);
|
||||
return ProductSV(x,1.0/r,x);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m dimensional solid unit sphere.
|
||||
|
||||
Returns:
|
||||
Upon success, returns the norm of x, upon failure returns -1.0.
|
||||
|
||||
Notes:
|
||||
The vector is drawn by drawing a m-vector from the standard normal
|
||||
distribution and a real number u from the uniform distribution on [0,1], and
|
||||
normalizing the vector so its length equal to u^(1/m).
|
||||
*/
|
||||
TVector dw_UniformUnitBall(TVector x)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/DimV(x)))/s,x);
|
||||
return x;
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
|
||||
|
||||
#include "dw_matrix_rand.h"
|
||||
#include "dw_rand.h"
|
||||
#include "dw_error.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
/******************************************************************************/
|
||||
/************************ Random Matrices and Vectors *************************/
|
||||
/******************************************************************************/
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with deviates drawn from the uniform distribution on [0,1]
|
||||
*/
|
||||
TVector dw_UniformVector(TVector x)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_uniform_rnd();
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x n matrix
|
||||
|
||||
Results
|
||||
Fills X with deviates drawn from the uniform distribution on [0,1]
|
||||
*/
|
||||
TMatrix dw_UniformMatrix(TMatrix X)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX;
|
||||
if (!X) { dw_Error(NULL_ERR); return (TMatrix)NULL; }
|
||||
for (pX=pElementM(X), i=RowM(X)*ColM(X)-1; i >= 0; i--) pX[i]=dw_uniform_rnd();
|
||||
return X;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with independent standard normal deviates
|
||||
*/
|
||||
TVector dw_NormalVector(TVector x)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_gaussian_rnd();
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x n matrix
|
||||
|
||||
Results
|
||||
Fills X with independent standard normal deviates
|
||||
*/
|
||||
TMatrix dw_NormalMatrix(TMatrix X)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX;
|
||||
if (!X) { dw_Error(NULL_ERR); return (TMatrix)NULL; }
|
||||
for (pX=pElementM(X), i=RowM(X)*ColM(X)-1; i >= 0; i--) pX[i]=dw_gaussian_rnd();
|
||||
return X;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : m-vector
|
||||
|
||||
Results
|
||||
Fills x with independent log normal deviates. The mean and standard
|
||||
deviation of the underlying normal distribution are passed.
|
||||
*/
|
||||
TVector dw_LogNormalVector(TVector x, PRECISION mean, PRECISION standard_deviation)
|
||||
{
|
||||
int i;
|
||||
if (!x) { dw_Error(NULL_ERR); return (TVector)NULL; }
|
||||
for (i=DimV(x)-1; i >= 0; i--) ElementV(x,i)=dw_lognormal_rnd(mean,standard_deviation);
|
||||
return x;
|
||||
}
|
||||
|
||||
/*
|
||||
Computes a matrix of gamma deviates. If x, a, and b represent X(i,j),
|
||||
A(i,j), and B(i,j), then density of x is
|
||||
|
||||
x^(a-1) exp(-x/b)
|
||||
------------------
|
||||
gamma(a) b^a
|
||||
|
||||
*/
|
||||
TMatrix dw_GammaMatrix(TMatrix X, TMatrix A, TMatrix B)
|
||||
{
|
||||
int i;
|
||||
PRECISION *pX, *pA, *pB;
|
||||
if (!A || !B)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if ((RowM(A) != RowM(B)) || (ColM(A) != ColM(B)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (!X)
|
||||
{
|
||||
if (!(X=CreateMatrix(RowM(A),ColM(A))))
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
else
|
||||
if ((RowM(X) != RowM(A)) || (ColM(X) != ColM(A)))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
for (pX=pElementM(X), pA=pElementM(A), pB=pElementM(B), i=RowM(X)*ColM(X)-1; i >= 0; i--)
|
||||
pX[i]=pB[i]*dw_gamma_rnd(pA[i]);
|
||||
return X;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes
|
||||
X : m x m matrix
|
||||
S : m x m non-singular matrix
|
||||
|
||||
Results
|
||||
X is drawn from the Wishart distribution with parameters sigma, nu, and m,
|
||||
where sigma=Inverse(S'S). The pdf of X is proportional to
|
||||
|
||||
|det(X)|^(0.5*(nu - m - 1))
|
||||
---------------------------- * exp(-0.5*tr(Inverse(sigma*X))
|
||||
|det(sigma)|^(0.5*nu)
|
||||
|
||||
|
||||
= |det(X)|^(0.5*(nu - m - 1)) |det(S)|^(0.5*nu) exp(-0.5*tr(S'*X*S))
|
||||
*/
|
||||
TMatrix dw_Wishart(TMatrix X, TMatrix S, int nu)
|
||||
{
|
||||
int m=RowM(S);
|
||||
TMatrix Z;
|
||||
|
||||
if ((m != ColM(S)) || (m != RowM(X)) || (m != ColM(X))) dw_Error(SIZE_ERR);
|
||||
|
||||
Z=dw_NormalMatrix(CreateMatrix(m,nu));
|
||||
ProductMM(Z,S,Z);
|
||||
ProductTransposeMM(X,Z,Z);
|
||||
FreeMatrix(Z);
|
||||
return X;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes
|
||||
x : n x n matrix
|
||||
T : n x n upper triangular matrix
|
||||
|
||||
Results
|
||||
x is drawn from the multivariate student-t distribution with parameters.
|
||||
The pdf of x is given by
|
||||
*/
|
||||
TVector dw_StudentT(TVector x, TMatrix T, int nu)
|
||||
{
|
||||
PRECISION r=0.0, s;
|
||||
int i, n=DimV(x);
|
||||
if ((n != ColM(T)) || (n != RowM(T))) dw_Error(SIZE_ERR);
|
||||
dw_NormalVector(x);
|
||||
ProductMV(x,T,x);
|
||||
for (i=nu; i > 0; i--)
|
||||
{
|
||||
s=dw_gaussian_rnd();
|
||||
r+=s*s;
|
||||
}
|
||||
ProductSV(x,sqrt((PRECISION)nu/r),x);
|
||||
return x;
|
||||
}
|
||||
|
||||
TMatrix dw_UniformOrthogonal(TMatrix Q)
|
||||
{
|
||||
TMatrix X;
|
||||
int i, j, err;
|
||||
|
||||
if (!Q)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
if (RowM(Q) != ColM(Q))
|
||||
{
|
||||
dw_Error(SIZE_ERR);
|
||||
return (TMatrix)NULL;
|
||||
}
|
||||
|
||||
/* Uncomment to use IMSL implementation */
|
||||
//imsls_d_random_orthogonal_matrix(RowM(Q),IMSLS_RETURN_USER,pElementM(Q),0);
|
||||
/**/
|
||||
|
||||
|
||||
/* Uncomment to use C code implementation */
|
||||
X=dw_NormalMatrix(CreateMatrix(RowM(Q),ColM(Q)));
|
||||
if (!(err=QR(Q,X,X)))
|
||||
for (i=RowM(X)-1; i >= 0; i--)
|
||||
if (ElementM(X,i,i) < 0)
|
||||
for (j=RowM(Q)-1; j >= 0; j--) ElementM(Q,j,i)=-ElementM(Q,j,i);
|
||||
FreeMatrix(X);
|
||||
if (err) return (TMatrix)NULL;
|
||||
/**/
|
||||
|
||||
return Q;
|
||||
}
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m-1 dimensional unit sphere.
|
||||
|
||||
Returns:
|
||||
The vector x.
|
||||
|
||||
Notes:
|
||||
The vector is obtained by drawing a m-vector from the standard normal
|
||||
distribution and then normalizing its length to one.
|
||||
*/
|
||||
TVector dw_UniformUnitSphere(TVector x)
|
||||
{
|
||||
PRECISION r;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((r=Norm(x)) == 0.0);
|
||||
return ProductSV(x,1.0/r,x);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Assumes:
|
||||
x : m-vector
|
||||
|
||||
Results:
|
||||
The vector x is filled with a vector drawn from the uniform distribution on
|
||||
the m dimensional solid unit sphere.
|
||||
|
||||
Returns:
|
||||
Upon success, returns the norm of x, upon failure returns -1.0.
|
||||
|
||||
Notes:
|
||||
The vector is drawn by drawing a m-vector from the standard normal
|
||||
distribution and a real number u from the uniform distribution on [0,1], and
|
||||
normalizing the vector so its length equal to u^(1/m).
|
||||
*/
|
||||
TVector dw_UniformUnitBall(TVector x)
|
||||
{
|
||||
PRECISION r, s;
|
||||
if (!x)
|
||||
{
|
||||
dw_Error(NULL_ERR);
|
||||
return (TVector)NULL;
|
||||
}
|
||||
do
|
||||
dw_NormalVector(x);
|
||||
while ((s=Norm(x)) == 0.0);
|
||||
ProductSV(x,(r=pow(dw_uniform_rnd(),1.0/DimV(x)))/s,x);
|
||||
return x;
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
|
||||
#ifndef __RANDOM_MATRIX__
|
||||
#define __RANDOM_MATRIX__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
/* Random Matrices and Vectors */
|
||||
TVector dw_UniformVector(TVector x);
|
||||
TMatrix dw_UniformMatrix(TMatrix X);
|
||||
TVector dw_NormalVector(TVector x);
|
||||
TMatrix dw_NormalMatrix(TMatrix X);
|
||||
TVector dw_LogNormalVector(TVector x, PRECISION mean, PRECISION standard_deviation);
|
||||
TMatrix dw_GammaMatrix(TMatrix X, TMatrix A, TMatrix B);
|
||||
TMatrix dw_Wishart(TMatrix X, TMatrix S, int nu);
|
||||
TVector dw_StudentT(TVector x, TMatrix T, int nu);
|
||||
TMatrix dw_UniformOrthogonal(TMatrix Q);
|
||||
TVector dw_UniformUnitSphere(TVector x);
|
||||
TVector dw_UniformUnitBall(TVector x);
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __RANDOM_MATRIX__
|
||||
#define __RANDOM_MATRIX__
|
||||
|
||||
#include "swzmatrix.h"
|
||||
|
||||
/* Random Matrices and Vectors */
|
||||
TVector dw_UniformVector(TVector x);
|
||||
TMatrix dw_UniformMatrix(TMatrix X);
|
||||
TVector dw_NormalVector(TVector x);
|
||||
TMatrix dw_NormalMatrix(TMatrix X);
|
||||
TVector dw_LogNormalVector(TVector x, PRECISION mean, PRECISION standard_deviation);
|
||||
TMatrix dw_GammaMatrix(TMatrix X, TMatrix A, TMatrix B);
|
||||
TMatrix dw_Wishart(TMatrix X, TMatrix S, int nu);
|
||||
TVector dw_StudentT(TVector x, TMatrix T, int nu);
|
||||
TMatrix dw_UniformOrthogonal(TMatrix Q);
|
||||
TVector dw_UniformUnitSphere(TVector x);
|
||||
TVector dw_UniformUnitBall(TVector x);
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,35 +1,35 @@
|
|||
|
||||
#ifndef __DW_RANDOM__
|
||||
#define __DW_RANDOM__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#include "prcsn.h"
|
||||
#include <stdio.h>
|
||||
|
||||
void dw_initialize_generator(int init);
|
||||
|
||||
void* dw_get_generator_state(void);
|
||||
int dw_get_generator_state_size(void);
|
||||
void dw_set_generator_state(void *state);
|
||||
void dw_print_generator_state(FILE *f);
|
||||
void dw_read_generator_state(FILE *f);
|
||||
|
||||
PRECISION dw_uniform_rnd(void);
|
||||
PRECISION dw_gaussian_rnd(void);
|
||||
PRECISION dw_lognormal_rnd(PRECISION mean, PRECISION standard_deviation);
|
||||
PRECISION dw_gamma_rnd(PRECISION a);
|
||||
|
||||
PRECISION dw_normal_cdf(PRECISION x);
|
||||
PRECISION dw_chi_square_cdf(PRECISION x, int df);
|
||||
PRECISION dw_chi_square_invcdf(PRECISION p, int df);
|
||||
PRECISION dw_log_gamma(PRECISION x);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef __DW_RANDOM__
|
||||
#define __DW_RANDOM__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#include "prcsn.h"
|
||||
#include <stdio.h>
|
||||
|
||||
void dw_initialize_generator(int init);
|
||||
|
||||
void* dw_get_generator_state(void);
|
||||
int dw_get_generator_state_size(void);
|
||||
void dw_set_generator_state(void *state);
|
||||
void dw_print_generator_state(FILE *f);
|
||||
void dw_read_generator_state(FILE *f);
|
||||
|
||||
PRECISION dw_uniform_rnd(void);
|
||||
PRECISION dw_gaussian_rnd(void);
|
||||
PRECISION dw_lognormal_rnd(PRECISION mean, PRECISION standard_deviation);
|
||||
PRECISION dw_gamma_rnd(PRECISION a);
|
||||
|
||||
PRECISION dw_normal_cdf(PRECISION x);
|
||||
PRECISION dw_chi_square_cdf(PRECISION x, int df);
|
||||
PRECISION dw_chi_square_invcdf(PRECISION p, int df);
|
||||
PRECISION dw_log_gamma(PRECISION x);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,33 +1,33 @@
|
|||
#ifndef __CONGRADMIN_H__
|
||||
#define __CONGRADMIN_H__
|
||||
#include "tzmatlab.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
|
||||
|
||||
void frprmn(double p[], int n, int *iter, double *fret,
|
||||
double (*func)(double [], int), void (*dfunc)(double [], double [], int, double (*func)(double [], int), double *, double),
|
||||
double *ftol_p, int *itmax_p, double *tol_brent_p, int *itmax_brent_p, double *grdh_p);
|
||||
//Outputs:
|
||||
// p[0, ..., n-1]: the location of the minimum if it converges, which replaces the starting value.
|
||||
// iter: pointer to the number of iterations that were performed.
|
||||
// fret: pointer to the minimum value of the function.
|
||||
//Inputs:
|
||||
// p[0, ..., n-1]: a starting point for the minimization.
|
||||
// n: the dimension of p.
|
||||
// ftol_p: pointer to the convergence tolerance on the objective function value. Default: 1.0e-4 if NULL.
|
||||
// itmax_p: pointer to the maximum number of iterations in the main minimization program frprmn(). Default: 2000 if NULL.
|
||||
// tol_brent_p: pointer to the convergence tolerance for the line minimization in brent(). Default: 2.0e-4 if NULL.
|
||||
// itmax_brent_p: pointer to the maximum number of iterations for the line minimization in brent(). Default: 100 if NULL.
|
||||
// grdh: pointer to the user's specified step size for a numerical gradient. If NULL, dfunc() (i.e., gradcd_gen()) will select grdh automatically.
|
||||
// func(): the objective function.
|
||||
// dfunc(): the gradient function computing the numerical gradient. In the form of gradcd_gen() in cstz.c.
|
||||
|
||||
void congradmin_SetPrintFile(char *filename);
|
||||
//If filename=NULL, no intermediate results will be printed out to a file.
|
||||
// void congradmin_SetPrintFile(FILE *fptr_sp);
|
||||
//If fptr_sp=NULL, no intermediate results will be printed out to a file.
|
||||
// void congradmin_SetPrintFile_db(FILE *fptr_sp);
|
||||
#endif
|
||||
#ifndef __CONGRADMIN_H__
|
||||
#define __CONGRADMIN_H__
|
||||
#include "tzmatlab.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
|
||||
|
||||
void frprmn(double p[], int n, int *iter, double *fret,
|
||||
double (*func)(double [], int), void (*dfunc)(double [], double [], int, double (*func)(double [], int), double *, double),
|
||||
double *ftol_p, int *itmax_p, double *tol_brent_p, int *itmax_brent_p, double *grdh_p);
|
||||
//Outputs:
|
||||
// p[0, ..., n-1]: the location of the minimum if it converges, which replaces the starting value.
|
||||
// iter: pointer to the number of iterations that were performed.
|
||||
// fret: pointer to the minimum value of the function.
|
||||
//Inputs:
|
||||
// p[0, ..., n-1]: a starting point for the minimization.
|
||||
// n: the dimension of p.
|
||||
// ftol_p: pointer to the convergence tolerance on the objective function value. Default: 1.0e-4 if NULL.
|
||||
// itmax_p: pointer to the maximum number of iterations in the main minimization program frprmn(). Default: 2000 if NULL.
|
||||
// tol_brent_p: pointer to the convergence tolerance for the line minimization in brent(). Default: 2.0e-4 if NULL.
|
||||
// itmax_brent_p: pointer to the maximum number of iterations for the line minimization in brent(). Default: 100 if NULL.
|
||||
// grdh: pointer to the user's specified step size for a numerical gradient. If NULL, dfunc() (i.e., gradcd_gen()) will select grdh automatically.
|
||||
// func(): the objective function.
|
||||
// dfunc(): the gradient function computing the numerical gradient. In the form of gradcd_gen() in cstz.c.
|
||||
|
||||
void congradmin_SetPrintFile(char *filename);
|
||||
//If filename=NULL, no intermediate results will be printed out to a file.
|
||||
// void congradmin_SetPrintFile(FILE *fptr_sp);
|
||||
//If fptr_sp=NULL, no intermediate results will be printed out to a file.
|
||||
// void congradmin_SetPrintFile_db(FILE *fptr_sp);
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,23 +1,23 @@
|
|||
#ifndef __CSMINWEL_H__
|
||||
#define __CSMINWEL_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <float.h>
|
||||
|
||||
//--- This extern variable allows an input by the user from an input data file.
|
||||
extern double GRADSTPS_CSMINWEL;
|
||||
|
||||
void csminwel(double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double *x, int n, double *H, double *gh,
|
||||
int (*grad)(double *x, int n, double *g, double **args, int *dims),
|
||||
double *fh, double crit, int *itct, int nit,
|
||||
int *fcount, int *retcodeh, double **args, int *dims);
|
||||
// Alternative but less clear way: ... (double (*fcn)(double *, int, double **, int *), ...
|
||||
|
||||
void csminwel_SetPrintFile(char *filename);
|
||||
int csminwel_randomseedChanged(int seednumber);
|
||||
|
||||
|
||||
#endif
|
||||
#ifndef __CSMINWEL_H__
|
||||
#define __CSMINWEL_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <float.h>
|
||||
|
||||
//--- This extern variable allows an input by the user from an input data file.
|
||||
extern double GRADSTPS_CSMINWEL;
|
||||
|
||||
void csminwel(double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double *x, int n, double *H, double *gh,
|
||||
int (*grad)(double *x, int n, double *g, double **args, int *dims),
|
||||
double *fh, double crit, int *itct, int nit,
|
||||
int *fcount, int *retcodeh, double **args, int *dims);
|
||||
// Alternative but less clear way: ... (double (*fcn)(double *, int, double **, int *), ...
|
||||
|
||||
void csminwel_SetPrintFile(char *filename);
|
||||
int csminwel_randomseedChanged(int seednumber);
|
||||
|
||||
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,199 +1,199 @@
|
|||
#ifndef __CSTZ_H__
|
||||
#define __CSTZ_H__
|
||||
#include "tzmatlab.h"
|
||||
#include "switch_opt.h" //DW's Markov-switching routines, only used by gradcd_timet() and ComputeCovarianceFromOuterProduct().
|
||||
|
||||
|
||||
typedef struct {
|
||||
double bound; //Real bounds to avoid extreme values that may make the P2 algorithm fail.
|
||||
double *p; //5-by-1 probabilities as {0.0, p/2, p, (1+p)/2, 1.0}.
|
||||
double *q; //5-by-1 quantiles. Only q[2] is used as an estimate of p[2]-quantile or p-quantile.
|
||||
int *m; //5-by-1 markers.
|
||||
int cnt;
|
||||
int ndeg; //Number of exceptions such as degenerate numbers like inf.
|
||||
} TSdp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **v;
|
||||
int n;
|
||||
} TSdvectorp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **M;
|
||||
int nrows;
|
||||
int ncols;
|
||||
} TSdmatrixp2m5;
|
||||
typedef struct {
|
||||
TSdmatrixp2m5 **C;
|
||||
int ncells;
|
||||
} TSdcellp2m5;
|
||||
typedef struct {
|
||||
TSdcellp2m5 **F;
|
||||
int ndims;
|
||||
} TSdfourthp2m5;
|
||||
TSdp2m5 *CreateP2m5(const double p, const double bound);
|
||||
TSdp2m5 *DestroyP2m5(TSdp2m5 *x_dp2m5);
|
||||
TSdvectorp2m5 *CreateVectorP2m5(const int n, const double p, const double bound);
|
||||
TSdvectorp2m5 *DestroyVectorP2m5(TSdvectorp2m5 *x_dvp2m5);
|
||||
TSdmatrixp2m5 *CreateMatrixP2m5(const int nrows, const int ncols, const double p, const double bound);
|
||||
TSdmatrixp2m5 *DestroyMatrixP2m5(TSdmatrixp2m5 *X_dmp2m5);
|
||||
TSdcellp2m5 *CreateCellP2m5(const TSivector *rows_iv, const TSivector *cols_iv, const double p, const double bound);
|
||||
TSdcellp2m5 *DestroyCellP2m5(TSdcellp2m5 *X_dcp2m5);
|
||||
TSdfourthp2m5 *CreateFourthP2m5(const int ndims, const TSivector *rows_iv, const TSivector *cols_iv, const double p, const double bound);
|
||||
TSdfourthp2m5 *DestroyFourthP2m5(TSdfourthp2m5 *X_d4p2m5);
|
||||
//
|
||||
int P2m5Update(TSdp2m5 *x_dp2m5, const double newval);
|
||||
void P2m5VectorUpdate(TSdvectorp2m5 *x_dvp2m5, const TSdvector *newval_dv);
|
||||
void P2m5MatrixUpdate(TSdmatrixp2m5 *X_dmp2m5, const TSdmatrix *newval_dm);
|
||||
void P2m5CellUpdate(TSdcellp2m5 *X_dcp2m5, const TSdcell *newval_dc);
|
||||
void P2m5FourthUpdate(TSdfourthp2m5 *X_d4p2m5, const TSdfourth *newval_d4);
|
||||
|
||||
|
||||
#if defined ( CSMINWEL_OPTIMIZATION )
|
||||
void fn_gradcd(double *g, double *x, int n, double grdh,
|
||||
double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double **args, int *dims);
|
||||
|
||||
void fn_hesscd(double *H, double *x, int n, double grdh,
|
||||
double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double **args, int *dims);
|
||||
#elif defined ( IMSL_OPTIMIZATION )
|
||||
void fn_gradcd(double *g, double *x, int n, double grdh,
|
||||
double fcn(int n, double *x));
|
||||
void fn_hesscd(double *H, double *x, int n, double grdh,
|
||||
double fcn(int n, double *x));
|
||||
#endif
|
||||
|
||||
//=== For the conjugate gradient method I or II
|
||||
void gradcd_gen(double *g, double *x, int n, double (*fcn)(double *x, int n), double *grdh, double f0);
|
||||
void gradfd_gen(double *g, double *x, int n, double (*fcn)(double *x, int n), double *grdh, double f0);
|
||||
|
||||
//=== For computing inverse Hessian.
|
||||
void gradcd_timet(TSdvector *g_dv, TSdvector *x_dv, int t, struct TStateModel_tag *smodel_ps, double (*fcn)(double *x, int t, struct TStateModel_tag *smodel_ps), double grdh, double f0);
|
||||
TSdmatrix *ComputeHessianFromOuterProduct(TSdmatrix *Hessian_dm, struct TStateModel_tag *smodel_ps, TSdvector *xhat_dv);
|
||||
TSdmatrix *ComputeCovarianceFromOuterProduct(TSdmatrix *Omega_dm, struct TStateModel_tag *smodel_ps, TSdvector *xhat_dv);
|
||||
|
||||
|
||||
|
||||
|
||||
int next_permutation(int *first, int *last);
|
||||
|
||||
//void fn_ergodp(double **aop, int *aod, mxArray *cp);
|
||||
void fn_cumsum(double **aos_v, int *aods_v, double *v, int d_v);
|
||||
int fn_cumsum_int(int *x_v, const int d_x_v);
|
||||
double fn_cumsum_lf(double *x_v, const int d_x_v);
|
||||
double fn_mean(const double *a_v, const int _n);
|
||||
|
||||
|
||||
//=== For sorting according to x_dv.
|
||||
void tz_sort(TSdvector *x_dv, char ad);
|
||||
void tz_sortindex_lf(TSivector *x_iv, TSdvector *base_dv, char ad);
|
||||
void tz_sortindex(TSivector *x_iv, TSvoidvector *base_voidv, char ad); //??????Not fully tested yet.
|
||||
//+
|
||||
void tz_sort_matrix(TSdmatrix *X_dm, char ad, char rc);
|
||||
TSdvector *tz_prctile_matrix(TSdvector *z_dv, const double prc, TSdmatrix *Z_dm, const char rc);
|
||||
TSdvector *tz_mean_matrix(TSdvector *z_dv, TSdmatrix *Z_dm, const char rc);
|
||||
//--- The following 3 functions should be hided (static) but are made visible to accomodate the old code that uses these functions.
|
||||
void fn_SetBaseArrayForComp(TSdvector *x_dv);
|
||||
int fn_compare(const void *i1, const void *i2);
|
||||
int fn_compare2(const void *i1, const void *i2);
|
||||
|
||||
|
||||
//=== Normalization for VARs.
|
||||
void fn_wznormalization(TSdvector *wznmlz_dv, TSdmatrix *A0draw_dm, TSdmatrix *A0peak_dm);
|
||||
|
||||
//=== Handling under or over flows with log values.
|
||||
typedef struct TSveclogsum_tag {
|
||||
//For a recurisve algorithm to compute the log of sum (and therefore log of mean). See p.81a and p.105 in TVBAR Notes.
|
||||
int n; //Number of sums, which is the dimension for N_iv, Ysum_dv, and ymax_dv.
|
||||
TSivector *N_iv; //(N_1, ..., N_n).
|
||||
TSdvector *logsum_dv, //(logofsum_1, ..., logofsum_n).
|
||||
*logmax_dv; //(logmax_1, ..., logmax_n).
|
||||
} TSveclogsum;
|
||||
struct TSveclogsum_tag *CreateVeclogsum(int n);
|
||||
struct TSveclogsum_tag *DestroyVeclogsum(struct TSveclogsum_tag *);
|
||||
//
|
||||
void UpdateSumFor1st2ndMoments(TSdvector *x1stsum_dv, TSdmatrix *X2ndsum_dm, const TSdvector *xdraw_dv);
|
||||
int tz_update_logofsum(double *Y_N_dp, double *y_Nmax_dp, double ynew, int N);
|
||||
int fn_update_logofsum(int N, double ynew, double *Y_N_dp, double *y_Nmax_dp);
|
||||
double fn_replace_logofsumsbt(double *yold, double _a, double ynew, double _b);
|
||||
|
||||
|
||||
|
||||
//---------------------------- Special functions and densities. ---------------------
|
||||
double fn_normalcdf(double x);
|
||||
double fn_normalinv(double p); //Inverse of normal cdf.
|
||||
double fn_chi2inv(double p, double df);
|
||||
//p = int_{0}^{\infty} chi2pdf(t, df) dt
|
||||
double fn_betainv(double p, double _alpha, double _beta);
|
||||
//p = int_{0}^{\infty} betapdf(t, _alpha, _beta) dt where betapdf(t,_alpha,_beta) \propt t^{_alpha-1}*(1-t)^(_beta-1}.
|
||||
double fn_gammalog(double x);
|
||||
//log gamma (x) where gamma(n+1) = n! and gamma(x) = int_0^{\infty} e^{-t} t^{x-1} dt.
|
||||
double fn_betalog(double x, double y);
|
||||
//log beta(x, y) where beta(x, y) = gamma(x)*gamm(y)/gamma(x+y).
|
||||
//+ Density functions
|
||||
double tz_lognormalpdf(double _x, double _m, double _s);
|
||||
double tz_logbetapdf(double _x, double _a, double _b);
|
||||
double tz_loggammapdf(double _x, double _a, double _b);
|
||||
double tz_loginversegammapdf(double _x, double _a, double _b);
|
||||
|
||||
|
||||
//---------------------------- Some high-level VAR functions ---------------------
|
||||
void fn_lev2growthanual(TSdmatrix *levgro_dm, const TSdmatrix *levgrominus1_dm, const TSivector *indxlogper_iv);
|
||||
void fn_ctfals_givenshocks_sm(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm,
|
||||
const TSivector *S_Tdraw_iv, const TSdcell *Bsdraw_dc, const TSdcell *A0sdrawinv_dc, const TSivector *noshocks_iv);
|
||||
void fn_ctfals_sm(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm, const TSivector *Snfores_iv, const TSdcell *Bsdraw_dc, const TSdcell *A0sdrawinv_dc);
|
||||
void fn_ctfals_policyonly(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm, const TSivector *S_Tdraw_iv, const int statecon, const int selej, const TSdcell *A0sdraw_dc, const TSdcell *Apsdraw_dc);
|
||||
void fn_impulse(TSdmatrix *imftran_dm, const TSdmatrix *Bh_dm, const TSdmatrix *swishtran_dm, const int nlags, const int imsteps);
|
||||
TSdmatrix *tz_impulse2levels(TSdmatrix *imflev_dm, TSdmatrix *imf_dm, TSivector *vlist2levels_iv);
|
||||
//
|
||||
void DynamicResponsesAR(TSdvector *resps_dv, const double c0, const TSdvector *a1_dv);
|
||||
void DynamicResponsesForStructuralEquation(TSdmatrix *Resps_dm, const int loclv, const int nlags, const TSdvector *a0p_dv);
|
||||
|
||||
|
||||
|
||||
//---------------------------- Some regular vector or matrix operations ---------------------
|
||||
double MinVector_lf(TSdvector *x_dv);
|
||||
TSdvector *ConvertVector2exp(TSdvector *y_dv, TSdvector *x_dv); //y=exp(x): output; x: input.
|
||||
TSdvector *ConvertVector2log(TSdvector *y_dv, TSdvector *x_dv); //y=log(x): output; x: input.
|
||||
double tz_normofvector(TSdvector *x_dv, double p);
|
||||
|
||||
|
||||
//---------------------------- Old Interface ---------------------
|
||||
double gammalog(double x);
|
||||
//log gamma (x) where gamma(n+1) = n! and gamma(x) = int_0^{\infty} e^{-t} t^{x-1} dt.
|
||||
|
||||
|
||||
|
||||
|
||||
//----------- Must keep the following forever. -------------
|
||||
/**
|
||||
typedef struct {
|
||||
double *p; //5-by-1 probabilities as {0.0, p/2, p, (1+p)/2, 1.0}.
|
||||
double *q; //5-by-1 quantiles. Only q[2] is used as an estimate of p[2]-quantile or p-quantile.
|
||||
int *m; //5-by-1 markers.
|
||||
int cnt;
|
||||
int ndeg; //Number of exceptions such as degenerate numbers like inf.
|
||||
} TSdp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **v;
|
||||
int n;
|
||||
} TSdvectorp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **M;
|
||||
int nrows;
|
||||
int ncols;
|
||||
} TSdmatrixp2m5;
|
||||
typedef struct {
|
||||
TSdmatrixp2m5 **C;
|
||||
int ncells;
|
||||
} TSdcellp2m5;
|
||||
|
||||
TSdp2m5 *CreateP2m5(const double p);
|
||||
TSdp2m5 *DestroyP2m5(TSdp2m5 *x_dp2m5);
|
||||
TSdvectorp2m5 *CreateVectorP2m5(const int n, const double p);
|
||||
TSdvectorp2m5 *DestroyVectorP2m5(TSdvectorp2m5 *x_dvp2m5);
|
||||
TSdmatrixp2m5 *CreateMatrixP2m5(const int nrows, const int ncols, const double p);
|
||||
TSdmatrixp2m5 *DestroyMatrixP2m5(TSdmatrixp2m5 *X_dmp2m5);
|
||||
TSdcellp2m5 *CreateCellP2m5(const TSivector *rows_iv, const TSivector *cols_iv, const double p);
|
||||
TSdcellp2m5 *DestroyCellP2m5(TSdcellp2m5 *X_dcp2m5);
|
||||
/**/
|
||||
#endif
|
||||
#ifndef __CSTZ_H__
|
||||
#define __CSTZ_H__
|
||||
#include "tzmatlab.h"
|
||||
#include "switch_opt.h" //DW's Markov-switching routines, only used by gradcd_timet() and ComputeCovarianceFromOuterProduct().
|
||||
|
||||
|
||||
typedef struct {
|
||||
double bound; //Real bounds to avoid extreme values that may make the P2 algorithm fail.
|
||||
double *p; //5-by-1 probabilities as {0.0, p/2, p, (1+p)/2, 1.0}.
|
||||
double *q; //5-by-1 quantiles. Only q[2] is used as an estimate of p[2]-quantile or p-quantile.
|
||||
int *m; //5-by-1 markers.
|
||||
int cnt;
|
||||
int ndeg; //Number of exceptions such as degenerate numbers like inf.
|
||||
} TSdp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **v;
|
||||
int n;
|
||||
} TSdvectorp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **M;
|
||||
int nrows;
|
||||
int ncols;
|
||||
} TSdmatrixp2m5;
|
||||
typedef struct {
|
||||
TSdmatrixp2m5 **C;
|
||||
int ncells;
|
||||
} TSdcellp2m5;
|
||||
typedef struct {
|
||||
TSdcellp2m5 **F;
|
||||
int ndims;
|
||||
} TSdfourthp2m5;
|
||||
TSdp2m5 *CreateP2m5(const double p, const double bound);
|
||||
TSdp2m5 *DestroyP2m5(TSdp2m5 *x_dp2m5);
|
||||
TSdvectorp2m5 *CreateVectorP2m5(const int n, const double p, const double bound);
|
||||
TSdvectorp2m5 *DestroyVectorP2m5(TSdvectorp2m5 *x_dvp2m5);
|
||||
TSdmatrixp2m5 *CreateMatrixP2m5(const int nrows, const int ncols, const double p, const double bound);
|
||||
TSdmatrixp2m5 *DestroyMatrixP2m5(TSdmatrixp2m5 *X_dmp2m5);
|
||||
TSdcellp2m5 *CreateCellP2m5(const TSivector *rows_iv, const TSivector *cols_iv, const double p, const double bound);
|
||||
TSdcellp2m5 *DestroyCellP2m5(TSdcellp2m5 *X_dcp2m5);
|
||||
TSdfourthp2m5 *CreateFourthP2m5(const int ndims, const TSivector *rows_iv, const TSivector *cols_iv, const double p, const double bound);
|
||||
TSdfourthp2m5 *DestroyFourthP2m5(TSdfourthp2m5 *X_d4p2m5);
|
||||
//
|
||||
int P2m5Update(TSdp2m5 *x_dp2m5, const double newval);
|
||||
void P2m5VectorUpdate(TSdvectorp2m5 *x_dvp2m5, const TSdvector *newval_dv);
|
||||
void P2m5MatrixUpdate(TSdmatrixp2m5 *X_dmp2m5, const TSdmatrix *newval_dm);
|
||||
void P2m5CellUpdate(TSdcellp2m5 *X_dcp2m5, const TSdcell *newval_dc);
|
||||
void P2m5FourthUpdate(TSdfourthp2m5 *X_d4p2m5, const TSdfourth *newval_d4);
|
||||
|
||||
|
||||
#if defined ( CSMINWEL_OPTIMIZATION )
|
||||
void fn_gradcd(double *g, double *x, int n, double grdh,
|
||||
double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double **args, int *dims);
|
||||
|
||||
void fn_hesscd(double *H, double *x, int n, double grdh,
|
||||
double (*fcn)(double *x, int n, double **args, int *dims),
|
||||
double **args, int *dims);
|
||||
#elif defined ( IMSL_OPTIMIZATION )
|
||||
void fn_gradcd(double *g, double *x, int n, double grdh,
|
||||
double fcn(int n, double *x));
|
||||
void fn_hesscd(double *H, double *x, int n, double grdh,
|
||||
double fcn(int n, double *x));
|
||||
#endif
|
||||
|
||||
//=== For the conjugate gradient method I or II
|
||||
void gradcd_gen(double *g, double *x, int n, double (*fcn)(double *x, int n), double *grdh, double f0);
|
||||
void gradfd_gen(double *g, double *x, int n, double (*fcn)(double *x, int n), double *grdh, double f0);
|
||||
|
||||
//=== For computing inverse Hessian.
|
||||
void gradcd_timet(TSdvector *g_dv, TSdvector *x_dv, int t, struct TStateModel_tag *smodel_ps, double (*fcn)(double *x, int t, struct TStateModel_tag *smodel_ps), double grdh, double f0);
|
||||
TSdmatrix *ComputeHessianFromOuterProduct(TSdmatrix *Hessian_dm, struct TStateModel_tag *smodel_ps, TSdvector *xhat_dv);
|
||||
TSdmatrix *ComputeCovarianceFromOuterProduct(TSdmatrix *Omega_dm, struct TStateModel_tag *smodel_ps, TSdvector *xhat_dv);
|
||||
|
||||
|
||||
|
||||
|
||||
int next_permutation(int *first, int *last);
|
||||
|
||||
//void fn_ergodp(double **aop, int *aod, mxArray *cp);
|
||||
void fn_cumsum(double **aos_v, int *aods_v, double *v, int d_v);
|
||||
int fn_cumsum_int(int *x_v, const int d_x_v);
|
||||
double fn_cumsum_lf(double *x_v, const int d_x_v);
|
||||
double fn_mean(const double *a_v, const int _n);
|
||||
|
||||
|
||||
//=== For sorting according to x_dv.
|
||||
void tz_sort(TSdvector *x_dv, char ad);
|
||||
void tz_sortindex_lf(TSivector *x_iv, TSdvector *base_dv, char ad);
|
||||
void tz_sortindex(TSivector *x_iv, TSvoidvector *base_voidv, char ad); //??????Not fully tested yet.
|
||||
//+
|
||||
void tz_sort_matrix(TSdmatrix *X_dm, char ad, char rc);
|
||||
TSdvector *tz_prctile_matrix(TSdvector *z_dv, const double prc, TSdmatrix *Z_dm, const char rc);
|
||||
TSdvector *tz_mean_matrix(TSdvector *z_dv, TSdmatrix *Z_dm, const char rc);
|
||||
//--- The following 3 functions should be hided (static) but are made visible to accomodate the old code that uses these functions.
|
||||
void fn_SetBaseArrayForComp(TSdvector *x_dv);
|
||||
int fn_compare(const void *i1, const void *i2);
|
||||
int fn_compare2(const void *i1, const void *i2);
|
||||
|
||||
|
||||
//=== Normalization for VARs.
|
||||
void fn_wznormalization(TSdvector *wznmlz_dv, TSdmatrix *A0draw_dm, TSdmatrix *A0peak_dm);
|
||||
|
||||
//=== Handling under or over flows with log values.
|
||||
typedef struct TSveclogsum_tag {
|
||||
//For a recurisve algorithm to compute the log of sum (and therefore log of mean). See p.81a and p.105 in TVBAR Notes.
|
||||
int n; //Number of sums, which is the dimension for N_iv, Ysum_dv, and ymax_dv.
|
||||
TSivector *N_iv; //(N_1, ..., N_n).
|
||||
TSdvector *logsum_dv, //(logofsum_1, ..., logofsum_n).
|
||||
*logmax_dv; //(logmax_1, ..., logmax_n).
|
||||
} TSveclogsum;
|
||||
struct TSveclogsum_tag *CreateVeclogsum(int n);
|
||||
struct TSveclogsum_tag *DestroyVeclogsum(struct TSveclogsum_tag *);
|
||||
//
|
||||
void UpdateSumFor1st2ndMoments(TSdvector *x1stsum_dv, TSdmatrix *X2ndsum_dm, const TSdvector *xdraw_dv);
|
||||
int tz_update_logofsum(double *Y_N_dp, double *y_Nmax_dp, double ynew, int N);
|
||||
int fn_update_logofsum(int N, double ynew, double *Y_N_dp, double *y_Nmax_dp);
|
||||
double fn_replace_logofsumsbt(double *yold, double _a, double ynew, double _b);
|
||||
|
||||
|
||||
|
||||
//---------------------------- Special functions and densities. ---------------------
|
||||
double fn_normalcdf(double x);
|
||||
double fn_normalinv(double p); //Inverse of normal cdf.
|
||||
double fn_chi2inv(double p, double df);
|
||||
//p = int_{0}^{\infty} chi2pdf(t, df) dt
|
||||
double fn_betainv(double p, double _alpha, double _beta);
|
||||
//p = int_{0}^{\infty} betapdf(t, _alpha, _beta) dt where betapdf(t,_alpha,_beta) \propt t^{_alpha-1}*(1-t)^(_beta-1}.
|
||||
double fn_gammalog(double x);
|
||||
//log gamma (x) where gamma(n+1) = n! and gamma(x) = int_0^{\infty} e^{-t} t^{x-1} dt.
|
||||
double fn_betalog(double x, double y);
|
||||
//log beta(x, y) where beta(x, y) = gamma(x)*gamm(y)/gamma(x+y).
|
||||
//+ Density functions
|
||||
double tz_lognormalpdf(double _x, double _m, double _s);
|
||||
double tz_logbetapdf(double _x, double _a, double _b);
|
||||
double tz_loggammapdf(double _x, double _a, double _b);
|
||||
double tz_loginversegammapdf(double _x, double _a, double _b);
|
||||
|
||||
|
||||
//---------------------------- Some high-level VAR functions ---------------------
|
||||
void fn_lev2growthanual(TSdmatrix *levgro_dm, const TSdmatrix *levgrominus1_dm, const TSivector *indxlogper_iv);
|
||||
void fn_ctfals_givenshocks_sm(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm,
|
||||
const TSivector *S_Tdraw_iv, const TSdcell *Bsdraw_dc, const TSdcell *A0sdrawinv_dc, const TSivector *noshocks_iv);
|
||||
void fn_ctfals_sm(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm, const TSivector *Snfores_iv, const TSdcell *Bsdraw_dc, const TSdcell *A0sdrawinv_dc);
|
||||
void fn_ctfals_policyonly(TSdmatrix *ctfalstran_dm, TSdvector *xprimeminus1_dv, const int bloc, const int eloc, const TSdmatrix *strshockstran_dm, const TSivector *S_Tdraw_iv, const int statecon, const int selej, const TSdcell *A0sdraw_dc, const TSdcell *Apsdraw_dc);
|
||||
void fn_impulse(TSdmatrix *imftran_dm, const TSdmatrix *Bh_dm, const TSdmatrix *swishtran_dm, const int nlags, const int imsteps);
|
||||
TSdmatrix *tz_impulse2levels(TSdmatrix *imflev_dm, TSdmatrix *imf_dm, TSivector *vlist2levels_iv);
|
||||
//
|
||||
void DynamicResponsesAR(TSdvector *resps_dv, const double c0, const TSdvector *a1_dv);
|
||||
void DynamicResponsesForStructuralEquation(TSdmatrix *Resps_dm, const int loclv, const int nlags, const TSdvector *a0p_dv);
|
||||
|
||||
|
||||
|
||||
//---------------------------- Some regular vector or matrix operations ---------------------
|
||||
double MinVector_lf(TSdvector *x_dv);
|
||||
TSdvector *ConvertVector2exp(TSdvector *y_dv, TSdvector *x_dv); //y=exp(x): output; x: input.
|
||||
TSdvector *ConvertVector2log(TSdvector *y_dv, TSdvector *x_dv); //y=log(x): output; x: input.
|
||||
double tz_normofvector(TSdvector *x_dv, double p);
|
||||
|
||||
|
||||
//---------------------------- Old Interface ---------------------
|
||||
double gammalog(double x);
|
||||
//log gamma (x) where gamma(n+1) = n! and gamma(x) = int_0^{\infty} e^{-t} t^{x-1} dt.
|
||||
|
||||
|
||||
|
||||
|
||||
//----------- Must keep the following forever. -------------
|
||||
/**
|
||||
typedef struct {
|
||||
double *p; //5-by-1 probabilities as {0.0, p/2, p, (1+p)/2, 1.0}.
|
||||
double *q; //5-by-1 quantiles. Only q[2] is used as an estimate of p[2]-quantile or p-quantile.
|
||||
int *m; //5-by-1 markers.
|
||||
int cnt;
|
||||
int ndeg; //Number of exceptions such as degenerate numbers like inf.
|
||||
} TSdp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **v;
|
||||
int n;
|
||||
} TSdvectorp2m5;
|
||||
typedef struct {
|
||||
TSdp2m5 **M;
|
||||
int nrows;
|
||||
int ncols;
|
||||
} TSdmatrixp2m5;
|
||||
typedef struct {
|
||||
TSdmatrixp2m5 **C;
|
||||
int ncells;
|
||||
} TSdcellp2m5;
|
||||
|
||||
TSdp2m5 *CreateP2m5(const double p);
|
||||
TSdp2m5 *DestroyP2m5(TSdp2m5 *x_dp2m5);
|
||||
TSdvectorp2m5 *CreateVectorP2m5(const int n, const double p);
|
||||
TSdvectorp2m5 *DestroyVectorP2m5(TSdvectorp2m5 *x_dvp2m5);
|
||||
TSdmatrixp2m5 *CreateMatrixP2m5(const int nrows, const int ncols, const double p);
|
||||
TSdmatrixp2m5 *DestroyMatrixP2m5(TSdmatrixp2m5 *X_dmp2m5);
|
||||
TSdcellp2m5 *CreateCellP2m5(const TSivector *rows_iv, const TSivector *cols_iv, const double p);
|
||||
TSdcellp2m5 *DestroyCellP2m5(TSdcellp2m5 *X_dcp2m5);
|
||||
/**/
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,69 +1,69 @@
|
|||
#ifndef __FN_FILESETUP_H__
|
||||
#define __FN_FILESETUP_H__
|
||||
#include <string.h>
|
||||
//#include <malloc.h> // For malloc, calloc, etc.
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "mathlib.h" //Used for tz_TransposeRegular().
|
||||
|
||||
int fn_ParseCommandLine(int n_arg, char **args, char ch);
|
||||
char *fn_ParseCommandLine_String(int n_arg, char **args, char ch, char *default_return);
|
||||
int fn_ParseCommandLine_Integer(int n_arg, char **args, char ch, int default_return);
|
||||
int fn_SetFilePosition(FILE *f, const char *id);
|
||||
|
||||
int fn_ReadVector_int(FILE *fptr, int *x_v, const int d_x_v);
|
||||
int fn_ReadVector_lf(FILE *fptr, double *x_v, const int d_x_v);
|
||||
int fn_ReadMatrix_int(FILE *fptr, int *x_m, const int r_x_m, const int c_x_m);
|
||||
int fn_ReadMatrix_lf(FILE *fptr, double *x_m, const int r_x_m, const int c_x_m);
|
||||
|
||||
int ReadNullTerminatedString(FILE *fptr, TScvector *x_cv);
|
||||
int ReadVector_int(FILE *fptr, TSivector *x_iv);
|
||||
int ReadVector_lf(FILE *fptr, TSdvector *x_dv);
|
||||
int ReadMatrix_int(FILE *fptr, TSimatrix *X_im);
|
||||
int ReadMatrix_lf(FILE *fptr, TSdmatrix *x_dm);
|
||||
int ReadCell_lf(FILE *fptr, TSdcell *x_dc);
|
||||
int ReadCellvec_lf(FILE *fptr, TSdcellvec *x_dcv);
|
||||
|
||||
void fn_WriteMatrix_f(FILE *fprt_debug, const double *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteMatrix_lf(FILE *fprt_debug, const double *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteMatrix_int(FILE *fprt_debug, const int *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteVector_f(FILE *fprt_debug, const double *x_v, const int d_x_v);
|
||||
|
||||
void WriteMatrix_f(FILE *fprt_debug, const TSdmatrix *x_dm);
|
||||
void WriteMatrix_lf(FILE *fprt_debug, const TSdmatrix *x_dm);
|
||||
void WriteMatrix(FILE *fprt_debug, const TSdmatrix *x_dm, const char *format);
|
||||
void WriteMatrixTranspose(FILE *fptr_debug, const TSdmatrix *x_dm, const char *format);
|
||||
void WriteCell_lf(FILE *fprt_debug, const TSdcell *x_dc);
|
||||
void WriteCell_f(FILE *fprt_debug, const TSdcell *x_dc);
|
||||
void WriteCell(FILE *fprt_debug, const TSdcell *x_dc, const char *format);
|
||||
void WriteCellTranspose(FILE *fptr_debug, const TSdcell *x_dc, const char *format);
|
||||
void WriteCellvec_lf(FILE *fprt_debug, const TSdcellvec *x_dcv);
|
||||
void WriteCellvec_f(FILE *fprt_debug, const TSdcellvec *x_dcv);
|
||||
void WriteCellvec(FILE *fptr_debug, const TSdcellvec *x_dcv, const char *format);
|
||||
void WriteFourth_f(FILE *fptr_debug, const TSdfourth *x_d4);
|
||||
void WriteFourth(FILE *fptr_debug, const TSdfourth *x_d4, const char *format);
|
||||
void WriteVector_f(FILE *fprt_debug, const TSdvector *x_dv);
|
||||
void WriteVector_lf(FILE *fprt_debug, const TSdvector *x_dv);
|
||||
void WriteVector(FILE *fprt_debug, const TSdvector *x_dv, const char *format);
|
||||
void WriteVector_column(FILE *fptr_debug, const TSdvector *x_dv, const char *format);
|
||||
void WriteCellvec_int(FILE *fptr_debug, const TSicellvec *x_icv);
|
||||
void WriteMatrix_int(FILE *fprt_debug, const TSimatrix *x_im);
|
||||
void WriteVector_int(FILE *fprt_debug, const TSivector *x_iv);
|
||||
|
||||
|
||||
void PrintVector_int(const TSivector *x_iv);
|
||||
void PrintVector(const TSdvector *x_dv, const char *format);
|
||||
void PrintVector_f(const TSdvector *x_dv);
|
||||
void PrintVector_dz(const TSdzvector *x_dzv);
|
||||
void PrintMatrix_int(const TSimatrix *X_im);
|
||||
void PrintMatrix_f(const TSdmatrix *x_dm);
|
||||
void PrintMatrix(const TSdmatrix *x_dm, const char *format);
|
||||
void PrintMatrix_dz(const TSdzmatrix *x_dzm);
|
||||
void PrintCellvec_f(const TSdcellvec *x_dcv);
|
||||
void PrintCell_f(const TSdcell *x_dc);
|
||||
void PrintCell(const TSdcell *x_dc, const char *format);
|
||||
void PrintFourthvec_f(TSdfourthvec *x_d4v);
|
||||
|
||||
|
||||
void ReprintInputData(FILE *fptr_in, FILE *fptr_out);
|
||||
#endif
|
||||
#ifndef __FN_FILESETUP_H__
|
||||
#define __FN_FILESETUP_H__
|
||||
#include <string.h>
|
||||
//#include <malloc.h> // For malloc, calloc, etc.
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "mathlib.h" //Used for tz_TransposeRegular().
|
||||
|
||||
int fn_ParseCommandLine(int n_arg, char **args, char ch);
|
||||
char *fn_ParseCommandLine_String(int n_arg, char **args, char ch, char *default_return);
|
||||
int fn_ParseCommandLine_Integer(int n_arg, char **args, char ch, int default_return);
|
||||
int fn_SetFilePosition(FILE *f, const char *id);
|
||||
|
||||
int fn_ReadVector_int(FILE *fptr, int *x_v, const int d_x_v);
|
||||
int fn_ReadVector_lf(FILE *fptr, double *x_v, const int d_x_v);
|
||||
int fn_ReadMatrix_int(FILE *fptr, int *x_m, const int r_x_m, const int c_x_m);
|
||||
int fn_ReadMatrix_lf(FILE *fptr, double *x_m, const int r_x_m, const int c_x_m);
|
||||
|
||||
int ReadNullTerminatedString(FILE *fptr, TScvector *x_cv);
|
||||
int ReadVector_int(FILE *fptr, TSivector *x_iv);
|
||||
int ReadVector_lf(FILE *fptr, TSdvector *x_dv);
|
||||
int ReadMatrix_int(FILE *fptr, TSimatrix *X_im);
|
||||
int ReadMatrix_lf(FILE *fptr, TSdmatrix *x_dm);
|
||||
int ReadCell_lf(FILE *fptr, TSdcell *x_dc);
|
||||
int ReadCellvec_lf(FILE *fptr, TSdcellvec *x_dcv);
|
||||
|
||||
void fn_WriteMatrix_f(FILE *fprt_debug, const double *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteMatrix_lf(FILE *fprt_debug, const double *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteMatrix_int(FILE *fprt_debug, const int *x_m, const int r_x_m, const int c_x_m);
|
||||
void fn_WriteVector_f(FILE *fprt_debug, const double *x_v, const int d_x_v);
|
||||
|
||||
void WriteMatrix_f(FILE *fprt_debug, const TSdmatrix *x_dm);
|
||||
void WriteMatrix_lf(FILE *fprt_debug, const TSdmatrix *x_dm);
|
||||
void WriteMatrix(FILE *fprt_debug, const TSdmatrix *x_dm, const char *format);
|
||||
void WriteMatrixTranspose(FILE *fptr_debug, const TSdmatrix *x_dm, const char *format);
|
||||
void WriteCell_lf(FILE *fprt_debug, const TSdcell *x_dc);
|
||||
void WriteCell_f(FILE *fprt_debug, const TSdcell *x_dc);
|
||||
void WriteCell(FILE *fprt_debug, const TSdcell *x_dc, const char *format);
|
||||
void WriteCellTranspose(FILE *fptr_debug, const TSdcell *x_dc, const char *format);
|
||||
void WriteCellvec_lf(FILE *fprt_debug, const TSdcellvec *x_dcv);
|
||||
void WriteCellvec_f(FILE *fprt_debug, const TSdcellvec *x_dcv);
|
||||
void WriteCellvec(FILE *fptr_debug, const TSdcellvec *x_dcv, const char *format);
|
||||
void WriteFourth_f(FILE *fptr_debug, const TSdfourth *x_d4);
|
||||
void WriteFourth(FILE *fptr_debug, const TSdfourth *x_d4, const char *format);
|
||||
void WriteVector_f(FILE *fprt_debug, const TSdvector *x_dv);
|
||||
void WriteVector_lf(FILE *fprt_debug, const TSdvector *x_dv);
|
||||
void WriteVector(FILE *fprt_debug, const TSdvector *x_dv, const char *format);
|
||||
void WriteVector_column(FILE *fptr_debug, const TSdvector *x_dv, const char *format);
|
||||
void WriteCellvec_int(FILE *fptr_debug, const TSicellvec *x_icv);
|
||||
void WriteMatrix_int(FILE *fprt_debug, const TSimatrix *x_im);
|
||||
void WriteVector_int(FILE *fprt_debug, const TSivector *x_iv);
|
||||
|
||||
|
||||
void PrintVector_int(const TSivector *x_iv);
|
||||
void PrintVector(const TSdvector *x_dv, const char *format);
|
||||
void PrintVector_f(const TSdvector *x_dv);
|
||||
void PrintVector_dz(const TSdzvector *x_dzv);
|
||||
void PrintMatrix_int(const TSimatrix *X_im);
|
||||
void PrintMatrix_f(const TSdmatrix *x_dm);
|
||||
void PrintMatrix(const TSdmatrix *x_dm, const char *format);
|
||||
void PrintMatrix_dz(const TSdzmatrix *x_dzm);
|
||||
void PrintCellvec_f(const TSdcellvec *x_dcv);
|
||||
void PrintCell_f(const TSdcell *x_dc);
|
||||
void PrintCell(const TSdcell *x_dc, const char *format);
|
||||
void PrintFourthvec_f(TSdfourthvec *x_d4v);
|
||||
|
||||
|
||||
void ReprintInputData(FILE *fptr_in, FILE *fptr_out);
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,67 +1,67 @@
|
|||
/*******************************************************************
|
||||
* [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div)
|
||||
*
|
||||
* System given as
|
||||
* g0*y(t)=g1*y(t-1)+c+psi*z(t)+pi*eta(t),
|
||||
* with z an exogenous variable process and eta being endogenously determined
|
||||
* one-step-ahead expectational errors. Returned system is
|
||||
* y(t)=G1*y(t-1)+C+impact*z(t)+ywt*inv(I-fmat*inv(L))*fwt*z(t+1) .
|
||||
* If z(t) is i.i.d., the last term drops out.
|
||||
* If div or stake is omitted from argument list, a div>1 or stake>1 is calculated.
|
||||
* eu(1)=1 for existence, eu(2)=1 for uniqueness. eu(1)=-1 for
|
||||
* existence only with not-serially correlated z(t); eu=[-2,-2] for coincident zeros.
|
||||
*
|
||||
* g0, g1: n-by-n matrices.
|
||||
* c: n-by-1 constant terms.
|
||||
* z(t): m-by-1 vector of exogenous residuals where m < n.
|
||||
* psi: n-by-m matrix.
|
||||
* eta(t): h-by-1 vector of expectational (endogenous) errors.
|
||||
* pi: n-by-h matrix.
|
||||
* div: a real number dividing stable and unstable roots.. If < 1.0, a div>1.0 is calculated mechanically.
|
||||
*-------
|
||||
* G1 or Theta_dm: n-by-n matrices.
|
||||
* C: n-by-1 vector of constant terms.
|
||||
* impact: n-by-m matrix.
|
||||
* gev: n-by-2 z vector of stacked generalized eigenvalues where gev(;,2) ./ gev(:,1) = eig(g0, g1).
|
||||
* ywt: n-by-nunstab z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
* fmat: nunstab-by-nunstab z matrix where nunstab is the number of non-stable roots.
|
||||
* fwt: nunstab-by-m z matrix.
|
||||
********************************************************************/
|
||||
|
||||
#ifndef __GENSYS_H__
|
||||
#define __GENSYS_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
//#include "fn_filesetup.h" //For DDDDebugging purpose.
|
||||
|
||||
#define REALSMALL 1e-7
|
||||
//#define PRINTWARNINGofSUNSPOT
|
||||
|
||||
typedef struct TSgensys_tag {
|
||||
//=== Output arguments.
|
||||
TSdmatrix *Theta_dm; //n-by-n.
|
||||
TSdvector *c_dv; //n-by-1.
|
||||
TSdmatrix *Impact_dm; //n-by-m.
|
||||
TSdzmatrix *Fmat_dzm; //nunstab-by-nunstab z matrix. Initialized to NULL and will be dynamically allocated whenever gensys() is called.
|
||||
TSdzmatrix *Fwt_dzm; //nunstab-by-m z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
TSdzmatrix *Ywt_dzm; //n-by-nunstab z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
TSdzmatrix *Gev_dzm; //n-by-2 z matrix of possible complex numbers.
|
||||
TSivector *eu_iv; //2-by-1.
|
||||
//=== Function itself.
|
||||
int (*gensys)(struct TSgensys_tag *, void *);
|
||||
//=== Input arguments, which are all intialized to 0.0 and whose flags are set to M_GE.
|
||||
TSdmatrix *G0_dm; //n-by-n.
|
||||
TSdmatrix *G1_dm; //n-by-n.
|
||||
TSdvector *c0_dv; //n-by-1.
|
||||
TSdmatrix *Psi_dm; //n-by-m.
|
||||
TSdmatrix *Pi_dm; //n-by-k whtere k is the number of expectational errors.
|
||||
double div; //Real number dividing stable and unstable roots.. If < 1.0, a div>1.0 is calculated mechanically.
|
||||
} TSgensys;
|
||||
//
|
||||
typedef int TFlinratexp(struct TSgensys_tag *, void *); //For linear rational expectations models.
|
||||
|
||||
struct TSgensys_tag *CreateTSgensys(TFlinratexp *func, const int _n, const int _m, const int _k, const double div);
|
||||
struct TSgensys_tag *DestroyTSgensys(struct TSgensys_tag *gensys_ps);
|
||||
int gensys_sims(struct TSgensys_tag *gensys_ps, void *dummy_ps);
|
||||
#endif
|
||||
|
||||
/*******************************************************************
|
||||
* [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div)
|
||||
*
|
||||
* System given as
|
||||
* g0*y(t)=g1*y(t-1)+c+psi*z(t)+pi*eta(t),
|
||||
* with z an exogenous variable process and eta being endogenously determined
|
||||
* one-step-ahead expectational errors. Returned system is
|
||||
* y(t)=G1*y(t-1)+C+impact*z(t)+ywt*inv(I-fmat*inv(L))*fwt*z(t+1) .
|
||||
* If z(t) is i.i.d., the last term drops out.
|
||||
* If div or stake is omitted from argument list, a div>1 or stake>1 is calculated.
|
||||
* eu(1)=1 for existence, eu(2)=1 for uniqueness. eu(1)=-1 for
|
||||
* existence only with not-serially correlated z(t); eu=[-2,-2] for coincident zeros.
|
||||
*
|
||||
* g0, g1: n-by-n matrices.
|
||||
* c: n-by-1 constant terms.
|
||||
* z(t): m-by-1 vector of exogenous residuals where m < n.
|
||||
* psi: n-by-m matrix.
|
||||
* eta(t): h-by-1 vector of expectational (endogenous) errors.
|
||||
* pi: n-by-h matrix.
|
||||
* div: a real number dividing stable and unstable roots.. If < 1.0, a div>1.0 is calculated mechanically.
|
||||
*-------
|
||||
* G1 or Theta_dm: n-by-n matrices.
|
||||
* C: n-by-1 vector of constant terms.
|
||||
* impact: n-by-m matrix.
|
||||
* gev: n-by-2 z vector of stacked generalized eigenvalues where gev(;,2) ./ gev(:,1) = eig(g0, g1).
|
||||
* ywt: n-by-nunstab z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
* fmat: nunstab-by-nunstab z matrix where nunstab is the number of non-stable roots.
|
||||
* fwt: nunstab-by-m z matrix.
|
||||
********************************************************************/
|
||||
|
||||
#ifndef __GENSYS_H__
|
||||
#define __GENSYS_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
//#include "fn_filesetup.h" //For DDDDebugging purpose.
|
||||
|
||||
#define REALSMALL 1e-7
|
||||
//#define PRINTWARNINGofSUNSPOT
|
||||
|
||||
typedef struct TSgensys_tag {
|
||||
//=== Output arguments.
|
||||
TSdmatrix *Theta_dm; //n-by-n.
|
||||
TSdvector *c_dv; //n-by-1.
|
||||
TSdmatrix *Impact_dm; //n-by-m.
|
||||
TSdzmatrix *Fmat_dzm; //nunstab-by-nunstab z matrix. Initialized to NULL and will be dynamically allocated whenever gensys() is called.
|
||||
TSdzmatrix *Fwt_dzm; //nunstab-by-m z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
TSdzmatrix *Ywt_dzm; //n-by-nunstab z matrix of possible complex numbers. Initialized to NULL and dynamically allocated.
|
||||
TSdzmatrix *Gev_dzm; //n-by-2 z matrix of possible complex numbers.
|
||||
TSivector *eu_iv; //2-by-1.
|
||||
//=== Function itself.
|
||||
int (*gensys)(struct TSgensys_tag *, void *);
|
||||
//=== Input arguments, which are all intialized to 0.0 and whose flags are set to M_GE.
|
||||
TSdmatrix *G0_dm; //n-by-n.
|
||||
TSdmatrix *G1_dm; //n-by-n.
|
||||
TSdvector *c0_dv; //n-by-1.
|
||||
TSdmatrix *Psi_dm; //n-by-m.
|
||||
TSdmatrix *Pi_dm; //n-by-k whtere k is the number of expectational errors.
|
||||
double div; //Real number dividing stable and unstable roots.. If < 1.0, a div>1.0 is calculated mechanically.
|
||||
} TSgensys;
|
||||
//
|
||||
typedef int TFlinratexp(struct TSgensys_tag *, void *); //For linear rational expectations models.
|
||||
|
||||
struct TSgensys_tag *CreateTSgensys(TFlinratexp *func, const int _n, const int _m, const int _k, const double div);
|
||||
struct TSgensys_tag *DestroyTSgensys(struct TSgensys_tag *gensys_ps);
|
||||
int gensys_sims(struct TSgensys_tag *gensys_ps, void *dummy_ps);
|
||||
#endif
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,300 +1,300 @@
|
|||
#ifndef __KALMAN_H__
|
||||
#define __KALMAN_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "mathlib.h"
|
||||
#include "switch.h"
|
||||
#include "fn_filesetup.h" //Used to call WriteMatrix(FPTR_DEBUG,....).
|
||||
|
||||
|
||||
typedef struct TSkalcvfurw_tag {
|
||||
//urw: univariate random walk kalman filter. Desigend specially for the 2006 AER SWZ paper.
|
||||
|
||||
//=== Input arguments.
|
||||
int indx_tvsigmasq; //0: constant siqmasq in Kalman updating (default);
|
||||
//1: Keyensian (project-specific) type of time-varying sigmasq in Kalman updating; See pp.37 and 37a in SWZ Learning NOTES;
|
||||
//2: project-specific type;
|
||||
//3: another project-specific type.
|
||||
double sigmasq; //Variance for the residual eps(t) of the measurement equation.
|
||||
int fss; //T: effective sample size (excluding lags).
|
||||
int kx; //dimension for x(t).
|
||||
TSdmatrix *V_dm; //kx-by-kx. Covariance (symmetric and positive definite) matrix for the residual eta(t) of the transition equation.
|
||||
TSdvector *ylhtran_dv; //1-by-T of y(t). The term lh means lelf hand side and tran means transpose.
|
||||
TSdmatrix *Xrhtran_dm; //kx-by-T of x(t). The term rh means right hand side and tran means transpose.
|
||||
TSdvector *z10_dv; //kx-by-1. Initial condition for prediction: z_{1|0}.
|
||||
TSdmatrix *P10_dm; //kx-by-kx symmetric matrix. Initial condition for the variance of the prediction: P_{1|0}.
|
||||
|
||||
//=== Output arguments.
|
||||
TSdvector *zupdate_dv; //kx-by-1. z_{T+1|T}.
|
||||
TSdmatrix *Zpredtran_dm; //kx-by-T matrix of one-step predicted values of z(t). [z_{2|1}, ..., z_{t+1|t}, ..., z_{T+1|T}].
|
||||
//Set to NULL (no output) if storeZ = 0;
|
||||
TSdcell *Ppred_dc; //T cells and kx-by-kx symmetric and positive definite matrix for each cell. Mean square errors of predicted state variables.
|
||||
//{P_{2|1}, ..., P{t+1|t}, ..., P{T+1|T}. Set to NULL (no output if storeV = 0).
|
||||
TSdvector *ylhtranpred_dv; //1-by-T one-step prediction of y(t) or ylhtran_dv. Added 03/17/05.
|
||||
|
||||
//=== Function itself.
|
||||
void (*learning_fnc)(struct TSkalcvfurw_tag *, void *);
|
||||
} TSkalcvfurw; //urw: univariate random walk.
|
||||
//
|
||||
typedef void TFlearninguni(struct TSkalcvfurw_tag *, void *); //For linear rational expectations models.
|
||||
|
||||
|
||||
//=== Better version is TSkalfilmsinputs_1stapp_tag. Kalman filter for constant or known-time-varying DSGE models.
|
||||
typedef struct TSkalfiltv_tag
|
||||
{
|
||||
//General (known-time-varying) Kalman filter for DSGE models.
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given.
|
||||
//
|
||||
// Inputs are as follows:
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-T matrix of time-varying input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-T matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition.
|
||||
// F is an n_z-by-n_z-by-T 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition.
|
||||
// V is an n_z-by-n_z-by-T 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition.
|
||||
// ------
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Not used if indxIni=0.)
|
||||
//
|
||||
// Outputs are as follows:
|
||||
// loglh is a value of the log likelihood function of the state-space model
|
||||
// under the assumption that errors are multivariate Gaussian.
|
||||
// zt_tm1 is an n_z-by-T matrices of one-step predicted state vectors with z0_0m1 as a initial condition
|
||||
// and with z_{t+1|t} as the last element. Thus, we can use it as a base-1 vector.
|
||||
// Pt_tm1 is an n_z-by-n_z-by-T 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition
|
||||
// and with P_{t+1|t} as the last element. Thus, we can use it as a base-1 cell.
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,1))\b(:,1)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1))
|
||||
// Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// March 2007, written by Tao Zha
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
//0: using the unconditional mean for any given regime at time 0. (Default value)
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-T.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-T.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-T. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-T. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-T.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-T.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-T. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdvector *z0_dv; //nz-by-1;
|
||||
TSdmatrix *P0_dm; //nz-by-nz.
|
||||
|
||||
//=== Output arguments.
|
||||
double loglh; //log likelihood.
|
||||
TSdmatrix *zt_tm1_dm; //nz-by-T.
|
||||
TSdcell *Pt_tm1_dc; //nz-by-nz-T.
|
||||
} TSkalfiltv;
|
||||
|
||||
|
||||
|
||||
//=== Inputs for filter for Markov-switching DSGE models at any time t.
|
||||
typedef struct TSkalfilmsinputs_1stapp_tag
|
||||
{
|
||||
//Inputs Markov-switching Kalman filter for DSGE models (conditional on all the regimes at time t).
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on the grand regime s_t that follows a Markov-chain process
|
||||
// and is taken as given.
|
||||
//
|
||||
// Inputs at time t are as follows where nst is number of grand regimes (including lagged regime
|
||||
// and coefficients and shock variances):
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-nst matrix of Markov-switching input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-nst 3-D of Markov-switching matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-nst 3-D of Markov-switching covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-nst 3-D of Markov-switching E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-nst matrix of Markov-switching input vectors in the state equation with b(:,st) as an initial condition.
|
||||
// (alternatively, with the ergodic weighted b(:,st) as an initial condition).
|
||||
// F is an n_z-by-n_z-by-nst 3-D of Markov-switching transition matrices in the state equation with F(:,:,st)
|
||||
// as an initial condition (alternatively, with the ergodic weighted F(:,:,st) as an initial condition).
|
||||
// V is an n_z-by-n_z-by-nRv 3-D of Markov-switching covariance matrices for the error in the state equation
|
||||
// with V(:,:,st) as an initial condition (alternatively, with the ergodic weighted V(:,:,st) as an initial condition).
|
||||
// ------
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-nst matrix of initial condition (Not used if indxIni=0).
|
||||
// P0 is an n_z-by-n_z-by-nst 3-D of initial condition (Not used if indxIni=0).
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,st))\b(:,st)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,st),F(:,:,st)))\vec(V(:,:,st))
|
||||
// Note that all eigenvalues of the matrix F(:,:,st) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// November 2007, written by Tao Zha. Revised, April 2008.
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int nst; //number of grand composite regimes (current and past regimes, coefficient and volatility regimes).
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0,
|
||||
//0: using the unconditional momnets for any given regime at time 0 (default when indxDiffuse = 0).
|
||||
int indxDiffuse; //1: using the diffuse condition for z_{1|0} and P_{1|0} (default option), according to Koopman and Durbin, "Filtering and Smoothing of State Vector for Diffuse State-Space Models," J. of Time Series Analysis, Vol 24(1), pp.85-99.
|
||||
//0: using the unconditional moments.
|
||||
double DiffuseScale; //A large (infinity) number when indxDiffuse = 1.
|
||||
int ztm1_track; //t-1 = -1: no initial conditions z_{1|0} and P_{1|0} has been computed yet, but will be using InitializeKalman_z10_P10(),
|
||||
//t-1 >= 0:T-1: z_{t|t-1} and P_{t|t-1} are updated up to t-1.
|
||||
int dtm1_track; //t-1 = -1: no etdata_dc->C[0] or Dtdata_d4->F[0] has been computed yet.
|
||||
//t-1 >= 0:T-1: etdata_dc->C[t-1] and Dtdata_d4->F[t-1] are updated up to t-1.
|
||||
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-nst.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-nst.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-nst. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-nst. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-nst.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-nst.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-nst. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdmatrix *z0_0_dm; //nz-by-nst. z_{0|0}.
|
||||
TSdmatrix *z0_dm; //nz-by-nst. z_{1|0}.
|
||||
TSdcell *P0_dc; //nz-by-nz-by-nst. P_{1|0}
|
||||
|
||||
|
||||
//=== Output arguments only used for 1st order approximation to zt and Pt depending on infinite past regimes.
|
||||
TSdcell *zt_tm1_dc; //nz-by-nst-by-(T+1), where z_{1|0} is an initial condition (1st element with t-1=0 or t=1 for base-1) and
|
||||
// the terminal condition z_{T+1|T} using Updatekalfilms_1stapp(T, ...) is not computed
|
||||
// when the likelihood logTimetCondLH_kalfilms_1stapp() is computed. Thus, z_{T+1|T}
|
||||
// has not legal value computed in most applications unless in out-of-sample forecasting problems.
|
||||
TSdfourth *Pt_tm1_d4; //nz-by-nz-by-nst-by-(T+1), where P_{1|0} is an initial condition (1st element with t-1=0) and
|
||||
// the terminal condition P_{T+1|T} using Updatekalfilms_1stapp(T, ...) is not computed
|
||||
// when the likelihood logTimetCondLH_kalfilms_1stapp() is computed. Thus, P_{T+1|T}
|
||||
// has not legal value computed in most applications unless in out-of-sample forecasting problems.
|
||||
//+ Will be save for updating likelihood and Kalman filter Updatekalfilms_1stapp(), so save time to recompute these objects again.
|
||||
TSdfourth *PHtran_tdata_d4; //nz-by-ny-by-nst-T, P_{t|t-1}*H_t'. Saved only for updating Kalman filter Updatekalfilms_1stapp().
|
||||
TSdcell *etdata_dc; //ny-by-nst-by-T (with base-0 T), forecast errors e_t in the likelihood.
|
||||
TSdcell *yt_tm1_dc; //ny-by-nst-by-T, one-step forecast y_{t|t-1} for t=0 to T-1 (base-0). Used to back out structural shocks.
|
||||
TSdfourth *Dtdata_d4; //ny-by-ny-nst-by-T, forecast covariance D_t in the likelihood. Saved for updating Kalman filter Updatekalfilms_1stapp().
|
||||
} TSkalfilmsinputs_1stapp;
|
||||
|
||||
|
||||
//=== OLD Code: Inputs for filter for Markov-switching DSGE models at any time t.
|
||||
typedef struct TSkalfilmsinputs_tag
|
||||
{
|
||||
//Inputs Markov-switching Kalman filter for DSGE models (conditional on all the regimes at time t).
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given.
|
||||
//
|
||||
// Inputs at time t are as follows where nRc is number of regimes for coefficients
|
||||
// nRv is number of regimes for volatility (shock variances):
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-nRc matrix of Markov-switching input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-nRc 3-D of Markov-switching matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-nRv 3-D of Markov-switching covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-nRv 3-D of Markov-switching E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-nRc matrix of Markov-switching input vectors in the state equation with b(:,1) as an initial condition.
|
||||
// F is an n_z-by-n_z-by-nRc 3-D of Markov-switching transition matrices in the state equation with F(:,:,1) as an initial condition.
|
||||
// V is an n_z-by-n_z-by-nRv 3-D of Markov-switching covariance matrices for the error in the state equation with V(:,:,1) as an initial condition.
|
||||
// ------
|
||||
// indxIndRegimes: 1: coefficient regime and volatility regime are independent; 0: these two regimes are synchronized completely.
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-nRc*nRv matrix of initial condition when indxIni=1 and indxIndRegimes=1. (Not used if indxIni=0.)
|
||||
// z0 is an n_z-by-nRv matrix of initial condition when indxIni=1 and indxIndRegimes=0. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z-by-nRc*nRv 3-D of initial condition when indxIni=1 and indxIndRegimes=1. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z-by-nRv 3-D of initial condition when indxIni=1 and indxIndRegimes=0. (Not used if indxIni=0.)
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,1))\b(:,1)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1))
|
||||
// Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// November 2007, written by Tao Zha
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int nRc; //number of composite regimes (current and past regimes) for coefficients.
|
||||
int nRstc; //number of coefficient regimes at time t.
|
||||
int nRv; //number of regimes for volatility (shock variances).
|
||||
int indxIndRegimes; //1: coefficient regime and volatility regime are independent; 0: these two regimes are synchronized completely.
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
//0: using the unconditional mean for any given regime at time 0. (Default value)
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-nRc.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-nRc.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-nRv. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-nRv. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-nRc.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-nRc.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-nRv. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdmatrix *z0_dm; //nz-by-nRc*nRv if indxIndRegimes == 1 or nz-by-nRv if indxIndRegimes == 0.
|
||||
TSdcell *P0_dc; //nz-by-nz-by-nRc*nRv if indxIndRegimes == 1 or nz-by-nz-by-nRv if indxIndRegimes == 0.
|
||||
|
||||
|
||||
//=== Output arguments only used for 1st order approximation to zt and Pt depending on infinite past regimes.
|
||||
TSdcell *zt_tm1_dc; //nz-by-nRc*nRv-by-T if indxIndRegimes==1, nz-by-nRv-by-T if indxIndRegimes==0 where nRc=nRv.
|
||||
TSdfourth *Pt_tm1_d4; //nz-by-nz-by-nRc*nRv-T if indxIndRegimes==1, nz-by-nz-by-nRv-by-T if indxIndRegimes==0 where nRc=nRv.
|
||||
} TSkalfilmsinputs;
|
||||
|
||||
|
||||
|
||||
|
||||
//--- Functions for univariate random walk kalman filter.
|
||||
TSkalcvfurw *CreateTSkalcvfurw(TFlearninguni *func, int T, int k, int tv); //, int storeZ, int storeV);
|
||||
TSkalcvfurw *DestroyTSkalcvfurw(TSkalcvfurw *kalcvfurw_ps);
|
||||
void kalcvf_urw(TSkalcvfurw *kalcvfurw_ps, void *dummy_ps);
|
||||
|
||||
//--- New Code: Functions for Markov-switching Kalman filter.
|
||||
struct TSkalfilmsinputs_1stapp_tag *CreateTSkalfilmsinputs_1stapp(int ny, int nz, int nst, int T);
|
||||
struct TSkalfilmsinputs_1stapp_tag *DestroyTSkalfilmsinputs_1stapp(struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps);
|
||||
int InitializeKalman_z10_P10(struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps, TSdmatrix *z10_dm, TSdcell *P10_dc);
|
||||
double logTimetCondLH_kalfilms_1stapp(int st, int inpt, struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps, struct TStateModel_tag *smodel_ps);
|
||||
|
||||
|
||||
|
||||
//--- OLD Code: Functions for general constant Kalman filter.
|
||||
struct TSkalfiltv_tag *CreateTSkalfiltv(int ny, int nz, int T);
|
||||
struct TSkalfiltv_tag *DestroyTSkalfiltv(struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
//Used to test tz_logTimetCondLH_kalfiltv(). (Done April 08). double tz_kalfiltv(struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
double tz_logTimetCondLH_kalfiltv(int st, int inpt, struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
|
||||
//--- OLD Code: Functions for Markov-switching Kalman filter.
|
||||
struct TSkalfilmsinputs_tag *CreateTSkalfilmsinputs(int ny, int nz, int nRc, int nRstc, int nRv, int indxIndRegimes, int T);
|
||||
struct TSkalfilmsinputs_tag *DestroyTSkalfilmsinputs(struct TSkalfilmsinputs_tag *kalfilmsinputs_ps);
|
||||
double tz_logTimetCondLH_kalfilms_1st_approx(int st, int inpt, struct TSkalfilmsinputs_tag *kalfilmsinputs_ps, struct TStateModel_tag *smodel_ps);
|
||||
//IMPORTANT NOTE: in the Markov-switching input file datainp_markov*.prn, it MUST be that
|
||||
// the coefficient regime is the 1st state variable, and
|
||||
// the volatility regime is the 2nd state variable.
|
||||
#endif
|
||||
|
||||
#ifndef __KALMAN_H__
|
||||
#define __KALMAN_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "mathlib.h"
|
||||
#include "switch.h"
|
||||
#include "fn_filesetup.h" //Used to call WriteMatrix(FPTR_DEBUG,....).
|
||||
|
||||
|
||||
typedef struct TSkalcvfurw_tag {
|
||||
//urw: univariate random walk kalman filter. Desigend specially for the 2006 AER SWZ paper.
|
||||
|
||||
//=== Input arguments.
|
||||
int indx_tvsigmasq; //0: constant siqmasq in Kalman updating (default);
|
||||
//1: Keyensian (project-specific) type of time-varying sigmasq in Kalman updating; See pp.37 and 37a in SWZ Learning NOTES;
|
||||
//2: project-specific type;
|
||||
//3: another project-specific type.
|
||||
double sigmasq; //Variance for the residual eps(t) of the measurement equation.
|
||||
int fss; //T: effective sample size (excluding lags).
|
||||
int kx; //dimension for x(t).
|
||||
TSdmatrix *V_dm; //kx-by-kx. Covariance (symmetric and positive definite) matrix for the residual eta(t) of the transition equation.
|
||||
TSdvector *ylhtran_dv; //1-by-T of y(t). The term lh means lelf hand side and tran means transpose.
|
||||
TSdmatrix *Xrhtran_dm; //kx-by-T of x(t). The term rh means right hand side and tran means transpose.
|
||||
TSdvector *z10_dv; //kx-by-1. Initial condition for prediction: z_{1|0}.
|
||||
TSdmatrix *P10_dm; //kx-by-kx symmetric matrix. Initial condition for the variance of the prediction: P_{1|0}.
|
||||
|
||||
//=== Output arguments.
|
||||
TSdvector *zupdate_dv; //kx-by-1. z_{T+1|T}.
|
||||
TSdmatrix *Zpredtran_dm; //kx-by-T matrix of one-step predicted values of z(t). [z_{2|1}, ..., z_{t+1|t}, ..., z_{T+1|T}].
|
||||
//Set to NULL (no output) if storeZ = 0;
|
||||
TSdcell *Ppred_dc; //T cells and kx-by-kx symmetric and positive definite matrix for each cell. Mean square errors of predicted state variables.
|
||||
//{P_{2|1}, ..., P{t+1|t}, ..., P{T+1|T}. Set to NULL (no output if storeV = 0).
|
||||
TSdvector *ylhtranpred_dv; //1-by-T one-step prediction of y(t) or ylhtran_dv. Added 03/17/05.
|
||||
|
||||
//=== Function itself.
|
||||
void (*learning_fnc)(struct TSkalcvfurw_tag *, void *);
|
||||
} TSkalcvfurw; //urw: univariate random walk.
|
||||
//
|
||||
typedef void TFlearninguni(struct TSkalcvfurw_tag *, void *); //For linear rational expectations models.
|
||||
|
||||
|
||||
//=== Better version is TSkalfilmsinputs_1stapp_tag. Kalman filter for constant or known-time-varying DSGE models.
|
||||
typedef struct TSkalfiltv_tag
|
||||
{
|
||||
//General (known-time-varying) Kalman filter for DSGE models.
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given.
|
||||
//
|
||||
// Inputs are as follows:
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-T matrix of time-varying input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-T matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition.
|
||||
// F is an n_z-by-n_z-by-T 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition.
|
||||
// V is an n_z-by-n_z-by-T 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition.
|
||||
// ------
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Not used if indxIni=0.)
|
||||
//
|
||||
// Outputs are as follows:
|
||||
// loglh is a value of the log likelihood function of the state-space model
|
||||
// under the assumption that errors are multivariate Gaussian.
|
||||
// zt_tm1 is an n_z-by-T matrices of one-step predicted state vectors with z0_0m1 as a initial condition
|
||||
// and with z_{t+1|t} as the last element. Thus, we can use it as a base-1 vector.
|
||||
// Pt_tm1 is an n_z-by-n_z-by-T 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition
|
||||
// and with P_{t+1|t} as the last element. Thus, we can use it as a base-1 cell.
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,1))\b(:,1)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1))
|
||||
// Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// March 2007, written by Tao Zha
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
//0: using the unconditional mean for any given regime at time 0. (Default value)
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-T.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-T.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-T. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-T. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-T.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-T.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-T. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdvector *z0_dv; //nz-by-1;
|
||||
TSdmatrix *P0_dm; //nz-by-nz.
|
||||
|
||||
//=== Output arguments.
|
||||
double loglh; //log likelihood.
|
||||
TSdmatrix *zt_tm1_dm; //nz-by-T.
|
||||
TSdcell *Pt_tm1_dc; //nz-by-nz-T.
|
||||
} TSkalfiltv;
|
||||
|
||||
|
||||
|
||||
//=== Inputs for filter for Markov-switching DSGE models at any time t.
|
||||
typedef struct TSkalfilmsinputs_1stapp_tag
|
||||
{
|
||||
//Inputs Markov-switching Kalman filter for DSGE models (conditional on all the regimes at time t).
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on the grand regime s_t that follows a Markov-chain process
|
||||
// and is taken as given.
|
||||
//
|
||||
// Inputs at time t are as follows where nst is number of grand regimes (including lagged regime
|
||||
// and coefficients and shock variances):
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-nst matrix of Markov-switching input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-nst 3-D of Markov-switching matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-nst 3-D of Markov-switching covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-nst 3-D of Markov-switching E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-nst matrix of Markov-switching input vectors in the state equation with b(:,st) as an initial condition.
|
||||
// (alternatively, with the ergodic weighted b(:,st) as an initial condition).
|
||||
// F is an n_z-by-n_z-by-nst 3-D of Markov-switching transition matrices in the state equation with F(:,:,st)
|
||||
// as an initial condition (alternatively, with the ergodic weighted F(:,:,st) as an initial condition).
|
||||
// V is an n_z-by-n_z-by-nRv 3-D of Markov-switching covariance matrices for the error in the state equation
|
||||
// with V(:,:,st) as an initial condition (alternatively, with the ergodic weighted V(:,:,st) as an initial condition).
|
||||
// ------
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-nst matrix of initial condition (Not used if indxIni=0).
|
||||
// P0 is an n_z-by-n_z-by-nst 3-D of initial condition (Not used if indxIni=0).
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,st))\b(:,st)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,st),F(:,:,st)))\vec(V(:,:,st))
|
||||
// Note that all eigenvalues of the matrix F(:,:,st) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// November 2007, written by Tao Zha. Revised, April 2008.
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int nst; //number of grand composite regimes (current and past regimes, coefficient and volatility regimes).
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0,
|
||||
//0: using the unconditional momnets for any given regime at time 0 (default when indxDiffuse = 0).
|
||||
int indxDiffuse; //1: using the diffuse condition for z_{1|0} and P_{1|0} (default option), according to Koopman and Durbin, "Filtering and Smoothing of State Vector for Diffuse State-Space Models," J. of Time Series Analysis, Vol 24(1), pp.85-99.
|
||||
//0: using the unconditional moments.
|
||||
double DiffuseScale; //A large (infinity) number when indxDiffuse = 1.
|
||||
int ztm1_track; //t-1 = -1: no initial conditions z_{1|0} and P_{1|0} has been computed yet, but will be using InitializeKalman_z10_P10(),
|
||||
//t-1 >= 0:T-1: z_{t|t-1} and P_{t|t-1} are updated up to t-1.
|
||||
int dtm1_track; //t-1 = -1: no etdata_dc->C[0] or Dtdata_d4->F[0] has been computed yet.
|
||||
//t-1 >= 0:T-1: etdata_dc->C[t-1] and Dtdata_d4->F[t-1] are updated up to t-1.
|
||||
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-nst.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-nst.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-nst. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-nst. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-nst.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-nst.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-nst. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdmatrix *z0_0_dm; //nz-by-nst. z_{0|0}.
|
||||
TSdmatrix *z0_dm; //nz-by-nst. z_{1|0}.
|
||||
TSdcell *P0_dc; //nz-by-nz-by-nst. P_{1|0}
|
||||
|
||||
|
||||
//=== Output arguments only used for 1st order approximation to zt and Pt depending on infinite past regimes.
|
||||
TSdcell *zt_tm1_dc; //nz-by-nst-by-(T+1), where z_{1|0} is an initial condition (1st element with t-1=0 or t=1 for base-1) and
|
||||
// the terminal condition z_{T+1|T} using Updatekalfilms_1stapp(T, ...) is not computed
|
||||
// when the likelihood logTimetCondLH_kalfilms_1stapp() is computed. Thus, z_{T+1|T}
|
||||
// has not legal value computed in most applications unless in out-of-sample forecasting problems.
|
||||
TSdfourth *Pt_tm1_d4; //nz-by-nz-by-nst-by-(T+1), where P_{1|0} is an initial condition (1st element with t-1=0) and
|
||||
// the terminal condition P_{T+1|T} using Updatekalfilms_1stapp(T, ...) is not computed
|
||||
// when the likelihood logTimetCondLH_kalfilms_1stapp() is computed. Thus, P_{T+1|T}
|
||||
// has not legal value computed in most applications unless in out-of-sample forecasting problems.
|
||||
//+ Will be save for updating likelihood and Kalman filter Updatekalfilms_1stapp(), so save time to recompute these objects again.
|
||||
TSdfourth *PHtran_tdata_d4; //nz-by-ny-by-nst-T, P_{t|t-1}*H_t'. Saved only for updating Kalman filter Updatekalfilms_1stapp().
|
||||
TSdcell *etdata_dc; //ny-by-nst-by-T (with base-0 T), forecast errors e_t in the likelihood.
|
||||
TSdcell *yt_tm1_dc; //ny-by-nst-by-T, one-step forecast y_{t|t-1} for t=0 to T-1 (base-0). Used to back out structural shocks.
|
||||
TSdfourth *Dtdata_d4; //ny-by-ny-nst-by-T, forecast covariance D_t in the likelihood. Saved for updating Kalman filter Updatekalfilms_1stapp().
|
||||
} TSkalfilmsinputs_1stapp;
|
||||
|
||||
|
||||
//=== OLD Code: Inputs for filter for Markov-switching DSGE models at any time t.
|
||||
typedef struct TSkalfilmsinputs_tag
|
||||
{
|
||||
//Inputs Markov-switching Kalman filter for DSGE models (conditional on all the regimes at time t).
|
||||
// It computes a sequence of one-step predictions and their covariance matrices, and the log likelihood.
|
||||
// The function uses a forward recursion algorithm. See also the Matlab function fn_kalfil_tv.m
|
||||
//
|
||||
// State space model is defined as follows:
|
||||
// y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation)
|
||||
// z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation)
|
||||
// where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given.
|
||||
//
|
||||
// Inputs at time t are as follows where nRc is number of regimes for coefficients
|
||||
// nRv is number of regimes for volatility (shock variances):
|
||||
// Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)].
|
||||
// a is an n_y-by-nRc matrix of Markov-switching input vectors in the measurement equation.
|
||||
// H is an n_y-by-n_z-by-nRc 3-D of Markov-switching matrices in the measurement equation.
|
||||
// R is an n_y-by-n_y-by-nRv 3-D of Markov-switching covariance matrices for the error in the measurement equation.
|
||||
// G is an n_z-by-n_y-by-nRv 3-D of Markov-switching E(eta_t * eps_t').
|
||||
// ------
|
||||
// b is an n_z-by-nRc matrix of Markov-switching input vectors in the state equation with b(:,1) as an initial condition.
|
||||
// F is an n_z-by-n_z-by-nRc 3-D of Markov-switching transition matrices in the state equation with F(:,:,1) as an initial condition.
|
||||
// V is an n_z-by-n_z-by-nRv 3-D of Markov-switching covariance matrices for the error in the state equation with V(:,:,1) as an initial condition.
|
||||
// ------
|
||||
// indxIndRegimes: 1: coefficient regime and volatility regime are independent; 0: these two regimes are synchronized completely.
|
||||
// indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
// 0: using the unconditional mean for any given regime at time 0.
|
||||
// z0 is an n_z-by-nRc*nRv matrix of initial condition when indxIni=1 and indxIndRegimes=1. (Not used if indxIni=0.)
|
||||
// z0 is an n_z-by-nRv matrix of initial condition when indxIni=1 and indxIndRegimes=0. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z-by-nRc*nRv 3-D of initial condition when indxIni=1 and indxIndRegimes=1. (Not used if indxIni=0.)
|
||||
// P0 is an n_z-by-n_z-by-nRv 3-D of initial condition when indxIni=1 and indxIndRegimes=0. (Not used if indxIni=0.)
|
||||
//
|
||||
// The initial state vector and its covariance matrix are computed under the bounded (stationary) condition:
|
||||
// z0_0m1 = (I-F(:,:,1))\b(:,1)
|
||||
// vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1))
|
||||
// Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary).
|
||||
//
|
||||
// November 2007, written by Tao Zha
|
||||
// See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003.
|
||||
|
||||
//=== Input arguments.
|
||||
int ny; //number of observables.
|
||||
int nz; //number of state variables.
|
||||
int nRc; //number of composite regimes (current and past regimes) for coefficients.
|
||||
int nRstc; //number of coefficient regimes at time t.
|
||||
int nRv; //number of regimes for volatility (shock variances).
|
||||
int indxIndRegimes; //1: coefficient regime and volatility regime are independent; 0: these two regimes are synchronized completely.
|
||||
int T; //sample size.
|
||||
int indxIni; //1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0;
|
||||
//0: using the unconditional mean for any given regime at time 0. (Default value)
|
||||
TSdmatrix *yt_dm; //ny-by-T.
|
||||
TSdmatrix *at_dm; //ny-by-nRc.
|
||||
TSdcell *Ht_dc; //ny-by-nz-by-nRc.
|
||||
TSdcell *Rt_dc; //ny-by-ny-by-nRv. Covariance matrix for the measurement equation.
|
||||
TSdcell *Gt_dc; //nz-by-ny-by-nRv. Cross-covariance.
|
||||
//
|
||||
TSdmatrix *bt_dm; //nz-by-nRc.
|
||||
TSdcell *Ft_dc; //nz-by-nz-by-nRc.
|
||||
TSdcell *Vt_dc; //nz-by-nz-by-nRv. Covariance matrix for the state equation.
|
||||
//
|
||||
TSdmatrix *z0_dm; //nz-by-nRc*nRv if indxIndRegimes == 1 or nz-by-nRv if indxIndRegimes == 0.
|
||||
TSdcell *P0_dc; //nz-by-nz-by-nRc*nRv if indxIndRegimes == 1 or nz-by-nz-by-nRv if indxIndRegimes == 0.
|
||||
|
||||
|
||||
//=== Output arguments only used for 1st order approximation to zt and Pt depending on infinite past regimes.
|
||||
TSdcell *zt_tm1_dc; //nz-by-nRc*nRv-by-T if indxIndRegimes==1, nz-by-nRv-by-T if indxIndRegimes==0 where nRc=nRv.
|
||||
TSdfourth *Pt_tm1_d4; //nz-by-nz-by-nRc*nRv-T if indxIndRegimes==1, nz-by-nz-by-nRv-by-T if indxIndRegimes==0 where nRc=nRv.
|
||||
} TSkalfilmsinputs;
|
||||
|
||||
|
||||
|
||||
|
||||
//--- Functions for univariate random walk kalman filter.
|
||||
TSkalcvfurw *CreateTSkalcvfurw(TFlearninguni *func, int T, int k, int tv); //, int storeZ, int storeV);
|
||||
TSkalcvfurw *DestroyTSkalcvfurw(TSkalcvfurw *kalcvfurw_ps);
|
||||
void kalcvf_urw(TSkalcvfurw *kalcvfurw_ps, void *dummy_ps);
|
||||
|
||||
//--- New Code: Functions for Markov-switching Kalman filter.
|
||||
struct TSkalfilmsinputs_1stapp_tag *CreateTSkalfilmsinputs_1stapp(int ny, int nz, int nst, int T);
|
||||
struct TSkalfilmsinputs_1stapp_tag *DestroyTSkalfilmsinputs_1stapp(struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps);
|
||||
int InitializeKalman_z10_P10(struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps, TSdmatrix *z10_dm, TSdcell *P10_dc);
|
||||
double logTimetCondLH_kalfilms_1stapp(int st, int inpt, struct TSkalfilmsinputs_1stapp_tag *kalfilmsinputs_1stapp_ps, struct TStateModel_tag *smodel_ps);
|
||||
|
||||
|
||||
|
||||
//--- OLD Code: Functions for general constant Kalman filter.
|
||||
struct TSkalfiltv_tag *CreateTSkalfiltv(int ny, int nz, int T);
|
||||
struct TSkalfiltv_tag *DestroyTSkalfiltv(struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
//Used to test tz_logTimetCondLH_kalfiltv(). (Done April 08). double tz_kalfiltv(struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
double tz_logTimetCondLH_kalfiltv(int st, int inpt, struct TSkalfiltv_tag *kalfiltv_ps);
|
||||
|
||||
//--- OLD Code: Functions for Markov-switching Kalman filter.
|
||||
struct TSkalfilmsinputs_tag *CreateTSkalfilmsinputs(int ny, int nz, int nRc, int nRstc, int nRv, int indxIndRegimes, int T);
|
||||
struct TSkalfilmsinputs_tag *DestroyTSkalfilmsinputs(struct TSkalfilmsinputs_tag *kalfilmsinputs_ps);
|
||||
double tz_logTimetCondLH_kalfilms_1st_approx(int st, int inpt, struct TSkalfilmsinputs_tag *kalfilmsinputs_ps, struct TStateModel_tag *smodel_ps);
|
||||
//IMPORTANT NOTE: in the Markov-switching input file datainp_markov*.prn, it MUST be that
|
||||
// the coefficient regime is the 1st state variable, and
|
||||
// the volatility regime is the 2nd state variable.
|
||||
#endif
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,395 +1,395 @@
|
|||
#ifndef __MATHLIB_H__
|
||||
#define __MATHLIB_H__
|
||||
#include "tzmatlab.h"
|
||||
#include "fn_filesetup.h" //Used to call WriteMatrix(FPTR_DEBUG,....).
|
||||
|
||||
//------------------------------------------------------
|
||||
// LAPACK routines -- all based on Intel MKL (or IMSL C Math library).
|
||||
//------------------------------------------------------
|
||||
int lurgen(TSdmatrix *lu_dm, TSivector *pivot_dv, TSdmatrix *x_dm);
|
||||
int eigrsym(TSdvector *eval_dv, TSdmatrix *eVec_dm, const TSdmatrix *S_dm);
|
||||
int invrtri(TSdmatrix *X_dm, TSdmatrix *A_dm, const char un);
|
||||
//The fastest way is to let X=A and A (and X) will be replaced by inv(A).
|
||||
int invspd(TSdmatrix *X_dm, TSdmatrix *A_dm, const char ul);
|
||||
//Inverse of a symmetric positive matrix A.
|
||||
//Fastest way: let X=A. Then, A (and X) will be replaced by inv(A).
|
||||
int invrgen(TSdmatrix *X_dm, TSdmatrix *A_dm);
|
||||
//Inverse of a general real matrix A.
|
||||
//If X=A, A (and X) will be replaced by inv(A).
|
||||
int eigrgen(TSdzvector *vals_dzv, TSdzmatrix *rights_dzm, TSdzmatrix *lefts_dzm, const TSdmatrix *x_dm);
|
||||
int chol(TSdmatrix *D_dm, TSdmatrix *S_dm, const char ul);
|
||||
// The fastest way for chol() is to let D = S, but D will be replaced by the Choleski factor.
|
||||
int BdivA_rrect(TSdmatrix *X_dm, const TSdmatrix *B_dm, const char lr, const TSdmatrix *A_dm);
|
||||
int BdivA_rgens(TSdmatrix *X_dm, const TSdmatrix *B_dm, const char lr, const TSdmatrix *A_dm);
|
||||
int bdivA_rgens(TSdvector *x_dv, const TSdvector *b_dv, const char lr, const TSdmatrix *A_dm);
|
||||
//If x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
// x = A\b or b/A if lr='\\' or lr='/' where A is a real general square matrix.
|
||||
void Aldivb_spd(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, char an);
|
||||
// Fastest way is to let x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
double detspd(TSdmatrix *S_dm);
|
||||
//Determinant of symmetric positive definite (SPD) matrix must be positive.
|
||||
//We set the return value to be -1 if this matrix is NOT SPD.
|
||||
double logdetspd(TSdmatrix *S_dm);
|
||||
//Determinant of symmetric positive definite (SPD) matrix must be positive.
|
||||
//We set the return value to be log(-1.0) (becomeing NaN) if this matrix is NOT SPD.
|
||||
double logdeterminant(TSdmatrix *A_dm);
|
||||
//
|
||||
//void eig_rgen_all(double *eval_v, double *evec_m, const double *x_m, const int _n);
|
||||
int chol_decomp(double *D, const double *x_m, const int _n, const char ul);
|
||||
int eigrgen_decomp(double *evalr_v, double *evali_v, double *revecr_m, double *reveci_m, double *levecr_m, double *leveci_m, const double *x_m, const int _n);
|
||||
int eigrsym_decomp(double *eval_v, double *evec_m, const double *s_m, const int _n, const char ul);
|
||||
int inv_spd(double *D, const double *s_m, const int _n, const char ul);
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// BLAS routines -- all based on Intel MKL (or IMSL C Math library).
|
||||
//------------------------------------------------------
|
||||
double VectorDotVector(TSdvector *x1_dv, TSdvector *x2_dv);
|
||||
//Output: Return sum(x1[i] * x2[i]) over i=1, ..., n.
|
||||
// Allows the case x1_dv = x2_dv.
|
||||
void ScalarTimesVectorUpdate(TSdvector *x2_dv, const double _alpha, TSdvector *x1_dv);
|
||||
//Output: x2 = alpha * x1 + x2;
|
||||
//Inputs:
|
||||
// alpha: a double scalar;
|
||||
// x1: n-by-1 double vector.
|
||||
void ScalarTimesVector(TSdvector *x_dv, const double _alpha, TSdvector *a_dv, const double _beta);
|
||||
//Output: x_dv = alpha*a_dv + beta*x_dv where x_dv is n-by-1.
|
||||
// When beta=0.0 and x_dv->v = a_dv->v, x_dv->v will be replaced by new values.
|
||||
//Inputs:
|
||||
// a_dv: n-by-1.
|
||||
// _alpha: a double scalar.
|
||||
// _beta: a double scalar.
|
||||
void VectorPlusMinusVectorUpdate(TSdvector *x_dv, const TSdvector *b_dv, double _alpha);
|
||||
//Output: x_dv = _alpha * b_dv + x_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
void VectorPlusMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv, double _alpha);
|
||||
//???????? Use tz_VectorPlusMinusVector() or VectorPlusVector() or VectorMinusVector().
|
||||
//???????? NOT finished yet.
|
||||
//????????Must add _beta for x_dv = alpha*a_dv + beta*b_dv.
|
||||
//??????????? NOT fully tested yet.
|
||||
//Output: x_dv = a_dv + _alpha * b_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
void VectorTimesSelf(TSdmatrix *C_dm, const TSdvector *a_dv, const double _alpha, const double _beta, const char ul);
|
||||
//Using MKL with a default to my own C code.
|
||||
//Output is the matrix C and all other arguments are inputs.
|
||||
//Computes C = alpah*a*a' + beta*C where
|
||||
// a is m-by-1,
|
||||
// C is m-by-m symmetric matrix,
|
||||
// alpha: a double scalar,
|
||||
// beta: a double scalar.
|
||||
// ul: if=='u' or 'U', only the upper triangular part of C is to be referenced; otherwise, only the lower triangular part of C is to be referenced;
|
||||
void VectorTimesVector(TSdmatrix *C_dm, const TSdvector *a_dv, const TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//?????? NOT tested for _beta != 1.0.
|
||||
//Output is the matrix C and all other arguments are inputs.
|
||||
//If beta != 0, always converting C (if symmetric or trianuglar) to a general matrix before the operation.
|
||||
//The fastest way is to let _beta = 1.0.
|
||||
//Computes C = alpah*a*b' + beta*C where
|
||||
// a is m-by-1,
|
||||
// b is n-by-1,
|
||||
// C is m-by-n general matrix,
|
||||
// alpha: a double scalar,
|
||||
// beta: a double scalar.
|
||||
void MatrixPlusMinusMatrixUpdate(TSdmatrix *X_dm, TSdmatrix *A_dm, double _alpha);
|
||||
//$$$$$ If A_dm or X_dm is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output: X =_alpha * A + X where X_dm is an m-by-n general (and possibly symmetric) matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general or symmetric matrix.
|
||||
// _alpha: double scalar.
|
||||
void MatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, const TSdvector *b_dv, const double _alpha, const double _beta, const char tn);
|
||||
//????? This is NOT checked yet: If x_dv = b_dv, x_dv or b_dv will be relaced by alpha*A*x + beta*x.
|
||||
//Output: x_dv->v = _alpha*A_dm'*b_dv + _beta*x_dv for tn=='T'; x_dv = _alpha*A_dm*b_dv + _beta*x_dv for tn=='N'
|
||||
// where x_dv->v is ncols-by-1 or nrows-by-1 and needs not be initialized if _beta is set to 0.0.
|
||||
//Inputs:
|
||||
// A_dm->M: nrows-by-ncols;
|
||||
// b_dv->v: nrows-by-1 or ncols-by-1;
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
// tn: if =='t' or 'T', transpose of A_dm is used; otherwise, A_dm itself (no transpose) is used.
|
||||
void TrimatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, const char tn, const char un);
|
||||
//Output: x_dv = A_dm'*b_dv for tn=='T'; x_dv = A_dm*b_dv for tn=='N' where x_dv->v is _n-by-1.
|
||||
// If x_dv = b_dv (which gives the fastest return, so try to use this option), x_dv will be relaced by A*b or A'*b.
|
||||
//Inputs:
|
||||
// A_dm->M: _n-by-_n triangular matrix.
|
||||
// b_dv->v: _n-by-1 vector.
|
||||
// tn: if =='T' or 't', transpose of A_dm is used; otherwise, A_dm itself (no transpose) is used.
|
||||
// un: if =='U' or 'u', A_dm is unit triangular; otherwise, A_dm is non-unit triangular (i.e., a regular triangular matrix).
|
||||
void SymmatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//????? This is NOT checked yet: If x_dv = b_dv, x_dv or b_dv will be relaced by alpha*A*x + beta*x.
|
||||
//Output:
|
||||
// x_dv = alpha*A_dm*b_dv + beta*x_dv where x_dv->v is _n-by-1.
|
||||
// When beta=0, there is no need to initialize the value of x_dv.
|
||||
//Inputs:
|
||||
// A_dm->M: _n-by-_n triangular matrix.
|
||||
// b_dv->v: _n-by-1 vector.
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
void VectorTimesMatrix(TSdvector *x_dv, const TSdvector *b_dv, TSdmatrix *A_dm, const double _alpha, const double _beta, const char tn);
|
||||
//Output: x_dv->v = _alpha*b_dv*A_dm + _beta*x_dv for tn=='N'; x_dv = _alpha*b_dv*A_dm' + _beta*x_dv for tn=='T'
|
||||
// where x_dv->v is 1-by-ncols or 1-by-nrows and needs not be initialized if _beta is set to 0.0.
|
||||
//Inputs:
|
||||
// A_dm->M: nrows-by-ncols;
|
||||
// b_dv->v: 1-by-nrows or 1-by-ncols;
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
// tn: if =='T' or 't', transpose of A_dm is used; otherwise (=='N' or 'n'), A_dm itself (no transpose) is used.
|
||||
void ScalarTimesMatrix(TSdmatrix *x_dm, const double _alpha, TSdmatrix *a_dm, const double _beta);
|
||||
//$$$$$ If a_dm or x_dm (when _beta!=0) is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output: x_dm = alpha*a_dm + beta*x_dm where x_dm is m-by-n.
|
||||
// Fastest way is to let beta=0.0 and x_dm->M = a_dm->M. Then x_dm->M will be replaced by new values.
|
||||
// However, with beta=0.0, x_dm and a_dm can be different.
|
||||
//Inputs:
|
||||
// a_dm: m-by-n.
|
||||
// _alpha: a double scalar.
|
||||
// _beta: a double scalar.
|
||||
void ScalarTimesMatrixSquare(TSdmatrix *B_dm, const double _alpha, TSdmatrix *A_dm, const char tn, const double _beta);
|
||||
//Outputs:
|
||||
// B = alpha*o(A) + beta*B, where o(A) = A' if tn=='T' or 't' or A if tn=='N' or 'n'.
|
||||
// If A=B, then A is replaced by alpha*o(A) + beta*A.
|
||||
//Inputs:
|
||||
// A_dm: n-by-n square matrix.
|
||||
// B_dm: n-by-n square matrix.
|
||||
// tn: 'T' (transpose of A) or 'N' (no transpose).
|
||||
// alpha, beta: double scalars.
|
||||
void MatrixTimesSelf(TSdmatrix *C_dm, const char ul, TSdmatrix *A_dm, const char tn, const double _alpha, const double _beta);
|
||||
//If tn=='N' or 'n', C = alpha*A*A' + beta*C.
|
||||
//If tn=='T' or 't', C = alpha*A'*A + beta*C.
|
||||
//If ul=='U' or 'u', C_dm->flag = M_SU;
|
||||
//If ul=='L' or 'l', C_dm->flag = M_SL;
|
||||
// C must be different from A.
|
||||
// C is n-by-n;
|
||||
// A is n-by-k if tn=='N';
|
||||
// k-by-n if tn=='T';
|
||||
// alpha is a double scalar,
|
||||
// beta is a double scalar.
|
||||
void MatrixTimesMatrix(TSdmatrix *C_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, const double _alpha, const double _beta, const char tn1, const char tn2);
|
||||
//Output is C and all other arguments are inputs.
|
||||
//Computes C = alpah*op(A)*op(B) + beta*C where op() is either transpose or not, depending on 't' or 'n',
|
||||
// op(A) is m-by-k,
|
||||
// op(B) is k-by-n,
|
||||
// C is m-by-n,
|
||||
// C must be different from A and from B.
|
||||
// A and B can be the same, however.
|
||||
// alpha is a double scalar,
|
||||
// beta is a double scalar.
|
||||
// tn1: if == 'T' or 't', the transpose of A is used; otherwise (== 'N' or 'n"), A itself (no transpose) is used.
|
||||
// tn2: if == 'T' or 't', the transpose of B is used; otherwise (== 'N' or 'n"), B itself (no transpose) is used.
|
||||
void SolveTriSysVector(TSdvector *x_dv, const TSdmatrix *T_dm, TSdvector *b_dv, const char tn, const char un);
|
||||
//Output --- computes x_dv = inv(T_dm)*b_dv by solving a triangular system of equation T_dm * x_dv = b_dv.
|
||||
// x_dv(_n-by-1) = inv(T_dm)*b_v if tn=='N'; = inv(T_dm')*b_v if tn=='T'.
|
||||
// Fastest way is to let x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
|
||||
|
||||
|
||||
|
||||
// #define ScalarTimesVector(x_v, a, b_v, _n) cblas_daxpy(_n, a, b_v, 1, x_v, 1)
|
||||
// //Output: x_v = a * b_v + x_v where double *x_v (_n-by-1) must be initialized.
|
||||
// //Inputs: a -- double scalar; b_v -- pointer (_n-by-1) to double.
|
||||
// #define VectorDotVector(a_v, b_v, _n) cblas_ddot(_n, a_v, 1, b_v, 1)
|
||||
// //Output: x=a_v'*b_v: double scalar.
|
||||
// //Inputs: a_v, b_v: pointer (_n-by-1) to double.
|
||||
|
||||
void SymmetricMatrixTimesVector(double *x_v, const double a, const double *A_m, const double *a_v, const double b, const int _n, const char ul);
|
||||
//Output: x_v = a*A_m*a_v + b*X_m where x_v (_n-by-1) must be allocated (but needs not be initialized).
|
||||
//Inputs:
|
||||
// A_m: _n-by-_n symmetric matrix;
|
||||
// a_v: _n-by-1;
|
||||
// a, b: scalars;
|
||||
// ul: if =='u' or 'U', upper triangular elements in A_m are filled; if =='l' or 'L', lower triangular elements in A_m are filled.
|
||||
void SolveTriangularSystemVector(double *x_v, const double *A_m, const double *b_v, const int _n, const char ul, const char tn, const char un);
|
||||
//Outputs:
|
||||
// x_v(_n-by-1) = inv(A_m)*b_v. If x_v=b_v, b_v will be overwritten by x_v.
|
||||
//-------
|
||||
//Inputs:
|
||||
// A_m: _n-by-_n upper or lower triangular matrix;
|
||||
// b_v: _n-by-1 vector.
|
||||
// ul: if =='u' or 'U', A_m is upper triangular; if =='l' or 'L', A_m is lower triangular.
|
||||
// tn: if =='t' or 'T', A_m' (transpose), instead of A_m, will be used; if =='n', A_m itself (no transpose) will be used.
|
||||
// un: if =='u' or 'U', A_m is a unit upper triangular (i.e., the diagonal being 1);
|
||||
// if =='n' or 'N', A_m is a non-unit upper triangular.
|
||||
//
|
||||
// Computes x_v = inv(A_m)*b_v by solving a triangular system of equation A_m * x_v = b_v.
|
||||
// Note I: Intel MLK cblas_dtrsv() does not test for singularity or near-singulariy of the system.
|
||||
// Such tests must be performed before calling this BLAS routine.
|
||||
// Note II: if x_v=b_v, b_v will be overwritten by x_v.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// MKL Vector Mathematical Library with default using my own routines.
|
||||
//------------------------------------------------------
|
||||
void VectorDotDivByVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//????????? NOT tested yet. 06/13/03.
|
||||
//--- The faster way is to use MKL VML with x_dv != a_dv and x_dv != b_dv; x = a./b;
|
||||
void ElementwiseVectorDivideVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//--- The faster way is to use MKL VML with y_dv != x_dv;
|
||||
void ElementwiseInverseofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
void ElementwiseSqrtofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
void ElementwiseLogtofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
//--- The faster way is to use MKL VML with Y_dm != X_dm;
|
||||
void ElementwiseInverseofMatrix(TSdmatrix *Y_dm, TSdmatrix *X_dm);
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// Matrix routines (my own).
|
||||
//------------------------------------------------------
|
||||
void tz_VectorPlusMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const double _alpha, const TSdvector *b_dv, const double _beta);
|
||||
//Output: x_dv = alpha*a_dv + beta*b_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// _alpha: double constant.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _beta: double constant.
|
||||
void VectorPlusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = a_dv + b_dv where x_dv is _n-by-1.
|
||||
// If x_dv = a_dv, a_dv will be replaced by x_dv.
|
||||
// If x_dv = b_dv, b_dv will be replaced by x_dv,
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = a_dv - b_dv where x_dv is _n-by-1.
|
||||
// If x_dv = a_dv, x_dv will be replaced by x_dv - b_dv.
|
||||
// If x_dv = b_dv, x_dv will be replaced by a_dv - x_dv.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorPlusVectorUpdate(TSdvector *x_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = b_dv + x_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorDotTimesVector(TSdvector *x_dv, const TSdvector *a_dv, TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//Output:
|
||||
// x_dv is _n-by-1.
|
||||
// x_dv = _alpha * a_dv .* b_dv + _beta * x_dv if x_dv != b_dv.
|
||||
// x_dv = _alpha * a_dv .* x_dv + _beta * x_dv if x_dv = b_dv.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
// _beta: a double scalar.
|
||||
void SwapColsofMatrix(TSdmatrix *X_dm, int j1, int j2);
|
||||
//??????? NOT tested yet.
|
||||
void SwapColsofMatrices(TSdmatrix *X1_dm, int j1, TSdmatrix *X2_dm, int j2);
|
||||
void SwapPositionsofMatrix(TSdmatrix *X_dm, int j1, int j2);
|
||||
void SwapMatricesofCell(TSdcell *A_dc, int c1, int c2);
|
||||
void SwapVectorsofCellvec(TSdcellvec *x_dcv, int c1, int c2);
|
||||
void SwapVectorsofCellvec_int(TSicellvec *x_icv, int c1, int c2);
|
||||
void PermuteColsofMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteRowsofMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteMatricesofCell(TSdcell *A_dc, const TSivector *indx_iv);
|
||||
void ScalarTimesColofMatrix(TSdvector *y_dv, double _alpha, TSdmatrix *x_dm, int _j);
|
||||
//????????? Default option, in the #else, has NOT been tested yet!
|
||||
void ScalarTimesColofMatrix2ColofMatrix(TSdmatrix *y_dm, int jy, double _alpha, TSdmatrix *x_dm, int jx);
|
||||
void ScalarTimesColofMatrixPlusVector2ColofMatrix(TSdmatrix *Y_dm, int jy, double _alpha, TSdmatrix *X_dm, int jx, double _beta, TSdvector *x_dv);
|
||||
// void ColofMatrixDotTimesVector(TSdvector *y_dv, TSdmatrix *X_dm, int jx, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void MatrixDotDivideVector_row(TSdmatrix *Y_dm, TSdmatrix *X_dm, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void RowofMatrixDotDivideVector(TSdvector *y_dv, TSdmatrix *X_dm, int ix, TSdvector *x_dv, double _alpha, double _beta);
|
||||
//??????? NOT tested yet, 01/02/04.
|
||||
void ColofMatrixDotTimesVector(TSdvector *y_dv, TSdmatrix *X_dm, int jx, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void ColofMatrixDotTimesColofMatrix(TSdvector *y_dv, TSdmatrix *X1_dm, int jx1, TSdmatrix *X2_dm, int jx2, double _alpha, double _beta);
|
||||
void ColofMatrixDotTimesColofMatrix2ColofMatrix(TSdmatrix *Y_dm, int jy, TSdmatrix *X1_dm, int jx1, TSdmatrix *X2_dm, int jx2, double _alpha, double _beta);
|
||||
void MatrixPlusMatrixUpdate(TSdmatrix *X_dm, TSdmatrix *A_dm);
|
||||
//Output: X = X + A where X_dm is an m-by-n general matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
void MatrixPlusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//Output: X = A + B where X_dm is an m-by-n general matrix.
|
||||
// If X=A, A will be replaced by X; if X=B, B will be replaced by X.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
void MatrixMinusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//Output: X = A - B where X_dm is an m-by-n general matrix.
|
||||
// If X=A, A will be replaced by X; if X=B, B will be replaced by X.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
void Matrix2PlusMinusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, TSdmatrix *C_dm, const double _alpha, const double _beta, const double _gamma);
|
||||
//????? Not yet exhaust all possibilities of alpha, beta, and gamma to get most efficiency. Add more as required. 10 February 2003.
|
||||
//Output: X = alpha*A + beta*B + gamma*C where X_dm is an m-by-n general matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
// C_dm: m-by-n general matrix.
|
||||
// _alpha: a double scalar for A_dm.
|
||||
// _beta: a double scalar for B_dm.
|
||||
// _gamma: a double scalar for C_dm.
|
||||
void MatrixPlusConstantDiagUpdate(TSdmatrix *X_dm, const double _alpha);
|
||||
//Output: X = X + diag([_alpha, ..., _alpha]) where X is an n-by-n square real matrix.
|
||||
void MatrixDotTimesMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, const double _alpha, const double _beta);
|
||||
//$$$$$ If A_dm or B_dm or X_dm (when _beta!=0) is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output:
|
||||
// X_dm is m-by-n.
|
||||
// X_dm = _alpha * A_dm .* B_dm + _beta * X_dm if X_dm != B_dm.
|
||||
// X_dm = _alpha * A_dm .* X_dm + _beta * X_dm if X_dm = B_dm.
|
||||
void CopyVector0(TSdvector *x1_dv, const TSdvector *x2_dv);
|
||||
void CopyMatrix0(TSdmatrix *x1_dm, TSdmatrix *x2_dm);
|
||||
void CopyCellvec0(TSdcellvec *x1_dcv, TSdcellvec *x2_dcv);
|
||||
void CopyCell0(TSdcell *x1_dc, TSdcell *x2_dc);
|
||||
void CopySubmatrix0(TSdmatrix *x1_dm, TSdmatrix *x2_dm, const int br, const int bc, const int nrs, const int ncs);
|
||||
void CopySubmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
void CopySubrowmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
//??????? NOT tested yet.
|
||||
void CopySubmatrix2rowmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
void CopySubrowmatrix2matrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
//??????? NOT tested yet.
|
||||
void CopySubvector(TSdvector *x1_dv, const int ptrloc1, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector_int(TSivector *x1_iv, const int ptrloc1, const TSivector *x2_iv, const int ptrloc2, const int nels);
|
||||
void CopySubmatrix2vector(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nels);
|
||||
void CopySubmatrix2vector_sub(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nrs, const int ncs);
|
||||
void CopySubmatrix2vector_int(TSivector *x1_iv, const int ptrloc1, TSimatrix *x2_im, const int br, const int bc, const int nels);
|
||||
void CopySubmatrix2vector_row(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nels);
|
||||
void CopySubvector2matrix(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector2rowmatrix(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector2matrix_sub(TSdmatrix *x1_dm, const int br, const int bc, const int nrs, const int ncs, TSdvector *x2_dv, const int ptrloc2);
|
||||
void CopySubvector2matrix_unr(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void TransposeSquare(TSdmatrix *B_dm, TSdmatrix *A_dm);
|
||||
//???????? Some options are NOT test yet. 2/27/03. ???????????
|
||||
void TransposeRegular(TSdmatrix *B_dm, const TSdmatrix *A_dm);
|
||||
TSdmatrix *tz_TransposeRegular(TSdmatrix *B_dm, const TSdmatrix *A_dm);
|
||||
void SUtoGE(TSdmatrix *x_dm);
|
||||
//Output: x_dm (nrows<=ncols) becomes a general matrix in addition to being upper symmetric.
|
||||
//Input: x_dm (nrows<=ncols) is upper symmetric.
|
||||
void SLtoGE(TSdmatrix *x_dm);
|
||||
//Output: x_dm (nrows>=ncols) becomes a general matrix in addition to being lower symmetric.
|
||||
//Input: x_dm (nrows>=ncols) is lower symmetric.
|
||||
double SumVector(TSdvector *x_dv);
|
||||
double MaxVector(TSdvector *x_dv);
|
||||
double MinVector(TSdvector *x_dv);
|
||||
int MaxVector_int(TSivector *x_iv);
|
||||
void SumMatrix(TSdvector *x_dv, const TSdmatrix *X_dm, const char rc);
|
||||
//+
|
||||
void diagdv(TSdvector *x_dv, TSdmatrix *x_dm);
|
||||
TSdmatrix *tz_DiagMatrix(TSdmatrix *X_dm, TSdvector *x_dv);
|
||||
double tracefabs(TSdmatrix *x_dm);
|
||||
double tracelogfabs(TSdmatrix *x_dm);
|
||||
double tracelog(TSdmatrix *x_dm);
|
||||
double sumoflogvector(TSdvector *x_dv);
|
||||
//
|
||||
TSdmatrix *tz_kron(TSdmatrix *C_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//C = kron(A, B), compatible with Matlab notation.
|
||||
//Inputs:
|
||||
// A_dm and B_dm: two real general matrices.
|
||||
//Outputs:
|
||||
// If C_dm == NULL, C_dm is created (memory allocated) and returned (thus, the memory must be destroyed outside this function).
|
||||
// If C_dm != NULL, C_dm's memory has already been allocated outside this function and the same C_dm will be returned.
|
||||
|
||||
|
||||
|
||||
|
||||
//=== Self-written routines.
|
||||
void ergodicp(TSdvector *p_dv, TSdmatrix *P_dm);
|
||||
//double *fn_ergodp2(const double *cp_m, const int _n);
|
||||
double *alloc_ergodp2(const double *cp_m, const int _n);
|
||||
#endif
|
||||
#ifndef __MATHLIB_H__
|
||||
#define __MATHLIB_H__
|
||||
#include "tzmatlab.h"
|
||||
#include "fn_filesetup.h" //Used to call WriteMatrix(FPTR_DEBUG,....).
|
||||
|
||||
//------------------------------------------------------
|
||||
// LAPACK routines -- all based on Intel MKL (or IMSL C Math library).
|
||||
//------------------------------------------------------
|
||||
int lurgen(TSdmatrix *lu_dm, TSivector *pivot_dv, TSdmatrix *x_dm);
|
||||
int eigrsym(TSdvector *eval_dv, TSdmatrix *eVec_dm, const TSdmatrix *S_dm);
|
||||
int invrtri(TSdmatrix *X_dm, TSdmatrix *A_dm, const char un);
|
||||
//The fastest way is to let X=A and A (and X) will be replaced by inv(A).
|
||||
int invspd(TSdmatrix *X_dm, TSdmatrix *A_dm, const char ul);
|
||||
//Inverse of a symmetric positive matrix A.
|
||||
//Fastest way: let X=A. Then, A (and X) will be replaced by inv(A).
|
||||
int invrgen(TSdmatrix *X_dm, TSdmatrix *A_dm);
|
||||
//Inverse of a general real matrix A.
|
||||
//If X=A, A (and X) will be replaced by inv(A).
|
||||
int eigrgen(TSdzvector *vals_dzv, TSdzmatrix *rights_dzm, TSdzmatrix *lefts_dzm, const TSdmatrix *x_dm);
|
||||
int chol(TSdmatrix *D_dm, TSdmatrix *S_dm, const char ul);
|
||||
// The fastest way for chol() is to let D = S, but D will be replaced by the Choleski factor.
|
||||
int BdivA_rrect(TSdmatrix *X_dm, const TSdmatrix *B_dm, const char lr, const TSdmatrix *A_dm);
|
||||
int BdivA_rgens(TSdmatrix *X_dm, const TSdmatrix *B_dm, const char lr, const TSdmatrix *A_dm);
|
||||
int bdivA_rgens(TSdvector *x_dv, const TSdvector *b_dv, const char lr, const TSdmatrix *A_dm);
|
||||
//If x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
// x = A\b or b/A if lr='\\' or lr='/' where A is a real general square matrix.
|
||||
void Aldivb_spd(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, char an);
|
||||
// Fastest way is to let x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
double detspd(TSdmatrix *S_dm);
|
||||
//Determinant of symmetric positive definite (SPD) matrix must be positive.
|
||||
//We set the return value to be -1 if this matrix is NOT SPD.
|
||||
double logdetspd(TSdmatrix *S_dm);
|
||||
//Determinant of symmetric positive definite (SPD) matrix must be positive.
|
||||
//We set the return value to be log(-1.0) (becomeing NaN) if this matrix is NOT SPD.
|
||||
double logdeterminant(TSdmatrix *A_dm);
|
||||
//
|
||||
//void eig_rgen_all(double *eval_v, double *evec_m, const double *x_m, const int _n);
|
||||
int chol_decomp(double *D, const double *x_m, const int _n, const char ul);
|
||||
int eigrgen_decomp(double *evalr_v, double *evali_v, double *revecr_m, double *reveci_m, double *levecr_m, double *leveci_m, const double *x_m, const int _n);
|
||||
int eigrsym_decomp(double *eval_v, double *evec_m, const double *s_m, const int _n, const char ul);
|
||||
int inv_spd(double *D, const double *s_m, const int _n, const char ul);
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// BLAS routines -- all based on Intel MKL (or IMSL C Math library).
|
||||
//------------------------------------------------------
|
||||
double VectorDotVector(TSdvector *x1_dv, TSdvector *x2_dv);
|
||||
//Output: Return sum(x1[i] * x2[i]) over i=1, ..., n.
|
||||
// Allows the case x1_dv = x2_dv.
|
||||
void ScalarTimesVectorUpdate(TSdvector *x2_dv, const double _alpha, TSdvector *x1_dv);
|
||||
//Output: x2 = alpha * x1 + x2;
|
||||
//Inputs:
|
||||
// alpha: a double scalar;
|
||||
// x1: n-by-1 double vector.
|
||||
void ScalarTimesVector(TSdvector *x_dv, const double _alpha, TSdvector *a_dv, const double _beta);
|
||||
//Output: x_dv = alpha*a_dv + beta*x_dv where x_dv is n-by-1.
|
||||
// When beta=0.0 and x_dv->v = a_dv->v, x_dv->v will be replaced by new values.
|
||||
//Inputs:
|
||||
// a_dv: n-by-1.
|
||||
// _alpha: a double scalar.
|
||||
// _beta: a double scalar.
|
||||
void VectorPlusMinusVectorUpdate(TSdvector *x_dv, const TSdvector *b_dv, double _alpha);
|
||||
//Output: x_dv = _alpha * b_dv + x_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
void VectorPlusMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv, double _alpha);
|
||||
//???????? Use tz_VectorPlusMinusVector() or VectorPlusVector() or VectorMinusVector().
|
||||
//???????? NOT finished yet.
|
||||
//????????Must add _beta for x_dv = alpha*a_dv + beta*b_dv.
|
||||
//??????????? NOT fully tested yet.
|
||||
//Output: x_dv = a_dv + _alpha * b_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
void VectorTimesSelf(TSdmatrix *C_dm, const TSdvector *a_dv, const double _alpha, const double _beta, const char ul);
|
||||
//Using MKL with a default to my own C code.
|
||||
//Output is the matrix C and all other arguments are inputs.
|
||||
//Computes C = alpah*a*a' + beta*C where
|
||||
// a is m-by-1,
|
||||
// C is m-by-m symmetric matrix,
|
||||
// alpha: a double scalar,
|
||||
// beta: a double scalar.
|
||||
// ul: if=='u' or 'U', only the upper triangular part of C is to be referenced; otherwise, only the lower triangular part of C is to be referenced;
|
||||
void VectorTimesVector(TSdmatrix *C_dm, const TSdvector *a_dv, const TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//?????? NOT tested for _beta != 1.0.
|
||||
//Output is the matrix C and all other arguments are inputs.
|
||||
//If beta != 0, always converting C (if symmetric or trianuglar) to a general matrix before the operation.
|
||||
//The fastest way is to let _beta = 1.0.
|
||||
//Computes C = alpah*a*b' + beta*C where
|
||||
// a is m-by-1,
|
||||
// b is n-by-1,
|
||||
// C is m-by-n general matrix,
|
||||
// alpha: a double scalar,
|
||||
// beta: a double scalar.
|
||||
void MatrixPlusMinusMatrixUpdate(TSdmatrix *X_dm, TSdmatrix *A_dm, double _alpha);
|
||||
//$$$$$ If A_dm or X_dm is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output: X =_alpha * A + X where X_dm is an m-by-n general (and possibly symmetric) matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general or symmetric matrix.
|
||||
// _alpha: double scalar.
|
||||
void MatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, const TSdvector *b_dv, const double _alpha, const double _beta, const char tn);
|
||||
//????? This is NOT checked yet: If x_dv = b_dv, x_dv or b_dv will be relaced by alpha*A*x + beta*x.
|
||||
//Output: x_dv->v = _alpha*A_dm'*b_dv + _beta*x_dv for tn=='T'; x_dv = _alpha*A_dm*b_dv + _beta*x_dv for tn=='N'
|
||||
// where x_dv->v is ncols-by-1 or nrows-by-1 and needs not be initialized if _beta is set to 0.0.
|
||||
//Inputs:
|
||||
// A_dm->M: nrows-by-ncols;
|
||||
// b_dv->v: nrows-by-1 or ncols-by-1;
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
// tn: if =='t' or 'T', transpose of A_dm is used; otherwise, A_dm itself (no transpose) is used.
|
||||
void TrimatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, const char tn, const char un);
|
||||
//Output: x_dv = A_dm'*b_dv for tn=='T'; x_dv = A_dm*b_dv for tn=='N' where x_dv->v is _n-by-1.
|
||||
// If x_dv = b_dv (which gives the fastest return, so try to use this option), x_dv will be relaced by A*b or A'*b.
|
||||
//Inputs:
|
||||
// A_dm->M: _n-by-_n triangular matrix.
|
||||
// b_dv->v: _n-by-1 vector.
|
||||
// tn: if =='T' or 't', transpose of A_dm is used; otherwise, A_dm itself (no transpose) is used.
|
||||
// un: if =='U' or 'u', A_dm is unit triangular; otherwise, A_dm is non-unit triangular (i.e., a regular triangular matrix).
|
||||
void SymmatrixTimesVector(TSdvector *x_dv, TSdmatrix *A_dm, TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//????? This is NOT checked yet: If x_dv = b_dv, x_dv or b_dv will be relaced by alpha*A*x + beta*x.
|
||||
//Output:
|
||||
// x_dv = alpha*A_dm*b_dv + beta*x_dv where x_dv->v is _n-by-1.
|
||||
// When beta=0, there is no need to initialize the value of x_dv.
|
||||
//Inputs:
|
||||
// A_dm->M: _n-by-_n triangular matrix.
|
||||
// b_dv->v: _n-by-1 vector.
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
void VectorTimesMatrix(TSdvector *x_dv, const TSdvector *b_dv, TSdmatrix *A_dm, const double _alpha, const double _beta, const char tn);
|
||||
//Output: x_dv->v = _alpha*b_dv*A_dm + _beta*x_dv for tn=='N'; x_dv = _alpha*b_dv*A_dm' + _beta*x_dv for tn=='T'
|
||||
// where x_dv->v is 1-by-ncols or 1-by-nrows and needs not be initialized if _beta is set to 0.0.
|
||||
//Inputs:
|
||||
// A_dm->M: nrows-by-ncols;
|
||||
// b_dv->v: 1-by-nrows or 1-by-ncols;
|
||||
// _alpha: double scalar;
|
||||
// _beta: double scalar;
|
||||
// tn: if =='T' or 't', transpose of A_dm is used; otherwise (=='N' or 'n'), A_dm itself (no transpose) is used.
|
||||
void ScalarTimesMatrix(TSdmatrix *x_dm, const double _alpha, TSdmatrix *a_dm, const double _beta);
|
||||
//$$$$$ If a_dm or x_dm (when _beta!=0) is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output: x_dm = alpha*a_dm + beta*x_dm where x_dm is m-by-n.
|
||||
// Fastest way is to let beta=0.0 and x_dm->M = a_dm->M. Then x_dm->M will be replaced by new values.
|
||||
// However, with beta=0.0, x_dm and a_dm can be different.
|
||||
//Inputs:
|
||||
// a_dm: m-by-n.
|
||||
// _alpha: a double scalar.
|
||||
// _beta: a double scalar.
|
||||
void ScalarTimesMatrixSquare(TSdmatrix *B_dm, const double _alpha, TSdmatrix *A_dm, const char tn, const double _beta);
|
||||
//Outputs:
|
||||
// B = alpha*o(A) + beta*B, where o(A) = A' if tn=='T' or 't' or A if tn=='N' or 'n'.
|
||||
// If A=B, then A is replaced by alpha*o(A) + beta*A.
|
||||
//Inputs:
|
||||
// A_dm: n-by-n square matrix.
|
||||
// B_dm: n-by-n square matrix.
|
||||
// tn: 'T' (transpose of A) or 'N' (no transpose).
|
||||
// alpha, beta: double scalars.
|
||||
void MatrixTimesSelf(TSdmatrix *C_dm, const char ul, TSdmatrix *A_dm, const char tn, const double _alpha, const double _beta);
|
||||
//If tn=='N' or 'n', C = alpha*A*A' + beta*C.
|
||||
//If tn=='T' or 't', C = alpha*A'*A + beta*C.
|
||||
//If ul=='U' or 'u', C_dm->flag = M_SU;
|
||||
//If ul=='L' or 'l', C_dm->flag = M_SL;
|
||||
// C must be different from A.
|
||||
// C is n-by-n;
|
||||
// A is n-by-k if tn=='N';
|
||||
// k-by-n if tn=='T';
|
||||
// alpha is a double scalar,
|
||||
// beta is a double scalar.
|
||||
void MatrixTimesMatrix(TSdmatrix *C_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, const double _alpha, const double _beta, const char tn1, const char tn2);
|
||||
//Output is C and all other arguments are inputs.
|
||||
//Computes C = alpah*op(A)*op(B) + beta*C where op() is either transpose or not, depending on 't' or 'n',
|
||||
// op(A) is m-by-k,
|
||||
// op(B) is k-by-n,
|
||||
// C is m-by-n,
|
||||
// C must be different from A and from B.
|
||||
// A and B can be the same, however.
|
||||
// alpha is a double scalar,
|
||||
// beta is a double scalar.
|
||||
// tn1: if == 'T' or 't', the transpose of A is used; otherwise (== 'N' or 'n"), A itself (no transpose) is used.
|
||||
// tn2: if == 'T' or 't', the transpose of B is used; otherwise (== 'N' or 'n"), B itself (no transpose) is used.
|
||||
void SolveTriSysVector(TSdvector *x_dv, const TSdmatrix *T_dm, TSdvector *b_dv, const char tn, const char un);
|
||||
//Output --- computes x_dv = inv(T_dm)*b_dv by solving a triangular system of equation T_dm * x_dv = b_dv.
|
||||
// x_dv(_n-by-1) = inv(T_dm)*b_v if tn=='N'; = inv(T_dm')*b_v if tn=='T'.
|
||||
// Fastest way is to let x_dv->v = b_dv->v. Then, x_dv->v will be replaced by new values.
|
||||
|
||||
|
||||
|
||||
|
||||
// #define ScalarTimesVector(x_v, a, b_v, _n) cblas_daxpy(_n, a, b_v, 1, x_v, 1)
|
||||
// //Output: x_v = a * b_v + x_v where double *x_v (_n-by-1) must be initialized.
|
||||
// //Inputs: a -- double scalar; b_v -- pointer (_n-by-1) to double.
|
||||
// #define VectorDotVector(a_v, b_v, _n) cblas_ddot(_n, a_v, 1, b_v, 1)
|
||||
// //Output: x=a_v'*b_v: double scalar.
|
||||
// //Inputs: a_v, b_v: pointer (_n-by-1) to double.
|
||||
|
||||
void SymmetricMatrixTimesVector(double *x_v, const double a, const double *A_m, const double *a_v, const double b, const int _n, const char ul);
|
||||
//Output: x_v = a*A_m*a_v + b*X_m where x_v (_n-by-1) must be allocated (but needs not be initialized).
|
||||
//Inputs:
|
||||
// A_m: _n-by-_n symmetric matrix;
|
||||
// a_v: _n-by-1;
|
||||
// a, b: scalars;
|
||||
// ul: if =='u' or 'U', upper triangular elements in A_m are filled; if =='l' or 'L', lower triangular elements in A_m are filled.
|
||||
void SolveTriangularSystemVector(double *x_v, const double *A_m, const double *b_v, const int _n, const char ul, const char tn, const char un);
|
||||
//Outputs:
|
||||
// x_v(_n-by-1) = inv(A_m)*b_v. If x_v=b_v, b_v will be overwritten by x_v.
|
||||
//-------
|
||||
//Inputs:
|
||||
// A_m: _n-by-_n upper or lower triangular matrix;
|
||||
// b_v: _n-by-1 vector.
|
||||
// ul: if =='u' or 'U', A_m is upper triangular; if =='l' or 'L', A_m is lower triangular.
|
||||
// tn: if =='t' or 'T', A_m' (transpose), instead of A_m, will be used; if =='n', A_m itself (no transpose) will be used.
|
||||
// un: if =='u' or 'U', A_m is a unit upper triangular (i.e., the diagonal being 1);
|
||||
// if =='n' or 'N', A_m is a non-unit upper triangular.
|
||||
//
|
||||
// Computes x_v = inv(A_m)*b_v by solving a triangular system of equation A_m * x_v = b_v.
|
||||
// Note I: Intel MLK cblas_dtrsv() does not test for singularity or near-singulariy of the system.
|
||||
// Such tests must be performed before calling this BLAS routine.
|
||||
// Note II: if x_v=b_v, b_v will be overwritten by x_v.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// MKL Vector Mathematical Library with default using my own routines.
|
||||
//------------------------------------------------------
|
||||
void VectorDotDivByVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//????????? NOT tested yet. 06/13/03.
|
||||
//--- The faster way is to use MKL VML with x_dv != a_dv and x_dv != b_dv; x = a./b;
|
||||
void ElementwiseVectorDivideVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//--- The faster way is to use MKL VML with y_dv != x_dv;
|
||||
void ElementwiseInverseofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
void ElementwiseSqrtofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
void ElementwiseLogtofVector(TSdvector *y_dv, TSdvector *x_dv);
|
||||
//--- The faster way is to use MKL VML with Y_dm != X_dm;
|
||||
void ElementwiseInverseofMatrix(TSdmatrix *Y_dm, TSdmatrix *X_dm);
|
||||
|
||||
|
||||
|
||||
//------------------------------------------------------
|
||||
// Matrix routines (my own).
|
||||
//------------------------------------------------------
|
||||
void tz_VectorPlusMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const double _alpha, const TSdvector *b_dv, const double _beta);
|
||||
//Output: x_dv = alpha*a_dv + beta*b_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// _alpha: double constant.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _beta: double constant.
|
||||
void VectorPlusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = a_dv + b_dv where x_dv is _n-by-1.
|
||||
// If x_dv = a_dv, a_dv will be replaced by x_dv.
|
||||
// If x_dv = b_dv, b_dv will be replaced by x_dv,
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorMinusVector(TSdvector *x_dv, const TSdvector *a_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = a_dv - b_dv where x_dv is _n-by-1.
|
||||
// If x_dv = a_dv, x_dv will be replaced by x_dv - b_dv.
|
||||
// If x_dv = b_dv, x_dv will be replaced by a_dv - x_dv.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorPlusVectorUpdate(TSdvector *x_dv, const TSdvector *b_dv);
|
||||
//Output: x_dv = b_dv + x_dv where x_dv is _n-by-1.
|
||||
//Inputs:
|
||||
// b_dv: _n-by-1 double vector.
|
||||
void VectorDotTimesVector(TSdvector *x_dv, const TSdvector *a_dv, TSdvector *b_dv, const double _alpha, const double _beta);
|
||||
//Output:
|
||||
// x_dv is _n-by-1.
|
||||
// x_dv = _alpha * a_dv .* b_dv + _beta * x_dv if x_dv != b_dv.
|
||||
// x_dv = _alpha * a_dv .* x_dv + _beta * x_dv if x_dv = b_dv.
|
||||
//Inputs:
|
||||
// a_dv: _n-by-1 double vector.
|
||||
// b_dv: _n-by-1 double vector.
|
||||
// _alpha: double scalar.
|
||||
// _beta: a double scalar.
|
||||
void SwapColsofMatrix(TSdmatrix *X_dm, int j1, int j2);
|
||||
//??????? NOT tested yet.
|
||||
void SwapColsofMatrices(TSdmatrix *X1_dm, int j1, TSdmatrix *X2_dm, int j2);
|
||||
void SwapPositionsofMatrix(TSdmatrix *X_dm, int j1, int j2);
|
||||
void SwapMatricesofCell(TSdcell *A_dc, int c1, int c2);
|
||||
void SwapVectorsofCellvec(TSdcellvec *x_dcv, int c1, int c2);
|
||||
void SwapVectorsofCellvec_int(TSicellvec *x_icv, int c1, int c2);
|
||||
void PermuteColsofMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteRowsofMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteMatrix(TSdmatrix *A_dm, const TSivector *indx_iv);
|
||||
void PermuteMatricesofCell(TSdcell *A_dc, const TSivector *indx_iv);
|
||||
void ScalarTimesColofMatrix(TSdvector *y_dv, double _alpha, TSdmatrix *x_dm, int _j);
|
||||
//????????? Default option, in the #else, has NOT been tested yet!
|
||||
void ScalarTimesColofMatrix2ColofMatrix(TSdmatrix *y_dm, int jy, double _alpha, TSdmatrix *x_dm, int jx);
|
||||
void ScalarTimesColofMatrixPlusVector2ColofMatrix(TSdmatrix *Y_dm, int jy, double _alpha, TSdmatrix *X_dm, int jx, double _beta, TSdvector *x_dv);
|
||||
// void ColofMatrixDotTimesVector(TSdvector *y_dv, TSdmatrix *X_dm, int jx, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void MatrixDotDivideVector_row(TSdmatrix *Y_dm, TSdmatrix *X_dm, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void RowofMatrixDotDivideVector(TSdvector *y_dv, TSdmatrix *X_dm, int ix, TSdvector *x_dv, double _alpha, double _beta);
|
||||
//??????? NOT tested yet, 01/02/04.
|
||||
void ColofMatrixDotTimesVector(TSdvector *y_dv, TSdmatrix *X_dm, int jx, TSdvector *x_dv, double _alpha, double _beta);
|
||||
void ColofMatrixDotTimesColofMatrix(TSdvector *y_dv, TSdmatrix *X1_dm, int jx1, TSdmatrix *X2_dm, int jx2, double _alpha, double _beta);
|
||||
void ColofMatrixDotTimesColofMatrix2ColofMatrix(TSdmatrix *Y_dm, int jy, TSdmatrix *X1_dm, int jx1, TSdmatrix *X2_dm, int jx2, double _alpha, double _beta);
|
||||
void MatrixPlusMatrixUpdate(TSdmatrix *X_dm, TSdmatrix *A_dm);
|
||||
//Output: X = X + A where X_dm is an m-by-n general matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
void MatrixPlusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//Output: X = A + B where X_dm is an m-by-n general matrix.
|
||||
// If X=A, A will be replaced by X; if X=B, B will be replaced by X.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
void MatrixMinusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//Output: X = A - B where X_dm is an m-by-n general matrix.
|
||||
// If X=A, A will be replaced by X; if X=B, B will be replaced by X.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
void Matrix2PlusMinusMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, TSdmatrix *C_dm, const double _alpha, const double _beta, const double _gamma);
|
||||
//????? Not yet exhaust all possibilities of alpha, beta, and gamma to get most efficiency. Add more as required. 10 February 2003.
|
||||
//Output: X = alpha*A + beta*B + gamma*C where X_dm is an m-by-n general matrix.
|
||||
//Inputs:
|
||||
// A_dm: m-by-n general matrix.
|
||||
// B_dm: m-by-n general matrix.
|
||||
// C_dm: m-by-n general matrix.
|
||||
// _alpha: a double scalar for A_dm.
|
||||
// _beta: a double scalar for B_dm.
|
||||
// _gamma: a double scalar for C_dm.
|
||||
void MatrixPlusConstantDiagUpdate(TSdmatrix *X_dm, const double _alpha);
|
||||
//Output: X = X + diag([_alpha, ..., _alpha]) where X is an n-by-n square real matrix.
|
||||
void MatrixDotTimesMatrix(TSdmatrix *X_dm, TSdmatrix *A_dm, TSdmatrix *B_dm, const double _alpha, const double _beta);
|
||||
//$$$$$ If A_dm or B_dm or X_dm (when _beta!=0) is only upper or lower symmetric, it will be always converted to a general (and symmetric) matrix. $$$$$$
|
||||
//Output:
|
||||
// X_dm is m-by-n.
|
||||
// X_dm = _alpha * A_dm .* B_dm + _beta * X_dm if X_dm != B_dm.
|
||||
// X_dm = _alpha * A_dm .* X_dm + _beta * X_dm if X_dm = B_dm.
|
||||
void CopyVector0(TSdvector *x1_dv, const TSdvector *x2_dv);
|
||||
void CopyMatrix0(TSdmatrix *x1_dm, TSdmatrix *x2_dm);
|
||||
void CopyCellvec0(TSdcellvec *x1_dcv, TSdcellvec *x2_dcv);
|
||||
void CopyCell0(TSdcell *x1_dc, TSdcell *x2_dc);
|
||||
void CopySubmatrix0(TSdmatrix *x1_dm, TSdmatrix *x2_dm, const int br, const int bc, const int nrs, const int ncs);
|
||||
void CopySubmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
void CopySubrowmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
//??????? NOT tested yet.
|
||||
void CopySubmatrix2rowmatrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
void CopySubrowmatrix2matrix(TSdmatrix *x1_dm, const int br1, const int bc1, TSdmatrix *x2_dm, const int br2, const int bc2, const int nrs, const int ncs);
|
||||
//??????? NOT tested yet.
|
||||
void CopySubvector(TSdvector *x1_dv, const int ptrloc1, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector_int(TSivector *x1_iv, const int ptrloc1, const TSivector *x2_iv, const int ptrloc2, const int nels);
|
||||
void CopySubmatrix2vector(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nels);
|
||||
void CopySubmatrix2vector_sub(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nrs, const int ncs);
|
||||
void CopySubmatrix2vector_int(TSivector *x1_iv, const int ptrloc1, TSimatrix *x2_im, const int br, const int bc, const int nels);
|
||||
void CopySubmatrix2vector_row(TSdvector *x1_dv, const int ptrloc1, TSdmatrix *x2_dm, const int br, const int bc, const int nels);
|
||||
void CopySubvector2matrix(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector2rowmatrix(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void CopySubvector2matrix_sub(TSdmatrix *x1_dm, const int br, const int bc, const int nrs, const int ncs, TSdvector *x2_dv, const int ptrloc2);
|
||||
void CopySubvector2matrix_unr(TSdmatrix *x1_dm, const int br, const int bc, const TSdvector *x2_dv, const int ptrloc2, const int nels);
|
||||
void TransposeSquare(TSdmatrix *B_dm, TSdmatrix *A_dm);
|
||||
//???????? Some options are NOT test yet. 2/27/03. ???????????
|
||||
void TransposeRegular(TSdmatrix *B_dm, const TSdmatrix *A_dm);
|
||||
TSdmatrix *tz_TransposeRegular(TSdmatrix *B_dm, const TSdmatrix *A_dm);
|
||||
void SUtoGE(TSdmatrix *x_dm);
|
||||
//Output: x_dm (nrows<=ncols) becomes a general matrix in addition to being upper symmetric.
|
||||
//Input: x_dm (nrows<=ncols) is upper symmetric.
|
||||
void SLtoGE(TSdmatrix *x_dm);
|
||||
//Output: x_dm (nrows>=ncols) becomes a general matrix in addition to being lower symmetric.
|
||||
//Input: x_dm (nrows>=ncols) is lower symmetric.
|
||||
double SumVector(TSdvector *x_dv);
|
||||
double MaxVector(TSdvector *x_dv);
|
||||
double MinVector(TSdvector *x_dv);
|
||||
int MaxVector_int(TSivector *x_iv);
|
||||
void SumMatrix(TSdvector *x_dv, const TSdmatrix *X_dm, const char rc);
|
||||
//+
|
||||
void diagdv(TSdvector *x_dv, TSdmatrix *x_dm);
|
||||
TSdmatrix *tz_DiagMatrix(TSdmatrix *X_dm, TSdvector *x_dv);
|
||||
double tracefabs(TSdmatrix *x_dm);
|
||||
double tracelogfabs(TSdmatrix *x_dm);
|
||||
double tracelog(TSdmatrix *x_dm);
|
||||
double sumoflogvector(TSdvector *x_dv);
|
||||
//
|
||||
TSdmatrix *tz_kron(TSdmatrix *C_dm, TSdmatrix *A_dm, TSdmatrix *B_dm);
|
||||
//C = kron(A, B), compatible with Matlab notation.
|
||||
//Inputs:
|
||||
// A_dm and B_dm: two real general matrices.
|
||||
//Outputs:
|
||||
// If C_dm == NULL, C_dm is created (memory allocated) and returned (thus, the memory must be destroyed outside this function).
|
||||
// If C_dm != NULL, C_dm's memory has already been allocated outside this function and the same C_dm will be returned.
|
||||
|
||||
|
||||
|
||||
|
||||
//=== Self-written routines.
|
||||
void ergodicp(TSdvector *p_dv, TSdmatrix *P_dm);
|
||||
//double *fn_ergodp2(const double *cp_m, const int _n);
|
||||
double *alloc_ergodp2(const double *cp_m, const int _n);
|
||||
#endif
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,496 +1,496 @@
|
|||
/************ 3 steps to find minimization solution. *****************
|
||||
* See details at the bottom of this file.
|
||||
* or lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
* or ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips
|
||||
*
|
||||
*
|
||||
* 1. minpack_csminwel_ps = CreateTSminpack();
|
||||
* 2. InitializeForMinproblem(minpack_csminwel_ps, ..., indxRanIniForMin);
|
||||
* //This is a local, project-specific function that initializes minpack_csminwel_ps->x_dv (note, NOT xtemp_dv)
|
||||
* // according to indxStartValuesForMin.
|
||||
* 3. minfinder(minpack_csminwel_ps);
|
||||
/*********************************************************************/
|
||||
|
||||
|
||||
#ifndef __OPTPACKAGE_H__
|
||||
#define __OPTPACKAGE_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "csminwel.h"
|
||||
#include "congradmin.h"
|
||||
#include "fn_filesetup.h" //fn_SetFilePosition(), etc.
|
||||
#include "mathlib.h" //CopyVector0(), etc.
|
||||
#include "switch_opt.h" //DW's optimization routines for Markov-switching models.
|
||||
#include "cstz.h" //Used for gradcd_gen() only in the IMSL linear constrainted problem.
|
||||
|
||||
//-------------- Attributes for selecting optimization packages. --------------
|
||||
#define MIN_DEFAULT 0 //0 or NULL: default or no minimization package.
|
||||
#define MIN_CSMINWEL 0x0001 //1: csminwel unconstrained minimization package.
|
||||
#define MIN_IMSL 0x0002 //2: IMSL unconstrained minimization package.
|
||||
#define MIN_IMSL_LNCONS 0x0004 //4: IMSL linearly constrained minimization package.
|
||||
#define MIN_IMSL_NLNCONS 0x0008 //8: IMSL nonlinearly constrained minimization package.
|
||||
#define MIN_CONGRADI 0x0010 //16: unconstrained conjugate gradient minimization method 1. Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
#define MIN_CONGRADII 0x0020 //2*16=32: unconstrained conjugate gradient minimization method 2. NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
//#define MIN_CONGRADII 0x0040 //4*16=2^6: unconstrained conjugate gradient minimization method 2.
|
||||
//#define MIN_CONGRADII 0x0080 //8*16=2^7: unconstrained conjugate gradient minimization method 2.
|
||||
//#define MIN_CONGRADII 0x0100 //16^2=2^8: unconstrained conjugate gradient minimization method 2.
|
||||
|
||||
|
||||
//-------------- Minimization package: unconstrained BFGS csminwel. --------------
|
||||
//--- The following three macros will be void if the input data file specifies the values of these macros.
|
||||
//--- The following three are used for the constant-parameter model only.
|
||||
#define CRIT_CSMINWEL 1.0e-09 //1.5e-08 (for monthly TVBVAR) //Overall convergence criterion for the function value.
|
||||
#define ITMAX_CSMINWEL 100000 //Maximum number of iterations.
|
||||
#define INI_H_CSMINWEL 1.0e-005 //Initial value for the diagonal of inverse Hessian in the quasi-Newton search.
|
||||
//1.0e-05 (sometimes used for SargentWZ USinflation project I)
|
||||
//5.0e-04 (for monthly TVBAR)
|
||||
//--- The following macros are used in csminwel.c. Have not got time to make them void by input values.
|
||||
#define INDXNUMGRAD_CSMINWEL 2 //Index for choosing the numerical gradient. 1, forward difference; 2, central difference.
|
||||
//central difference method is twice as slower as forward difference.
|
||||
|
||||
|
||||
//-------------- Minimization package: linearly-nconstrained IMSL. --------------
|
||||
#define CRIT_IMSLCONLIN 1.0e-09 //Overall convergence criterion on the first-order conditions.
|
||||
#define ITMAX_IMSLCONLIN 100000 //Maximum number of iterations.
|
||||
|
||||
//-------------- Minimization package: conjugate gradient method I. --------------
|
||||
#define CRIT_CONGRAD1 1.0e-09 //Overall convergence criterion on the first-order conditions.
|
||||
#define ITMAX_CONGRAD1 100000 //Maximum number of iterations.
|
||||
|
||||
|
||||
//struct TSminpack_tag;
|
||||
|
||||
// extern struct TSminpack_tag *MINPACK_PS;
|
||||
|
||||
|
||||
//typedef void TFminfinder(struct TSminpack_tag *, const int ipackage); //If ipackage = MIN_CWMINWEL, uses csminwel; etc.
|
||||
//int n, double *x_ptr, double g_ptr); //, void *mingrad_etc_ptr);
|
||||
//typedef void TFmingrad_imsl(struct TSminpack_tag *); //NOT used yet.
|
||||
//typedef void TFmingrad(void); //int n, double *x_ptr, double g_ptr); //, void *mingrad_etc_ptr);
|
||||
|
||||
//======================================================
|
||||
// Old way of using cwminwel. No longer used in my new code. 11/01/05.
|
||||
//======================================================
|
||||
//------- For unconstrained BFGS csminwel only. -------
|
||||
typedef struct TSetc_csminwel_tag {
|
||||
//=== Optional input arguments (originally set up by Iskander), often or no longer NOT used, so we set to NULL at this point.
|
||||
double **args; //k-by-q.
|
||||
int *dims; //k-by-1;
|
||||
int _k;
|
||||
|
||||
//=== Mandatory input arguments.
|
||||
TSdmatrix *Hx_dm; //n-by-n inverse Hessian. Output as well, when csminwel is done.
|
||||
double crit; //Overall convergence criterion for the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
|
||||
//=== Some reported input arguments.
|
||||
double ini_h_csminwel;
|
||||
int indxnumgrad_csminwel;
|
||||
double gradstps_csminwel; //Step size for the numerical gradient if no analytical gradient is available.
|
||||
|
||||
|
||||
//=== Output arguments.
|
||||
int badg; //If (badg==0), analytical gradient is used; otherwise, numerical gradient will be produced.
|
||||
int niter; //Number of iterations taken by csminwel.
|
||||
int fcount; //Number of function evaluations used by csminwel.
|
||||
int retcode; //Return code for the terminating condition.
|
||||
// 0, normal step (converged). 1, zero gradient (converged).
|
||||
// 4,2, back and forth adjustment of stepsize didn't finish.
|
||||
// 3, smallest stepsize still improves too slow. 5, largest step still improves too fast.
|
||||
// 6, no improvement found.
|
||||
} TSetc_csminwel;
|
||||
|
||||
|
||||
//=============================================================
|
||||
// New ways of making optimization packages.
|
||||
//=============================================================
|
||||
typedef struct TSminpack_tag {
|
||||
//=== Input arguments.
|
||||
int package; //Minimization package or routine.
|
||||
TSdvector *x_dv; //n-by-1 of estimated parameters.
|
||||
TSdvector *g_dv; //n-by-1 of gradient. When no analytical gradient is provided, it returns the numerical one.
|
||||
//$$$$ The x_dv and g_dv are only used minfinder(). In the wrapper function like minobj_csminwelwrap(), we must
|
||||
//$$$$ use xtemp_dv and gtemp_dv to be repointed to the temporary array created in csminwel() itself. See below.
|
||||
|
||||
TSdvector *xtemp_dv; //$$$$Used within the minimization problem.
|
||||
TSdvector *gtemp_dv; //$$$$Used within the minimization problem.
|
||||
//$$$$WARNING: Note the vector xtemp_dv->v or gtemp_dv-v itself is not allocated memory, but only the POINTER.
|
||||
//$$$$ Within the minimization routine like csminwel(), the temporary array x enters as the argument in
|
||||
//$$$$ the objective function to compare with other values. If we use minpack_ps->x_dv->v = x
|
||||
//$$$$ in a wrapper function like minobj_csminwelwrap() where x is a temporay array in csminwel(),
|
||||
//$$$$ this tempoary array (e.g., x[0] in csminwel()) within the csminwel minimization routine
|
||||
//$$$$ will be freed after the csminwel minimization is done. Consequently, minpack_ps->x_dv-v, which
|
||||
//$$$$ which was re-pointed to this tempoary array, will freed as well. Thus, no minimization results
|
||||
//$$$$ would be stored and trying to access to minpack_ps->x_dv would cause memory leak.
|
||||
//$$$$ We don't need, however, to create another temporary pointer within the objective function itself,
|
||||
//$$$$ but we must use minpack_ps->xtemp_dv for a *wrapper* function instead and at the end of
|
||||
//$$$$ minimization, minpack_ps->x_dv will have the value of minpack_ps->xtemp_dv, which is automatically
|
||||
//$$$$ taken care of by csminwel with the lines such as
|
||||
//$$$$ memcpy(xh,x[3],n*sizeof(double));
|
||||
//$$$$ where xh and minpack_ps->x_dv->v point to the same memory space.
|
||||
|
||||
TSdvector *x0_dv; //n-by-1 of initial or starting values of the estimated parameters.
|
||||
|
||||
|
||||
//--- Created here. Contains csminwel arguments iter, retcodeh, etc. or those that are essential to minimization package.
|
||||
void *etc_package_ps;
|
||||
|
||||
//--- Created outside of this structure. Including, say, csminwel input arguments such as convergence criteria
|
||||
//--- or block-wise csminwel input arguments.
|
||||
void *etc_project_ps;
|
||||
void *(*DestroyTSetc_project)(void *);
|
||||
//--- Optional.
|
||||
char *filename_printout;
|
||||
|
||||
//--- Minimization function for objective function.
|
||||
//--- May *NOT* be needed for swithcing model because DW's switch_opt.c takes care of things.
|
||||
double (*minobj)(struct TSminpack_tag *); ////From the input argument of CreateTSminpack().
|
||||
/*** This function is used only for the constant-parameter case, NOT for DW's Markov-swtiching case. ***/
|
||||
//--- Optional: Minimization function for analytical gradient. Often NOT available.
|
||||
void (*mingrad)(struct TSminpack_tag *); //From the input argument of CreateTSminpack().
|
||||
|
||||
//=== Output arguments.
|
||||
double fret; //Returned value of the objective function.
|
||||
double fret0; //Returned value of the objective function at the initial or starting values x0.
|
||||
|
||||
} TSminpack;
|
||||
|
||||
typedef double TFminobj(struct TSminpack_tag *); //int n, double *x_ptr); //, void *minobj_etc_ptr);
|
||||
typedef void TFmingrad(struct TSminpack_tag *);
|
||||
typedef void *TFmindestroy_etcproject(void *);
|
||||
typedef void TFSetPrintFile(char *);
|
||||
|
||||
//======= Function prototypes. =======//
|
||||
TSminpack *CreateTSminpack(TFminobj *minobj_func, void **etc_project_pps, TFmindestroy_etcproject *etcproject_func, TFmingrad *mingrad_func, char *filename_printout, const int n, const int package);
|
||||
TSminpack *DestroyTSminpack(TSminpack *);
|
||||
|
||||
|
||||
//=== Used for the constant-parameter model.
|
||||
//--- 28/Oct/07: The function InitializeForMinproblem_const() has not been used even for the constant-parameter model.
|
||||
//--- For examples, see lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
//--- or ExamplesForC.prn under D:\ZhaData\CommonFiles\C_Examples_DebugTips.
|
||||
//NOT used: void InitializeForMinproblem_const(struct TSminpack_tag *minpack_ps, char *filename_sp, TSdvector *gphi_dv, int indxStartValuesForMin);
|
||||
//---
|
||||
void minfinder(TSminpack *minpack_ps);
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------//
|
||||
//---------- New ways of making optimization packages. 03/10/06. -------//
|
||||
//------------------------------------------------------------------------------//
|
||||
//================ For the csminwel minimization problem. ================//
|
||||
//=== Step 1.
|
||||
typedef struct TSargs_blockcsminwel_tag
|
||||
{
|
||||
//Arguments for blockwise minimization.
|
||||
|
||||
//=== Within the block: sequence of convergence criteria.
|
||||
double criterion_start; //Default: 1.0e-3;
|
||||
double criterion_end; //Default: 1.0e-6;
|
||||
double criterion_increment; //Default: 0.1;
|
||||
int max_iterations_start; //Default: 50; Max # of iterations for csminwel. The starting value is small because criterion_start
|
||||
// is coarse at the start. As the convergence criterion is getting tighter, the max # of
|
||||
// iteration increases as it is multiplied by max_iterations_increment.
|
||||
double max_iterations_increment; //Default: 2.0; Used to multiply the max # of iterations in csminwel as the convergence
|
||||
// criterion tightens.
|
||||
double ini_h_scale; //Default: 5.0e-4; 1.0e-05 (sometimes used for SargentWZ USinflation project I)
|
||||
// 5.0e-04 (for monthly TVBAR)
|
||||
//=== Outside the blocks.
|
||||
int max_block_iterations; //Default: 100;
|
||||
|
||||
//------------------------------------------------------------
|
||||
//Step size for numerical gradient only when the value of x is less than 1.0 in absolute value.
|
||||
//If abs(x)>1.0, the step size is GRADSTPS_CSMINWEL*x.
|
||||
//
|
||||
//For the time-varying-parameter model, GRADSTPS_CSMINWEL takes the values of gradstps_csminwel_dv:
|
||||
// 1st element: gradient step for the model parameters (tends to be large; the default value is 1.0e-02).
|
||||
// 2nd element: gradient step for the transition probability matrix (tends to be smaller; the default value is 1.0e-03)
|
||||
// 3rd element: gradient step for all the parameters (tends to be smaller; the default value is 1.0e-03 or 1.0e-04).
|
||||
//For the constant-parameter model:
|
||||
// GRADSTPS_CSMINWEL takes the value of gradstps_csminwel_const. The default value is 1.0e-04 (for monthly TBVAR)
|
||||
//------------------------------------------------------------
|
||||
TSdvector *gradstps_csminwel_dv; //3-by-1. For the time-varying-parameter model only.
|
||||
double gradstps_csminwel_const; //For the constant-parameter model.
|
||||
|
||||
//--- pointer to the input data file that contains all the data on convergence, max iterations, etc.
|
||||
FILE *fptr_input1;
|
||||
} TSargs_blockcsminwel;
|
||||
struct TSargs_blockcsminwel_tag *CreateTSargs_blockcsminwel(FILE *fptr_input1);
|
||||
//If fptr_input1==NULL or no no values supplied when fptr_input1 != NULL, default values are taken.
|
||||
struct TSargs_blockcsminwel_tag *DestroyTSargs_blockcsminwel(struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps);
|
||||
//+
|
||||
typedef struct TStateModel_tag *TFDestroyTStateModel(struct TStateModel_tag *);
|
||||
typedef struct TSetc_minproj_tag
|
||||
{
|
||||
//For optimization of the posterior or likelihood function.
|
||||
struct TStateModel_tag *smodel_ps;
|
||||
struct TStateModel_tag *(*DestroyTStateModel)(struct TStateModel_tag *);
|
||||
//
|
||||
struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps;
|
||||
struct TSargs_blockcsminwel_tag *(*DestroyTSargs_blockcsminwel)(struct TSargs_blockcsminwel_tag *);
|
||||
} TSetc_minproj;
|
||||
//
|
||||
struct TSetc_minproj_tag *CreateTSetc_minproj(struct TStateModel_tag **smodel_pps, TFDestroyTStateModel *DestroyTStateModel_func,
|
||||
struct TSargs_blockcsminwel_tag **args_blockcsminwel_pps, struct TSargs_blockcsminwel_tag *(*DestroyTSargs_blockcsminwel)(struct TSargs_blockcsminwel_tag *));
|
||||
struct TSetc_minproj_tag *DestroyTSetc_minproj(struct TSetc_minproj_tag *);
|
||||
//And creates the following user's function.
|
||||
//static double minneglogpost(struct TSminpack_tag *minpack_ps); //For the constant-parameter only.
|
||||
//=== Step 2. Belongs to the user's responsibility because this function must be able to deal with
|
||||
// (1) constant-parameter case without using DW's functions;
|
||||
// (2) allowing us to generate parameters randomly, which depends on the specific model.
|
||||
// See lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
// or ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips.
|
||||
//---
|
||||
//void InitializeForMinproblem(struct TSminpack_tag *minpack_ps, char *filename_sp, TSdvector *gphi_dv, int indxStartValuesForMin);
|
||||
//=== Step 3.
|
||||
void minfinder_blockcsminwel(struct TSminpack_tag *minpack_ps, int indx_findMLE); //Blockwise minimization.
|
||||
//indx_findMLE: 1: find MLE without a prior, 0: find posterior (with a prior).
|
||||
|
||||
|
||||
|
||||
|
||||
//================ For IMSL multivariate linearly-constrained minimizaiton package only. ================//
|
||||
typedef struct TSpackage_imslconlin_tag
|
||||
{
|
||||
//=== Non-simple constraints.
|
||||
int npars_tot; //Total number of free parameters for the optimaization.
|
||||
//For example, model free parameters + free transition matrix parameters in the regime-switching case.
|
||||
int neqs; //Number of equality constraints, excluding simple bound constraints. Must be no greater than ncons.
|
||||
//IMSL dictates that equality constraints come always BEFORE inequality constrains.
|
||||
int ncons; //Total number of constrains, including equality and inequality constraints, but excluding simple bounds.
|
||||
TSdvector *lh_coefs_dv; //ncons*npars_tot-by-1. ALWAYS initialized to be 0.0.
|
||||
//Left-hand coefficients in the linear constrains (excluding simple bounds).
|
||||
//IMSL rule: lh_coefs_dv stacks the neqs rows of equality constraints first, followed by the inequality constraints.
|
||||
//Set to NULL if ncons=0;
|
||||
TSdvector *rh_constraints_dv; //ncons-by-1. Set to NULL if ncons=0.
|
||||
//Right-hand constraints in the equality and non-equality constrains (excluding simple bounds).
|
||||
|
||||
|
||||
//=== Simple bounds.
|
||||
TSdvector *lowbounds_dv; //npars_tot-by-1. ALWAYS initialized to -BIGREALNUMBER for thes simple lower bounds.
|
||||
//If a component is unbounded, choose a very negative large value (e.g., -BIGREALNUMBER).
|
||||
TSdvector *upperbounds_dv; //npars_tot-by-1. ALWAYS initialized to +BIGREALNUMBER for thes simple lower bounds.
|
||||
//If a component is unbounded, choose a very positive large value (e.g., BIGREALNUMBER).
|
||||
|
||||
//=== Other output.
|
||||
TSdvector *xsaved_dv; //npars_tot-by-1. Saved the parameters that give the minimal value of the objective function.
|
||||
|
||||
//=== Other inputs.
|
||||
double crit; //Overall convergence criterion on the first-order conditions.
|
||||
int itmax; //Maximum number of iterations.
|
||||
} TSpackage_imslconlin;
|
||||
//+
|
||||
struct TSpackage_imslconlin_tag *CreateTSpackagae_imslconlin(const int npars_tot, const int neqs, const int ncons);
|
||||
struct TSpackage_imslconlin_tag *DestroyTSpackagae_imslconlin(struct TSpackage_imslconlin_tag *package_imslconlin_ps);
|
||||
void minfinder_noblockimslconlin(struct TSpackage_imslconlin_tag *package_imslconlin_ps, struct TSminpack_tag *minpack_ps, char *filename_printout, int ntheta);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//================ For conjugate gradient method I only. ================//
|
||||
typedef struct TSpackage_congrad1_tag
|
||||
{
|
||||
//=== Input arguments.
|
||||
double crit; //Overall convergence criterion on the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
|
||||
//=== Output arguments.
|
||||
int niters; //Number of iterations.
|
||||
} TSpackage_congrad1;
|
||||
//+
|
||||
struct TSpackage_congrad1_tag *CreateTSpackage_congrad1(void);
|
||||
struct TSpackage_congrad1_tag *DestroyTSpackage_congrad1(struct TSpackage_congrad1_tag *package_congrad1_ps);
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
//------- For unconstrained BFGS csminwel only. -------
|
||||
typedef struct TSminpack_csminwel_tag {
|
||||
//=== Optional input arguments, often NOT used, so we set to NULL at this point.
|
||||
double **args; //k-by-q.
|
||||
int *dims; //k-by-1;
|
||||
int _k;
|
||||
|
||||
//=== Mandatory input arguments.
|
||||
TSdmatrix *Hx_dm; //n-by-n inverse Hessian. Output as well, when csminwel is done.
|
||||
double crit; //Overall convergence criterion for the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
// double grdh; //Step size for the numerical gradient if no analytical gradient is available.
|
||||
|
||||
//=== Initial input arguments.
|
||||
double ini_h_csminwel;
|
||||
int indxnumgrad_csminwel;
|
||||
double gradstps_csminwel;
|
||||
|
||||
|
||||
//=== Output arguments.
|
||||
int badg; //If (badg==0), analytical gradient is used; otherwise, numerical gradient will be produced.
|
||||
int niter; //Number of iterations taken by csminwel.
|
||||
int fcount; //Number of function evaluations used by csminwel.
|
||||
int retcode; //Return code for the terminating condition.
|
||||
// 0, normal step (converged). 1, zero gradient (converged).
|
||||
// 4,2, back and forth adjustment of stepsize didn't finish.
|
||||
// 3, smallest stepsize still improves too slow. 5, largest step still improves too fast.
|
||||
// 6, no improvement found.
|
||||
} TSminpack_csminwel;
|
||||
/**/
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*************** 3 steps to find minimization solution. *****************
|
||||
//---------------------------------
|
||||
//-- For concrete examples, see
|
||||
//-- lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
//-- ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips
|
||||
//---------------------------------
|
||||
|
||||
//------ For the csminwel minimization problem. -------
|
||||
//--- Step 1. Creats a number of csminwel structures for both Markov-switching and constant-parameter models.
|
||||
static double minobj(struct TSminpack_tag *minpack_ps); //This function is for the constant-parameter model only.
|
||||
//--- Step 2.
|
||||
static void InitializeForMinproblem(struct TSminpack_tag *minpack_ps, char *filename_sp);
|
||||
//--- Step 3.
|
||||
//For the constant-parameter model, run minfinder(minpack_ps); //Constant-parameter case.
|
||||
//For the regime-switching model, run minfinder_blockcsminwel(minpack_ps); //Time-varying case.
|
||||
*
|
||||
*
|
||||
*
|
||||
|
||||
|
||||
//=== main.c
|
||||
|
||||
int indxInitializeTransitionMatrix;
|
||||
//--- My model structure.
|
||||
struct TSlwzmodel_tag *lwzmodel_ps = NULL;
|
||||
//--- Waggoner's Markov switching package.
|
||||
struct TMarkovStateVariable_tag *sv_ps = NULL;
|
||||
ThetaRoutines *sroutines_ps = NULL;
|
||||
struct TStateModel_tag *smodel_ps = NULL;
|
||||
//--- General (csminwel) minimization for constant-parameter.
|
||||
struct TSetc_minproj_tag *etc_minproj_ps = NULL;
|
||||
struct TSminpack_tag *minpack_ps = NULL;
|
||||
//--- Blockwise (csminwel) minimization for regime-switching model.
|
||||
struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps = NULL;
|
||||
|
||||
|
||||
//-----------------
|
||||
// Reads from the command line the user-specified input file and the most-often-used integer arguments such as sample size.
|
||||
//-----------------
|
||||
cl_modeltag = fn_ParseCommandLine_String(n_arg,args_cl,'t',(char *)NULL); // Tag for different models.
|
||||
if (!cl_modeltag) fn_DisplayError(".../main(): No model tag is specified yet");
|
||||
//--- Type of the model: (0) const, (1) varionly, (2) trendinf, (3) policyonly, and (4) firmspolicy.
|
||||
if (!strncmp("const", cl_modeltag, 5)) indx_tvmodel = 0;
|
||||
else if (!strncmp("varionly", cl_modeltag, 5)) indx_tvmodel = 1;
|
||||
else if (!strncmp("trendinf", cl_modeltag, 5)) indx_tvmodel = 2;
|
||||
else if (!strncmp("policyonly", cl_modeltag, 5)) indx_tvmodel = 3;
|
||||
else if (!strncmp("firmspolicy", cl_modeltag, 5)) indx_tvmodel = 4;
|
||||
else fn_DisplayError("main(): the model tag is NOT properly selected");
|
||||
indxStartValuesForMin = fn_ParseCommandLine_Integer(n_arg,args_cl,'c',1);
|
||||
sprintf(filename_sp_vec_minproj, "outdatasp_min_%s.prn", cl_modeltag);
|
||||
//+
|
||||
sprintf(filenamebuffer, "dataraw.prn");
|
||||
cl_filename_rawdata = fn_ParseCommandLine_String(n_arg,args_cl,'r',filenamebuffer); //Raw data input file.
|
||||
fptr_rawdata = tzFopen(cl_filename_rawdata,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_common.prn");
|
||||
cl_filename_input1 = fn_ParseCommandLine_String(n_arg,args_cl,'i',filenamebuffer); //Common setup input data file.
|
||||
fptr_input1 = tzFopen(cl_filename_input1,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_%s.prn", cl_modeltag);
|
||||
cl_filename_input2 = fn_ParseCommandLine_String(n_arg,args_cl,'s',filenamebuffer); //Model-specific setupt input data file.
|
||||
fptr_input2 = tzFopen(cl_filename_input2,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_markov_%s.prn", cl_modeltag);
|
||||
cl_filename_markov = fn_ParseCommandLine_String(n_arg,args_cl,'m',filenamebuffer); //Markov-switching setup input data file.
|
||||
fptr_markov = tzFopen(cl_filename_markov,"r");
|
||||
//--- Output data files.
|
||||
sprintf(filenamebuffer, "outdata_debug_%s.prn", cl_modeltag);
|
||||
FPTR_DEBUG = tzFopen(filenamebuffer,"w"); //Debug output file.
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdataout_%s.prn", cl_modeltag);
|
||||
fptr_output = tzFopen(filenamebuffer,"w"); //Final output file.
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab_%s.prn", cl_modeltag);
|
||||
fptr_matlab = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab1_%s.prn", cl_modeltag);
|
||||
fptr_matlab1 = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab2_%s.prn", cl_modeltag);
|
||||
fptr_matlab2 = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab3_%s.prn", cl_modeltag);
|
||||
fptr_matlab3 = tzFopen(filenamebuffer, "w");
|
||||
|
||||
|
||||
//----------------------------------------------
|
||||
//--- Memory allocation and structure creation.
|
||||
//--- The order matters!
|
||||
//----------------------------------------------
|
||||
//--- Model structure. ---
|
||||
lwzmodel_ps = CreateTSlwzmodel(fptr_rawdata, fptr_input1, fptr_input2, fptr_markov, indx_tvmodel, indxStartValuesForMin);
|
||||
sprintf(lwzmodel_ps->tag_modeltype_cv->v, cl_modeltag);
|
||||
lwzmodel_ps->tag_modeltype_cv->flag = V_DEF;
|
||||
|
||||
|
||||
//====== Waggoner's Markov switching variables. ======
|
||||
sv_ps = CreateMarkovStateVariable_File(fptr_markov, (char *)NULL, lwzmodel_ps->fss);
|
||||
//In this case, fptr_markov points to datainp_markov_const.prn, which can be found in D:\ZhaData\CommonFiles\C_Examples_DebugTips\DW_MarkovInputFiles.
|
||||
sroutines_ps = CreateThetaRoutines_empty();
|
||||
sroutines_ps->pLogConditionalLikelihood = logTimetCondLH; //User's: logTimetCondLH
|
||||
sroutines_ps->pLogPrior = logpriordensity_usingDW; //User's: pLogPrior
|
||||
sroutines_ps->pNumberFreeParametersTheta = NumberOfFreeModelSpecificParameters; //User's: NumberOfFreeModelSpecificParameters,
|
||||
sroutines_ps->pConvertFreeParametersToTheta = ConvertFreeParameters2ModelSpecificParameters; //User's: ConvertFreeParameters2ModelSpecificParameters,
|
||||
sroutines_ps->pConvertThetaToFreeParameters = ConvertModelSpecificParameters2FreeParameters; //User's: ConvertModelSpecificParameters2FreeParameters,
|
||||
sroutines_ps->pThetaChanged = tz_thetaChanged; //User's: Notification routine (need to refresh everything given new parameters?)
|
||||
sroutines_ps->pTransitionMatrixChanged = tz_TransitionMatrixChanged; //User's: Notification routine (need to refresh everything given new parameters?)
|
||||
smodel_ps = CreateStateModel_new(sv_ps, sroutines_ps, (void *)lwzmodel_ps);
|
||||
//--- Optional.
|
||||
if (!indx_tvmodel && fn_SetFilePosition(fptr_markov, "//== indxInitializeTransitionMatrix ==//"))
|
||||
if ((fscanf(fptr_markov, " %d ", &indxInitializeTransitionMatrix) == 1) && indxInitializeTransitionMatrix)
|
||||
ReadTransitionMatrices(fptr_markov, (char*)NULL, "Initial: ", smodel_ps); //Waggoner's function.
|
||||
|
||||
|
||||
//--- Minimization problem: Step 1. ---
|
||||
args_blockcsminwel_ps = CreateTSargs_blockcsminwel(fptr_input1);
|
||||
//Blockwise (csminwel) minimization arguments, reading convergence criteria or using default values if fptr_input1 is set to NULL.
|
||||
//fptr_input1 contains parameters for both constant-parameter and Markov-switching models.
|
||||
etc_minproj_ps = CreateTSetc_minproj(&smodel_ps, (TFDestroyTStateModel *)NULL, &args_blockcsminwel_ps, DestroyTSargs_blockcsminwel);
|
||||
//Taking convergence criteria and my model structure smodel_ps into minpack_ps.
|
||||
minpack_ps = CreateTSminpack((TFminobj *)minobj, (void **)&etc_minproj_ps, (TFmindestroy_etcproject *)NULL, (TFmingrad *)NULL,
|
||||
filename_sp_vec_minproj,
|
||||
lwzmodel_ps->xphi_dv->n+NumberFreeParametersQ(smodel_ps),
|
||||
MIN_CSMINWEL);
|
||||
//minobj is for the constant-parameter model only in which case, NumberFreeParametersQ(smodel_ps) will be 0.
|
||||
|
||||
|
||||
//-----------------
|
||||
// Main matter.
|
||||
//-----------------
|
||||
time(&lwzmodel_ps->prog_begtime); //Beginning time of the whole program.
|
||||
InitializeGlobleSeed(lwzmodel_ps->randomseed = 0); //2764 If seednumber==0, a value is computed using the system clock.
|
||||
csminwel_randomseedChanged(lwzmodel_ps->randomseed); //Using the same (or different) seednumber to reset csminwel seednumber for random perturbation.
|
||||
//=== Finding the peak value of the logLH or logPosterior
|
||||
if (lwzmodel_ps->indxEstFinder)
|
||||
{
|
||||
//Minimization problem: Steps 2 and 3.
|
||||
|
||||
InitializeForMinproblem(minpack_ps, filename_sp_vec_minproj); //Initialization for minimization.
|
||||
//======= 1st round of minimization. =======
|
||||
//--------------------------
|
||||
//-- csminwel minimization where
|
||||
//-- minpack_ps->x_dv contains the minimizing vector of parameters.
|
||||
//-- minpack_ps->fret contains the minimized value.
|
||||
//--------------------------
|
||||
|
||||
if (!lwzmodel_ps->indx_tvmodel) minfinder(minpack_ps); //Constant-parameter case.
|
||||
else minfinder_blockcsminwel(minpack_ps); //Time-varying case.
|
||||
}
|
||||
else InitializeForMinproblem(minpack_ps, filename_sp_vec_minproj);
|
||||
time(&lwzmodel_ps->prog_endtime); //Ending time of the whole program.
|
||||
/*************************************************************************/
|
||||
|
||||
/************ 3 steps to find minimization solution. *****************
|
||||
* See details at the bottom of this file.
|
||||
* or lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
* or ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips
|
||||
*
|
||||
*
|
||||
* 1. minpack_csminwel_ps = CreateTSminpack();
|
||||
* 2. InitializeForMinproblem(minpack_csminwel_ps, ..., indxRanIniForMin);
|
||||
* //This is a local, project-specific function that initializes minpack_csminwel_ps->x_dv (note, NOT xtemp_dv)
|
||||
* // according to indxStartValuesForMin.
|
||||
* 3. minfinder(minpack_csminwel_ps);
|
||||
/*********************************************************************/
|
||||
|
||||
|
||||
#ifndef __OPTPACKAGE_H__
|
||||
#define __OPTPACKAGE_H__
|
||||
|
||||
#include "tzmatlab.h"
|
||||
#include "csminwel.h"
|
||||
#include "congradmin.h"
|
||||
#include "fn_filesetup.h" //fn_SetFilePosition(), etc.
|
||||
#include "mathlib.h" //CopyVector0(), etc.
|
||||
#include "switch_opt.h" //DW's optimization routines for Markov-switching models.
|
||||
#include "cstz.h" //Used for gradcd_gen() only in the IMSL linear constrainted problem.
|
||||
|
||||
//-------------- Attributes for selecting optimization packages. --------------
|
||||
#define MIN_DEFAULT 0 //0 or NULL: default or no minimization package.
|
||||
#define MIN_CSMINWEL 0x0001 //1: csminwel unconstrained minimization package.
|
||||
#define MIN_IMSL 0x0002 //2: IMSL unconstrained minimization package.
|
||||
#define MIN_IMSL_LNCONS 0x0004 //4: IMSL linearly constrained minimization package.
|
||||
#define MIN_IMSL_NLNCONS 0x0008 //8: IMSL nonlinearly constrained minimization package.
|
||||
#define MIN_CONGRADI 0x0010 //16: unconstrained conjugate gradient minimization method 1. Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
#define MIN_CONGRADII 0x0020 //2*16=32: unconstrained conjugate gradient minimization method 2. NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
//#define MIN_CONGRADII 0x0040 //4*16=2^6: unconstrained conjugate gradient minimization method 2.
|
||||
//#define MIN_CONGRADII 0x0080 //8*16=2^7: unconstrained conjugate gradient minimization method 2.
|
||||
//#define MIN_CONGRADII 0x0100 //16^2=2^8: unconstrained conjugate gradient minimization method 2.
|
||||
|
||||
|
||||
//-------------- Minimization package: unconstrained BFGS csminwel. --------------
|
||||
//--- The following three macros will be void if the input data file specifies the values of these macros.
|
||||
//--- The following three are used for the constant-parameter model only.
|
||||
#define CRIT_CSMINWEL 1.0e-09 //1.5e-08 (for monthly TVBVAR) //Overall convergence criterion for the function value.
|
||||
#define ITMAX_CSMINWEL 100000 //Maximum number of iterations.
|
||||
#define INI_H_CSMINWEL 1.0e-005 //Initial value for the diagonal of inverse Hessian in the quasi-Newton search.
|
||||
//1.0e-05 (sometimes used for SargentWZ USinflation project I)
|
||||
//5.0e-04 (for monthly TVBAR)
|
||||
//--- The following macros are used in csminwel.c. Have not got time to make them void by input values.
|
||||
#define INDXNUMGRAD_CSMINWEL 2 //Index for choosing the numerical gradient. 1, forward difference; 2, central difference.
|
||||
//central difference method is twice as slower as forward difference.
|
||||
|
||||
|
||||
//-------------- Minimization package: linearly-nconstrained IMSL. --------------
|
||||
#define CRIT_IMSLCONLIN 1.0e-09 //Overall convergence criterion on the first-order conditions.
|
||||
#define ITMAX_IMSLCONLIN 100000 //Maximum number of iterations.
|
||||
|
||||
//-------------- Minimization package: conjugate gradient method I. --------------
|
||||
#define CRIT_CONGRAD1 1.0e-09 //Overall convergence criterion on the first-order conditions.
|
||||
#define ITMAX_CONGRAD1 100000 //Maximum number of iterations.
|
||||
|
||||
|
||||
//struct TSminpack_tag;
|
||||
|
||||
// extern struct TSminpack_tag *MINPACK_PS;
|
||||
|
||||
|
||||
//typedef void TFminfinder(struct TSminpack_tag *, const int ipackage); //If ipackage = MIN_CWMINWEL, uses csminwel; etc.
|
||||
//int n, double *x_ptr, double g_ptr); //, void *mingrad_etc_ptr);
|
||||
//typedef void TFmingrad_imsl(struct TSminpack_tag *); //NOT used yet.
|
||||
//typedef void TFmingrad(void); //int n, double *x_ptr, double g_ptr); //, void *mingrad_etc_ptr);
|
||||
|
||||
//======================================================
|
||||
// Old way of using cwminwel. No longer used in my new code. 11/01/05.
|
||||
//======================================================
|
||||
//------- For unconstrained BFGS csminwel only. -------
|
||||
typedef struct TSetc_csminwel_tag {
|
||||
//=== Optional input arguments (originally set up by Iskander), often or no longer NOT used, so we set to NULL at this point.
|
||||
double **args; //k-by-q.
|
||||
int *dims; //k-by-1;
|
||||
int _k;
|
||||
|
||||
//=== Mandatory input arguments.
|
||||
TSdmatrix *Hx_dm; //n-by-n inverse Hessian. Output as well, when csminwel is done.
|
||||
double crit; //Overall convergence criterion for the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
|
||||
//=== Some reported input arguments.
|
||||
double ini_h_csminwel;
|
||||
int indxnumgrad_csminwel;
|
||||
double gradstps_csminwel; //Step size for the numerical gradient if no analytical gradient is available.
|
||||
|
||||
|
||||
//=== Output arguments.
|
||||
int badg; //If (badg==0), analytical gradient is used; otherwise, numerical gradient will be produced.
|
||||
int niter; //Number of iterations taken by csminwel.
|
||||
int fcount; //Number of function evaluations used by csminwel.
|
||||
int retcode; //Return code for the terminating condition.
|
||||
// 0, normal step (converged). 1, zero gradient (converged).
|
||||
// 4,2, back and forth adjustment of stepsize didn't finish.
|
||||
// 3, smallest stepsize still improves too slow. 5, largest step still improves too fast.
|
||||
// 6, no improvement found.
|
||||
} TSetc_csminwel;
|
||||
|
||||
|
||||
//=============================================================
|
||||
// New ways of making optimization packages.
|
||||
//=============================================================
|
||||
typedef struct TSminpack_tag {
|
||||
//=== Input arguments.
|
||||
int package; //Minimization package or routine.
|
||||
TSdvector *x_dv; //n-by-1 of estimated parameters.
|
||||
TSdvector *g_dv; //n-by-1 of gradient. When no analytical gradient is provided, it returns the numerical one.
|
||||
//$$$$ The x_dv and g_dv are only used minfinder(). In the wrapper function like minobj_csminwelwrap(), we must
|
||||
//$$$$ use xtemp_dv and gtemp_dv to be repointed to the temporary array created in csminwel() itself. See below.
|
||||
|
||||
TSdvector *xtemp_dv; //$$$$Used within the minimization problem.
|
||||
TSdvector *gtemp_dv; //$$$$Used within the minimization problem.
|
||||
//$$$$WARNING: Note the vector xtemp_dv->v or gtemp_dv-v itself is not allocated memory, but only the POINTER.
|
||||
//$$$$ Within the minimization routine like csminwel(), the temporary array x enters as the argument in
|
||||
//$$$$ the objective function to compare with other values. If we use minpack_ps->x_dv->v = x
|
||||
//$$$$ in a wrapper function like minobj_csminwelwrap() where x is a temporay array in csminwel(),
|
||||
//$$$$ this tempoary array (e.g., x[0] in csminwel()) within the csminwel minimization routine
|
||||
//$$$$ will be freed after the csminwel minimization is done. Consequently, minpack_ps->x_dv-v, which
|
||||
//$$$$ which was re-pointed to this tempoary array, will freed as well. Thus, no minimization results
|
||||
//$$$$ would be stored and trying to access to minpack_ps->x_dv would cause memory leak.
|
||||
//$$$$ We don't need, however, to create another temporary pointer within the objective function itself,
|
||||
//$$$$ but we must use minpack_ps->xtemp_dv for a *wrapper* function instead and at the end of
|
||||
//$$$$ minimization, minpack_ps->x_dv will have the value of minpack_ps->xtemp_dv, which is automatically
|
||||
//$$$$ taken care of by csminwel with the lines such as
|
||||
//$$$$ memcpy(xh,x[3],n*sizeof(double));
|
||||
//$$$$ where xh and minpack_ps->x_dv->v point to the same memory space.
|
||||
|
||||
TSdvector *x0_dv; //n-by-1 of initial or starting values of the estimated parameters.
|
||||
|
||||
|
||||
//--- Created here. Contains csminwel arguments iter, retcodeh, etc. or those that are essential to minimization package.
|
||||
void *etc_package_ps;
|
||||
|
||||
//--- Created outside of this structure. Including, say, csminwel input arguments such as convergence criteria
|
||||
//--- or block-wise csminwel input arguments.
|
||||
void *etc_project_ps;
|
||||
void *(*DestroyTSetc_project)(void *);
|
||||
//--- Optional.
|
||||
char *filename_printout;
|
||||
|
||||
//--- Minimization function for objective function.
|
||||
//--- May *NOT* be needed for swithcing model because DW's switch_opt.c takes care of things.
|
||||
double (*minobj)(struct TSminpack_tag *); ////From the input argument of CreateTSminpack().
|
||||
/*** This function is used only for the constant-parameter case, NOT for DW's Markov-swtiching case. ***/
|
||||
//--- Optional: Minimization function for analytical gradient. Often NOT available.
|
||||
void (*mingrad)(struct TSminpack_tag *); //From the input argument of CreateTSminpack().
|
||||
|
||||
//=== Output arguments.
|
||||
double fret; //Returned value of the objective function.
|
||||
double fret0; //Returned value of the objective function at the initial or starting values x0.
|
||||
|
||||
} TSminpack;
|
||||
|
||||
typedef double TFminobj(struct TSminpack_tag *); //int n, double *x_ptr); //, void *minobj_etc_ptr);
|
||||
typedef void TFmingrad(struct TSminpack_tag *);
|
||||
typedef void *TFmindestroy_etcproject(void *);
|
||||
typedef void TFSetPrintFile(char *);
|
||||
|
||||
//======= Function prototypes. =======//
|
||||
TSminpack *CreateTSminpack(TFminobj *minobj_func, void **etc_project_pps, TFmindestroy_etcproject *etcproject_func, TFmingrad *mingrad_func, char *filename_printout, const int n, const int package);
|
||||
TSminpack *DestroyTSminpack(TSminpack *);
|
||||
|
||||
|
||||
//=== Used for the constant-parameter model.
|
||||
//--- 28/Oct/07: The function InitializeForMinproblem_const() has not been used even for the constant-parameter model.
|
||||
//--- For examples, see lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
//--- or ExamplesForC.prn under D:\ZhaData\CommonFiles\C_Examples_DebugTips.
|
||||
//NOT used: void InitializeForMinproblem_const(struct TSminpack_tag *minpack_ps, char *filename_sp, TSdvector *gphi_dv, int indxStartValuesForMin);
|
||||
//---
|
||||
void minfinder(TSminpack *minpack_ps);
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------//
|
||||
//---------- New ways of making optimization packages. 03/10/06. -------//
|
||||
//------------------------------------------------------------------------------//
|
||||
//================ For the csminwel minimization problem. ================//
|
||||
//=== Step 1.
|
||||
typedef struct TSargs_blockcsminwel_tag
|
||||
{
|
||||
//Arguments for blockwise minimization.
|
||||
|
||||
//=== Within the block: sequence of convergence criteria.
|
||||
double criterion_start; //Default: 1.0e-3;
|
||||
double criterion_end; //Default: 1.0e-6;
|
||||
double criterion_increment; //Default: 0.1;
|
||||
int max_iterations_start; //Default: 50; Max # of iterations for csminwel. The starting value is small because criterion_start
|
||||
// is coarse at the start. As the convergence criterion is getting tighter, the max # of
|
||||
// iteration increases as it is multiplied by max_iterations_increment.
|
||||
double max_iterations_increment; //Default: 2.0; Used to multiply the max # of iterations in csminwel as the convergence
|
||||
// criterion tightens.
|
||||
double ini_h_scale; //Default: 5.0e-4; 1.0e-05 (sometimes used for SargentWZ USinflation project I)
|
||||
// 5.0e-04 (for monthly TVBAR)
|
||||
//=== Outside the blocks.
|
||||
int max_block_iterations; //Default: 100;
|
||||
|
||||
//------------------------------------------------------------
|
||||
//Step size for numerical gradient only when the value of x is less than 1.0 in absolute value.
|
||||
//If abs(x)>1.0, the step size is GRADSTPS_CSMINWEL*x.
|
||||
//
|
||||
//For the time-varying-parameter model, GRADSTPS_CSMINWEL takes the values of gradstps_csminwel_dv:
|
||||
// 1st element: gradient step for the model parameters (tends to be large; the default value is 1.0e-02).
|
||||
// 2nd element: gradient step for the transition probability matrix (tends to be smaller; the default value is 1.0e-03)
|
||||
// 3rd element: gradient step for all the parameters (tends to be smaller; the default value is 1.0e-03 or 1.0e-04).
|
||||
//For the constant-parameter model:
|
||||
// GRADSTPS_CSMINWEL takes the value of gradstps_csminwel_const. The default value is 1.0e-04 (for monthly TBVAR)
|
||||
//------------------------------------------------------------
|
||||
TSdvector *gradstps_csminwel_dv; //3-by-1. For the time-varying-parameter model only.
|
||||
double gradstps_csminwel_const; //For the constant-parameter model.
|
||||
|
||||
//--- pointer to the input data file that contains all the data on convergence, max iterations, etc.
|
||||
FILE *fptr_input1;
|
||||
} TSargs_blockcsminwel;
|
||||
struct TSargs_blockcsminwel_tag *CreateTSargs_blockcsminwel(FILE *fptr_input1);
|
||||
//If fptr_input1==NULL or no no values supplied when fptr_input1 != NULL, default values are taken.
|
||||
struct TSargs_blockcsminwel_tag *DestroyTSargs_blockcsminwel(struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps);
|
||||
//+
|
||||
typedef struct TStateModel_tag *TFDestroyTStateModel(struct TStateModel_tag *);
|
||||
typedef struct TSetc_minproj_tag
|
||||
{
|
||||
//For optimization of the posterior or likelihood function.
|
||||
struct TStateModel_tag *smodel_ps;
|
||||
struct TStateModel_tag *(*DestroyTStateModel)(struct TStateModel_tag *);
|
||||
//
|
||||
struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps;
|
||||
struct TSargs_blockcsminwel_tag *(*DestroyTSargs_blockcsminwel)(struct TSargs_blockcsminwel_tag *);
|
||||
} TSetc_minproj;
|
||||
//
|
||||
struct TSetc_minproj_tag *CreateTSetc_minproj(struct TStateModel_tag **smodel_pps, TFDestroyTStateModel *DestroyTStateModel_func,
|
||||
struct TSargs_blockcsminwel_tag **args_blockcsminwel_pps, struct TSargs_blockcsminwel_tag *(*DestroyTSargs_blockcsminwel)(struct TSargs_blockcsminwel_tag *));
|
||||
struct TSetc_minproj_tag *DestroyTSetc_minproj(struct TSetc_minproj_tag *);
|
||||
//And creates the following user's function.
|
||||
//static double minneglogpost(struct TSminpack_tag *minpack_ps); //For the constant-parameter only.
|
||||
//=== Step 2. Belongs to the user's responsibility because this function must be able to deal with
|
||||
// (1) constant-parameter case without using DW's functions;
|
||||
// (2) allowing us to generate parameters randomly, which depends on the specific model.
|
||||
// See lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
// or ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips.
|
||||
//---
|
||||
//void InitializeForMinproblem(struct TSminpack_tag *minpack_ps, char *filename_sp, TSdvector *gphi_dv, int indxStartValuesForMin);
|
||||
//=== Step 3.
|
||||
void minfinder_blockcsminwel(struct TSminpack_tag *minpack_ps, int indx_findMLE); //Blockwise minimization.
|
||||
//indx_findMLE: 1: find MLE without a prior, 0: find posterior (with a prior).
|
||||
|
||||
|
||||
|
||||
|
||||
//================ For IMSL multivariate linearly-constrained minimizaiton package only. ================//
|
||||
typedef struct TSpackage_imslconlin_tag
|
||||
{
|
||||
//=== Non-simple constraints.
|
||||
int npars_tot; //Total number of free parameters for the optimaization.
|
||||
//For example, model free parameters + free transition matrix parameters in the regime-switching case.
|
||||
int neqs; //Number of equality constraints, excluding simple bound constraints. Must be no greater than ncons.
|
||||
//IMSL dictates that equality constraints come always BEFORE inequality constrains.
|
||||
int ncons; //Total number of constrains, including equality and inequality constraints, but excluding simple bounds.
|
||||
TSdvector *lh_coefs_dv; //ncons*npars_tot-by-1. ALWAYS initialized to be 0.0.
|
||||
//Left-hand coefficients in the linear constrains (excluding simple bounds).
|
||||
//IMSL rule: lh_coefs_dv stacks the neqs rows of equality constraints first, followed by the inequality constraints.
|
||||
//Set to NULL if ncons=0;
|
||||
TSdvector *rh_constraints_dv; //ncons-by-1. Set to NULL if ncons=0.
|
||||
//Right-hand constraints in the equality and non-equality constrains (excluding simple bounds).
|
||||
|
||||
|
||||
//=== Simple bounds.
|
||||
TSdvector *lowbounds_dv; //npars_tot-by-1. ALWAYS initialized to -BIGREALNUMBER for thes simple lower bounds.
|
||||
//If a component is unbounded, choose a very negative large value (e.g., -BIGREALNUMBER).
|
||||
TSdvector *upperbounds_dv; //npars_tot-by-1. ALWAYS initialized to +BIGREALNUMBER for thes simple lower bounds.
|
||||
//If a component is unbounded, choose a very positive large value (e.g., BIGREALNUMBER).
|
||||
|
||||
//=== Other output.
|
||||
TSdvector *xsaved_dv; //npars_tot-by-1. Saved the parameters that give the minimal value of the objective function.
|
||||
|
||||
//=== Other inputs.
|
||||
double crit; //Overall convergence criterion on the first-order conditions.
|
||||
int itmax; //Maximum number of iterations.
|
||||
} TSpackage_imslconlin;
|
||||
//+
|
||||
struct TSpackage_imslconlin_tag *CreateTSpackagae_imslconlin(const int npars_tot, const int neqs, const int ncons);
|
||||
struct TSpackage_imslconlin_tag *DestroyTSpackagae_imslconlin(struct TSpackage_imslconlin_tag *package_imslconlin_ps);
|
||||
void minfinder_noblockimslconlin(struct TSpackage_imslconlin_tag *package_imslconlin_ps, struct TSminpack_tag *minpack_ps, char *filename_printout, int ntheta);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//================ For conjugate gradient method I only. ================//
|
||||
typedef struct TSpackage_congrad1_tag
|
||||
{
|
||||
//=== Input arguments.
|
||||
double crit; //Overall convergence criterion on the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
|
||||
//=== Output arguments.
|
||||
int niters; //Number of iterations.
|
||||
} TSpackage_congrad1;
|
||||
//+
|
||||
struct TSpackage_congrad1_tag *CreateTSpackage_congrad1(void);
|
||||
struct TSpackage_congrad1_tag *DestroyTSpackage_congrad1(struct TSpackage_congrad1_tag *package_congrad1_ps);
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
//------- For unconstrained BFGS csminwel only. -------
|
||||
typedef struct TSminpack_csminwel_tag {
|
||||
//=== Optional input arguments, often NOT used, so we set to NULL at this point.
|
||||
double **args; //k-by-q.
|
||||
int *dims; //k-by-1;
|
||||
int _k;
|
||||
|
||||
//=== Mandatory input arguments.
|
||||
TSdmatrix *Hx_dm; //n-by-n inverse Hessian. Output as well, when csminwel is done.
|
||||
double crit; //Overall convergence criterion for the function value.
|
||||
int itmax; //Maximum number of iterations.
|
||||
// double grdh; //Step size for the numerical gradient if no analytical gradient is available.
|
||||
|
||||
//=== Initial input arguments.
|
||||
double ini_h_csminwel;
|
||||
int indxnumgrad_csminwel;
|
||||
double gradstps_csminwel;
|
||||
|
||||
|
||||
//=== Output arguments.
|
||||
int badg; //If (badg==0), analytical gradient is used; otherwise, numerical gradient will be produced.
|
||||
int niter; //Number of iterations taken by csminwel.
|
||||
int fcount; //Number of function evaluations used by csminwel.
|
||||
int retcode; //Return code for the terminating condition.
|
||||
// 0, normal step (converged). 1, zero gradient (converged).
|
||||
// 4,2, back and forth adjustment of stepsize didn't finish.
|
||||
// 3, smallest stepsize still improves too slow. 5, largest step still improves too fast.
|
||||
// 6, no improvement found.
|
||||
} TSminpack_csminwel;
|
||||
/**/
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*************** 3 steps to find minimization solution. *****************
|
||||
//---------------------------------
|
||||
//-- For concrete examples, see
|
||||
//-- lwz_est.c in D:\ZhaData\WorkDisk\LiuWZ\Project2_empirical\EstimationOct07
|
||||
//-- ExamplesForC.prn in D:\ZhaData\CommonFiles\C_Examples_DebugTips
|
||||
//---------------------------------
|
||||
|
||||
//------ For the csminwel minimization problem. -------
|
||||
//--- Step 1. Creats a number of csminwel structures for both Markov-switching and constant-parameter models.
|
||||
static double minobj(struct TSminpack_tag *minpack_ps); //This function is for the constant-parameter model only.
|
||||
//--- Step 2.
|
||||
static void InitializeForMinproblem(struct TSminpack_tag *minpack_ps, char *filename_sp);
|
||||
//--- Step 3.
|
||||
//For the constant-parameter model, run minfinder(minpack_ps); //Constant-parameter case.
|
||||
//For the regime-switching model, run minfinder_blockcsminwel(minpack_ps); //Time-varying case.
|
||||
*
|
||||
*
|
||||
*
|
||||
|
||||
|
||||
//=== main.c
|
||||
|
||||
int indxInitializeTransitionMatrix;
|
||||
//--- My model structure.
|
||||
struct TSlwzmodel_tag *lwzmodel_ps = NULL;
|
||||
//--- Waggoner's Markov switching package.
|
||||
struct TMarkovStateVariable_tag *sv_ps = NULL;
|
||||
ThetaRoutines *sroutines_ps = NULL;
|
||||
struct TStateModel_tag *smodel_ps = NULL;
|
||||
//--- General (csminwel) minimization for constant-parameter.
|
||||
struct TSetc_minproj_tag *etc_minproj_ps = NULL;
|
||||
struct TSminpack_tag *minpack_ps = NULL;
|
||||
//--- Blockwise (csminwel) minimization for regime-switching model.
|
||||
struct TSargs_blockcsminwel_tag *args_blockcsminwel_ps = NULL;
|
||||
|
||||
|
||||
//-----------------
|
||||
// Reads from the command line the user-specified input file and the most-often-used integer arguments such as sample size.
|
||||
//-----------------
|
||||
cl_modeltag = fn_ParseCommandLine_String(n_arg,args_cl,'t',(char *)NULL); // Tag for different models.
|
||||
if (!cl_modeltag) fn_DisplayError(".../main(): No model tag is specified yet");
|
||||
//--- Type of the model: (0) const, (1) varionly, (2) trendinf, (3) policyonly, and (4) firmspolicy.
|
||||
if (!strncmp("const", cl_modeltag, 5)) indx_tvmodel = 0;
|
||||
else if (!strncmp("varionly", cl_modeltag, 5)) indx_tvmodel = 1;
|
||||
else if (!strncmp("trendinf", cl_modeltag, 5)) indx_tvmodel = 2;
|
||||
else if (!strncmp("policyonly", cl_modeltag, 5)) indx_tvmodel = 3;
|
||||
else if (!strncmp("firmspolicy", cl_modeltag, 5)) indx_tvmodel = 4;
|
||||
else fn_DisplayError("main(): the model tag is NOT properly selected");
|
||||
indxStartValuesForMin = fn_ParseCommandLine_Integer(n_arg,args_cl,'c',1);
|
||||
sprintf(filename_sp_vec_minproj, "outdatasp_min_%s.prn", cl_modeltag);
|
||||
//+
|
||||
sprintf(filenamebuffer, "dataraw.prn");
|
||||
cl_filename_rawdata = fn_ParseCommandLine_String(n_arg,args_cl,'r',filenamebuffer); //Raw data input file.
|
||||
fptr_rawdata = tzFopen(cl_filename_rawdata,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_common.prn");
|
||||
cl_filename_input1 = fn_ParseCommandLine_String(n_arg,args_cl,'i',filenamebuffer); //Common setup input data file.
|
||||
fptr_input1 = tzFopen(cl_filename_input1,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_%s.prn", cl_modeltag);
|
||||
cl_filename_input2 = fn_ParseCommandLine_String(n_arg,args_cl,'s',filenamebuffer); //Model-specific setupt input data file.
|
||||
fptr_input2 = tzFopen(cl_filename_input2,"r");
|
||||
//+
|
||||
sprintf(filenamebuffer, "datainp_markov_%s.prn", cl_modeltag);
|
||||
cl_filename_markov = fn_ParseCommandLine_String(n_arg,args_cl,'m',filenamebuffer); //Markov-switching setup input data file.
|
||||
fptr_markov = tzFopen(cl_filename_markov,"r");
|
||||
//--- Output data files.
|
||||
sprintf(filenamebuffer, "outdata_debug_%s.prn", cl_modeltag);
|
||||
FPTR_DEBUG = tzFopen(filenamebuffer,"w"); //Debug output file.
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdataout_%s.prn", cl_modeltag);
|
||||
fptr_output = tzFopen(filenamebuffer,"w"); //Final output file.
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab_%s.prn", cl_modeltag);
|
||||
fptr_matlab = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab1_%s.prn", cl_modeltag);
|
||||
fptr_matlab1 = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab2_%s.prn", cl_modeltag);
|
||||
fptr_matlab2 = tzFopen(filenamebuffer, "w");
|
||||
//+
|
||||
sprintf(filenamebuffer, "outdatainp_matlab3_%s.prn", cl_modeltag);
|
||||
fptr_matlab3 = tzFopen(filenamebuffer, "w");
|
||||
|
||||
|
||||
//----------------------------------------------
|
||||
//--- Memory allocation and structure creation.
|
||||
//--- The order matters!
|
||||
//----------------------------------------------
|
||||
//--- Model structure. ---
|
||||
lwzmodel_ps = CreateTSlwzmodel(fptr_rawdata, fptr_input1, fptr_input2, fptr_markov, indx_tvmodel, indxStartValuesForMin);
|
||||
sprintf(lwzmodel_ps->tag_modeltype_cv->v, cl_modeltag);
|
||||
lwzmodel_ps->tag_modeltype_cv->flag = V_DEF;
|
||||
|
||||
|
||||
//====== Waggoner's Markov switching variables. ======
|
||||
sv_ps = CreateMarkovStateVariable_File(fptr_markov, (char *)NULL, lwzmodel_ps->fss);
|
||||
//In this case, fptr_markov points to datainp_markov_const.prn, which can be found in D:\ZhaData\CommonFiles\C_Examples_DebugTips\DW_MarkovInputFiles.
|
||||
sroutines_ps = CreateThetaRoutines_empty();
|
||||
sroutines_ps->pLogConditionalLikelihood = logTimetCondLH; //User's: logTimetCondLH
|
||||
sroutines_ps->pLogPrior = logpriordensity_usingDW; //User's: pLogPrior
|
||||
sroutines_ps->pNumberFreeParametersTheta = NumberOfFreeModelSpecificParameters; //User's: NumberOfFreeModelSpecificParameters,
|
||||
sroutines_ps->pConvertFreeParametersToTheta = ConvertFreeParameters2ModelSpecificParameters; //User's: ConvertFreeParameters2ModelSpecificParameters,
|
||||
sroutines_ps->pConvertThetaToFreeParameters = ConvertModelSpecificParameters2FreeParameters; //User's: ConvertModelSpecificParameters2FreeParameters,
|
||||
sroutines_ps->pThetaChanged = tz_thetaChanged; //User's: Notification routine (need to refresh everything given new parameters?)
|
||||
sroutines_ps->pTransitionMatrixChanged = tz_TransitionMatrixChanged; //User's: Notification routine (need to refresh everything given new parameters?)
|
||||
smodel_ps = CreateStateModel_new(sv_ps, sroutines_ps, (void *)lwzmodel_ps);
|
||||
//--- Optional.
|
||||
if (!indx_tvmodel && fn_SetFilePosition(fptr_markov, "//== indxInitializeTransitionMatrix ==//"))
|
||||
if ((fscanf(fptr_markov, " %d ", &indxInitializeTransitionMatrix) == 1) && indxInitializeTransitionMatrix)
|
||||
ReadTransitionMatrices(fptr_markov, (char*)NULL, "Initial: ", smodel_ps); //Waggoner's function.
|
||||
|
||||
|
||||
//--- Minimization problem: Step 1. ---
|
||||
args_blockcsminwel_ps = CreateTSargs_blockcsminwel(fptr_input1);
|
||||
//Blockwise (csminwel) minimization arguments, reading convergence criteria or using default values if fptr_input1 is set to NULL.
|
||||
//fptr_input1 contains parameters for both constant-parameter and Markov-switching models.
|
||||
etc_minproj_ps = CreateTSetc_minproj(&smodel_ps, (TFDestroyTStateModel *)NULL, &args_blockcsminwel_ps, DestroyTSargs_blockcsminwel);
|
||||
//Taking convergence criteria and my model structure smodel_ps into minpack_ps.
|
||||
minpack_ps = CreateTSminpack((TFminobj *)minobj, (void **)&etc_minproj_ps, (TFmindestroy_etcproject *)NULL, (TFmingrad *)NULL,
|
||||
filename_sp_vec_minproj,
|
||||
lwzmodel_ps->xphi_dv->n+NumberFreeParametersQ(smodel_ps),
|
||||
MIN_CSMINWEL);
|
||||
//minobj is for the constant-parameter model only in which case, NumberFreeParametersQ(smodel_ps) will be 0.
|
||||
|
||||
|
||||
//-----------------
|
||||
// Main matter.
|
||||
//-----------------
|
||||
time(&lwzmodel_ps->prog_begtime); //Beginning time of the whole program.
|
||||
InitializeGlobleSeed(lwzmodel_ps->randomseed = 0); //2764 If seednumber==0, a value is computed using the system clock.
|
||||
csminwel_randomseedChanged(lwzmodel_ps->randomseed); //Using the same (or different) seednumber to reset csminwel seednumber for random perturbation.
|
||||
//=== Finding the peak value of the logLH or logPosterior
|
||||
if (lwzmodel_ps->indxEstFinder)
|
||||
{
|
||||
//Minimization problem: Steps 2 and 3.
|
||||
|
||||
InitializeForMinproblem(minpack_ps, filename_sp_vec_minproj); //Initialization for minimization.
|
||||
//======= 1st round of minimization. =======
|
||||
//--------------------------
|
||||
//-- csminwel minimization where
|
||||
//-- minpack_ps->x_dv contains the minimizing vector of parameters.
|
||||
//-- minpack_ps->fret contains the minimized value.
|
||||
//--------------------------
|
||||
|
||||
if (!lwzmodel_ps->indx_tvmodel) minfinder(minpack_ps); //Constant-parameter case.
|
||||
else minfinder_blockcsminwel(minpack_ps); //Time-varying case.
|
||||
}
|
||||
else InitializeForMinproblem(minpack_ps, filename_sp_vec_minproj);
|
||||
time(&lwzmodel_ps->prog_endtime); //Ending time of the whole program.
|
||||
/*************************************************************************/
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,364 +1,364 @@
|
|||
/*********
|
||||
* _cv: Pointer to TScvector (character vector).
|
||||
* _iv: Pointer to TSivector (integer vector).
|
||||
* _im: Pointer to TSimatrix (integer matrix).
|
||||
* _dv: Pointer to TSdvector (double vector).
|
||||
* _dm: Pointer to TSdmatrix (double matrix).
|
||||
* _dc: Pointer to TSdcell (double cell -- pointer to pointer to a matrix).
|
||||
* _dcv: Pointer to TSdcellvec (double cell -- pointer to pointer to a vector).
|
||||
* _d4: Pointer to TSdfourth (double fourth dimension -- pointer to pointer to pointer to a matrix).
|
||||
* _dzv: Pointer to TSdzvector (double complex vector).
|
||||
* _dzm: Pointer to TSdzmatrix (double complex matrix).
|
||||
*
|
||||
* _s: structure variable.
|
||||
* _ps: pointer to a structure.
|
||||
* _sv: an array of structures.
|
||||
*
|
||||
* _sdv: structure (NOT pointer to structure) that contains TSdvector.
|
||||
* _sdm: structure (NOT pointer to structure) that contains TSdmatrix.
|
||||
*
|
||||
* ???????? OLD NOTATIONS ??????????
|
||||
* _v: C row or column vector pointer.
|
||||
* _vint: C row or column vector pointer to integer.
|
||||
* _m: C matrix pointer.
|
||||
* _mint: C matrix pointer to integer.
|
||||
* _m3: C 3-D matrix pointer.
|
||||
* _ppm: C pointer to pointer to a matrix.
|
||||
* d_???_ppm: the number of pointers that are pointed to by _ppm.
|
||||
* rv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of rows, each of the numbers coresponding to a pointed matrix.
|
||||
* cv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of columns, each of the numbers coresponding to a pointed matrix.
|
||||
* d_???_v: dimension size.
|
||||
* r_???_m: numbers of rows.
|
||||
* c_???_m: number of columns.
|
||||
* r_???_m3: number of rows.
|
||||
* c_???_m3: number of columns.
|
||||
* t_???_m3: number of a third dimension.
|
||||
*********/
|
||||
|
||||
|
||||
#ifndef __TZMATLAB__
|
||||
#define __TZMATLAB__
|
||||
#define _ISOC99_SOURCE //Using C99 features for gcc or icc on Linux. Must be placed as the first line above all #include lines.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // For rand(), size_t, exit, malloc, free, qsort, EXIT_FAILURE.
|
||||
#include <memory.h> //For memcpy, etc. Alternative: string.h
|
||||
#include <math.h> //For isfinite.
|
||||
#include <float.h> //For DBL_MIN, etc.
|
||||
#include <time.h> //For time(), etc.
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define USE_DEBUG_FILE //When defined, one must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_DEBUG; //For debugging. Applied to all functions and all .c files that call tzmatlab.h.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_OPT; //For recording the optimization intermediate results.
|
||||
//Applied to minfinder_blockcsminwel() in optpackage.c.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
//#define USE_IMSL_MATH_LIBRARY
|
||||
//#define USE_IMSL_STAT_LIBRARY
|
||||
#define USE_GSL_LIBRARY
|
||||
//#define USE_MKL_LIBRARY
|
||||
/*******************************************************************************/
|
||||
|
||||
// #define NEWVERSIONofDW_SWITCH //If defined, using DW's new switch program (implemented in 2008),
|
||||
// which may be incompatible with previous programs, such as ...\SargentWZ2\EstProbModel\EstimationJuly07USED
|
||||
//If undef, using the old, working switch program for, say, ...\SargentWZ2\EstProbModel\EstimationJuly07USED.
|
||||
//Files that are affected are: cstz.c, kalman.c, optpackage.c,
|
||||
|
||||
|
||||
#define SWITCHTOIMSLCMATH // define: use IMSL special functions like gammlog; undef: use my own default code if it exists.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
// #define INTELCMATHLIBRARY // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define IMSLCMATHLIBRARY // define: use IMSL C Math library; undef: use others.
|
||||
//#define MATLABCMATHLIBRARY // define: use Matlab C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define SWITCHTOINTELCMATH // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define SWITCHTOTZCMATH // define: use my own C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for optimization routines except that CG?_ and CSMINWEL_ can be chosen together.--------
|
||||
//#define IMSL_OPTIMIZATION // IMSL optimization routines.
|
||||
#define CSMINWEL_OPTIMIZATION //Sims's optimization routine.
|
||||
#define CGI_OPTIMIZATION //Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
//NOT available yet! #define CGII_OPTIMIZATION //NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
|
||||
//-------Only one of the following for random number generating routines.--------
|
||||
#define IMSL_RANDOMNUMBERGENERATOR // IMSL random number generator.
|
||||
//#define CASE2_RANDOMNUMBERGENERATOR //Imported from the C recipe book -- case 2 and my own (Iskander) code for generating a gamma distribution.
|
||||
|
||||
//-------Only one of the following statistical packages.--------
|
||||
#define IMSL_STATISTICSTOOLBOX // IMSL statistical package.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
#if defined(USE_MKL_LIBRARY)
|
||||
#include "mkl.h"
|
||||
#else
|
||||
#if defined (USE_GSL_LIBRARY)
|
||||
#include "gsl_cblas.h"
|
||||
#endif
|
||||
#include "blas_lapack.h"
|
||||
#undef SWITCHTOINTELCMATH
|
||||
// #undef INTELCMATHLIBRARY
|
||||
#endif
|
||||
|
||||
#if defined(USE_GSL_LIBRARY)
|
||||
#include "gsl_sf_gamma.h"
|
||||
#include "gsl_cdf.h"
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_MATH_LIBRARY)
|
||||
#include <imsl.h> //IMSL math package.
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef SWITCHTOIMSLCMATH
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef IMSL_RANDOMNUMBERGENERATOR
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_STAT_LIBRARY)
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_STATISTICSTOOLBOX
|
||||
#endif
|
||||
/*******************************************************************************/
|
||||
|
||||
//-------If define: use matlab API interface; otherwise (undef), use C console.
|
||||
#undef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
|
||||
|
||||
//---------------
|
||||
#ifdef MATLABCMATHLIBRARY
|
||||
#include "matlab.h" // For all mlf???? functions.
|
||||
#include "matrix.h" // For mxGetM, mxCreatDoubleMatrix, etc.
|
||||
#endif
|
||||
#ifdef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
#include "mex.h" // For all mex??? calls. Matlab API (application program interface or external interface).
|
||||
#define printf mexPrintf
|
||||
#define malloc mxMalloc
|
||||
#define calloc mxCalloc
|
||||
#define free mxFree
|
||||
#endif
|
||||
|
||||
|
||||
//-------------- Attributes for the real double matrix type TSdmatrix. --------------
|
||||
//-------------- Whenever a matrix is initialized, the default is M_GE, but nothing else. --------------
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
// #define M_UTU 0x0040 //2^6: An unit upper triangular matrix.
|
||||
// #define M_LTU 0x0080 //2^7: An unit lower triangular matrix.
|
||||
//-------------- Attributes for the real double vector type TSdvector or the character vector type TScvector. --------------
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
|
||||
|
||||
//-------------- Other macro definitions. --------------
|
||||
#define BLOCKSIZE_FOR_INTEL_MKL 128 //A machine-dependent value (typically, 16 to 64) required for optimum performance of the blocked algorithm in Intel MKL.
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define BIGREALNUMBER 1.0E+30
|
||||
#define MACHINEZERO DBL_MIN
|
||||
#define EPSILON DBL_EPSILON //1.0E-015. In Standard C, DBL_EPSILON = 2.2204460492503131
|
||||
#define SQRTEPSILON 1.490116119384766E-008 //1.0E-15. In Standard C, DBL_EPSILON = 2.2204460492503131E-016
|
||||
#define SQRTMACHINEZERO 1.490116119384766E-008
|
||||
//This is really not correct, because this number is sqrt(epsion), where DBL_MIN is around 1.0e-300.
|
||||
#define MACHINEINFINITY DBL_MAX
|
||||
#define MACHINE_EXP_INFINITY DBL_MAX_EXP
|
||||
#define EXP_NEARINFINITY 1000
|
||||
//===
|
||||
#define TZ_TRUE 1
|
||||
#define TZ_FALSE 0
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
#define tzMalloc(elt_count, type) (type *)m_alloc((elt_count)*sizeof(type))
|
||||
#define tzCalloc(elt_count, type) (type *)c_alloc((elt_count), sizeof(type))
|
||||
#define tzDestroy(x) {if ((x)) { \
|
||||
free((x)); \
|
||||
(x) = NULL; \
|
||||
}}
|
||||
#define tzFclose(x) {if ((x)) { \
|
||||
fclose((x)); \
|
||||
(x) = (FILE *)NULL; \
|
||||
}}
|
||||
#define mos(i, j, nrows) ((j)*(nrows)+(i)) //i: ith row; j: jth column; nrows: number of rows for the matrix.
|
||||
//Offset(os) for a matrix(m) in column major order and with base 0. See Reek pp.241-242.
|
||||
#define square(x) ((x) * (x)) //Must be careful to avoid using, say, square(tmpd=2) or square(++x).
|
||||
#define _max(a, b) ((a)>(b) ? (a) : (b)) // Macro max or __max is already defined in stdlib.h in MS visual C++, but mex.h may overwrite the max macro so we use _max.
|
||||
#define _min(a, b) ((a)>(b) ? (b) : (a))
|
||||
#define swap(a, b, stemp) {(stemp)=(a); (a)=(b); (b)=(stemp);}
|
||||
//
|
||||
#ifndef isfinite
|
||||
#define isfinite(x) _finite(x) //_finite is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// All these Microsoft functions are not yet C99 compatible.
|
||||
#endif
|
||||
//--- The following does not work.
|
||||
// #ifndef FP_NAN
|
||||
// #define FP_NAN _FPCLASS_SNAN //_FPCLASS_SNAN is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// // All these Microsoft functions are not yet C99 compatible.
|
||||
// #endif
|
||||
#define isdiagonalmatrix(x) (((x)->flag & (M_UT | M_LT)) == (M_UT | M_LT)) //x is the tz type of matrix.
|
||||
//
|
||||
#define DestroyDatesVector_lf(x) DestroyVector_lf(x)
|
||||
|
||||
|
||||
//---------------
|
||||
typedef struct TScvector_tag
|
||||
{
|
||||
char *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TScvector;
|
||||
typedef struct TSvoidvector_tag
|
||||
{
|
||||
void *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSvoidvector;
|
||||
typedef struct {
|
||||
int *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSivector;
|
||||
typedef struct {
|
||||
int *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSimatrix;
|
||||
typedef struct {
|
||||
TSivector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicellvec;
|
||||
typedef struct {
|
||||
TSimatrix **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicell;
|
||||
//=== Real types.
|
||||
typedef struct {
|
||||
double *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
typedef struct {
|
||||
double *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct {
|
||||
TSdmatrix **C; //ncells-by-1 cells (C) and a pointer to matrix in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcell;
|
||||
typedef struct {
|
||||
TSdvector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcellvec;
|
||||
typedef struct {
|
||||
TSdcell **F; //ndims-by-1 fourths (F) and a pointer to cell in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourth;
|
||||
typedef struct {
|
||||
TSdcellvec **F; //ndims-by-1 fourths (F) and a pointer to cellvec in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourthvec;
|
||||
//=== Complex types.
|
||||
typedef struct {
|
||||
TSdvector *real; //Real part.
|
||||
TSdvector *imag; //Imaginary part.
|
||||
} TSdzvector;
|
||||
typedef struct {
|
||||
TSdmatrix *real; //Real part.
|
||||
TSdmatrix *imag; //Imaginary part.
|
||||
} TSdzmatrix;
|
||||
|
||||
|
||||
|
||||
//----------------- Some high-level functions. -----------------
|
||||
int fn_locofyearqm(int q_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
void fn_DisplayError(char *msg_s);
|
||||
void *m_alloc(size_t size);
|
||||
void *c_alloc(size_t elt_count, size_t elt_size);
|
||||
|
||||
/**
|
||||
TSvoidvector *CreateVector_void(int _n);
|
||||
TSvoidvector *DestroyVector_void(TSvoidvector *x_voidv);
|
||||
/**/
|
||||
|
||||
TScvector *CreateVector_c(int _n);
|
||||
TScvector *DestroyVector_c(TScvector *x_s);
|
||||
TSivector *CreateVector_int(int _n);
|
||||
TSivector *DestroyVector_int(TSivector *x_iv);
|
||||
TSimatrix *CreateMatrix_int(int nrows, int ncols);
|
||||
TSimatrix *DestroyMatrix_int(TSimatrix *x_im);
|
||||
TSicellvec *CreateCellvec_int(TSivector *n_iv);
|
||||
TSicellvec *DestroyCellvec_int(TSicellvec *x_icv);
|
||||
TSicell *CreateCell_int(TSivector *row_iv, TSivector *col_iv);
|
||||
TSicell *DestroyCell_int(TSicell *x_ic);
|
||||
|
||||
TSdvector *CreateVector_lf(int _n);
|
||||
TSdvector *DestroyVector_lf(TSdvector *x_iv);
|
||||
TSdmatrix *CreateMatrix_lf(int nrows, int ncols);
|
||||
TSdmatrix *DestroyMatrix_lf(TSdmatrix *x_im);
|
||||
TSdcell *CreateCell_lf(TSivector *row_iv, TSivector *col_iv);
|
||||
TSdcell *DestroyCell_lf(TSdcell *x_dc);
|
||||
TSdcellvec *CreateCellvec_lf(TSivector *n_iv);
|
||||
TSdcellvec *DestroyCellvec_lf(TSdcellvec *x_dcv);
|
||||
TSdfourth *CreateFourth_lf(int ndims, TSivector *row_iv, TSivector *col_iv);
|
||||
TSdfourth *DestroyFourth_lf(TSdfourth *x_d4);
|
||||
TSdfourthvec *CreateFourthvec_lf(int ndims, TSivector *n_iv);
|
||||
TSdfourthvec *DestroyFourthvec_lf(TSdfourthvec *x_d4v);
|
||||
|
||||
TSdzvector *CreateVector_dz(int _n);
|
||||
TSdzvector *DestroyVector_dz(TSdzvector *x_dzv);
|
||||
TSdzmatrix *CreateMatrix_dz(int nrows, int ncols);
|
||||
TSdzmatrix *DestroyMatrix_dz(TSdzmatrix *x_dzm);
|
||||
|
||||
//+
|
||||
TSdmatrix *CreateZeroMatrix_lf(const int nrows, const int ncols);
|
||||
TSdmatrix *CreateIdentityMatrix_lf(const int nrows, const int ncols);
|
||||
//TSdvector *CreateZerosVector_lf(int _n);
|
||||
TSivector *CreateConstantVector_int( const int _n, const int _k);
|
||||
TSimatrix *CreateConstantMatrix_int(const int nrows, const int ncols, const int _n);
|
||||
TSicellvec *CreateConstantCellvec_int(TSivector *n_iv, const int _n);
|
||||
TSicell *CreateConstantCell_int(TSivector *row_iv, TSivector *col_iv, const int _n);
|
||||
TSdvector *CreateConstantVector_lf(const int _n, const double _alpha);
|
||||
TSdmatrix *CreateConstantMatrix_lf(const int nrows, const int ncols, const double _alpha);
|
||||
TSdcellvec *CreateConstantCellvec_lf(TSivector *n_iv, const double _alpha);
|
||||
TSdcell *CreateConstantCell_lf(TSivector *row_iv, TSivector *col_iv, const double _alpha);
|
||||
TSdvector *CreateDatesVector_lf(int nq_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
//+
|
||||
void InitializeConstantVector_lf(TSdvector *x_dv, const double _alpha);
|
||||
void InitializeConstantVector_int(TSivector *x_iv, const int _k);
|
||||
void InitializeConstantMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeDiagonalMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeConstantMatrix_int(TSimatrix *x_dm, const int _alpha);
|
||||
void InitializeConstantCellvec_lf(TSdcellvec *x_dcv, const double _alpha);
|
||||
void InitializeConstantCell_lf(TSdcell *x_dc, const double _alpha);
|
||||
void InitializeConstantFourthvec_lf(TSdfourthvec *x_d4v, const double _alpha);
|
||||
void InitializeConstantFourth_lf(TSdfourth *x_d4, const double _alpha);
|
||||
|
||||
|
||||
void NegateColofMatrix_lf(TSdvector *y_dv, TSdmatrix *x_dm, int _j);
|
||||
void InitializeConstantColofMatrix_lf(TSdmatrix *X_dm, int jx, double _alpha);
|
||||
|
||||
FILE *tzFopen(char *filename, char *mode);
|
||||
#endif
|
||||
/*********
|
||||
* _cv: Pointer to TScvector (character vector).
|
||||
* _iv: Pointer to TSivector (integer vector).
|
||||
* _im: Pointer to TSimatrix (integer matrix).
|
||||
* _dv: Pointer to TSdvector (double vector).
|
||||
* _dm: Pointer to TSdmatrix (double matrix).
|
||||
* _dc: Pointer to TSdcell (double cell -- pointer to pointer to a matrix).
|
||||
* _dcv: Pointer to TSdcellvec (double cell -- pointer to pointer to a vector).
|
||||
* _d4: Pointer to TSdfourth (double fourth dimension -- pointer to pointer to pointer to a matrix).
|
||||
* _dzv: Pointer to TSdzvector (double complex vector).
|
||||
* _dzm: Pointer to TSdzmatrix (double complex matrix).
|
||||
*
|
||||
* _s: structure variable.
|
||||
* _ps: pointer to a structure.
|
||||
* _sv: an array of structures.
|
||||
*
|
||||
* _sdv: structure (NOT pointer to structure) that contains TSdvector.
|
||||
* _sdm: structure (NOT pointer to structure) that contains TSdmatrix.
|
||||
*
|
||||
* ???????? OLD NOTATIONS ??????????
|
||||
* _v: C row or column vector pointer.
|
||||
* _vint: C row or column vector pointer to integer.
|
||||
* _m: C matrix pointer.
|
||||
* _mint: C matrix pointer to integer.
|
||||
* _m3: C 3-D matrix pointer.
|
||||
* _ppm: C pointer to pointer to a matrix.
|
||||
* d_???_ppm: the number of pointers that are pointed to by _ppm.
|
||||
* rv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of rows, each of the numbers coresponding to a pointed matrix.
|
||||
* cv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of columns, each of the numbers coresponding to a pointed matrix.
|
||||
* d_???_v: dimension size.
|
||||
* r_???_m: numbers of rows.
|
||||
* c_???_m: number of columns.
|
||||
* r_???_m3: number of rows.
|
||||
* c_???_m3: number of columns.
|
||||
* t_???_m3: number of a third dimension.
|
||||
*********/
|
||||
|
||||
|
||||
#ifndef __TZMATLAB__
|
||||
#define __TZMATLAB__
|
||||
#define _ISOC99_SOURCE //Using C99 features for gcc or icc on Linux. Must be placed as the first line above all #include lines.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // For rand(), size_t, exit, malloc, free, qsort, EXIT_FAILURE.
|
||||
#include <memory.h> //For memcpy, etc. Alternative: string.h
|
||||
#include <math.h> //For isfinite.
|
||||
#include <float.h> //For DBL_MIN, etc.
|
||||
#include <time.h> //For time(), etc.
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define USE_DEBUG_FILE //When defined, one must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_DEBUG; //For debugging. Applied to all functions and all .c files that call tzmatlab.h.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_OPT; //For recording the optimization intermediate results.
|
||||
//Applied to minfinder_blockcsminwel() in optpackage.c.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
//#define USE_IMSL_MATH_LIBRARY
|
||||
//#define USE_IMSL_STAT_LIBRARY
|
||||
#define USE_GSL_LIBRARY
|
||||
//#define USE_MKL_LIBRARY
|
||||
/*******************************************************************************/
|
||||
|
||||
// #define NEWVERSIONofDW_SWITCH //If defined, using DW's new switch program (implemented in 2008),
|
||||
// which may be incompatible with previous programs, such as ...\SargentWZ2\EstProbModel\EstimationJuly07USED
|
||||
//If undef, using the old, working switch program for, say, ...\SargentWZ2\EstProbModel\EstimationJuly07USED.
|
||||
//Files that are affected are: cstz.c, kalman.c, optpackage.c,
|
||||
|
||||
|
||||
#define SWITCHTOIMSLCMATH // define: use IMSL special functions like gammlog; undef: use my own default code if it exists.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
// #define INTELCMATHLIBRARY // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define IMSLCMATHLIBRARY // define: use IMSL C Math library; undef: use others.
|
||||
//#define MATLABCMATHLIBRARY // define: use Matlab C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define SWITCHTOINTELCMATH // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define SWITCHTOTZCMATH // define: use my own C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for optimization routines except that CG?_ and CSMINWEL_ can be chosen together.--------
|
||||
//#define IMSL_OPTIMIZATION // IMSL optimization routines.
|
||||
#define CSMINWEL_OPTIMIZATION //Sims's optimization routine.
|
||||
#define CGI_OPTIMIZATION //Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
//NOT available yet! #define CGII_OPTIMIZATION //NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
|
||||
//-------Only one of the following for random number generating routines.--------
|
||||
#define IMSL_RANDOMNUMBERGENERATOR // IMSL random number generator.
|
||||
//#define CASE2_RANDOMNUMBERGENERATOR //Imported from the C recipe book -- case 2 and my own (Iskander) code for generating a gamma distribution.
|
||||
|
||||
//-------Only one of the following statistical packages.--------
|
||||
#define IMSL_STATISTICSTOOLBOX // IMSL statistical package.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
#if defined(USE_MKL_LIBRARY)
|
||||
#include "mkl.h"
|
||||
#else
|
||||
#if defined (USE_GSL_LIBRARY)
|
||||
#include "gsl_cblas.h"
|
||||
#endif
|
||||
#include "blas_lapack.h"
|
||||
#undef SWITCHTOINTELCMATH
|
||||
// #undef INTELCMATHLIBRARY
|
||||
#endif
|
||||
|
||||
#if defined(USE_GSL_LIBRARY)
|
||||
#include "gsl_sf_gamma.h"
|
||||
#include "gsl_cdf.h"
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_MATH_LIBRARY)
|
||||
#include <imsl.h> //IMSL math package.
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef SWITCHTOIMSLCMATH
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef IMSL_RANDOMNUMBERGENERATOR
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_STAT_LIBRARY)
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_STATISTICSTOOLBOX
|
||||
#endif
|
||||
/*******************************************************************************/
|
||||
|
||||
//-------If define: use matlab API interface; otherwise (undef), use C console.
|
||||
#undef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
|
||||
|
||||
//---------------
|
||||
#ifdef MATLABCMATHLIBRARY
|
||||
#include "matlab.h" // For all mlf???? functions.
|
||||
#include "matrix.h" // For mxGetM, mxCreatDoubleMatrix, etc.
|
||||
#endif
|
||||
#ifdef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
#include "mex.h" // For all mex??? calls. Matlab API (application program interface or external interface).
|
||||
#define printf mexPrintf
|
||||
#define malloc mxMalloc
|
||||
#define calloc mxCalloc
|
||||
#define free mxFree
|
||||
#endif
|
||||
|
||||
|
||||
//-------------- Attributes for the real double matrix type TSdmatrix. --------------
|
||||
//-------------- Whenever a matrix is initialized, the default is M_GE, but nothing else. --------------
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
// #define M_UTU 0x0040 //2^6: An unit upper triangular matrix.
|
||||
// #define M_LTU 0x0080 //2^7: An unit lower triangular matrix.
|
||||
//-------------- Attributes for the real double vector type TSdvector or the character vector type TScvector. --------------
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
|
||||
|
||||
//-------------- Other macro definitions. --------------
|
||||
#define BLOCKSIZE_FOR_INTEL_MKL 128 //A machine-dependent value (typically, 16 to 64) required for optimum performance of the blocked algorithm in Intel MKL.
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define BIGREALNUMBER 1.0E+30
|
||||
#define MACHINEZERO DBL_MIN
|
||||
#define EPSILON DBL_EPSILON //1.0E-015. In Standard C, DBL_EPSILON = 2.2204460492503131
|
||||
#define SQRTEPSILON 1.490116119384766E-008 //1.0E-15. In Standard C, DBL_EPSILON = 2.2204460492503131E-016
|
||||
#define SQRTMACHINEZERO 1.490116119384766E-008
|
||||
//This is really not correct, because this number is sqrt(epsion), where DBL_MIN is around 1.0e-300.
|
||||
#define MACHINEINFINITY DBL_MAX
|
||||
#define MACHINE_EXP_INFINITY DBL_MAX_EXP
|
||||
#define EXP_NEARINFINITY 1000
|
||||
//===
|
||||
#define TZ_TRUE 1
|
||||
#define TZ_FALSE 0
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
#define tzMalloc(elt_count, type) (type *)m_alloc((elt_count)*sizeof(type))
|
||||
#define tzCalloc(elt_count, type) (type *)c_alloc((elt_count), sizeof(type))
|
||||
#define tzDestroy(x) {if ((x)) { \
|
||||
free((x)); \
|
||||
(x) = NULL; \
|
||||
}}
|
||||
#define tzFclose(x) {if ((x)) { \
|
||||
fclose((x)); \
|
||||
(x) = (FILE *)NULL; \
|
||||
}}
|
||||
#define mos(i, j, nrows) ((j)*(nrows)+(i)) //i: ith row; j: jth column; nrows: number of rows for the matrix.
|
||||
//Offset(os) for a matrix(m) in column major order and with base 0. See Reek pp.241-242.
|
||||
#define square(x) ((x) * (x)) //Must be careful to avoid using, say, square(tmpd=2) or square(++x).
|
||||
#define _max(a, b) ((a)>(b) ? (a) : (b)) // Macro max or __max is already defined in stdlib.h in MS visual C++, but mex.h may overwrite the max macro so we use _max.
|
||||
#define _min(a, b) ((a)>(b) ? (b) : (a))
|
||||
#define swap(a, b, stemp) {(stemp)=(a); (a)=(b); (b)=(stemp);}
|
||||
//
|
||||
#ifndef isfinite
|
||||
#define isfinite(x) _finite(x) //_finite is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// All these Microsoft functions are not yet C99 compatible.
|
||||
#endif
|
||||
//--- The following does not work.
|
||||
// #ifndef FP_NAN
|
||||
// #define FP_NAN _FPCLASS_SNAN //_FPCLASS_SNAN is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// // All these Microsoft functions are not yet C99 compatible.
|
||||
// #endif
|
||||
#define isdiagonalmatrix(x) (((x)->flag & (M_UT | M_LT)) == (M_UT | M_LT)) //x is the tz type of matrix.
|
||||
//
|
||||
#define DestroyDatesVector_lf(x) DestroyVector_lf(x)
|
||||
|
||||
|
||||
//---------------
|
||||
typedef struct TScvector_tag
|
||||
{
|
||||
char *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TScvector;
|
||||
typedef struct TSvoidvector_tag
|
||||
{
|
||||
void *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSvoidvector;
|
||||
typedef struct {
|
||||
int *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSivector;
|
||||
typedef struct {
|
||||
int *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSimatrix;
|
||||
typedef struct {
|
||||
TSivector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicellvec;
|
||||
typedef struct {
|
||||
TSimatrix **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicell;
|
||||
//=== Real types.
|
||||
typedef struct {
|
||||
double *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
typedef struct {
|
||||
double *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct {
|
||||
TSdmatrix **C; //ncells-by-1 cells (C) and a pointer to matrix in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcell;
|
||||
typedef struct {
|
||||
TSdvector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcellvec;
|
||||
typedef struct {
|
||||
TSdcell **F; //ndims-by-1 fourths (F) and a pointer to cell in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourth;
|
||||
typedef struct {
|
||||
TSdcellvec **F; //ndims-by-1 fourths (F) and a pointer to cellvec in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourthvec;
|
||||
//=== Complex types.
|
||||
typedef struct {
|
||||
TSdvector *real; //Real part.
|
||||
TSdvector *imag; //Imaginary part.
|
||||
} TSdzvector;
|
||||
typedef struct {
|
||||
TSdmatrix *real; //Real part.
|
||||
TSdmatrix *imag; //Imaginary part.
|
||||
} TSdzmatrix;
|
||||
|
||||
|
||||
|
||||
//----------------- Some high-level functions. -----------------
|
||||
int fn_locofyearqm(int q_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
void fn_DisplayError(char *msg_s);
|
||||
void *m_alloc(size_t size);
|
||||
void *c_alloc(size_t elt_count, size_t elt_size);
|
||||
|
||||
/**
|
||||
TSvoidvector *CreateVector_void(int _n);
|
||||
TSvoidvector *DestroyVector_void(TSvoidvector *x_voidv);
|
||||
/**/
|
||||
|
||||
TScvector *CreateVector_c(int _n);
|
||||
TScvector *DestroyVector_c(TScvector *x_s);
|
||||
TSivector *CreateVector_int(int _n);
|
||||
TSivector *DestroyVector_int(TSivector *x_iv);
|
||||
TSimatrix *CreateMatrix_int(int nrows, int ncols);
|
||||
TSimatrix *DestroyMatrix_int(TSimatrix *x_im);
|
||||
TSicellvec *CreateCellvec_int(TSivector *n_iv);
|
||||
TSicellvec *DestroyCellvec_int(TSicellvec *x_icv);
|
||||
TSicell *CreateCell_int(TSivector *row_iv, TSivector *col_iv);
|
||||
TSicell *DestroyCell_int(TSicell *x_ic);
|
||||
|
||||
TSdvector *CreateVector_lf(int _n);
|
||||
TSdvector *DestroyVector_lf(TSdvector *x_iv);
|
||||
TSdmatrix *CreateMatrix_lf(int nrows, int ncols);
|
||||
TSdmatrix *DestroyMatrix_lf(TSdmatrix *x_im);
|
||||
TSdcell *CreateCell_lf(TSivector *row_iv, TSivector *col_iv);
|
||||
TSdcell *DestroyCell_lf(TSdcell *x_dc);
|
||||
TSdcellvec *CreateCellvec_lf(TSivector *n_iv);
|
||||
TSdcellvec *DestroyCellvec_lf(TSdcellvec *x_dcv);
|
||||
TSdfourth *CreateFourth_lf(int ndims, TSivector *row_iv, TSivector *col_iv);
|
||||
TSdfourth *DestroyFourth_lf(TSdfourth *x_d4);
|
||||
TSdfourthvec *CreateFourthvec_lf(int ndims, TSivector *n_iv);
|
||||
TSdfourthvec *DestroyFourthvec_lf(TSdfourthvec *x_d4v);
|
||||
|
||||
TSdzvector *CreateVector_dz(int _n);
|
||||
TSdzvector *DestroyVector_dz(TSdzvector *x_dzv);
|
||||
TSdzmatrix *CreateMatrix_dz(int nrows, int ncols);
|
||||
TSdzmatrix *DestroyMatrix_dz(TSdzmatrix *x_dzm);
|
||||
|
||||
//+
|
||||
TSdmatrix *CreateZeroMatrix_lf(const int nrows, const int ncols);
|
||||
TSdmatrix *CreateIdentityMatrix_lf(const int nrows, const int ncols);
|
||||
//TSdvector *CreateZerosVector_lf(int _n);
|
||||
TSivector *CreateConstantVector_int( const int _n, const int _k);
|
||||
TSimatrix *CreateConstantMatrix_int(const int nrows, const int ncols, const int _n);
|
||||
TSicellvec *CreateConstantCellvec_int(TSivector *n_iv, const int _n);
|
||||
TSicell *CreateConstantCell_int(TSivector *row_iv, TSivector *col_iv, const int _n);
|
||||
TSdvector *CreateConstantVector_lf(const int _n, const double _alpha);
|
||||
TSdmatrix *CreateConstantMatrix_lf(const int nrows, const int ncols, const double _alpha);
|
||||
TSdcellvec *CreateConstantCellvec_lf(TSivector *n_iv, const double _alpha);
|
||||
TSdcell *CreateConstantCell_lf(TSivector *row_iv, TSivector *col_iv, const double _alpha);
|
||||
TSdvector *CreateDatesVector_lf(int nq_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
//+
|
||||
void InitializeConstantVector_lf(TSdvector *x_dv, const double _alpha);
|
||||
void InitializeConstantVector_int(TSivector *x_iv, const int _k);
|
||||
void InitializeConstantMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeDiagonalMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeConstantMatrix_int(TSimatrix *x_dm, const int _alpha);
|
||||
void InitializeConstantCellvec_lf(TSdcellvec *x_dcv, const double _alpha);
|
||||
void InitializeConstantCell_lf(TSdcell *x_dc, const double _alpha);
|
||||
void InitializeConstantFourthvec_lf(TSdfourthvec *x_d4v, const double _alpha);
|
||||
void InitializeConstantFourth_lf(TSdfourth *x_d4, const double _alpha);
|
||||
|
||||
|
||||
void NegateColofMatrix_lf(TSdvector *y_dv, TSdmatrix *x_dm, int _j);
|
||||
void InitializeConstantColofMatrix_lf(TSdmatrix *X_dm, int jx, double _alpha);
|
||||
|
||||
FILE *tzFopen(char *filename, char *mode);
|
||||
#endif
|
||||
|
|
|
@ -1,360 +1,360 @@
|
|||
/*********
|
||||
* _cv: Pointer to TScvector (character vector).
|
||||
* _iv: Pointer to TSivector (integer vector).
|
||||
* _im: Pointer to TSimatrix (integer matrix).
|
||||
* _dv: Pointer to TSdvector (double vector).
|
||||
* _dm: Pointer to TSdmatrix (double matrix).
|
||||
* _dc: Pointer to TSdcell (double cell -- pointer to pointer to a matrix).
|
||||
* _dcv: Pointer to TSdcellvec (double cell -- pointer to pointer to a vector).
|
||||
* _d4: Pointer to TSdfourth (double fourth dimension -- pointer to pointer to pointer to a matrix).
|
||||
* _dzv: Pointer to TSdzvector (double complex vector).
|
||||
* _dzm: Pointer to TSdzmatrix (double complex matrix).
|
||||
*
|
||||
* _s: structure variable.
|
||||
* _ps: pointer to a structure.
|
||||
* _sv: an array of structures.
|
||||
*
|
||||
* _sdv: structure (NOT pointer to structure) that contains TSdvector.
|
||||
* _sdm: structure (NOT pointer to structure) that contains TSdmatrix.
|
||||
*
|
||||
* ???????? OLD NOTATIONS ??????????
|
||||
* _v: C row or column vector pointer.
|
||||
* _vint: C row or column vector pointer to integer.
|
||||
* _m: C matrix pointer.
|
||||
* _mint: C matrix pointer to integer.
|
||||
* _m3: C 3-D matrix pointer.
|
||||
* _ppm: C pointer to pointer to a matrix.
|
||||
* d_???_ppm: the number of pointers that are pointed to by _ppm.
|
||||
* rv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of rows, each of the numbers coresponding to a pointed matrix.
|
||||
* cv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of columns, each of the numbers coresponding to a pointed matrix.
|
||||
* d_???_v: dimension size.
|
||||
* r_???_m: numbers of rows.
|
||||
* c_???_m: number of columns.
|
||||
* r_???_m3: number of rows.
|
||||
* c_???_m3: number of columns.
|
||||
* t_???_m3: number of a third dimension.
|
||||
*********/
|
||||
|
||||
|
||||
#ifndef __TZMATLAB__
|
||||
#define __TZMATLAB__
|
||||
#define _ISOC99_SOURCE //Using C99 features for gcc or icc on Linux. Must be placed as the first line above all #include lines.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // For rand(), size_t, exit, malloc, free, qsort, EXIT_FAILURE.
|
||||
#include <memory.h> //For memcpy, etc. Alternative: string.h
|
||||
#include <math.h> //For isfinite.
|
||||
#include <float.h> //For DBL_MIN, etc.
|
||||
#include <time.h> //For time(), etc.
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define USE_DEBUG_FILE //When defined, one must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_DEBUG; //For debugging. Applied to all functions and all .c files that call tzmatlab.h.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_OPT; //For recording the optimization intermediate results.
|
||||
//Applied to minfinder_blockcsminwel() in optpackage.c.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
//#define USE_IMSL_MATH_LIBRARY
|
||||
//#define USE_IMSL_STAT_LIBRARY
|
||||
#define USE_GSL_LIBRARY
|
||||
#define USE_MKL_LIBRARY
|
||||
/*******************************************************************************/
|
||||
|
||||
#define NEWVERSIONofDW_SWITCH //If defined, using DW's new switch program (implemented in 2008),
|
||||
// which may be incompatible with previous programs, such as ...\SargentWZ2\EstProbModel\EstimationJuly07USED
|
||||
//If undef, using the old, working switch program for, say, ...\SargentWZ2\EstProbModel\EstimationJuly07USED.
|
||||
//Files that are affected are: cstz.c, kalman.c, optpackage.c,
|
||||
|
||||
|
||||
#define SWITCHTOIMSLCMATH // define: use IMSL special functions like gammlog; undef: use my own default code if it exists.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define INTELCMATHLIBRARY // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define IMSLCMATHLIBRARY // define: use IMSL C Math library; undef: use others.
|
||||
//#define MATLABCMATHLIBRARY // define: use Matlab C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define SWITCHTOINTELCMATH // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define SWITCHTOTZCMATH // define: use my own C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for optimization routines except that CG?_ and CSMINWEL_ can be chosen together.--------
|
||||
//#define IMSL_OPTIMIZATION // IMSL optimization routines.
|
||||
#define CSMINWEL_OPTIMIZATION //Sims's optimization routine.
|
||||
#define CGI_OPTIMIZATION //Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
//NOT available yet! #define CGII_OPTIMIZATION //NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
|
||||
//-------Only one of the following for random number generating routines.--------
|
||||
#define IMSL_RANDOMNUMBERGENERATOR // IMSL random number generator.
|
||||
//#define CASE2_RANDOMNUMBERGENERATOR //Imported from the C recipe book -- case 2 and my own (Iskander) code for generating a gamma distribution.
|
||||
|
||||
//-------Only one of the following statistical packages.--------
|
||||
#define IMSL_STATISTICSTOOLBOX // IMSL statistical package.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
#if defined(USE_MKL_LIBRARY)
|
||||
#include "mkl.h"
|
||||
#else
|
||||
#include "blas_lapack.h"
|
||||
#undef SWITCHTOINTELCMATH
|
||||
#endif
|
||||
|
||||
#if defined(USE_GSL_LIBRARY)
|
||||
#include "gsl_sf_gamma.h"
|
||||
#include "gsl_cdf.h"
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_MATH_LIBRARY)
|
||||
#include <imsl.h> //IMSL math package.
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef SWITCHTOIMSLCMATH
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef IMSL_RANDOMNUMBERGENERATOR
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_STAT_LIBRARY)
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_STATISTICSTOOLBOX
|
||||
#endif
|
||||
/*******************************************************************************/
|
||||
|
||||
//-------If define: use matlab API interface; otherwise (undef), use C console.
|
||||
#undef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
|
||||
|
||||
//---------------
|
||||
#ifdef MATLABCMATHLIBRARY
|
||||
#include "matlab.h" // For all mlf???? functions.
|
||||
#include "matrix.h" // For mxGetM, mxCreatDoubleMatrix, etc.
|
||||
#endif
|
||||
#ifdef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
#include "mex.h" // For all mex??? calls. Matlab API (application program interface or external interface).
|
||||
#define printf mexPrintf
|
||||
#define malloc mxMalloc
|
||||
#define calloc mxCalloc
|
||||
#define free mxFree
|
||||
#endif
|
||||
|
||||
|
||||
//-------------- Attributes for the real double matrix type TSdmatrix. --------------
|
||||
//-------------- Whenever a matrix is initialized, the default is M_GE, but nothing else. --------------
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
// #define M_UTU 0x0040 //2^6: An unit upper triangular matrix.
|
||||
// #define M_LTU 0x0080 //2^7: An unit lower triangular matrix.
|
||||
//-------------- Attributes for the real double vector type TSdvector or the character vector type TScvector. --------------
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
|
||||
|
||||
//-------------- Other macro definitions. --------------
|
||||
#define BLOCKSIZE_FOR_INTEL_MKL 128 //A machine-dependent value (typically, 16 to 64) required for optimum performance of the blocked algorithm in Intel MKL.
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define BIGREALNUMBER 1.0E+30
|
||||
#define MACHINEZERO DBL_MIN
|
||||
#define EPSILON DBL_EPSILON //1.0E-015. In Standard C, DBL_EPSILON = 2.2204460492503131
|
||||
#define SQRTEPSILON 1.490116119384766E-008 //1.0E-15. In Standard C, DBL_EPSILON = 2.2204460492503131E-016
|
||||
#define SQRTMACHINEZERO 1.490116119384766E-008
|
||||
//This is really not correct, because this number is sqrt(epsion), where DBL_MIN is around 1.0e-300.
|
||||
#define MACHINEINFINITY DBL_MAX
|
||||
#define MACHINE_EXP_INFINITY DBL_MAX_EXP
|
||||
#define EXP_NEARINFINITY 1000
|
||||
//===
|
||||
#define TZ_TRUE 1
|
||||
#define TZ_FALSE 0
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
#define tzMalloc(elt_count, type) (type *)m_alloc((elt_count)*sizeof(type))
|
||||
#define tzCalloc(elt_count, type) (type *)c_alloc((elt_count), sizeof(type))
|
||||
#define tzDestroy(x) {if ((x)) { \
|
||||
free((x)); \
|
||||
(x) = NULL; \
|
||||
}}
|
||||
#define tzFclose(x) {if ((x)) { \
|
||||
fclose((x)); \
|
||||
(x) = (FILE *)NULL; \
|
||||
}}
|
||||
#define mos(i, j, nrows) ((j)*(nrows)+(i)) //i: ith row; j: jth column; nrows: number of rows for the matrix.
|
||||
//Offset(os) for a matrix(m) in column major order and with base 0. See Reek pp.241-242.
|
||||
#define square(x) ((x) * (x)) //Must be careful to avoid using, say, square(tmpd=2) or square(++x).
|
||||
#define _max(a, b) ((a)>(b) ? (a) : (b)) // Macro max or __max is already defined in stdlib.h in MS visual C++, but mex.h may overwrite the max macro so we use _max.
|
||||
#define _min(a, b) ((a)>(b) ? (b) : (a))
|
||||
#define swap(a, b, stemp) {(stemp)=(a); (a)=(b); (b)=(stemp);}
|
||||
//
|
||||
#ifndef isfinite
|
||||
#define isfinite(x) _finite(x) //_finite is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// All these Microsoft functions are not yet C99 compatible.
|
||||
#endif
|
||||
//--- The following does not work.
|
||||
// #ifndef FP_NAN
|
||||
// #define FP_NAN _FPCLASS_SNAN //_FPCLASS_SNAN is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// // All these Microsoft functions are not yet C99 compatible.
|
||||
// #endif
|
||||
#define isdiagonalmatrix(x) (((x)->flag & (M_UT | M_LT)) == (M_UT | M_LT)) //x is the tz type of matrix.
|
||||
//
|
||||
#define DestroyDatesVector_lf(x) DestroyVector_lf(x)
|
||||
|
||||
|
||||
//---------------
|
||||
typedef struct TScvector_tag
|
||||
{
|
||||
char *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TScvector;
|
||||
typedef struct TSvoidvector_tag
|
||||
{
|
||||
void *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSvoidvector;
|
||||
typedef struct {
|
||||
int *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSivector;
|
||||
typedef struct {
|
||||
int *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSimatrix;
|
||||
typedef struct {
|
||||
TSivector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicellvec;
|
||||
typedef struct {
|
||||
TSimatrix **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicell;
|
||||
//=== Real types.
|
||||
typedef struct {
|
||||
double *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
typedef struct {
|
||||
double *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct {
|
||||
TSdmatrix **C; //ncells-by-1 cells (C) and a pointer to matrix in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcell;
|
||||
typedef struct {
|
||||
TSdvector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcellvec;
|
||||
typedef struct {
|
||||
TSdcell **F; //ndims-by-1 fourths (F) and a pointer to cell in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourth;
|
||||
typedef struct {
|
||||
TSdcellvec **F; //ndims-by-1 fourths (F) and a pointer to cellvec in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourthvec;
|
||||
//=== Complex types.
|
||||
typedef struct {
|
||||
TSdvector *real; //Real part.
|
||||
TSdvector *imag; //Imaginary part.
|
||||
} TSdzvector;
|
||||
typedef struct {
|
||||
TSdmatrix *real; //Real part.
|
||||
TSdmatrix *imag; //Imaginary part.
|
||||
} TSdzmatrix;
|
||||
|
||||
|
||||
|
||||
//----------------- Some high-level functions. -----------------
|
||||
int fn_locofyearqm(int q_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
void fn_DisplayError(char *msg_s);
|
||||
void *m_alloc(size_t size);
|
||||
void *c_alloc(size_t elt_count, size_t elt_size);
|
||||
|
||||
/**
|
||||
TSvoidvector *CreateVector_void(int _n);
|
||||
TSvoidvector *DestroyVector_void(TSvoidvector *x_voidv);
|
||||
/**/
|
||||
|
||||
TScvector *CreateVector_c(int _n);
|
||||
TScvector *DestroyVector_c(TScvector *x_s);
|
||||
TSivector *CreateVector_int(int _n);
|
||||
TSivector *DestroyVector_int(TSivector *x_iv);
|
||||
TSimatrix *CreateMatrix_int(int nrows, int ncols);
|
||||
TSimatrix *DestroyMatrix_int(TSimatrix *x_im);
|
||||
TSicellvec *CreateCellvec_int(TSivector *n_iv);
|
||||
TSicellvec *DestroyCellvec_int(TSicellvec *x_icv);
|
||||
TSicell *CreateCell_int(TSivector *row_iv, TSivector *col_iv);
|
||||
TSicell *DestroyCell_int(TSicell *x_ic);
|
||||
|
||||
TSdvector *CreateVector_lf(int _n);
|
||||
TSdvector *DestroyVector_lf(TSdvector *x_iv);
|
||||
TSdmatrix *CreateMatrix_lf(int nrows, int ncols);
|
||||
TSdmatrix *DestroyMatrix_lf(TSdmatrix *x_im);
|
||||
TSdcell *CreateCell_lf(TSivector *row_iv, TSivector *col_iv);
|
||||
TSdcell *DestroyCell_lf(TSdcell *x_dc);
|
||||
TSdcellvec *CreateCellvec_lf(TSivector *n_iv);
|
||||
TSdcellvec *DestroyCellvec_lf(TSdcellvec *x_dcv);
|
||||
TSdfourth *CreateFourth_lf(int ndims, TSivector *row_iv, TSivector *col_iv);
|
||||
TSdfourth *DestroyFourth_lf(TSdfourth *x_d4);
|
||||
TSdfourthvec *CreateFourthvec_lf(int ndims, TSivector *n_iv);
|
||||
TSdfourthvec *DestroyFourthvec_lf(TSdfourthvec *x_d4v);
|
||||
|
||||
TSdzvector *CreateVector_dz(int _n);
|
||||
TSdzvector *DestroyVector_dz(TSdzvector *x_dzv);
|
||||
TSdzmatrix *CreateMatrix_dz(int nrows, int ncols);
|
||||
TSdzmatrix *DestroyMatrix_dz(TSdzmatrix *x_dzm);
|
||||
|
||||
//+
|
||||
TSdmatrix *CreateZeroMatrix_lf(const int nrows, const int ncols);
|
||||
TSdmatrix *CreateIdentityMatrix_lf(const int nrows, const int ncols);
|
||||
//TSdvector *CreateZerosVector_lf(int _n);
|
||||
TSivector *CreateConstantVector_int( const int _n, const int _k);
|
||||
TSimatrix *CreateConstantMatrix_int(const int nrows, const int ncols, const int _n);
|
||||
TSicellvec *CreateConstantCellvec_int(TSivector *n_iv, const int _n);
|
||||
TSicell *CreateConstantCell_int(TSivector *row_iv, TSivector *col_iv, const int _n);
|
||||
TSdvector *CreateConstantVector_lf(const int _n, const double _alpha);
|
||||
TSdmatrix *CreateConstantMatrix_lf(const int nrows, const int ncols, const double _alpha);
|
||||
TSdcellvec *CreateConstantCellvec_lf(TSivector *n_iv, const double _alpha);
|
||||
TSdcell *CreateConstantCell_lf(TSivector *row_iv, TSivector *col_iv, const double _alpha);
|
||||
TSdvector *CreateDatesVector_lf(int nq_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
//+
|
||||
void InitializeConstantVector_lf(TSdvector *x_dv, const double _alpha);
|
||||
void InitializeConstantVector_int(TSivector *x_iv, const int _k);
|
||||
void InitializeConstantMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeDiagonalMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeConstantMatrix_int(TSimatrix *x_dm, const int _alpha);
|
||||
void InitializeConstantCellvec_lf(TSdcellvec *x_dcv, const double _alpha);
|
||||
void InitializeConstantCell_lf(TSdcell *x_dc, const double _alpha);
|
||||
void InitializeConstantFourthvec_lf(TSdfourthvec *x_d4v, const double _alpha);
|
||||
void InitializeConstantFourth_lf(TSdfourth *x_d4, const double _alpha);
|
||||
|
||||
|
||||
void NegateColofMatrix_lf(TSdvector *y_dv, TSdmatrix *x_dm, int _j);
|
||||
void InitializeConstantColofMatrix_lf(TSdmatrix *X_dm, int jx, double _alpha);
|
||||
|
||||
FILE *tzFopen(char *filename, char *mode);
|
||||
#endif
|
||||
/*********
|
||||
* _cv: Pointer to TScvector (character vector).
|
||||
* _iv: Pointer to TSivector (integer vector).
|
||||
* _im: Pointer to TSimatrix (integer matrix).
|
||||
* _dv: Pointer to TSdvector (double vector).
|
||||
* _dm: Pointer to TSdmatrix (double matrix).
|
||||
* _dc: Pointer to TSdcell (double cell -- pointer to pointer to a matrix).
|
||||
* _dcv: Pointer to TSdcellvec (double cell -- pointer to pointer to a vector).
|
||||
* _d4: Pointer to TSdfourth (double fourth dimension -- pointer to pointer to pointer to a matrix).
|
||||
* _dzv: Pointer to TSdzvector (double complex vector).
|
||||
* _dzm: Pointer to TSdzmatrix (double complex matrix).
|
||||
*
|
||||
* _s: structure variable.
|
||||
* _ps: pointer to a structure.
|
||||
* _sv: an array of structures.
|
||||
*
|
||||
* _sdv: structure (NOT pointer to structure) that contains TSdvector.
|
||||
* _sdm: structure (NOT pointer to structure) that contains TSdmatrix.
|
||||
*
|
||||
* ???????? OLD NOTATIONS ??????????
|
||||
* _v: C row or column vector pointer.
|
||||
* _vint: C row or column vector pointer to integer.
|
||||
* _m: C matrix pointer.
|
||||
* _mint: C matrix pointer to integer.
|
||||
* _m3: C 3-D matrix pointer.
|
||||
* _ppm: C pointer to pointer to a matrix.
|
||||
* d_???_ppm: the number of pointers that are pointed to by _ppm.
|
||||
* rv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of rows, each of the numbers coresponding to a pointed matrix.
|
||||
* cv_???_ppm: a vector (with dimension d_???_ppm) pointer of numbers of columns, each of the numbers coresponding to a pointed matrix.
|
||||
* d_???_v: dimension size.
|
||||
* r_???_m: numbers of rows.
|
||||
* c_???_m: number of columns.
|
||||
* r_???_m3: number of rows.
|
||||
* c_???_m3: number of columns.
|
||||
* t_???_m3: number of a third dimension.
|
||||
*********/
|
||||
|
||||
|
||||
#ifndef __TZMATLAB__
|
||||
#define __TZMATLAB__
|
||||
#define _ISOC99_SOURCE //Using C99 features for gcc or icc on Linux. Must be placed as the first line above all #include lines.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // For rand(), size_t, exit, malloc, free, qsort, EXIT_FAILURE.
|
||||
#include <memory.h> //For memcpy, etc. Alternative: string.h
|
||||
#include <math.h> //For isfinite.
|
||||
#include <float.h> //For DBL_MIN, etc.
|
||||
#include <time.h> //For time(), etc.
|
||||
|
||||
#include "modify_for_mex.h"
|
||||
|
||||
#define USE_DEBUG_FILE //When defined, one must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_DEBUG; //For debugging. Applied to all functions and all .c files that call tzmatlab.h.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
extern FILE *FPTR_OPT; //For recording the optimization intermediate results.
|
||||
//Applied to minfinder_blockcsminwel() in optpackage.c.
|
||||
//Initiated to NULL in tzmatlab.c.
|
||||
//Must use tzFopen to give the file name in the main .c file.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
//#define USE_IMSL_MATH_LIBRARY
|
||||
//#define USE_IMSL_STAT_LIBRARY
|
||||
#define USE_GSL_LIBRARY
|
||||
#define USE_MKL_LIBRARY
|
||||
/*******************************************************************************/
|
||||
|
||||
#define NEWVERSIONofDW_SWITCH //If defined, using DW's new switch program (implemented in 2008),
|
||||
// which may be incompatible with previous programs, such as ...\SargentWZ2\EstProbModel\EstimationJuly07USED
|
||||
//If undef, using the old, working switch program for, say, ...\SargentWZ2\EstProbModel\EstimationJuly07USED.
|
||||
//Files that are affected are: cstz.c, kalman.c, optpackage.c,
|
||||
|
||||
|
||||
#define SWITCHTOIMSLCMATH // define: use IMSL special functions like gammlog; undef: use my own default code if it exists.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define INTELCMATHLIBRARY // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define IMSLCMATHLIBRARY // define: use IMSL C Math library; undef: use others.
|
||||
//#define MATLABCMATHLIBRARY // define: use Matlab C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for math library.--------
|
||||
#define SWITCHTOINTELCMATH // define: use Intel MKL LAPACK library; undef: use others.
|
||||
//#define SWITCHTOTZCMATH // define: use my own C math library; undef: use others.
|
||||
|
||||
//-------Only one of the following for optimization routines except that CG?_ and CSMINWEL_ can be chosen together.--------
|
||||
//#define IMSL_OPTIMIZATION // IMSL optimization routines.
|
||||
#define CSMINWEL_OPTIMIZATION //Sims's optimization routine.
|
||||
#define CGI_OPTIMIZATION //Polak-Ribiere conjugate gradient method without using derivative information in performing the line minimization.
|
||||
//NOT available yet! #define CGII_OPTIMIZATION //NOT available yet! Pletcher-Reeves conjugate gradient method using derivative information in performing the line minimization.
|
||||
|
||||
//-------Only one of the following for random number generating routines.--------
|
||||
#define IMSL_RANDOMNUMBERGENERATOR // IMSL random number generator.
|
||||
//#define CASE2_RANDOMNUMBERGENERATOR //Imported from the C recipe book -- case 2 and my own (Iskander) code for generating a gamma distribution.
|
||||
|
||||
//-------Only one of the following statistical packages.--------
|
||||
#define IMSL_STATISTICSTOOLBOX // IMSL statistical package.
|
||||
|
||||
/*******************************************************************************/
|
||||
/* Added by DW 9/1/08 */
|
||||
/*******************************************************************************/
|
||||
#if defined(USE_MKL_LIBRARY)
|
||||
#include "mkl.h"
|
||||
#else
|
||||
#include "blas_lapack.h"
|
||||
#undef SWITCHTOINTELCMATH
|
||||
#endif
|
||||
|
||||
#if defined(USE_GSL_LIBRARY)
|
||||
#include "gsl_sf_gamma.h"
|
||||
#include "gsl_cdf.h"
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_MATH_LIBRARY)
|
||||
#include <imsl.h> //IMSL math package.
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef SWITCHTOIMSLCMATH
|
||||
#undef IMSL_OPTIMIZATION
|
||||
#undef IMSL_RANDOMNUMBERGENERATOR
|
||||
#endif
|
||||
|
||||
#if defined(USE_IMSL_STAT_LIBRARY)
|
||||
#include <imsls.h> //IMSL statistical package.
|
||||
#else
|
||||
#undef IMSL_STATISTICSTOOLBOX
|
||||
#endif
|
||||
/*******************************************************************************/
|
||||
|
||||
//-------If define: use matlab API interface; otherwise (undef), use C console.
|
||||
#undef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
|
||||
|
||||
//---------------
|
||||
#ifdef MATLABCMATHLIBRARY
|
||||
#include "matlab.h" // For all mlf???? functions.
|
||||
#include "matrix.h" // For mxGetM, mxCreatDoubleMatrix, etc.
|
||||
#endif
|
||||
#ifdef WIN_MATLABAPI // define: use matlab API interface; undef: use C dos console.
|
||||
#include "mex.h" // For all mex??? calls. Matlab API (application program interface or external interface).
|
||||
#define printf mexPrintf
|
||||
#define malloc mxMalloc
|
||||
#define calloc mxCalloc
|
||||
#define free mxFree
|
||||
#endif
|
||||
|
||||
|
||||
//-------------- Attributes for the real double matrix type TSdmatrix. --------------
|
||||
//-------------- Whenever a matrix is initialized, the default is M_GE, but nothing else. --------------
|
||||
#define M_UNDEF 0 //0 or NULL: No attribute will be given when memory is allocated but no values are initialized.
|
||||
#define M_GE 0x0001 //1: A general matrix.
|
||||
#define M_SU 0x0002 //2: A symmetric (must be square) matrix but only the upper triangular part is referenced.
|
||||
#define M_SL 0x0004 //4: A symmetric (must be square) matrix but only the lower triangular part is referenced.
|
||||
#define M_UT 0x0008 //8: A upper triangular (trapezoidal if nrows < ncols) matrix but only the upper triangular part is referenced.
|
||||
#define M_LT 0x0010 //16: A lower triangular (trapezoidal if nrows > ncols) matrix but only the lower triangular part is referenced.
|
||||
#define M_CN 0x0020 //32: A constant (CN) matrix (All elements are the same or no (N) change from one to another).
|
||||
// #define M_UTU 0x0040 //2^6: An unit upper triangular matrix.
|
||||
// #define M_LTU 0x0080 //2^7: An unit lower triangular matrix.
|
||||
//-------------- Attributes for the real double vector type TSdvector or the character vector type TScvector. --------------
|
||||
#define V_UNDEF 0 //Zero or NULL: No values have been assigned to the double vector.
|
||||
#define V_DEF 1 //True: Values have been assigned to the double vector.
|
||||
|
||||
|
||||
//-------------- Other macro definitions. --------------
|
||||
#define BLOCKSIZE_FOR_INTEL_MKL 128 //A machine-dependent value (typically, 16 to 64) required for optimum performance of the blocked algorithm in Intel MKL.
|
||||
#define NEARINFINITY 1.0E+300
|
||||
#define BIGREALNUMBER 1.0E+30
|
||||
#define MACHINEZERO DBL_MIN
|
||||
#define EPSILON DBL_EPSILON //1.0E-015. In Standard C, DBL_EPSILON = 2.2204460492503131
|
||||
#define SQRTEPSILON 1.490116119384766E-008 //1.0E-15. In Standard C, DBL_EPSILON = 2.2204460492503131E-016
|
||||
#define SQRTMACHINEZERO 1.490116119384766E-008
|
||||
//This is really not correct, because this number is sqrt(epsion), where DBL_MIN is around 1.0e-300.
|
||||
#define MACHINEINFINITY DBL_MAX
|
||||
#define MACHINE_EXP_INFINITY DBL_MAX_EXP
|
||||
#define EXP_NEARINFINITY 1000
|
||||
//===
|
||||
#define TZ_TRUE 1
|
||||
#define TZ_FALSE 0
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
#define tzMalloc(elt_count, type) (type *)m_alloc((elt_count)*sizeof(type))
|
||||
#define tzCalloc(elt_count, type) (type *)c_alloc((elt_count), sizeof(type))
|
||||
#define tzDestroy(x) {if ((x)) { \
|
||||
free((x)); \
|
||||
(x) = NULL; \
|
||||
}}
|
||||
#define tzFclose(x) {if ((x)) { \
|
||||
fclose((x)); \
|
||||
(x) = (FILE *)NULL; \
|
||||
}}
|
||||
#define mos(i, j, nrows) ((j)*(nrows)+(i)) //i: ith row; j: jth column; nrows: number of rows for the matrix.
|
||||
//Offset(os) for a matrix(m) in column major order and with base 0. See Reek pp.241-242.
|
||||
#define square(x) ((x) * (x)) //Must be careful to avoid using, say, square(tmpd=2) or square(++x).
|
||||
#define _max(a, b) ((a)>(b) ? (a) : (b)) // Macro max or __max is already defined in stdlib.h in MS visual C++, but mex.h may overwrite the max macro so we use _max.
|
||||
#define _min(a, b) ((a)>(b) ? (b) : (a))
|
||||
#define swap(a, b, stemp) {(stemp)=(a); (a)=(b); (b)=(stemp);}
|
||||
//
|
||||
#ifndef isfinite
|
||||
#define isfinite(x) _finite(x) //_finite is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// All these Microsoft functions are not yet C99 compatible.
|
||||
#endif
|
||||
//--- The following does not work.
|
||||
// #ifndef FP_NAN
|
||||
// #define FP_NAN _FPCLASS_SNAN //_FPCLASS_SNAN is for Microsoft C++ compiler only (in float.h, which strangely is not ANSI compible),
|
||||
// // All these Microsoft functions are not yet C99 compatible.
|
||||
// #endif
|
||||
#define isdiagonalmatrix(x) (((x)->flag & (M_UT | M_LT)) == (M_UT | M_LT)) //x is the tz type of matrix.
|
||||
//
|
||||
#define DestroyDatesVector_lf(x) DestroyVector_lf(x)
|
||||
|
||||
|
||||
//---------------
|
||||
typedef struct TScvector_tag
|
||||
{
|
||||
char *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TScvector;
|
||||
typedef struct TSvoidvector_tag
|
||||
{
|
||||
void *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSvoidvector;
|
||||
typedef struct {
|
||||
int *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSivector;
|
||||
typedef struct {
|
||||
int *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSimatrix;
|
||||
typedef struct {
|
||||
TSivector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicellvec;
|
||||
typedef struct {
|
||||
TSimatrix **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSicell;
|
||||
//=== Real types.
|
||||
typedef struct {
|
||||
double *v; //v: vector.
|
||||
int n;
|
||||
int flag; //flag: no legal values are assigned if 0 and legal values are assigned if 1.
|
||||
} TSdvector;
|
||||
typedef struct {
|
||||
double *M; //M: matrix.
|
||||
int nrows, ncols;
|
||||
int flag; //flag: Refers to M_GE, M_SU, M_SL, M_UT, and M_LT in tzmatlab.h.
|
||||
} TSdmatrix;
|
||||
typedef struct {
|
||||
TSdmatrix **C; //ncells-by-1 cells (C) and a pointer to matrix in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcell;
|
||||
typedef struct {
|
||||
TSdvector **C; //ncells-by-1 cells (C) and a ponter to vector in each cell.
|
||||
int ncells; //Number of pointers (cells) to pointer.
|
||||
} TSdcellvec;
|
||||
typedef struct {
|
||||
TSdcell **F; //ndims-by-1 fourths (F) and a pointer to cell in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourth;
|
||||
typedef struct {
|
||||
TSdcellvec **F; //ndims-by-1 fourths (F) and a pointer to cellvec in each fourth.
|
||||
int ndims; //Number of pointers (fourth dimensions) to pointer.
|
||||
} TSdfourthvec;
|
||||
//=== Complex types.
|
||||
typedef struct {
|
||||
TSdvector *real; //Real part.
|
||||
TSdvector *imag; //Imaginary part.
|
||||
} TSdzvector;
|
||||
typedef struct {
|
||||
TSdmatrix *real; //Real part.
|
||||
TSdmatrix *imag; //Imaginary part.
|
||||
} TSdzmatrix;
|
||||
|
||||
|
||||
|
||||
//----------------- Some high-level functions. -----------------
|
||||
int fn_locofyearqm(int q_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
|
||||
|
||||
|
||||
|
||||
//---------------
|
||||
void fn_DisplayError(char *msg_s);
|
||||
void *m_alloc(size_t size);
|
||||
void *c_alloc(size_t elt_count, size_t elt_size);
|
||||
|
||||
/**
|
||||
TSvoidvector *CreateVector_void(int _n);
|
||||
TSvoidvector *DestroyVector_void(TSvoidvector *x_voidv);
|
||||
/**/
|
||||
|
||||
TScvector *CreateVector_c(int _n);
|
||||
TScvector *DestroyVector_c(TScvector *x_s);
|
||||
TSivector *CreateVector_int(int _n);
|
||||
TSivector *DestroyVector_int(TSivector *x_iv);
|
||||
TSimatrix *CreateMatrix_int(int nrows, int ncols);
|
||||
TSimatrix *DestroyMatrix_int(TSimatrix *x_im);
|
||||
TSicellvec *CreateCellvec_int(TSivector *n_iv);
|
||||
TSicellvec *DestroyCellvec_int(TSicellvec *x_icv);
|
||||
TSicell *CreateCell_int(TSivector *row_iv, TSivector *col_iv);
|
||||
TSicell *DestroyCell_int(TSicell *x_ic);
|
||||
|
||||
TSdvector *CreateVector_lf(int _n);
|
||||
TSdvector *DestroyVector_lf(TSdvector *x_iv);
|
||||
TSdmatrix *CreateMatrix_lf(int nrows, int ncols);
|
||||
TSdmatrix *DestroyMatrix_lf(TSdmatrix *x_im);
|
||||
TSdcell *CreateCell_lf(TSivector *row_iv, TSivector *col_iv);
|
||||
TSdcell *DestroyCell_lf(TSdcell *x_dc);
|
||||
TSdcellvec *CreateCellvec_lf(TSivector *n_iv);
|
||||
TSdcellvec *DestroyCellvec_lf(TSdcellvec *x_dcv);
|
||||
TSdfourth *CreateFourth_lf(int ndims, TSivector *row_iv, TSivector *col_iv);
|
||||
TSdfourth *DestroyFourth_lf(TSdfourth *x_d4);
|
||||
TSdfourthvec *CreateFourthvec_lf(int ndims, TSivector *n_iv);
|
||||
TSdfourthvec *DestroyFourthvec_lf(TSdfourthvec *x_d4v);
|
||||
|
||||
TSdzvector *CreateVector_dz(int _n);
|
||||
TSdzvector *DestroyVector_dz(TSdzvector *x_dzv);
|
||||
TSdzmatrix *CreateMatrix_dz(int nrows, int ncols);
|
||||
TSdzmatrix *DestroyMatrix_dz(TSdzmatrix *x_dzm);
|
||||
|
||||
//+
|
||||
TSdmatrix *CreateZeroMatrix_lf(const int nrows, const int ncols);
|
||||
TSdmatrix *CreateIdentityMatrix_lf(const int nrows, const int ncols);
|
||||
//TSdvector *CreateZerosVector_lf(int _n);
|
||||
TSivector *CreateConstantVector_int( const int _n, const int _k);
|
||||
TSimatrix *CreateConstantMatrix_int(const int nrows, const int ncols, const int _n);
|
||||
TSicellvec *CreateConstantCellvec_int(TSivector *n_iv, const int _n);
|
||||
TSicell *CreateConstantCell_int(TSivector *row_iv, TSivector *col_iv, const int _n);
|
||||
TSdvector *CreateConstantVector_lf(const int _n, const double _alpha);
|
||||
TSdmatrix *CreateConstantMatrix_lf(const int nrows, const int ncols, const double _alpha);
|
||||
TSdcellvec *CreateConstantCellvec_lf(TSivector *n_iv, const double _alpha);
|
||||
TSdcell *CreateConstantCell_lf(TSivector *row_iv, TSivector *col_iv, const double _alpha);
|
||||
TSdvector *CreateDatesVector_lf(int nq_m, int yrstart, int qmstart, int yrend, int qmend);
|
||||
//+
|
||||
void InitializeConstantVector_lf(TSdvector *x_dv, const double _alpha);
|
||||
void InitializeConstantVector_int(TSivector *x_iv, const int _k);
|
||||
void InitializeConstantMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeDiagonalMatrix_lf(TSdmatrix *x_dm, const double _alpha);
|
||||
void InitializeConstantMatrix_int(TSimatrix *x_dm, const int _alpha);
|
||||
void InitializeConstantCellvec_lf(TSdcellvec *x_dcv, const double _alpha);
|
||||
void InitializeConstantCell_lf(TSdcell *x_dc, const double _alpha);
|
||||
void InitializeConstantFourthvec_lf(TSdfourthvec *x_d4v, const double _alpha);
|
||||
void InitializeConstantFourth_lf(TSdfourth *x_d4, const double _alpha);
|
||||
|
||||
|
||||
void NegateColofMatrix_lf(TSdvector *y_dv, TSdmatrix *x_dm, int _j);
|
||||
void InitializeConstantColofMatrix_lf(TSdmatrix *X_dm, int jx, double _alpha);
|
||||
|
||||
FILE *tzFopen(char *filename, char *mode);
|
||||
#endif
|
||||
|
|
Loading…
Reference in New Issue