# Ox Class Reference

## Chapter contents:

Database class
  Database function members
  Database data members

Modelbase class
  Modelbase function members

PcFiml class
  PcFiml function members

PcFimlDgp class
  PcFimlDgp function members

PcNaiveDgp class
  PcNaiveDgp function members

RanMC class
  RanMC function members

Sample class
  Sample function members
  Sample data members

Simulation class
  Simulation function members

## Database class

The `Database` class stores a matrix of data, together with the sample period (the class derives from the Sample class), and the names of the variables. Functions to create a database from disk files (ASCII, GiveWin and spreadsheet formats) are provided.

In addition, the `Database` class has built-in support to select variables (for modelling) from the database. Variables are selected by name, optionally with a lag length, and allocated to a group (e.g. to distinguish between dependent and independent variables). A sample period for the selection can be set. This selection can then be extracted from the database. The selected sample is always adjusted so as not to include missing values (PcGive files use -9999.99 for missing values, this is translated to `.NaN` when the file is loaded). To use the class, link in the database code and include `database.h`. This is most easily done by adding an `#import <database>` statement at the top of your source code.

### Database overview

Base class | Sample class
Construction/Information
Database | Constructor
Create | Create a database (not needed when using Load...)
Info | Print summary information
SetDbName | Sets the database name
GetDbName | Gets the database name
Data input/output
Load | Load a data file
LoadDht | Load a GAUSS .dht/.dat file
LoadDta | Load a Stata .dta file
LoadFmtVar | Load a formatted .dat file
LoadIn7 | Load a .in7/.bn7 file
LoadObs | Load a human-readable file which is ordered by observation
LoadVar | Load a human-readable file which is ordered by variable
LoadWks | Load a Lotus spreadsheet file
LoadXls | Load an Excel spreadsheet file
SaveFmtVar | Save the database as a formatted .dat file
SaveIn7 | Save the database as a .in7/.bn7 file
SaveObs | Save the database as a human-readable file which is ordered by observation
SaveVar | Save the database as a human-readable file which is ordered by variable
SaveWks | Save the database as a Lotus spreadsheet file
SaveXls | Save the database as an Excel spreadsheet file
Adding/removing variables/observations
Append | Append variables
Deterministic | Create deterministic variables
Grow | Add observations to the database sample
Remove | Remove the named variable from the database
RemoveObsIf | Remove observations from the database
Rename | Rename a variable
Renew | Renew data on variables
RenewBlock | Renew data without checking
Extraction
GetAll | Return the whole data matrix
GetAllNames | return all variable names
GetSample | Returns text with database sample
GetVar | Get the data on the named variable(s)
GetVarByIndex | Get the data on variable(s) by the variable index
GetVarIndex | Get the database indices of the named variables
GetVarNameByIndex | Get variable name(s) by database index
Variable selection
DeSelect | Remove a selection
DeSelectByIndex | Remove a selected variable by its index
DeSelectByName | Remove a selected variable by its name
FindSelection | Finde seletion index of a variable
ForceSelSample | Set the selection sample without checking
GetGroup | Get a group of selected variables
GetGroupLag | Get a group of selected variables wich have the specified lag
GetGroupLagNames | Get the names of a group of selected variables wich have the specified lag
GetGroupNames | Get the names of a group of selected variables
GetMaxGroupLag | Get the highest lag in a selection group
GetMaxSelLag | Get the highest lag in the selection
GetSelEnd | Get the observation index of the selection end
GetSelInfo | Get the whole selection info
GetSelSample | returns a string with the selected sample text
GetSelStart | Get the observation index of the selection start
Select | Select named variables into a selection group
SelectByIndex | Select variables into a selection group by index
SetSelInfo | Set the whole selection info
SetSelSample | Set the selection sample

### Database function members

    Database::Append(const mNew, const asNew);
    Database::Append(const mNew, const asNew, const iT1);

`mNew`
  in: T `x` k matrix with the new variables
`asNew`
  in: array with k variable names of the new variables
`iT1`
  in: starting observation index in database (0 if missing)

Appends the k new variables to the database, storing the observations and variable names. The first observation has database index `iT1` (omit the third argument, use 0 if the variables start at the same sample point as the database), the last is the end of the database sample, or the end of `mNew`, whichever comes first.

    Database::Create(const iFreq, const iYear1, const iPeriod1,
        const iYear2, const iPeriod2);

`iFreq`
  in: int, frequency
`iYear1`
  in: int, start year
`iPeriod1`
  in: int, start period
`iYear2`
  in: int, end year
`iPeriod2`
  in: int, end period

Creates a database. Use this when the database is not to be loaded from disk. The `Append` member function allows adding data to the database.

    Database::Database();

Constructor.

    Database::DeSelect();
    Database::DeSelectByIndex(const iSel);
    Database::DeSelectByName(const sVar, const iGroup, const iLag);

`iSel`
  in: int or matrix: selection indices of variables to delete
`sVar`
  in: string: database name of variable to delete
`iGroup`
  in: int: group identifier of variable to delete
`iLag`
  in: int: lag length of variable to delete

`DeSelect` clears the current selection completely.

The other two functions delete specific variable(s) from the current selection. The selection sample is not changed.

    Database::Deterministic(const iCseason);

Appends constant, trend and seasonals to the database. These variables are named `Constant`, `Trend` and `Season`. `Season_1`, ..., `Season_`x, where x is the frequency.

`Season` has a 1 in quarter 1 (for quarterly data), and zeros elsewhere, `Season_1` has a 1 in quarter 2, etc.

If `iCseason` is 0, normal seasonals are created. If `iCseason` is 1, the seasonals are centred (with quarterly observations, for quarter 1: 0.75, -0.25, -0.25, -0.25, ...), in which case the names are `CSeason`, `CSeason_1`, ..., `CSeason_`x. No seasonals are created if `iCseason` is < 0.

    Database::FindSelection(const sVar, const iLag);

`sVar`
  in: string, variable name
`iLag`
  in: int, lag length

Returns the selection index of the specified variable with the specified lag, or -1 if it is not selected.

    Database::ForceSelSample(const iYear1, const iPeriod1,
        const iYear2, const iPeriod2);

`iYear1`
  in: start year of selection, use -1 for earliest year and period
`iPeriod1`
  in: start period of selection
`iYear2`
  in: end year of selection, use -1 for latest year and period
`iPeriod2`
  in: end period of selection

Returns the number of observations in the sample.

Sets a selection a sample for the variables previously selected with the `Select` function. This function does not check for missing values. Use `SetSelSample()` to set a sample with checking for missing values.

    Database::GetAll();
    Database::GetAllNames();

`GetAll()` returns the whole database matrix. `GetAllNames()` returns an array with all the variable names.

    Database::GetGroup(const iGroup);
    Database::GetGroupLag(const iGroup, const iLag1, const iLag2);

`iGroup`
  in: int, group number
`iLag1`
  in: int, first lag
`iLag2`
  in: int, last lag

`GetGroup` returns a T `x` n matrix with all selected variables of group `iGroup`.

`GetGroupLag` returns only those with the specified lag length. If no database sample has been selected yet, the return value is a 0.

    Database::GetGroupLagNames(const iGroup, const iLag1,
        const iLag2, aasNames);
    Database::GetGroupNames(const iGroup, const aasNames);

`iGroup`
  in: int, group number
`iLag1`
  in: int, first lag
`iLag2`
  in: int, last lag
`aasNames`
  in: array
  out: will hold an array of strings with the names of the variables with specified group and lag

`GetGroupLagNames` gets the names of all selected variables of group `iGroup` which have a lag in `iLag1` ... `iLag2`. `GetGroupNames` gets the names of all variables in the group. The selection sample period must have been set.

    Database::GetMaxGroupLag(iGroup);
    Database::GetMaxSelLag();

`GetMaxSelLag` returns the highest lag in all selected variables. `GetMaxGroupLag` returns the highest lag in selected variables of the specified group `iGroup`.

    Database::GetSample();

`GetSample` returns a string with the database sample, e.g. `"1980 (1) - 1990 (2)"`.

    Database::GetSelStart();
    Database::GetSelEnd();

`GetSelStart` returns the database index of the first observation of the selected sample. `GetSelEnd` returns the database index of the last observation of the selected sample.

    Database::GetSelInfo();

Returns a 1 `x` 5 array with the selection information as follows (c is the number of selected variables):

  0: 1 `x` c matrix with database indices of selected variables
  1: 1 `x` c matrix with group index of selected variables
  2: 1 `x` c matrix with lag lengths of selected variables
  3: integer, first selection observation
  4: integer, last selection observation.

    Database::GetSelSample();

`GetSelSample` returns a string with the selected sample text, e.g. `"1980 (1) - 1984 (2)"`.

    Database::GetVar(const sName);
    Database::GetVarByIndex(const iVar);
    Database::GetVarNameByIndex(const iVar);

`sName`
  in: string or array of strings with variable names
`iVar`
  in: int or matrix of database indices of variables

Returns a matrix with the specified variable(s), or the empty matrix if the variable cannot be found.

    Database::GetVarIndex(const asName);

`asName`
  in: string or array of strings with variable names

Returns the database indices of the specified variable(s), or the empty matrix if none are found.

    Database::GetVarNameByIndex(const iVar);

`iVar`
  in: int or matrix of database indices of variables

Returns an array with the names of the specified variable(s). If `iVar` is a scalar, s single string is returned.

    Database::Grow(const cTadd);

`cTadd`
  in: int, number of observations to grow database sample by

    Database::Info();

Prints information on the contents of the database.

    Database::Load(const sFilename);
    Database::LoadDht(const sFilename, const iYear1,
        const iPeriod1, const iFreq);
    Database::LoadDta(const sFilename, const iYear1,
        const iPeriod1, const iFreq);
    Database::LoadFmtVar(const sFilename);
    Database::LoadIn7(const sFilename);
    Database::LoadObs(const sFilename, const cVar,const cObs,
        const iYear1, const iPeriod1, const iFreq,
        const fOffendMis);
    Database::LoadVar(const sFilename, const cVar,const cObs,
        const iYear1, const iPeriod1, const iFreq,
        const fOffendMis);
    Database::LoadWks(const sFilename);
    Database::LoadXls(const sFilename);

`sFilename`
  in: string, filename
`cVar`
  in: int, number of variables
`cObs`
  in: int, number of observations
`iYear1`
  in: int, start year
`iPeriod1`
  in: int, start period
`iFreq`
  in: int, frequency
`fOffendMis`
  in: int, TRUE:offending text treated as missing value FALSE: offending text skipped

`Load` creates the database and loads the specified data file from disk. The file type is derived from the extension.

`LoadDht` creates the database and loads the specified Gauss data file from disk.

`LoadDta` creates the database and loads the specified Stata (version 4--6) data file from disk.

`LoadIn7` creates the database and loads the specified GiveWin file (which is the same as a PcGive 7 data file) from disk.

`LoadFmtVar` creates the database and loads the ASCII file with formatting information from disk. In GiveWin this is called `Data with load info'. Such a file is human-readable, with the data ordered by variable, and each variable preceded by a line of the type:

`>` name year1 period1 year2 period2 frequency

`LoadObs` and `LoadVar` create the database and load the specified human-readable data file from disk. The data is ordered by observation (`LoadObs`), or by variable. Since there is no information on the sample or the variable names in these files, the sample must be provided as function arguments. The variable names are set to Var1, Var2, etc., use `Rename` to rename the variables.

`LoadWks` and `LoadXLS` create the database and load the specified spreadsheet file from disk. A `.wks` or `.wk1` file is a Lotus file, an `.xls` file is an Excel worksheet.

`Database` class can read the following types of Excel file:

- Excel 2.1, 3.0, 4.0 worksheets;
- Excel 5.0, 95, 97 workbooks.

When saving an Excel file, it is written in Excel 2.1 format. ,

    Database::Remove(const sName);
    Database::RemoveObsIf(const vRemove)

`sName`
  in: string, variable name
`vRemove`
  in: matrix with T elements: 0 for observations to keep, 0 otherwise

Removes the named variable or specified observations from the database.

    Database::Rename(const sNewName, const sOldName);

`sNewName`
  in: new name
`sOldName`
  in: name of database variable to rename

Renames a database variable.

    Database::Renew(const mNew, const asName);
    Database::Renew(const mNew, const asName, const iT1);

`mNew`
  in: T `x` k matrix
`asName`
  in: array with k variable names (or string if k=1)
`iT1`
  in: first observation (0 if argument is missing)

Renews the observations on the named variable. The first new observation has database index `iT1`, the last is the end of the database sample, or the end of `mNew`, whichever comes first. If a non-existent variable is renewed, the variable is created first using `Append`. The database sample can be changed by `Grow`, not by `Renew` or `Append`.

    Database::RenewBlock(const mNew, const iVarIndex);

`mNew`
  in: T `x` k matrix
`iVarIndex`
  in: database index of first variable to renew

Renews the observations on the k variables starting from the first, without any checking for existence.

    Database::SaveIn7(const sFilename);
    Database::SaveFmtVar(const sFilename);
    Database::SaveObs(const sFilename);
    Database::SaveVar(const sFilename);
    Database::SaveWks(const sFilename);
    Database::SaveXls(const sFilename);

`sFilename`
  in: string, filename

`SaveIn7` saves the database as a GiveWin file.

`SaveFmtVar` saves the database as a formatted ASCII file. Also see under `LoadFmtVar`.

`SaveObs` and `SaveVar` save the database as a human-readable data file, ordered by observation, or by variable. Also see under `LoadObs`, `LoadVar`.

`SaveWks` and `SaveXls` save the database as a Lotus or Excel spreadsheet file. Also see under `LoadWks`, `LoadXls`.

    Database::Select(const iGroup, const aSel);
    Database::SelectByIndex(const iGroup, const iVar,
        const iLag0, const iLag1);

`iGroup`
  in: int, group number
`aSel`
  in: 3k array, specifying name, start lag, end lag
`iVar`
  in: int: database index of variable to select
  in: matrix: database index of k variables to select
`iLag0`
  in: int: initial lag length of variables to select
  in: matrix: k initial lag lengths of variables to select
`iLag1`
  in: int: final lag length of variables to select
  in: matrix: k final lag lengths of variables to select

Selects variables by name and with specified lags, and assigns the `iGroup` number to the selection. The `aSel` argument is an array consisting of sequences of three values: name, start lag, end lag. After a sample period is set, the selection can be extracted from the database.

    Database::SetDbName(const sName);

Sets the database name to sName. Note that a call to any of the `Load`... functions sets the database name to the file argument.

    Database::SetSelInfo(const asInfo);

`asInfo`
  in: 1 `x` 5 array with selection info

Sets the selection based on the specified input array. No checking is done on the input values. The selection information should be organized as follows (c is the number of selected variables):

  0: 1 `x` c matrix with database indices of selected variables
  1: 1 `x` c matrix with group index of selected variables
  2: 1 `x` c matrix with lag lengths of selected variables
  3: integer, first selection observation
  4: integer, last selection observation.

The last two arguments may be omitted, in which case a call to `SetSelSample` may be required.

    Database::SetSelSample(const iYear1, const iPeriod1,
        const iYear2, const iPeriod2);

`iYear1`
  in: int, start year of selection, use -1 for earliest year and period
`iPeriod1`
  in: int, start period of selection
`iYear2`
  in: int, end year of selection, use -1 for latest year and period
`iPeriod2`
  in: int, end period of selection

Selects a sample for the variables previously selected with the `Select` function. The actually selected sample will be the largest starting from the specified starting date (but not exceeding the specified end date) without any missing values. Use `DeSelect` to deselect the current sample and variables.

### Database data members

`m_mData`
  data matrix (T `x` k)
`m_asNames`
  variable names (array with k strings)
`m_mVarsel`
  variable selection (1 `x` s matrix with selection) the selection consists of indices in `m_mData` and `m_asNames`
`m_mLagsel`
  lag length of each entry in `m_mVarsel` (1 `x` s matrix)
`m_mSelgroup`
  group number of each entry in `m_mVarsel` (1 `x` s matrix)
`m_iT1sel`
  row index in `m_mData` of first selected observation (int)
`m_iT2sel`
  row index in `m_mData` of last selected observation (int)
`m_dMisVal`
  missing value (double)
Sample class data members

## Modelbase class

The `Modelbase` class derives from the `Database` class to implement model estimation features. `Modelbase` is not intended to be used directly, but as a base for a more specialized class. A range of virtual member functions allows for customization of the class. `Modelbase` facilitates interactive use with GiveWin through the OxPack program. Dialogs and a test menu are easily created by overriding just a few virtual functions. Additional information is provided separately. In most cases, model estimation involves the following steps (key virtual functions are given in parentheses):

- Call constructor (`Modelbase`), specify package name and version (`GetPackage`, `GetVersion`).
- Initialize data: extract estimation data from underlying database (`InitData`).
- Initialize parameters (`InitPar`): specify the number of parameters; set fixed parameters (if any); determine starting values (if necessary).
- Estimate model (`Estimate` or `DoEstimation`).
- Produce model output and evaluation (`GetParNames`, `Covar`, `Output`, etc.).

`Modelbase` has a few essential properties to track this procedure:

Model status | `GetModelStatus`, `SetModelStatus`
Maximization method | `GetMethod`, `SetMethod`
Estimation result | `GetResult`, `SetResult`
Parameters | `GetPar`, `SetPar`, `GetParCount`, `SetParCount`
Fixed/Free parameters | `GetFreeParCount`, `GetFreePar`, `SetFreePar`,
| `FixPar`, `FreePar`
Covariance | `Covar`

The `samples/database/mbclass.ox` example shows a minimal `Modelbase` implementation:

    #include <oxstd.h>
    #import  <modelbase>

    class Ols : Modelbase
    {
        decl m_mRes;
        decl m_dSigmaSqr;

        Ols();
        GetPackageName();
        GetPackageVersion();
        DoEstimation(vP);
    };

    Ols::Ols()
    {
        Modelbase();
    }
    Ols::GetPackageName()
    {
        return "Ols";
    }
    Ols::GetPackageVersion()
    {
        return "1.0";
    }
    Ols::DoEstimation(vP)
    {
        decl cp = columns(m_mX);
        SetParCount(cp);

        olsc(m_mY, m_mX, &vP, &m_mCovar);
        m_mRes = m_mY - m_mX * vP;
        m_dSigmaSqr = m_mRes'm_mRes / (rows(m_mY) - cp);
        m_mCovar *= m_dSigmaSqr;

        SetResult(MAX_CONV);

        return vP;
    }

    main()
    {
        decl ols = new Ols();

        ols.Load("data/data.in7");
        ols.Deterministic(FALSE);

        ols.Select(Y_VAR, {"CONS", 0, 2});
        ols.Select(X_VAR, {"Constant", 0, 0, "INC" , 0, 2});

        ols.Estimate();
    }

The program produces:

    Ols package version 1.0, object created on 19-03-1999

    ---- Ols ----
    The estimation sample is 1953 (3) - 1992 (3)
    The dependent variable is: CONS
                      Coefficient  Std.Error  t-value  t-prob
    CONS_1                1.31039    0.07564     17.3   0.000
    CONS_2              -0.352108    0.07915     4.45   0.000
    Constant             -2.17250      11.19    0.194   0.846
    INC                  0.508481    0.03606     14.1   0.000
    INC_1               -0.577251    0.05816     9.92   0.000
    INC_2                0.112122    0.05325     2.11   0.037

    log-likelihood           .NaN
    no. of observations       157  no. of parameters         6
    AIC                      .NaN  AIC/T                  .NaN
    mean(CONS)             875.78  var(CONS)           182.397

At first sight it may be somewhat surprising how much this program achives with so little coding. But, with an understanding of virtual functions, the documentation below, and the actual source code of `Modelbase` (in ox\src), it should be possible to implement a `Modelbase` derived package. Other examples of the use of `Modelbase` are the Arfima and DPD packages.

### Modelbase overview

Functions which are used in a minimal implementation are marked as follows:

- * virtual function to override,
- ** need to be called as part of the estimation procedure.

Base class | Database class
General
`Modelbase` | constructor
`ClearEstimation` | removes results fom previous estimation
`ClearModel` | sets model status to `MS_NONE`
`GetMethod` | get the estimation method
`GetModelStatus` | get the model status (`MS_`....)
`GetPackageName`* | returns name of the package
`GetPackageVersion`* | returns version of the package
`GetResult` | get the estimation result
`IsUnivariate` | returns `TRUE` if only one `Y_VAR` allowed
`SetMethod` | set the estimation method
`SetModelStatus`** | set the model status (`MS_`....)
`SetPrint` | switch printing on or off
`SetResult`** | set the estimation result
parameter related
`FixPar` | fixes parameters
`FreePar` | frees parameters
`GetFreePar` | get the vector of free parameters, p `x`1
`GetFreeParCount` | get number of free parameters p
`GetFreeParNames` | get the names of the free parameters, array of length p
`GetPar` | get the vector of all parameters, q `x`1
`GetParCount` | get number of parameters q (including fixed)
`GetParNames`* | get the names of all parameters, array of length q
`GetParStatus` | returns full parameter info
`MapParToFree` | return the free parameters from the argument
`ResetFixedPar` | reset the values of the fixed parameters
`SetFreePar` | set the free parameters
`SetPar`** | set the full parameter vector
`SetParCount`** | set the number of parameters q (including fixed)
move up in model status
`DoEstimation` | low level estimate
`Estimate` | high level estimate
`InitData` | get the data: Y,X
`InitPar` | initializes the parameter values
`SetStartPar` | set the starting values
covariance evaluation
`Covar`* | sets `m_mCovar`
get model results
`GetCovar` | returns p `x` p covariance matrix
`GetCovarRobust` | returns `<>` or p `x` p robust covariance matrix
`GetLogLik` | return the log-likelihood, `m_dLogLik`
`GetResVar` | returns residual variance, n `x` n
`GetResiduals` | returns residual matrix, T `x` n
`GetStdErr` | returns the std.errors (0 for fixed) q `x`1
`GetStdErrRobust` | returns `<>` or robust standard errors
`GetcDfLoss` | returns degrees of freedom lost (for tailt, AIC)
`GetcT` | returns actual no of variables to use in output, `m_cT`
post estimation
`Output` | prints output
`OutputHeader` | prints output header, returns `TRUE` to print rest
`OutputPar` | prints parameter estimates
`OutputLogLik` | prints log-likelihood, AIC, etc.
`OutputMax` | prints maximization result and starting values
`PrintTestVal` | prints a test statistic
`TestRestrictions` | tests restrictions on the parameters
OxPack related, separately documented
`GetLongRunInfo` | returns 0 or info on long-run
`GetLongRunNames` | returns 0 or names of long-run parameters
`ReceiveData` | receive the data for estimation
`ReceiveDialog` | receive output from a dialog
`ReceiveModel` | receive the model specification
`SendDialog` | send a dialog
`SendFunctions` | send specification of special functions
`SendMenu` | send a menu list
`SendMethods` | send the estimation methods
`SendResults` | send an output variable
`SendSpecials` | send the names of special variables
`SendVarStatus` | send the types of variables

### Modelbase function members

    virtual Modelbase::ClearEstimation()
    virtual Modelbase::ClearModel();

`ClearEstimation()` clears the model estimation settings. `ClearModel()` sets the model status to `MS_NONE`, and calls `ClearEstimation()`.

    virtual Modelbase::Covar();

In some models, the evaluation of the variance-covariance matrix of the estimated parameters is costly, therefore, this matrix is only computed on demand: when the covariance matrix does not yet exist, `Covar()` is called to compute it. By default, the `m_mCovar` member variable of `Modelbase` is -1 when estimation commences (through a call to `ClearEstimation()`). `Covar()` should set `m_mCovar` to the variance-covariance matrix (but `Estimate()` or `DoEstimation()` may also do this, as in the example above). `Covar()` can optionally set `m_mCovarRobust` as well. If the covariance matrix does not exist, `Covar()` is automatically called when using `GetCovar()`, `GetCovarRobust()`, `GetStdErr()`, or `GetStdErrRobust()`. This procedure ensures that the covariance is only computed once when required, and not at all when not required (in some Monte Carlo experiments, for example).

    virtual Modelbase::DoEstimation(vPar);
    virtual Modelbase::Estimate();

`vPar`
  in: matrix, vector of starting values (free parameters), p `x`1

`DoEstimation()` returns:

- Direct estimation: p `x`1 matrix with the estimated parameters.
- Iterative estimation: array of length 3, with respectively:
  - p `x`1 matrix with the estimated parameters,
  - string, name of the iterative procedure (`"BFGS"` for example),
  - `TRUE` if numerical derivatives were used, `FALSE` otherwise.

`Estimate()` returns `TRUE` if estimation was successful, `FALSE` otherwise.

There are two ways to implement estimation:

- Override `DoEstimation()`, which is called from `Modelbase::Estimate`. In this case, the derived `DoEstimation()` returns the estimated parameters, and sets `m_iResult`, see `SetResult()`. Prior to calling `DoEstimation()`, `Modelbase::Estimate()` will call `InitData()`, `InitPar()` and `ClearEstimation()`. Afterwards, it will update the model status, and, if estimation was successful, `Output()`, and, if iterative estimation was used: `OutputMax()`.
- Override `Estimate()`, in which case `DoEstimation()` is not automatically called. This provides complete control, but requires more code. For example, a slightly simplified version of `Modelbase::Estimate()` is given below, showing the essential properties which must be set:
  - estimated free parameters: `SetFreePar()`,
  - `m_iResult`, see `SetResult()`
  - `m_iModelStatus`, see `SetModelStatus()`.

    Modelbase::Estimate()
    {
        decl  vpstart, vpfree, estout;

        if (!InitPar())          // calls InitData() if necessary
            return FALSE;

        vpstart = GetFreePar();  // map pars to estimation format
        estout = DoEstimation(vpstart); // do the estimation
        vpfree = isarray(estout) ? estout[0] : estout;

        SetFreePar(vpfree);// map estimated pars to normal format

        if (m_iResult >= MAX_CONV && m_iResult < MAX_MAXIT)
            m_iModelStatus = MS_ESTIMATED;
        else
            m_iModelStatus = MS_EST_FAILED;

        if (m_fPrint)
        {   Output();
            if (isarray(estout))
                OutputMax(estout[1],m_iResult,vpstart,estout[2]);
        }
        return m_iModelStatus == MS_ESTIMATED;
    }

    Modelbase::FixPar(const iP, const dFix);

`iP`
  in: int, index of parameter to fix
`dFix`
  in: double, value to fix parameter at

`FixPar()` is used to fix a parameter at the specified value. Subsequently, this parameter is omitted from the vector returned by `GetFreePar()`.

    Modelbase::FreePar(const iP)

`iP`
  in: int, index of parameter to free, use -1 to free all

Frees a parameter which was previously fixed by `FixPar()`.

    Database::GetDbName();

Returns a string with the database name.

    virtual Modelbase::GetcDfLoss();

Returns the loss in degrees of freedom in the estimated model. The default is the number of estimated parameters.

Only override this function if the number to be used in the output is different from that number of free parameters in the estimation.

    virtual Modelbase::GetcT();

Returns an integer with the actual number of observations to be used in the output.

Only override this function if the number reported in the output is different from that used in the estimation (`m_cT`).

    Modelbase::GetCovar();
    Modelbase::GetCovarRobust();

Returns the p `x` p variance-covariance matrix of the free parameters.

See `Covar` for an explanation of the implementation.

    Modelbase::GetFreePar();
    Modelbase::GetFreeParCount();
    Modelbase::GetFreeParNames();

`GetFreePar` returns the p `x`1 vector with free parameters.
`GetFreeParCount` returns the free parameter count p.
`GetFreeParNames` returns an array of length p with the names of the free parameters.

`GetFreePar` returns the current values of the free parameters. Parameters are fixed with `FixPar()`. The value of free parameters is set with `SetFreePar()`.

    Modelbase::GetLogLik();

Returns the log-likelihood, which is the value of the `m_dLogLik` member variable.

    Modelbase::GetMethod();

Returns an integer representing the estimation method, which is the value of the `m_iMethod` member variable.

    Modelbase::GetModelStatus();

Returns the model estimation status:

value | description
--- | ---
`MS_NONE` | no model preparatory action has been taken,
`MS_DATA` | estimation data has been extracted from the database,
`MS_PARAMS` | the starting values for estimation have been set,
`MS_ESTIMATED` | the model has been estimated,
`MS_EST_FAILED` | model estimation has failed.

This value is stored in the `m_iModelStatus` member variable.

    virtual Modelbase::GetPackageName();

Returns the name of the modelling package.

This virtual function should be overridden by the derived class.

    virtual Modelbase::GetPackageVersion();

Returns the version number of the modelling package.

This virtual function should be overridden by the derived class.

    Modelbase::GetPar();
    Modelbase::GetParCount();
    virtual Modelbase::GetParNames();

`GetPar` returns the q `x`1 vector with the current parameter values (both fixed and free).
`GetParCount` returns the total parameter count q (both fixed and free parameters).
`GetParNames` returns an array of length q with the names of the parameters.

`GetParNames` should be overridden to use proper labels in the output.

    Modelbase::GetParStatus();

Returns array with:

1. total number of parameters q,
2. q `x`1 matrix with 1 in position of free parameters, and 0 for fixed,
3. q `x`1 matrix with fixed value in position of fixed parameters (free positions are unused),

This function is infrequently used.

    virtual Modelbase::GetResiduals();

Returns the T `x` n matrix with residuals (n equals 1 for univariate models).

Must be overridden by the derived class to return residuals.

    Modelbase::GetResult();

The estimation result (normally a value from `MaxBFGS`), which is the value of the `m_iResult` member variable.

    virtual Modelbase::GetResVar();

Returns the n `x` n matrix with the residual variance (n equals 1 for univariate models).

Must be overridden by the derived class.

    Modelbase::GetStdErr();
    Modelbase::GetStdErrRobust();

Returns the q `x`1 vector with standard errors (0 at position of fixed parameters).

See `Covar` for an explanation of the implementation.

    virtual Modelbase::InitData();

Returns `TRUE` if successful.

Extracts the data for estimation from the underlying database. Sets the model status to `MS_DATA` if successful.

    virtual Modelbase::InitPar();

Returns `TRUE` if successful.

Gets starting values for the estimation procedure. Sets the model status to `MS_PARAMS` if successful.

    virtual Modelbase::IsUnivariate();

Returns `TRUE` if only one dependent variable (`Y_VAR`) is allowed.

This virtual function should be overridden by the derived class if multivariate models are implemented.

    Modelbase::MapParToFree(const vPar);

`vPar`
  in: int, q vector with parameter values (both fixed and free)

Returns a p `x`1 vector with free parameter values.

Extracts and returns the free parameter values from a full parameter vector.

    Modelbase::Modelbase();

Constructor function.

    virtual Modelbase::Output();

Prints the estimation output.

    Modelbase::OutputHeader(const sTitle);

`sTitle`
  in: string, title

Called by `Output` to print the header section.

    Modelbase::OutputLogLik();

Called by `Output` to print the loglikelihood and other summary statistics.

    Modelbase::OutputMax(const sMethod, const iResult, const vPstart,
        const bNumerical);

`sMethod`
  in: maximization method
`iResult`
  in: int, maximization result
`vPstart`
  in: vector with starting values
`bNumerical`
  in: int, `TRUE` if using numerical derivatives

Called by `Estimate` to print the starting values and method used for iterative estimation.

    Modelbase::OutputPar();

Called by `Output` to print the parameter estimates.

    static PrintTestVal(const dTest, const cR, const cTdf, const sLabel);

`dTest`
  in: test statistic
`cR`
  in: first degrees of freedom
`cTdf`
  in: second degrees of freedom
`sLabel`
  in: name of test

Prints a test statistic and its significance. If `cTdf` is zero, the test is assumed to have Chi2(`cR`) distribution, otherwise an F(`cR`,`cTdf`) distribution.

    Modelbase::ResetFixedPar();

Resets the fixed parameters to their prespecified values.

    Database::SetDbName(const sName);

Sets the database name.

    Modelbase::SetFreePar(const vParFree);

`vParFree`
  in: p vector with free parameter values

    Modelbase::SetMethod(const iMethod);

`iMethod`
  in: int, estimation method (no values are predefined in Modelbase)

Sets `m_iMethod`.

    Modelbase::SetModelStatus(const );

`iModelStatus`
  in: int, model status to set, one of: `MS_NONE`, `MS_DATA`, `MS_PARAMS`, `MS_ESTIMATED`, `MS_EST_FAILED`

Sets `m_iModelStatus`.

    Modelbase::SetPar(const vPar);
    Modelbase::SetParCount(const cPar);
    Modelbase::SetParCount(const cPar, const bAdd);

`vPar`
  in: q `x`1 vector with new parameter values (both fixed and free)
`cPar`
  in: int, total number of parameters (fixed and free)
`bAdd`
  in: (optional) int, `TRUE`: add parameters to current count; else set the count.

`SetParCount()` must be called for the other parameter functions to work.

    Modelbase::SetPrint(fPrint);

`fPrint`
  in: int, `TRUE` to switch printing on, `FALSE` to switch off.

For Monte Carlo experiments, it can be useful to switch off printing.

    Modelbase::SetResult(const iResult);

Sets the estimation result (normally a value from `MaxBFGS`), which is the value of the `m_iResult` member variable.

    virtual Modelbase::SetStartPar(const vParFree);

`vParFree`
  in: p vector with the starting values for the free parameters

This is an alternative to `InitPar`, allowing for direct setting of the starting parameters prior to estimation.

    virtual Modelbase::TestRestrictions(vSel);
    virtual Modelbase::TestRestrictions(mR, const vR);

`vSel`
  in: p vector, with a 1 for the coefficients which tested to be zero, 0 otherwise
`mR`
  in: s `x` p matrix R
`vR`
  in: s vector r

The one-argument version tests whether one or more coefficients are zero. The second form tests restrictions of the type R\theta=r. Both are implemented as a Wald test with a Chi2(s) distribution.
This function requires that `Covar()` and `GetParNames()` are implemented, and `SetPar()` or `SetParFree()` are used to set the estimated parameters.

## PcFiml class

The `PcFiml` class provides part of the advanced computations available in the menu driven computer program PcFiml. The class is derived from the `Database` class, and provides model formulation using variable names. The class allows for estimating a Vector Autoregression (VAR), cointegration analysis (`Johansen procedure'), and multivariate regression model (such as an unrestricted reduced form, URF), as well as a simultaneous equations model (2SLS, 3SLS, FIML). No identities equations are currently possible. Mis-specification tests include: vector autoregression, vector normality, vector heteroscedasticity, vector portmanteau, as well as a Chow test.

### PcFiml function members

`ArTest(const iAr1, const iAr2);`
  System vector AR test for lags `iAr1`... `iAr2`.
`Chow(const iYear, const iPeriod);`
  Forecast Chow tests for break on or after `iYear` (`iPeriod`).
`Cointegration();`
  Estimate cointegrating space.
`CointegrationI2();`
  I(2) cointegration analysis.
`EgeArTest(const iAr1, const iAr2);`
  Model vector AR test for lags `iAr1`...`iAr2`.
`Estimate();`
  Estimate the system (NB: use `->SetSelSample()` first).
`Fiml();`
  Do FIML estimation.
`GetOmega();`
  Returns n `x` n matrix of URF/RRF residual variance V'V/(T-k).
`GetPi();`
  Returns n `x` k matrix of URF/RRF coefficients.
`GetResiduals();`
  Returns T `x` n matrix V of URF/RRF residuals.
`GetResult();`
  Returns results from FIML estimation (return code from `MaxBFGS`).
`GetStatus();`
  Returns status of Constant and Trend (0: no constant; 1: restricted constant; 2: unrestricted constant; 4: unrestricted trend; 3: restricted trend).
`GetVarNames(const aasY, const aasW);`
  Returns n ~ n1 ~ k (n1 is no of lagged ys); puts list of varnames in arguments.
`GetVarPi();`
  Returns n `x` k matrix with variances of RRF/URF coefficients.
`GetVarRf();`
  System: returns full nk `x` nk variance-covariance matrix of URF coefficients;
  Model: returns full nk `x` nk variance-covariance matrix of RRF coefficients.
`GetVarTheta();`
  System: returns full nk `x` nk variance-covariance matrix of URF coefficients;
  Model: returns full np `x` np variance-covariance matrix of model coefficients.
`HeteroTest(const fStand, const fCross);`
  Vector heteroscedasticity test.
`NormalityTest();`
  Vector normality test.
`Output(const fSys, const fCoint);`
  Print System and/or Cointegration results.
`PcFiml();`
  Constructor.
`Portmanteau(const iLag);`
  Vector portmanteau test up to lag `iLag`.
`SetEquation(const sEquation, const aModel);`
  Delete or add variable from model.
`SetPrint(fPrint);`
  Toggles print switch.
`SetPrintUrf(fPrintUrf);`
  Toggles URF print switch.
`ThreeSLS();`
  Do 3SLS estimation.
`TwoSLS();`
  Do 2SLS estimation.

## PcFimlDgp class

The `PcFimlDgp` class is a data generation process (DGP), designed for use in dynamic econometric Monte Carlo experiments. Unlike the `PcNaiveDgp` class, it derives from `Database` to formulate the DGP and store the generated data. This makes the DGP more general, but somewhat more complex. The class is used through the header file `pcfimldgp.h`. The design is an n-variate version DGP:

  yt = Pi wt + ut,
  zt = C0 zt-1 + vt.

The vectors yt and ut are n `x` 1, wt is k `x` 1 so that the coefficient matrix Pi is n `x` k. The zt vector is q `x` 1, making C0 q `x` q. The zs can be kept fixed between experiments, or regenerated for the experiment. A distribution for ut and vt can be specified.

### PcFimlDgp function members

    PcFimlDgp::Asymp();

Prints an asymptotic analysis of the current DGP.

    PcFimlDgp::Create(const iFreq, const iYear1, const iPeriod1,
        const cTdiscard, const mxDgpLag, const mxT);

`iFreq`
  in: int, database frequency
`iYear1`
  in: int, start year of observation
`iPeriod1`
  in: int, start period of observation
`cTdiscard`
  in: int, number of discards
`mxDgpLag`
  in: int, maximum lag to be used in DGP
`mxT`
  in: int, maximum sample size to be used (this excludes lags and discards)

Creates the database. After this, `Select` may be used to formulate the DGP, with group identifier `Y_VAR` or `Z_VAR`. The database name of the variables are `"Ya"`, `"Yb"`, ..., and `"Za"`, `"Zb"`, .... The `Constant`, `Trend` and normal `Seasonal`s are automatically created.

    PcFimlDgp::DiscardZ();

Discards the current zt; the next call to `GenerateTo()` will generate new observations on zt.

    PcFimlDgp::Generate(const cT);

`cT`
  in: int, sample size T

`GenerateTo` returns generated (Y:U), as a T `x` 2n matrix.
Generates `cT` observation of the current DGP.

    virtual PcFimlDgp::GenerateU(const cT);
    virtual PcFimlDgp::GenerateV(const cT);
    virtual PcFimlDgp::GenerateZ(const cT, const mC0t, const mV);
    virtual PcFimlDgp::GenerateY(const cT, const mPit, const mU);
    virtual PcFimlDgp::GenerateU_t(const iT);
    virtual PcFimlDgp::GenerateV_t(const iT);
    virtual PcFimlDgp::GenerateZ_t(const iT, const mC0t);
    virtual PcFimlDgp::GenerateY_t(const iT, const mPit);

`cT`
  in: int, sample size T
`iT`
  in: int, current observation t
`mC0t`
  in: q `x` q matrix C0'
`mPit`
  in: k `x` n matrix Pi'
`mV`
  in: T `x` q matrix U
`mU`
  in: T `x` n matrix V

These virtual functions are called by `GenerateTo()` to generate the data. The sub-t versions are called when using a for loop for data generation. This is the case after a call to `UseObsLoop(TRUE)`.

    PcFimlDgp::GetU();
    PcFimlDgp::GetV();
    PcFimlDgp::GetY();
    PcFimlDgp::GetZ();

`GetU` returns current U as a T `x` n matrix.
`GetV` returns current V as a T `x` q matrix.
`GetY` returns current Y as a T `x` n matrix.
`GetZ` returns current Z as a T `x` q matrix.

    PcFimlDgp::PcFimlDgp(const cY, const cZ);

`cY`
  in: int, n, dimension of yt
`cZ`
  in: int, q, dimension of zt

Constructor.

    PcFimlDgp::Prepare();

Virtual function which must be called prior to data generation.

    PcFimlDgp::Print();

Prints the setup of the current DGP.

    PcFimlDgp::SetDistribution(const iEqn, const iDist,
        mPar1, mPar2);

See under the PcNaive DGP.

    PcFimlDgp::SetFixedZ(const fSetting);

See under the PcNaive DGP.

    PcFimlDgp::SetInit(const iDgp, const mInit);

`iDgp`
  in: one of: `Y_DGP`, `Z_DGP`
`mInit`
  in: or or:
  `Y_DGP`: s `x` n matrix
  `Z_DGP`: s `x` q matrix

Specifies initial values for the DGP (default is 0).

    PcFimlDgp::SetYParameter(const mPit);

`mPit`
  in: k `x` n matrix Pi'

Sets the parameters for the yt equation.

    PcFimlDgp::SetZParameter(const mC0);

`mC0`
  in: q `x` q matrix C0

Sets the parameters for the zt equation.

    PcFimlDgp::UseObsLoop(const bUseObsLoop);

`bUseObsLoop`
  in: TRUE: generate data by looping over observations

By default, the data are generated using matrix expressions. Use this to generate the data in a for loop. This is considerably slower, but gives more flexibility.

## PcNaiveDgp class

The `PcNaiveDgp` class is a data generation process (DGP), designed for use in dynamic econometric Monte Carlo experiments. The class is used through the header file `pcnaive.h`. The design is an n-variate version DGP:

  yt = A0yt + A1yt-1 + A2zt + a3 + A5yt-2 + ut,
  ut = B0ut-1 + et + B1et-1,
  zt = C0zt-1 + c1 + c2t + vt.

The vectors yt,ut,et are n `x` 1, so that the coefficient matrices A0,A1,B0,B1 are n `x` n, and a3 is n `x` 1. The zt vector is q `x` 1, making a2 n `x` q, C0 q `x` q, and c1,c2 q `x` 1. The zs can be kept fixed between experiments, or regenerated for the experiment. A distribution for et and vt can be specified.

### PcNaiveDgp function members

    PcNaiveDgp::Asymp();

Prints an asymptotic analysis of the current DGP: companion matrix with eigenvalues, together with cointegrating space and level of integration of DGP: I(0), I(1) or I(2).

    PcNaiveDgp::DiscardZ();

Discards the current zt; the next call to `Generate()` will generate new observations on zt.

    PcNaiveDgp::Generate(const cT);
    PcNaiveDgp::GenerateTo(const cT);

`cT`
  in: int, sample size T

`Generate` returns generated Y = (y0 ... y_T)', as a T `x` n matrix.
`GenerateTo` returns generated (Y:U), as a T `x` 2n matrix.
Generates `cT` observation of the current DGP.

    PcNaiveDgp::GenerateBreakTo(const cT, const iTbreak,
        const iTreset, const mA0, const mA1, const mA2,
        const mA3, const mA5)

`cT`
  in: int, sample size T
`iTbreak`
  in: int, T1, first observation with break
`iTreset`
  in: int, T2, first observation after the break
`mA0`
  in: n `x` n matrix A0* must have zeros on the diagonal
`mA1`
  in: n `x` n matrix A1*
`mA2`
  in: n `x` q matrix A2*
`mA3`
  in: n `x` 1 matrix a3*
`mA5`
  in: n `x` n matrix A5*

Returns generated (Y:U), as a T `x` 2n matrix.

Generates `cT` observation of the current DGP, using the alternative DGP over the specified period.

    PcNaiveDgp::GetU();
    PcNaiveDgp::GetY();
    PcNaiveDgp::GetZ();

`GetU` returns current U as a T `x` n matrix.

`GetY` returns current Y as a T `x` n matrix (as does `Generate`).

`GetZ` returns current Z as a T `x` q matrix.

    PcNaiveDgp::PcNaiveDgp(const cY, const cZ);

`cY`
  in: int, n, dimension of yt
`cZ`
  in: int, q, dimension of zt

Constructor.

    PcNaiveDgp::Print();

Prints the setup of the current DGP.

    PcNaiveDgp::SetDistribution(const iEqn, const iDist,
        mPar1, mPar2);

`iEqn`
  in: one of: `U_DGP`, `Z_DGP`
`iDist`
  in: one of: `NO_DIST`, `NORMAL`, `MVNORMAL`, `LOGNORMAL`, `T_DIST`, `F_DIST`, `EXPONENTIAL`, `MVNARCH`, `MVNHETERO`
`mPar1`
  in: first parameter of distribution, `MVNARCH`, `MVNHETERO`: n `x` n for yt, ut; q `x` q for zt others: n `x` 1 for yt, ut; q `x` 1 for zt
`mPar2`
  in: second parameter of distribution, `MVNORMAL`, `MVNARCH`, `MVNHETERO`: n `x` n for yt, ut; q `x` q for zt others: n `x` 1 for yt, ut; q `x` 1 for zt

Specifies the distribution for the u, or z equations given above. The first argument indicates the equation, the second the distribution. The last two arguments parameterize the distribution.

    PcNaiveDgp::SetFixedZ(const fSetting);

Specifies whether zt is fixed (`fSetting` equals `TRUE`) or not. Fixed zt is only generated once, until a call to `DiscardZ` or `SetFixedZ` is made. By default zt is fixed.

    PcNaiveDgp::SetInit(const iDgp, const mInit);

`iDgp`
  in: one of: `Y_DGP`, `Z_DGP`
`mInit`
  in: or or:
  `Y_DGP`: 1 `x` n or 2 `x` n matrix
  `Z_DGP`: 1 `x` q matrix

Specifies initial values for the DGP (default is 0).

    PcNaiveDgp::SetUParameter(const mLagAr, const mLagMa);

`mLagAr`
  in: n `x` n matrix B0
`mLagMa`
  in: n `x` n matrix B1

Sets the parameters for the et equation.

    PcNaiveDgp::SetYParameter(const mA0, const mA1,	const mA2, const mA3);
    PcNaiveDgp::SetYParameter(const mA0, const mA1,	const mA2, const mA3,
        const mA5);

`mA0`
  in: n `x` n matrix A0 must have zeros on the diagonal
`mA1`
  in: n `x` n matrix A1
`mA2`
  in: n `x` q matrix A2
`mA3`
  in: n `x` 1 matrix a3
`mA5`
  in: (optional argument) n `x` n matrix A5

Sets the parameters for the yt equation.

    PcNaiveDgp::SetYParameterEcm(const mAlpha,
        const mBeta, const mA2, const mA3);
    PcNaiveDgp::SetYParameterEcm(const mAlpha,
        const mBeta, const mA2, const mA3, const mA5);

`mAlpha`
  in: n `x` p matrix alpha
`mBeta`
  in: n `x` p matrix beta
`mA2`
  in: n `x` q matrix A2
`mA3`
  in: n `x` 1 matrix a3
`mA5`
  in: (optional argument) n `x` n matrix A5*

Sets the parameters for the yt equation in equilibrium correction form.

    PcNaiveDgp::SetZParameter(const mC0, const mC1, const mC2);

`mC0`
  in: q `x` q matrix C0
`mC1`
  in: q `x` 1 matrix c1
`mC2`
  in: q `x` 1 matrix c2

Sets the parameters for the zt equation.

    PcNaiveDgp::SetZCustom(mCZ);

`mCZ`
  in: T `x` q matrix with custom values.

Installs a custom Z.

## RanMC class

The `RanMC` class provides random number generation of specific distribution for use by the PcNaiveDgp and PcFimlDgp classes. All member functions are static, and can be used without constructing an object, for example as:

        x = RanMC::Choleski(x);

### RanMC function members

    static RanMC::Choleski(const mSig);

Returns Choleski decomposition of `mSig`. `mSig` may have zeros on the diagonal. The corresponding rows and columns are ignored in the decomposition, and will be zero in the return value.

    static RanMC::CheckDist(const sFunc, iDist, mPar1, mPar2);

Returns an array of three values:

`iDist`, distribution
`mPar1` matrix, adjusted input value
`mPar2` matrix, adjusted input value

    static RanMC::RanDist(const iDist, const cT, const cY, const mDf1,
        const mDf2);

Returns a T `x` n matrix of random numbers from the specified distribution. The distribution parameters must be as returned from `CheckDist()`.

    static RanMC::RanDist1(const iDist, const cY, const mDf1,
        const mDf2, const mUlag, const mYlag);

Returns a 1 `x` n matrix of random numbers from the specified distribution. The distribution parameters must be as returned from `CheckDist()`.

    static RanMC::WriteDist(const sPar, const iDist, const mDf1,
        const mDf2);

Writes the used distribution. The distribution parameters must be as returned from `CheckDist()`.

## Sample class

The `Sample` class stores a time interval, and the frequency, e.g. 1980 (1) -- 1990 (1), with frequency 4 (i.e. quarterly observations). The `Sample` class is only used to derive from. It requires linking in the database code, and inclusion of `database.h`. This is most easily done by adding an `#import <database>` statement at the top of your source code.

### Sample function members

    Sample::GetFrequency();

The frequency.

    Sample::GetIndex(const iYear, const iPeriod);

The index of the specified time point.

    Sample::GetPeriod1();

The period of the first observation.

    Sample::GetPeriod2();

The period of the last observation.

    Sample::GetSize();

The number of observations in the sample.

    Sample::GetYear1();

The year of the first observation.

    Sample::GetYear2();

The year of the last observation.

    Sample::ObsPeriod(iObs);

The period of the observation index.

    Sample::ObsYear(iObs);

The year of the observation index.

### Sample data members

`m_iFreq`
  data frequency (int)
`m_iYear1`
  year of first observation (int)
`m_iPeriod1`
  period of first observation (int)
`m_iYear2`
  year of last observation (int)
`m_iPeriod2`
  period of last observation (int)

## Simulation class

The `Simulation` class can be used to set up Monte Carlo experiments. Derive your own simulation experimentation class from this, overriding the virtual functions. `Simulation` will handle the replications and storage, and print the final results. The type of data it can handle are coefficients, test statistics and p-values of test statistics. The class is used through the header file `simula.h`.

A table is printed at the end, which gives the results, for coefficients:

- mean: mean over all replications (MC mean),
- std.dev: standard deviation around MC mean (MCSD),
- mean bias: MC mean - true value,
- se mean bias: MCSD / sqrt(M),
- rmse: standard deviation around true value, sqrt(MCSD^2 + mean bias^2),

where M is the number of replications and rmse is the root of the mean squared error.

### Simulation function members

    virtual Simulation::Generate(const iRep, const cT,
        const mxT);

`iRep`
  in: int, index of current replication (0 is first)
`cT`
  in: int, sample size to be used for replication
`mxT`
  in: int, maximum sample size to be used for replication (this is only relevant when using common random numbers)

The functions should return 1 if successful, 0 if the replications failed.

If the call to the `Generate` function fails, it is retried until a successful return (so always returning 0, or not returning a value could result in an infinite loop). The number of rejected replications is reported in the output.

The derived class must override the virtual function. It is called for every replication, and must perform the actual replication. The results from this replication are obtained by the `simula` class by calling `GetCoefficients`, `GetPvalues` and `GetTestStatistics`.

    virtual Simulation::GetCoefficients();
    virtual Simulation::GetPvalues();
    virtual Simulation::GetTestStatistics();

The functions return 0 if the information is not generated, otherwise:

`GetCoefficients`
  sc `x` 1 matrix with the observed coefficients
`GetPvalues`
  sp `x` 1 matrix with observed p-values of the tests
`GetTestStatistics`
  st `x` 1 matrix with the observed test statistics

Virtual functions which the derived class must override.

    virtual Simulation::IsTwoSided();

Returns a vector of 0-1 values, with a 1 for each test statistics which is two-sided. If this function is not provided, all tests are one-sided.

    virtual Simulation::Plot(const iRep, const iT)

`iRep`
  in: int, index of current replication (0 is first)
`iT`
  in: int, sample size of current replication

Virtual plot function. The default version does nothing.

    Simulation::SaveIn7(const sFilename);
    Simulation::SaveRecIn7(const sFilename);

`sFilename`
  in: destination file name

Saves simulation results to the named file.
`SaveIn7` stores the test and coefficient values.
`SaveRecIn7` stores: coefficients, MCSE, Bias, RMSE, test critical values (right tail), rejection frequencies and moments.

    Simulation::SetCoefNames(const asNames)
    Simulation::SetTestNames(const asNames)

`asNames`
  in: array with names. For `SetCoefNames`: array with sc names; for `SetTestNames`: array with st names.

Installs the names of tests statistics and coefficients, to make the report more readable.

    Simulation::SetPlotRep(const iPlotRep);
    Simulation::SetRecursive(const bRecursive);
    Simulation::SetStore(const bStore);

`iPlotRep`
  in: call `Plot()` every `iPlotRep` replications (default is 0)
`bRecursive`
  in: `TRUE`: do recursive Monte Carlo (default is `FALSE`)
`bStore`
  in: store results of all replications for later access (default is `FALSE`)

    Simulation::Simulate()

This is the core function. It runs the Monte Carlo experiment, and prints the results.

    Simulation::Simulation(const mT, const mxT,
        const cRep, const fCommon, const dSeed,
        const mPvalue, const mTrueParam);

`mT`
  in: 1 `x` r matrix of sample sizes
`mxT`
  in: int, maximum sample size
`cRep`
  in: int, number of replications
`fCommon`
  in: 1: reset seed for each experiment; else 0
`dSeed`
  in: double, resets seed to `dSeed` if `fCommon == TRUE`
`mPvalue`
  in: 1 `x` sp matrix with p-values to test at, only used if `GetPvalues` returns p-values
`mTrueParam`
  in: 1 `x` sc matrix with true parameters, only used if `GetCoefficients` returns coefficients

Constructor function.

Ox version 3.00. © JA Doornik This file last changed
.