ModelBaseEcon Reference
Public interface
ModelBaseEcon.ModelBaseEcon
— ModuleModelBaseEcon
This package is part of the StateSpaceEcon ecosystem. It provides the basic elements needed for model definition. StateSpaceEcon works with model objects defined with ModelBaseEcon.
ModelBaseEcon.Equation
— Typestruct Equation <: AbstractEquation ⋯ end
Data type representing a single equation in a model.
Equations are defined in @equations
blocks. The actual equation instances are later created with @initialize
and stored within the model object.
Equation flags can be specified by annotating the equation definition with one or more @<flag>
. See EqnFlags
for details.
Each equation has two functions associated with it, one which computes the residual and the other computes both the residual and the gradient . Usually there's no need to users to call these functions directly. They are used internally by the solvers.
ModelBaseEcon.LogTransform
— TypeLogTransform <: Transformation
The log
transformation. The inverse is of course exp
. This is the default for variables declared with @log
.
ModelBaseEcon.Model
— Typemutable struct Model <: AbstractModel ⋯ end
Data structure that represents a macroeconomic model.
ModelBaseEcon.ModelParam
— Typemutable struct ModelParam ⋯ end
Contains a model parameter. For a simple parameter it simply stores its value. For a link or an alias, it stores the link information and also caches the current value for speed.
ModelBaseEcon.ModelVariable
— Typestruct ModelVariable ⋯ end
Data type for model variables. ModelVariable
functions like a Symbol
in many respects, but also holds meta-information about the variable, such as doc string, the variable type, transformation, steady state behaviour.
Variable types include
:var
- a regular variable is endogenous by default, but can be exogenized.:shock
- a shock variable is exogenous by default, but can be endogenized. Steady state is 0.:exog
- an exogenous variable is always exogenous.
These can be declared with @variables
, @shocks
, and @exogenous
blocks. You can also use @exog
within an @variables
block to declare an exogenous variable.
Transformations include
:none
- no transformation. This is the default. In steady state these variables exhibit linear growth.:log
- logarithm. This is useful for variables that must be always strictly positive. Internally the solver work with the logarithm of the variable. in steady state these variables exhibit exponential growth (the log variable grows linearly).:neglog
- same as:log
but for variables that are strictly negative.
These can be declared with @logvariables
, @neglogvariables
, @log
, @neglog
.
Steady state behaviours include
:const
- these variables have zero slope in steady state and final conditions.:growth
- these variables have constant slope in steady state and final conditions. The meaning of "slope" changes depending on the transformation. For:log
and:neglog
variables this is the growth rate, while for:none
variables it is the usual slope of linear growth.
Shock variables are always :const
while regular variables are assumed :growth
. They can be declared :const
using @steady
.
ModelBaseEcon.NegLogTransform
— TypeNegLogTransform <: Transformation
The log(-x)
, with the inverse being -exp(x)
. Use this when the variable is negative with exponential behaviour (toward -∞).
ModelBaseEcon.NoTransform
— TypeNoTransform <: Transformation
The identity transformation.
ModelBaseEcon.Parameters
— TypeParameters([mod::Module])
When creating an instance of Parameters
, optionally one can specify the module in which parameter expressions will be evaluated. This only matters if there are any link parameters that depend on custom functions or global variables/constants. In this case, the mod
argument should be the module in which these definitions exist.
ModelBaseEcon.Parameters
— Typestruct Parameters <: AbstractDict{Symbol, Any} ⋯ end
Container for model parameters. It functions as a Dict
where the keys are the parameter names. Simple parameter values are stored directly. Special parameters depend on other parameters are are wrapped in the appropriate data structures to keep track of such dependencies. There are two types of special parameters - aliases and links.
Individual parameters can be accessed in two different ways - dot and bracket notation.
Read access by dot notation calls peval
while bracket notation doesn't. This makes no difference for simple parameters. For special parameters, access by bracket notation returns its internal structure, while access by dot notation returns its current value depending on other parameters.
Write access is the same in both dot and bracket notation. The new parameter value is assigned directly in the case of simple parameter. To create an alias parameter, use the @alias
macro. To create a link parameter use the @link
macro.
See also: ModelParam
, peval
, @alias
, @link
, update_links!
.
ModelBaseEcon.SteadyStateData
— TypeSteadyStateData
Data structure that holds information about the steady state solution of the Model. This includes a collection of SteadyStateVariable
s and two collections of SteadyStateEquation
s - one for the steady state equations generated from dynamic equations and another for steady state constraints created with @steadystate
.
ModelBaseEcon.SteadyStateEquation
— Typestruct SteadyStateEquation <: AbstractEquation ⋯ end
Data structure representing an individual steady state equation.
Steady state equations can be constructed from the dynamic equations of the model. Each steady state variable has two unknowns, level and slope, so from each dynamic equation we construct two steady state equations.
Steady state equations can also be constructed with @steadystate
after @initialize
has been called. We call such equations steady state constraints.
ModelBaseEcon.Transformation
— Typeabstract type Transformation end
The base class for all variable transformations.
ModelBaseEcon.add_equation!
— Methodadd_equation!(model::Model, eqn_key::Symbol, expr::Expr; modelmodule::Module)
Process the given expression in the context of the given module, create the Equation() instance for it, and add it to the model instance.
Usually there's no need to call this function directly. It is called during @initialize
.
ModelBaseEcon.alleqns
— Methodalleqns(ssd::SteadyStateData)
Return a list of all steady state equations.
The list contains all explicitly added steady state constraints and all equations derived from the dynamic system.
ModelBaseEcon.assign_parameters!
— Functionassign_parameters!(model, collection; [options])
assign_parameters!(model; [options], param=value, ...)
Assign values to model parameters. New parameters can be given as key-value pairs in the function call, or in a collection, such as a Dict
, for example.
Individual parameters can be assigned directly to the model
using dot notation. This function should be more convenient when all parameters values are loaded from a file and available in a dictionary or some other key-value collection.
There are two options that control the behaviour.
preserve_links=true
- if set totrue
new values for link-parameters are ignored and the link is updated automatically from the new values of parameters it depends on. If set tofalse
any link parameters are overwritten and become non-link parameters set to the given new values.check=true
- if a parameter with the given name does not exist we ignore it. Whencheck
is set totrue
we issue a warning, when set tofalse
we ignore it silently.
See also: export_parameters
and export_parameters!
Example
julia> @using_example E1
julia> assign_parameters(E1.model; α=0.3, β=0.7)
ModelBaseEcon.assign_sstate!
— Functionassign_sstate!(model, collection)
assign_sstate!(model; var = value, ...)
Assign a steady state solution from the given collection of name=>value pairs into the given model.
In each pair, the value can be a number in which case it is assigned as the level and the slope is set to 0. The value can also be a Tuple
or a Vector
in which case the first two elements are assigned as the level and the slope. Finally, the value can itself be a name-value collection (like a named tuple or a dictionary) with fields :level
and :slope
. Variables whose steady states are found in the collection are assigned and also marked as solved.
ModelBaseEcon.eval_R!
— Functioneval_R!(res::AbstractArray{Float64,1}, point::AbstractArray{Float64, 2}, ::MED) where MED <: AbstractModelEvaluationData
Evaluate the model residual at the given point using the given model evaluation structure. The residual is stored in the provided vector.
Implementation details (for developers)
When creating a new type of model evaluation data, you must define a method of this function specialized to it.
The point
argument will be a 2d array, with the number of rows equal to maxlag+maxlead+1
and the number of columns equal to the number of variables+shocks+auxvars
of the model. The res
vector will have the same length as the number of equations + auxiliary equations. Your implementation must not modify point
and must update res
.
See also: eval_RJ
ModelBaseEcon.eval_RJ
— Functioneval_RJ(point::AbstractArray{Float64, 2}, ::MED) where MED <: AbstractModelEvaluationData
Evaluate the model residual and its Jacobian at the given point using the given model evaluation structure. Return a tuple, with the first element being the residual and the second element being the Jacobian.
Implementation details (for developers)
When creating a new type of model evaluation data, you must define a method of this function specialized to it.
The point
argument will be a 2d array, with the number of rows equal to maxlag+maxlead+1
and the number of columns equal to the number of variables+shocks+auxvars
of the model. Your implementation must not modify point
and must return the tuple of (residual, Jacobian) evaluated at the given point
. The Jacobian is expected to be SparseMatrixCSC
(this might change in the future).
See also: eval_R!
ModelBaseEcon.export_model
— Functionexport_model(model, name, file::IO)
export_model(model, name, path::String)
Export the model into a module file. The name
parameter is used for the name of the module as well as the module file. The module file is created in the directory specified by the optional third argument.
ModelBaseEcon.export_parameters
— Functionexport_parameters(model; include_links=true)
export_parameters(parameters; include_links=true)
Write all parameters into a Dict{Symbol, Any}
. For link and alias parameter, only their current value is stored, the linking information is not. Set include_links=false
to suppress the writing of link and alias parameters.
Use assign_parameters!
to restore the parameters values from the container created here.
ModelBaseEcon.export_parameters!
— Methodexport_parameters!(container, model; include_links=true)
export_parameters!(container, parameters; include_links=true)
Write all parameters into the given container
. The parameters are push!
-ed as name => value
pairs. For link and alias parameter, only their current value is stored, the linking information is not. Set include_links=false
to suppress the writing of link and alias parameters.
Use assign_parameters!
to restore the parameters values from the container created here.
ModelBaseEcon.export_sstate
— Functionexport_sstate(model)
Return a dictionary containing the steady state solution stored in the given model. The value for each variable will be a number, if the variable has zero slope, or a named tuple (level = NUM, slope=NUM)
.
ModelBaseEcon.export_sstate!
— Functionexport_sstate!(container, model)
Fill the given container with the steady state solution stored in the given model. The value for each variable will be a number, if the variable has zero slope, or else a named tuple of the form (level = NUM, slope=NUM)
.
ModelBaseEcon.find_main_equation
— Methodfind_main_equation(model, var)
Return the name of the first equation that contains var[t]
. Return nothing
if there's no such equation.
ModelBaseEcon.findequations
— Methodfindequations(m::Model, sym::Symbol; verbose=true)
Prints the equations which use the the given symbol in the provided model and returns a vector with their keys. Only returns the vector if verbose is set to false
.
ModelBaseEcon.fullprint
— Functionfullprint(model)
If a model contains more than 20 variables or more than 20 equations, its display is truncated. In this case you can call fullprint
to see the whole model.
ModelBaseEcon.get_unused_symbols
— Methodget_unused_symbols(model::Model)
Returns a dictionary with vectors of the unused variables, shocks, and parameters.
ModelBaseEcon.geteqn
— Methodgeteqn(i, ssd::SteadyStateData)
Return the i-th steady state equation. Index i is interpreted as in the output of alleqns(::SteadyStateData)
. Calling geteqn(i, sdd)
has the same effect as alleqn(ssd)[i]
, but it's more efficient.
Example
# Iterate all equations like this:
for i = 1:neqns(ssd)
eqn = geteqn(i, ssd)
# do something awesome with `eqn` and `i`
end
ModelBaseEcon.inverse_transform
— Functioninverse_transform(x, var::ModelVariable)
Apply the inverse transformation associated with model variable m
to data x
.
See also inverse_transformation
ModelBaseEcon.inverse_transformation
— Functioninverse_transformation(::Type{<:Transformation})
Return a Function
that will be called to transform the simulation data after solving. See also transformation
.
It is expected that transformation(T) ∘ inverse_transformation(T) == identity
and inverse_transformation(T) ∘ transformation(T) == identity
, but these is not verified.
ModelBaseEcon.isexog
— Methodisexog(v)
Return true
if the given ModelVariable
is exogenous, otherwise return false
.
ModelBaseEcon.islin
— Methodislin(v)
Return true
if the given ModelVariable
is a no-transformation variable, otherwise return false
.
ModelBaseEcon.islinearized
— Methodislinearized(model::Model)
Return true
if the given model is linearized and false
otherwise.
ModelBaseEcon.islog
— Methodislog(v)
Return true
if the given ModelVariable
is a log-transformation variable, otherwise return false
.
ModelBaseEcon.isneglog
— Methodisneglog(v)
Return true
if the given ModelVariable
is a negative-log-transformation variable, otherwise return false
.
ModelBaseEcon.isshock
— Methodisshock(v)
Return true
if the given ModelVariable
is a shock, otherwise return false
.
ModelBaseEcon.issssolved
— Methodissssolved(sstate::SteadyStateData)
Return true
if the steady state has been solved, or false
otherwise.
This function only checks that the steady state is marked as solved. It does not verify that the stored steady state values actually satisfy the steady state system of equations. Use check_sstate
from StateSpaceEcon for that.
ModelBaseEcon.issteady
— Methodissteady(v)
Return true
if the given ModelVariable
is zero-slope, otherwise return false
.
ModelBaseEcon.linearize!
— Functionlinearize!(model::Model; <keyword arguments>)
Transform model into its linear approximation about its steady state.
Keyword arguments
sstate
- linearize about the provided steady state solutiondeviation
::Bool - whether or not the linearized model will treat data passed to it as deviation from the steady state
See also: linearized
and with_linearized
ModelBaseEcon.linearized
— Methodlinearized(model::Model; <arguments>)
Create a new model that is the linear approximation of the given model about its steady state.
Keyword arguments
sstate
- linearize about the provided steady state solutiondeviation
::Bool - whether or not the linearized model will tread data passed
to is as deviation from the steady state
See also: linearize!
and with_linearized
ModelBaseEcon.logm
— Methodlogm(x) = log(-x)
ModelBaseEcon.mexp
— Methodmexp(x) = -exp(x)
ModelBaseEcon.need_transform
— Functionneed_transform(v)
Return true
if there is a transformation associated with model variable v
, otherwise return false
.
ModelBaseEcon.neqns
— Methodneqns(ssd::SteadyStateData)
Return the total number of equations in the steady state system, including the ones added explicitly as steady state constraints and the ones derived from the dynamic system.
ModelBaseEcon.peval
— Functionpeval(params, what)
Evaluate the given expression in the context of the given parameters params
.
If what
is a ModelParam
, its current value is returned. If it's a link and there's a chance it might be out of date, call update_links!
.
If what
is a Symbol or an Expr, all mentions of parameter names are substituted by their values and the expression is evaluated.
If what is any other value, it is returned unchanged.
See also: Parameters
, @alias
, @link
, ModelParam
, update_links!
.
ModelBaseEcon.print_linearized
— Functionprint_linearized(io, model)
print_linearized(model)
Write the system of equations of the linearized model.
ModelBaseEcon.printsstate
— Methodprintsstate([io::IO,] ssd::SteadyStateData)
Display steady state solution.
Steady state solution is presented in a table, where the first column is the name of the variable, the second and third columns are the corresponding values of the level and the slope. If the value is not determined (as per its mask
value) then it is displayed as "*".
ModelBaseEcon.refresh_med!
— Functionrefresh_med!(model)
Refresh the model evaluation data stored within the given model instance. Most notably, this is necessary when the steady state is used in the dynamic equations.
Normally there's no need for the end-used to call this function. It should be called when necessay by the solver.
ModelBaseEcon.selective_linearize!
— Methodselective_linearize!(model)
Instruct the model instance to use selective linearization. Only equations annotated with @lin
in the model definition will be linearized about the current steady state solution while the rest of the eq
ModelBaseEcon.to_exog
— Methodto_exog(v)
Make an exogenous ModelVariable
from v
.
ModelBaseEcon.to_lin
— Methodto_lin(v)
Make a no-transformation ModelVariable
from v
.
ModelBaseEcon.to_log
— Methodto_log(v)
Make a log-transformation ModelVariable
from v
.
ModelBaseEcon.to_neglog
— Methodto_neglog(v)
Make a negative-log-transformation ModelVariable
from v
.
ModelBaseEcon.to_shock
— Methodto_shock(v)
Make a shock ModelVariable
from v
.
ModelBaseEcon.to_steady
— Methodto_steady(v)
Make a zero-slope ModelVariable
from v
.
ModelBaseEcon.transform
— Functiontransform(x, var::ModelVariable)
Apply the transformation associated with model variable m
to data x
.
See also transformation
.
ModelBaseEcon.transformation
— Functiontransformation(::Type{<:Transformation})
Return a Function
that will be substituted into the model equations and will be called to transform the input data before solving. See also inverse_transformation
.
It is expected that transformation(T) ∘ inverse_transformation(T) == identity
and inverse_transformation(T) ∘ transformation(T) == identity
, but these is not verified.
ModelBaseEcon.update_links!
— Methodupdate_links!(model)
update_links!(params)
Recompute the current values of all parameters.
Typically when a new value of a parameter is assigned, all parameter links and aliases that depend on it are updated recursively. If a parameter is mutable, e.g. a Vector or another collection, its value can be updated in place without re-assigning the parameter, thus the automatic update does not happen. In this case, it is necessary to call update_links!
manually.
ModelBaseEcon.with_linearized
— Methodwith_linearized(F::Function, model::Model; <arguments>)
Apply the given function on a new model that is the linear approximation of the given model about its steady state. This is meant to be used with the do
syntax, as in the example below.
Keyword arguments
sstate
- linearize about the provided steady state solutiondeviation
::Bool - whether or not the linearized model will tread data passed
to is as deviation from the steady state
See also: linearize!
and with_linearized
Example
with_linearized(m) do lm
# do something awesome with linearized model `lm`
end
# model `m` is still non-linear.
ModelBaseEcon.@alias
— Macro@alias name
Create a parameter alias. Use @alias
in the @parameters
section of your model definition.
@parameters model begin
a = 5
b = @alias a
end
ModelBaseEcon.@autoexogenize
— Macro@autoexogenize model begin
varname = shkname
...
end
Define a mapping between variables and shocks that can be used to conveniently swap exogenous and endogenous variables.
You can also remove pairs from the model by prefacing each removed pair with @delete
.
ModelBaseEcon.@autoshocks
— Macro@autoshocks model [suffix]
Create a list of shocks that matches the list of variables. Each shock name is created from a variable name by appending suffix. Default suffix is "_shk", but it can be specified as the second argument too.
ModelBaseEcon.@d
— MacroModelBaseEcon.@dlog
— MacroModelBaseEcon.@equations
— Macro@equations model begin
:eqnkey => lhs = rhs
lhs = rhs
...
end
Replace equations with the given keys with the equation provided. Equations provided without a key or with a non-existing key will be added to the model. The keys must be provided with their full symbol reference, including the :
.
To find the key for an equation, see summarize
. For equation details, see Equation
.
Changes like this should be followed by a call to @reinitialize
on the model.
ModelBaseEcon.@exogenous
— Macro@exogenous
Like @variables
, but the names declared with @exogenous
are exogenous.
ModelBaseEcon.@initialize
— Macro@initialize model
Prepare a model instance for analysis. Call this macro after all parameters, variable names, shock names and equations have been declared and defined.
ModelBaseEcon.@lag
— Macro@lag(expr[, n=1])
Apply the lag operator to the given expression.
ModelBaseEcon.@lead
— Macro@lead(expr[, n=1])
Apply the lead operator to the given expression. Equivalent to @lag(expr, -n)
.
ModelBaseEcon.@link
— Macro@link expr
Create a parameter link. Use @link
in the @parameters
section of your model definition.
If your parameter depends on other parameters, then you use @link
to declare that. The expression can be any valid Julia code.
@parameters model begin
a = 5
b = @link a + 1
end
When a parameter the link depends on is assigned a new value, the link that depends on it gets updated automatically.
There are two cases in which the value of a link does not get updated automatically. If the parameter it depends on is mutable, e.g. a Vector
, it is possible for it to get updated in place. The other case is when the link contains global variable or custom function.
In such case, it is necessary to call update_links!
.
ModelBaseEcon.@load_example
— MacroDeprecated. Use @using_example
instead.
ModelBaseEcon.@logvariables
— Macro@logvariables
Same as @variables
, but the variables declared with @logvariables
are log-transformed.
ModelBaseEcon.@movav
— Macro@movav(expr, n)
Apply moving average with n periods backwards on the given expression. For example: @movav(x[t], 3) = (x[t] + x[t-1] + x[t-2]) / 3
.
See also @lag
.
ModelBaseEcon.@movavew
— Macro@movavew(expr, n, r)
Apply moving average with exponential weights with ratio r
. For example: @moveavew(x[t], 3, 0.7) = (x[t] + 0.7*x[t-1] + 0.7^2x[t-2]) / (1 + 0.7 + 0.7^2)
See also @movsumew
ModelBaseEcon.@movavw
— Macro@movavw(expr, n, weights)
@movavw(expr, n, w1, w2, ..., wn)
Apply moving weighted average with n periods backwards to the given expression with the given weights normalized to sum one. For example: @movavw(x[t], w, 2) = (w[1]*x[t] + w[2]*x[t-1])/(w[1]+w[2])
See also @lag
.
ModelBaseEcon.@movsum
— Macro@movsum(expr, n)
Apply moving sum with n periods backwards on the given expression. For example: @movsum(x[t], 3) = x[t] + x[t-1] + x[t-2]
.
See also @lag
.
ModelBaseEcon.@movsumew
— Macro@movsumew(expr, n, r)
Apply moving sum with exponential weights with ratio r
. For example: @movsumew(x[t], 3, 0.7) = x[t] + 0.7*x[t-1] + 0.7^2x[t-2]
See also @movavew
ModelBaseEcon.@movsumw
— Macro@movsumw(expr, n, weights)
Apply moving weighted sum with n periods backwards to the given expression with the given weights. For example: @movsumw(x[t], w, 3) = w[1]*x[t] + w[2]*x[t-1] + w[3]*x[t-2]
See also @lag
.
ModelBaseEcon.@neglogvariables
— Macro@neglogvariables
Same as @variables
, but the variables declared with @neglogvariables
are negative-log-transformed.
ModelBaseEcon.@parameters
— Macro@parameters model begin
name = value
...
end
Declare and define the model parameters.
The parameters must have values. Provide the information in a series of assignment statements wrapped inside a begin-end block. Use @link
and @alias
to define dynamic links. See Parameters
.
ModelBaseEcon.@parameters
— Macroparams = @parameters
When called without any arguments, return an empty Parameters
container, with its evaluation module set to the module in which the macro is being called.
ModelBaseEcon.@peval
— Macro@peval params what
Evaluate the expression what
within the context of the given set of parameters
ModelBaseEcon.@reinitialize
— Macro@reinitialize model
Process the changes made to a model and prepare the model instance for analysis. Call this macro after all changes to parameters, variable names, shock names, equations, autoexogenize lists, and removed steadystate equations have been declared and defined.
Additional/new steadystate constraints can be added after the call to @reinitialize
.
ModelBaseEcon.@replaceparameterlinks
— Macro@replaceparameterlinks model oldmodel => newmodel
This function is used when a model uses parameters which link to another model object. The function must be called with a pair of models as they appear in the Main module.
This is useful when ones models are modularized and include sattelite models. The function can then be used to link the parameters in modified copies of the sattelite model to modified copies of the main model. For example, if the FRBUS_VAR model has a main model and a sattelite model the following workflow would make sense.
using FRBUS_VAR
m = deepcopy(FRBUS_VAR.model)
m_sattelite = deepcopy(FRBUS_VAR.sattelitemodel)
## INSERT CHANGES to m
@reinitialize m
@replaceparameterlinks m_sattelite FRBUS_VAR.model => m
@reinitialize m_sattelite
Changes like this should be followed by a call to @reinitialize
on the model.
ModelBaseEcon.@shocks
— Macro@shocks
Like @variables
, but the names declared with @shocks
are shocks.
ModelBaseEcon.@steadystate
— Macro@steadystate model [type] lhs = rhs
@steadystate model begin
lhs = rhs
@delete _SSEQ1 _SSEQ2
@level lhs = rhs
@slope lhs = rhs
end
@steadystate model @delete _SSEQ1 _SSEQ2
Add a steady state equation to the model.
The steady state system of the model is automatically derived from the dynamic system. Use this macro to define additional equations for the steady state. This is particularly useful in the case of a non-linear model that might have multiple steady state, or the steady state might be difficult to solve for, to help the steady state solver find the one you want to use.
model
is the model instance you want to updatetype
(optional) is the type of constraint you want to add. This can belevel
or slope
. If missing, the default is level
lhs = rhs
is the expression defining the steady state constraint. In the
equation, use variables and shocks from the model, but without any t-references.
There is also a block form of this which allows for several steadystate equations. These can be preceeded by @level or @slope to specify the type. @level is the default. Steadystate equations can also be removed with @delete lines followed by a list of constraint keys.
ModelBaseEcon.@steadyvariables
— Macro@steadyvariables
Same as @variables
, but the variables declared with @steadyvariables
have zero slope in their steady state and final conditions.
ModelBaseEcon.@using_example
— Macro@using_example name
Load models from the package examples/ folder. The @load_example
version is deprecated - stop using it now.
ModelBaseEcon.@variables
— Macro@variables model name1 name2 ...
@variables model begin
name1
name2
...
end
Declare the names of variables in the model.
In the begin-end
version the variable names can be preceeded by a description (like a docstring) and flags like @log
, @steady
, @exog
, etc. See ModelVariable
for details about this.
You can also remove variables from the model by prefacing one or more variables with @delete
.
Options
ModelBaseEcon.OptionsMod
— ModuleOptionsMod
Sub-module of ModelBaseEcon, although it can be used independently. Implements the Options
data structure.
Contents
Options
getoption
- read the value of an optiongetoption!
- if not present, also create an optionsetoption!
- create or update the value of an option
ModelBaseEcon.OptionsMod.Options
— TypeOptions
A collection of key-value pairs representing the options controlling the behaviour or the definition of a Model object. The key is the option name and is always a Symbol, or converted to Symbol, while the value can be anything.
The options can be accessed using dot notation. Functions getoption
and setoption!
are also provided. They can be used for programmatic processing of options as well as when the option name is not a valid Julia identifier.
See also: Options
, getoption
, getoption!
, setoption!
Examples
julia> o = Options(maxiter=20, tol=1e-7)
Options:
maxiter=20
tol=1.0e-7
julia> o.maxiter = 25
25
julia> o
Options:
maxiter=25
tol=1.0e-7
ModelBaseEcon.OptionsMod.Options
— MethodOptions(::Options)
Construct an Options instance as an exact copy of an existing instance.
ModelBaseEcon.OptionsMod.Options
— MethodOptions(key=value, ...)
Options(:key=>value, ...)
Construct an Options instance with key-value pairs given as keyword arguments or as a list of pairs. If the latter is used, each key must be a Symbol
.
ModelBaseEcon.OptionsMod.getoption
— Functiongetoption(o::Options; name=default [, name=default, ...])
getoption(o::Options, name, default)
Retrieve the value of an option or a set of options. The provided defaults are used when the option doesn't exit.
The return value is the value of the option requested or, if the option doesn't exist, the default. In the first version of the function, if there are more than one options requested, the return value is a tuple.
In the second version, the name could be a symbol or a string, which can be helpful if the name of the option is not a valid identifier.
ModelBaseEcon.OptionsMod.getoption!
— Functiongetoption!(o::Options; name=default [, name=default, ...])
getoption!(o::Options, name, default)
Retrieve the value of an option or a set of options. If the name does not match an existing option, the Options instance is updated by inserting the given name and default value.
The return value is the value of the option requested (or the default). In the first version of the function, if there are more than one options requested, the return value is a tuple.
In the second version, the name could be a symbol or a string, which can be helpful if the name of the option is not a valid identifier.
ModelBaseEcon.OptionsMod.setoption!
— Functionsetoption!(o::Options; name=default [, name=default, ...])
setoption!(o::Options, name, default)
Retrieve the value of an option or a set of options. If the name does not match an existing option, the Options instance is updated by inserting the given name and default value.
The return value is the value of the option requested (or the default). In the first version of the function, if there are more than one options requested, the return value is a tuple.
In the second version, the name could be a symbol or a string, which can be helpful if the name of the option is not a valid identifier.
Internals
ModelBaseEcon.AbstractEquation
— Typeabstract type AbstractEquation end
Base type for Equation
.
ModelBaseEcon.AbstractModel
— Typeabstract type AbstractModel end
Base type for Model
.
ModelBaseEcon.AbstractModelEvaluationData
— TypeModelBaseEcon.AbstractParam
— Typeabstract type AbstractParam end
Base type for model parameters.
ModelBaseEcon.EqnFlags
— Typemutable struct EqnFlags ⋯ end
Holds information about the equation. Flags can be specified in the model definition by annotating the equation with @<flag>
(insert the flag you want to raise in place of <flag>
). Multiple flags may be applied to the same equation.
Supported flags:
@log lhs = rhs
instructs the model parser to make the residuallog(lhs / rhs)
. Normally the residual islhs - rhs
.@lin lhs = rhs
marks the equation for selective linearization.
ModelBaseEcon.EqnNotReadyError
— Typestruct EqnNotReadyError <: ModelErrorBase
Concrete error type used to indicate that a given equation has not been prepared for use in the model yet.
ModelBaseEcon.LinearizationError
— TypeLinearizationError <: ModelErrorBase
A concrete error type used when a model cannot be linearized for some reason.
ModelBaseEcon.LinearizedModelEvaluationData
— TypeLinearizedModelEvaluationData <: AbstractModelEvaluationData
Model evaluation data for the linearized model.
ModelBaseEcon.ModelErrorBase
— Typeabstract type ModelErrorBase <: Exception end
Abstract error type, base for specific error types used in ModelBaseEcon.
Implementation (note for developers)
When implementing a derived error type, override two functions:
msg(e::SomeModelError)
returning a string with the error message;hint(e::SomeModelError)
returning a string containing a suggestion of how to fix the problem. Optional, if not implemented for a type, the fallback implementation returns an empty string.
ModelBaseEcon.ModelEvaluationData
— TypeModelEvaluationData <: AbstractModelEvaluationData
The standard model evaluation data used in the general case and by default.
ModelBaseEcon.ModelEvaluationData
— MethodModelEvaluationData(model::AbstractModel)
Create the standard evaluation data structure for the given model.
ModelBaseEcon.ModelFlags
— Typemutable struct ModelFlags ⋯ end
Model flags include
ssZeroSlope
- Set totrue
to instruct the solvers that all variables have zero slope in steady state and final conditions. In other words the model is stationary.
ModelBaseEcon.ModelNotInitError
— Typestruct ModelNotInitError <: ModelErrorBase
Specific error type used when there's an attempt to use a Model object that has not been initialized.
ModelBaseEcon.NotImplementedError
— Typestruct NotImplementedError <: ModelErrorBase
Specific error type used when a feature is planned but not yet implemented.
ModelBaseEcon.SSEqnData
— TypeSSEqnData
Internal structure used for evaluation of the residual of the steady state equation derived from a dynamic equation.
This data type is for internal use only and not intended to be used directly by users.
ModelBaseEcon.SteadyStateVariable
— Typestruct SteadyStateVariable ⋯ end
Holds the steady state solution for one variable, which includes the values of two steady state unknowns - level and slope.
Base.iterate
— Functioniterate(params::Parameters)
Iterates the given Parameters collection in the order of dependency. Specifically, each parameter comes up only after all parameters it depends on have already been visited. The order within that is alphabetical.
ModelBaseEcon.at_d
— FunctionModelBaseEcon.at_dlog
— MethodModelBaseEcon.at_lag
— Methodat_lag(expr[, n=1])
Apply the lag operator to the given expression.
ModelBaseEcon.at_lead
— Functionat_lead(expr[, n=1])
Apply the lead operator to the given expression. Equivalent to at_lag(expr, -n)
.
ModelBaseEcon.at_movav
— Methodat_movav(expr, n)
Apply moving average with n periods backwards on the given expression. For example: at_movav(x[t], 3) = (x[t] + x[t-1] + x[t-2]) / 3
.
See also at_lag
.
ModelBaseEcon.at_movavew
— Methodat_movavew(expr, n, r)
Apply moving average with exponential weights with ratio r
. For example: at_moveavew(x[t], 3, 0.7) = (x[t] + 0.7*x[t-1] + 0.7^2x[t-2]) / (1 + 0.7 + 0.7^2)
See also at_movsumew
ModelBaseEcon.at_movavw
— Methodat_movavw(expr, n, weights)
at_movavw(expr, n, w1, w2, ..., wn)
Apply moving weighted average with n periods backwards to the given expression with the given weights normalized to sum one. For example: at_movavw(x[t], w, 2) = (w[1]*x[t] + w[2]*x[t-1])/(w[1]+w[2])
See also at_lag
.
ModelBaseEcon.at_movsum
— Methodat_movsum(expr, n)
Apply moving sum with n periods backwards on the given expression. For example: at_movsum(x[t], 3) = x[t] + x[t-1] + x[t-2]
.
See also at_lag
.
ModelBaseEcon.at_movsumew
— Methodat_movsumew(expr, n, r)
Apply moving sum with exponential weights with ratio r
. For example: at_movsumew(x[t], 3, 0.7) = x[t] + 0.7*x[t-1] + 0.7^2x[t-2]
See also at_movavew
ModelBaseEcon.at_movsumw
— Methodat_movsumw(expr, n, weights)
Apply moving weighted sum with n periods backwards to the given expression with the given weights. For example: at_movsumw(x[t], w, 3) = w[1]*x[t] + w[2]*x[t-1] + w[3]*x[t-2]
See also at_lag
.
ModelBaseEcon.delete_aux_equations!
— Methoddelete_aux_equations!(m::Model, eqn_key::Symbol)
Removes the aux equations associated with a given equation from the model.
ModelBaseEcon.equation_map
— Methodequation_map(e::Model)
Returns a dictionary with the keys being the symbols used in the models equations and the values being a vector of equation keys for equations which use these symbols.
ModelBaseEcon.equation_symbols
— Methodequation_symbols(e::Equation)
The a vector of symbols of the non-mathematical arguments in the provided equation.
ModelBaseEcon.find_symbols!
— Methodfind_symbols!(dest::Vector, v::Vector{Any})
Take a vector of equation arguments and add the non-mathematical ones to the destination vector.
ModelBaseEcon.funcsyms
— Functionfuncsyms(mod::Module)
Create a pair of identifiers that does not conflict with existing identifiers in the given module.
Internal function. Do not call directly.
Implementation (for developers)
We need two identifiers resid_N
and RJ_N
where "N" is some integer number. The first is going to be the name of the function that evaluates the equation and the second is going to be the name of the function that evaluates both the equation and its gradient.
ModelBaseEcon.get_aux_equation_keys
— Methodget_aux_equation_keys(m::Model, eqn_key::Symbol)
Returns a vector of symbol keys for the Aux equations used for the given equation.
ModelBaseEcon.get_next_equation_name
— Functionget_next_equation_name(eqns::OrderedDict{Symbol,Equation})
Returns the next available equation name of the form :_EQ#
. The initial guess is at the number of equations + 1.
ModelBaseEcon.hint
— Methodhint(::ModelErrorBase)
Return the hint message - a suggestion of how the problem might be fixed.
ModelBaseEcon.initfuncs
— Methodinitfuncs(mod::Module)
Initialize the given module before creating functions that evaluate residuals and thier gradients.
Internal function. Do not call directly.
Implementation (for developers)
Declare the necessary types in the module where the model is being defined. There are two such types. First is EquationEvaluator
, which is callable and stores a collection of parameters. The call will be defined in makefuncs
and will evaluate the residual. The other type is EquationGradient
, which is also callable and stores the EquationEvaluator
together with a DiffResult
and a GradientConfig
used by ForwardDiff
. Its call is defined here and computes the residual and the gradient.
ModelBaseEcon.initialize!
— Methodinitialize!(model, modelmodule)
In the model file, after all declarations of flags, parameters, variables, and equations are done, it is necessary to initialize the model instance. Usually it is easier to call @initialize
, which automatically sets the modelmodule
value. When it is necessary to set the modelmodule
argument to some other module, then this can be done by calling this function instead of the macro.
ModelBaseEcon.initssdata!
— Methodinitssdata!(m::AbstractModel)
Create and initialize the SteadyStateData
structure of the given model.
This function is for internal use only and not intended to be called directly by users. It is called during @initialize
.
ModelBaseEcon.make_sseqn
— Functionmake_sseqn(model::AbstractModel, eqn::Equation, shift::Bool, eqn_name::Symbol, var_to_idx)
Create a steady state equation from the given dynamic equation for the given model.
This function is for internal use only and not intended to be called directly by users.
ModelBaseEcon.makefuncs
— Methodmakefuncs(expr, tssyms, sssyms, psyms, mod)
Create two functions that evaluate the residual and its gradient for the given expression.
Internal function. Do not call directly.
Arguments
expr
: the expressiontssyms
: list of time series variable symbolssssyms
: list of steady state symbolspsyms
: list of parameter symbols
Return value
Return a quote block to be evaluated in the module where the model is being defined. The quote block contains definitions of the residual function (as a callable EquationEvaluator
instance) and a second function that evaluates both the residual and its gradient (as a callable EquationGradient
instance).
ModelBaseEcon.modelerror
— Functionmodelerror(ME::Type{<:ModelErrorBase}, args...; kwargs...)
Raise an exception derived from ModelErrorBase
.
ModelBaseEcon.moduleof
— Functionmoduleof(equation)
moduleof(model)
Return the module in which the given equation or model was initialized.
ModelBaseEcon.msg
— Functionmsg(::ModelErrorBase)
Return the error message - a description of what went wrong.
ModelBaseEcon.precompile_dual_funcs
— Methodprecompilefuncs(N::Int)
Pre-compiles functions used by models for a ForwardDiff.Dual
numbers with chunk size N
.
Internal function. Do not call directly
ModelBaseEcon.precompilefuncs
— Methodprecompilefuncs(resid, RJ, resid_param, N::Int)
Pre-compiles the given resid
and RJ
functions together with the dual-number arithmetic required by ForwardDiff.
Internal function. Do not call directly
ModelBaseEcon.prettyprint_equation
— Methodprettyprint_equation(m::Model, eq::Equation; target::Symbol, eq_symbols::Vector{Any}=[])
Print the provided equation with the variables colored according to their type.
Keyword arguments
* `m`::Model - The model which contains the variables and equations.
* `eq`::Equation - The equation in question
* `target`::Symbol - if provided, the specified symbol will be presented in bright green.
* `eq_symbols`::Vector{Any} - a vector of symbols present in the equation. Can slightly speed up processing if provided.
ModelBaseEcon.process_equation
— Functionprocess_equation(model::Model, expr; <keyword arguments>)
Process the given expression in the context of the given model and create an Equation() instance for it.
This function is for internal use only and should not be called directly.
ModelBaseEcon.reinitialize!
— Methodreinitialize!(model, modelmodule)
In the model file, after all changes to flags, parameters, variables, shocks, autoexogenize pairs, equations, and steadystate equations are done, it is necessary to reinitialize the model instance. Usually it is easier to call @reinitialize
, which automatically sets the modelmodule
value. When it is necessary to set the modelmodule
argument to some other module, then this can be done by calling this function instead of the macro.
ModelBaseEcon.setss!
— Methodsetss!(model::AbstractModel, expr::Expr; type::Symbol, modelmodule::Module, eqn_key=:_undefined_, var_to_idx=get_var_to_idx(model))
Add a steady state equation to the model. Equations added by setss!
are in addition to the equations generated automatically from the dynamic system.
This function is for internal use only and not intended to be called directly by users. Use @steadystate
instead of calling this function.
ModelBaseEcon.sseqn_resid_RJ
— Methodsseqn_resid_RJ(sed::SSEqnData)
Create the eval_resid
and eval_RJ
for a steady state equation derived from a dynamic equation using information from the given SSEqnData
.
This function is for internal use only and not intended to be called directly by users.
ModelBaseEcon.update_auxvars
— Methodupdate_auxvars(point, model; tol=model.tol, default=0.0)
Calculate the values of auxiliary variables from the given values of regular variables and shocks.
Auxiliary variables were introduced as substitutions, e.g. log(expression) was replaced by aux1 and equation was added exp(aux1) = expression, where expression contains regular variables and shocks.
This function uses the auxiliary equation to compute the value of the auxiliary variable for the given values of other variables. Note that the given values of other variables might be inadmissible, in the sense that expression is negative. If that happens, the auxiliary variable is set to the given default
value.
If the point
array does not contain space for the auxiliary variables, it is extended appropriately.
If there are no auxiliary variables/equations in the model, return a copy of point
.
The current implementation is specialized only to log substitutions. TODO: implement a general approach that would work for any substitution.
ModelBaseEcon.updatessdata!
— Methodupdatessdata!(m::AbstractModel)
SteadyStateData
structure of the given model during reinitialization.
This function is for internal use only and not intended to be called directly by users. It is called during @reinitialize
.
Options
Base.merge!
— Methodmerge!(o1::Options, o2::Options...)
Update the first argument, adding all options from the remaining arguments. If the same option exists in multiple places, use the last one.
Base.merge
— Methodmerge(o1::Options, o2::Options, ...)
Merge the given Options instances into a new Options instance. If the same option key exists in more than one instance, keep the value from the last one.