Пример #1
0
def solve_recursive_block(equations):
    from dolo.symbolic.symbolic import Equation
    system = {eq.lhs: eq.rhs for eq in equations}
    from dolo.misc.triangular_solver import solve_triangular_system
    sol = solve_triangular_system(system)
    solved_equations = [Equation(eq.lhs, sol[eq.lhs]) for eq in equations]
    return solved_equations
Пример #2
0
    def read_calibration(self, to_numpy=True):
        model = self
        from dolo.misc.triangular_solver import solve_triangular_system

        dvars = dict()
        dvars.update(model.parameters_values)
        dvars.update(model.init_values)
        for v in model.variables:
            if v not in dvars:
                dvars[v] = 0
        undeclared_parameters = []
        for p in model.parameters:
            if p not in dvars:
                undeclared_parameters.append(p)
                dvars[p] = 0
                raise Warning(
                    'No initial value for parameters : ' +
                    str.join(', ', [p.name for p in undeclared_parameters]))

        values = solve_triangular_system(dvars)

        y = [values[v] for v in model.variables]
        x = [0 for s in model.shocks]
        params = [values[v] for v in model.parameters]
        resp = [y, x, params]
        if to_numpy:
            import numpy
            return [numpy.array(e, dtype=numpy.float64) for e in resp]
        else:
            return resp
Пример #3
0
    def read_calibration(self,to_numpy=True):
        model = self
        from dolo.misc.triangular_solver import solve_triangular_system

        dvars = dict()
        dvars.update(model.parameters_values)
        dvars.update(model.init_values)
        for v in model.variables:
            if v not in dvars:
                dvars[v] = 0
        undeclared_parameters = []
        for p in model.parameters:
            if p not in dvars:
                undeclared_parameters.append(p)
                dvars[p] = 0
                raise Warning('No initial value for parameters : ' + str.join(', ', [p.name for p in undeclared_parameters]) )

        values = solve_triangular_system(dvars)

        y = [values[v] for v in model.variables]
        x = [0 for s in model.shocks]
        params = [values[v] for v in model.parameters]
        resp = [y,x,params]
        if to_numpy:
            import numpy
            return [numpy.array(e, dtype=numpy.float64) for e in resp]
        else:
            return resp
Пример #4
0
def solve_recursive_block(equations):
    from dolo.symbolic.symbolic import Equation
    system = {eq.lhs: eq.rhs for eq in equations}
    from dolo.misc.triangular_solver import solve_triangular_system
    sol = solve_triangular_system(system)
    solved_equations = [Equation(eq.lhs, sol[eq.lhs]) for eq in equations]
    return solved_equations
    def test_solve_symbolic_system(self):
        from dolo.misc.triangular_solver import solve_triangular_system

        import sympy
        [w, x, y, z, t] = vars = sympy.symbols('w, x, y, z, t')

        eqs = [x + y + z + t, y + z, z, 1, 1]

        sdict = {s: eqs[i] for i, s in enumerate(vars)}

        solution = solve_triangular_system(sdict)

        assert (solution[z] == 1)
        assert (solution[t] == 1)
        assert (solution[y] == 1)
        assert (solution[x] == 2)
        assert (solution[w] == 5)
Пример #6
0
    def update(self):

        """Propagates changes in symbolic structure"""
        self.symbols = OrderedDict(
            (k, tuple(str(h) for h in v)) for k, v in self.symbols_s.iteritems()
        )  # dict: string -> (list: sympy)

        l = []
        for e in self.symbols_s.keys():
            if e not in ("shocks", "parameters"):
                l.extend(self.symbols_s[e])

        # for backward compatibility
        self.variables = l
        self.shocks = self.symbols_s["shocks"]
        self.parameters = self.symbols_s["parameters"]

        # update calibration
        from dolo.misc.triangular_solver import solve_triangular_system

        calibration_dict = solve_triangular_system(self.calibration_s)  # calibration dict : sympy -> float
        self.calibration_dict = calibration_dict

        calibration = OrderedDict()  # calibration dict (by group) : string -> ( sympy -> float )

        for vg in self.symbols_s:
            vars = self.symbols_s[vg]
            values = [(float(calibration_dict[v]) if v in calibration_dict else nan) for v in vars]
            calibration[vg] = numpy.array(values, dtype=floatX)

        sigma = self.covariances_s.subs(self.calibration_s)
        sigma = numpy.array(sigma).astype(floatX)

        calibration["covariances"] = sigma
        self.calibration = calibration
        self.sigma = sigma

        l = []
        for eqg, eq in self.equations_groups.iteritems():
            l.extend(eq)
        self.equations = l
Пример #7
0
    def update(self):

        '''Propagates changes in symbolic structure'''
        self.symbols = OrderedDict( (k, tuple(str(h) for h in v) ) for k,v in self.symbols_s.iteritems() )                  # dict: string -> (list: sympy)

        l = []
        for e in self.symbols_s.keys():
            if e not in ('shocks','parameters'):
                l.extend(self.symbols_s[e])

        # for backward compatibility
        self.variables = l
        self.shocks = self.symbols_s['shocks']
        self.parameters = self.symbols_s['parameters']


        # update calibration
        from dolo.misc.triangular_solver import solve_triangular_system
        calibration_dict = solve_triangular_system(self.calibration_s) # calibration dict : sympy -> float
        self.calibration_dict = calibration_dict

        calibration = OrderedDict()  # calibration dict (by group) : string -> ( sympy -> float )

        for vg in self.symbols_s:
            vars = self.symbols_s[vg]
            values = [ (float(calibration_dict[v]) if v in calibration_dict else nan) for v in vars]
            calibration[vg] = numpy.array( values, dtype=floatX )

        sigma = self.covariances_s.subs(self.calibration_s)
        sigma = numpy.array( sigma ).astype( floatX )

        calibration['covariances'] = sigma
        self.calibration = calibration
        self.sigma = sigma


        l = []
        for eqg,eq in self.equations_groups.iteritems():
            l.extend(eq)
        self.equations = l
Пример #8
0
    def read_covariances(self, to_numpy=True):

        # TODO: we could return a dict instead

        # duplicated code
        model = self
        from dolo.misc.triangular_solver import solve_triangular_system
        dvars = dict()
        dvars.update(model.parameters_values)
        dvars.update(model.init_values)
        for v in model.variables:
            if v not in dvars:
                dvars[v] = 0
        undeclared_parameters = []
        for p in model.parameters:
            if p not in dvars:
                undeclared_parameters.append(p)
                dvars[p] = 0
                raise Warning(
                    'No initial value for parameters : ' +
                    str.join(', ', [p.name for p in undeclared_parameters]))

        values = solve_triangular_system(dvars)

        if 'covariances' in self and self['covariances'] is not None:
            m = self['covariances']
            m = m.subs(values)
        else:
            m = sympy.zeros((len(self.shocks), ) * 2)

        import numpy
        resp = numpy.array(m).astype(numpy.float)

        if to_numpy:
            import numpy
            return numpy.array(resp, dtype=numpy.float64)
        else:
            return resp
Пример #9
0
    def test_solve_symbolic_system(self):
        from dolo.misc.triangular_solver import solve_triangular_system

        import sympy
        [w,x,y,z,t] = vars = sympy.symbols('w, x, y, z, t')

        eqs = [
            x + y + z + t,
            y + z,
            z,
            1,
            1
        ]

        sdict = {s:eqs[i] for i,s in enumerate(vars) }

        solution = solve_triangular_system(sdict)

        assert(solution[z]==1)
        assert(solution[t]==1)
        assert(solution[y]==1)
        assert(solution[x]==2)
        assert(solution[w]==5)
Пример #10
0
    def read_covariances(self,to_numpy=True):

        # TODO: we could return a dict instead

        # duplicated code
        model = self
        from dolo.misc.triangular_solver import solve_triangular_system
        dvars = dict()
        dvars.update(model.parameters_values)
        dvars.update(model.init_values)
        for v in model.variables:
            if v not in dvars:
                dvars[v] = 0
        undeclared_parameters = []
        for p in model.parameters:
            if p not in dvars:
                undeclared_parameters.append(p)
                dvars[p] = 0
                raise Warning('No initial value for parameters : ' + str.join(', ', [p.name for p in undeclared_parameters]) )

        values = solve_triangular_system(dvars)

        if 'covariances' in self and self['covariances'] is not None:
            m = self['covariances']
            m = m.subs(values)
        else:
            m = sympy.zeros( (len(self.shocks),)*2 )

        import numpy
        resp = numpy.array(m).astype(numpy.float)

        if to_numpy:
            import numpy
            return numpy.array(resp, dtype=numpy.float64)
        else:
            return resp
Пример #11
0
def simple_global_representation(self,
                                 allow_future_shocks=True,
                                 solve_systems=False):

    resp = {}
    eq_g = self.equations_groups
    v_g = self.symbols_s
    if 'expectation' in eq_g:
        resp['f_eqs'] = [
            eq.gap for eq in eq_g['arbitrage'] + eq_g['expectation']
        ]  # TODO: complementarity conditions
        resp['controls'] = v_g['controls'] + v_g['expectations']
    else:
        resp['f_eqs'] = [eq.gap for eq in eq_g['arbitrage']
                         ]  # TODO: complementarity conditions
        resp['controls'] = list(v_g['controls'])

    resp['g_eqs'] = [eq.rhs for eq in eq_g['transition']]

    if 'auxiliary' in eq_g:

        sdict = {}
        from dolo.symbolic.symbolic import timeshift
        auxies = list(eq_g['auxiliary'])
        if 'auxiliary_2' in eq_g:
            auxies += list(eq_g['auxiliary_2'])
        for eq in auxies:
            sdict[eq.lhs] = eq.rhs
            sdict[eq.lhs(1)] = timeshift(eq.rhs, 1)
            sdict[eq.lhs(-1)] = timeshift(eq.rhs, -1)
        from dolo.misc.triangular_solver import solve_triangular_system
        sdict = solve_triangular_system(sdict)
        resp['a_eqs'] = [sdict[v] for v in v_g['auxiliary']]
        resp['auxiliaries'] = [v for v in v_g['auxiliary']]
        resp['f_eqs'] = [eq.subs(sdict) for eq in resp['f_eqs']]
        resp['g_eqs'] = [eq.subs(sdict) for eq in resp['g_eqs']]

    elif 'auxiliary_2' in eq_g:
        sdict = {}
        from dolo.misc.misc import timeshift
        auxies = eq_g['auxiliary_2']
        for eq in auxies:
            sdict[eq.lhs] = eq.rhs
            sdict[eq.lhs(1)] = timeshift(eq.rhs, 1)
            sdict[eq.lhs(-1)] = timeshift(eq.rhs, -1)
        from dolo.misc.calculus import simple_triangular_solve
        sdict = simple_triangular_solve(sdict)
        resp['f_eqs'] = [eq.subs(sdict) for eq in resp['f_eqs']]
        resp['g_eqs'] = [eq.subs(sdict) for eq in resp['g_eqs']]

    if not allow_future_shocks:
        # future shocks are replaced by 0
        zero_shocks = {s(1): 0 for s in self.shocks}
        resp['f_eqs'] = [eq.subs(zero_shocks) for eq in resp['f_eqs']]

    if solve_systems:
        from dolo.misc.triangular_solver import solve_triangular_system
        system = {s: resp['g_eqs'][i] for i, s in enumerate(v_g['states'])}
        new_geqs = solve_triangular_system(system)
        resp['g_eqs'] = [new_geqs[s] for s in v_g['states']]

    resp['states'] = v_g['states']
    resp['shocks'] = self.shocks  #['shocks_ordering'] # TODO: bad
    resp['parameters'] = self.parameters  #['parameters_ordering']

    return resp
    ]

    from sympy import exp

    eqs = [
        x + y*k_2 + z*exp(x_1 + t),
        (y + z)**0.3,
        z,
        (k_1 + k_2)**0.3,
        k_2**x_1
    ]

    sdict = {s:eqs[i] for i,s in enumerate(vars) }

    from dolo.misc.triangular_solver import solve_triangular_system
    order = solve_triangular_system(sdict, return_order=True)

    ordered_vars  = [ v for v in order ]
    ordered_eqs = [ eqs[vars.index(v)] for v in order ]

    pprint(ordered_vars)
    pprint(ordered_eqs)


    import numpy

    floatX = numpy.float32
    s0 = numpy.array( [2,5], dtype=floatX)
    x0 = numpy.array( [2,2], dtype=floatX)
    p0 = numpy.array( [4,3], dtype=floatX)
Пример #13
0
    def export_to_modfile(
        self, output_file=None, return_text=False, options={}, append="", comments="", solve_init_state=False
    ):

        model = self.model
        # init_state = self.get_init_dict()

        default = {"steady": False, "check": False, "dest": "dynare", "order": 1, "use_dll": False}  # default options
        for o in default:
            if not o in options:
                options[o] = default[o]

        init_block = ["// Generated by Dolo"]
        init_block.append("// Model basename : " + self.model.fname)
        init_block.append(comments)
        init_block.append("")
        init_block.append("var " + str.join(",", map(str, self.model.variables)) + ";")
        init_block.append("")
        init_block.append("varexo " + str.join(",", map(str, self.model.shocks)) + ";")
        init_block.append("")
        init_block.append("parameters " + str.join(",", map(str, self.model.parameters)) + ";")

        init_state = model.parameters_values.copy()
        init_state.update(model.init_values.copy())

        from dolo.misc.triangular_solver import solve_triangular_system

        if not solve_init_state:
            itd = model.init_values
            order = solve_triangular_system(init_state, return_order=True)
        else:
            itd, order = solve_triangular_system(init_state)

        for p in order:
            if p in model.parameters:
                # init_block.append(p.name + " = " + str(init_state[p]) + ";")
                if p in model.parameters_values:
                    init_block.append(p.name + " = " + str(model.parameters_values[p]).replace("**", "^") + ";")

        printer = CustomPrinter()
        model_block = []
        if options["use_dll"]:
            model_block.append("model(use_dll);")
        else:
            model_block.append("model;")
        for eq in self.model.equations:
            s = printer.doprint(eq)
            s = s.replace("==", "=")
            s = s.replace("**", "^")
            #            s = s.replace("_b1","(-1)") # this should allow lags more than 1
            #            s = s.replace("_f1","(+1)") # this should allow lags more than 1
            model_block += "\n"
            if "name" in eq.tags:
                model_block.append("// eq %s : %s" % (eq.n, eq.tags.get("name")))
            else:
                model_block.append("// eq %s" % (eq.n))
            if len(eq.tags) > 0:
                model_block.append("[ {0} ]".format(" , ".join(["{0} = '{1}'".format(k, eq.tags[k]) for k in eq.tags])))
            model_block.append(s + ";")
        model_block.append("end;")

        if options["dest"] == "dynare":
            shocks_block = []
            if model.covariances != None:
                shocks_block.append("shocks;")
                cov_shape = model.covariances.shape
                for i in range(cov_shape[0]):
                    for j in range(i, cov_shape[1]):
                        cov = model.covariances[i, j]
                        if cov != 0:
                            tcov = str(cov).replace("**", "^")
                            if i == j:
                                shocks_block.append("var " + str(self.model.shocks[i]) + " = " + tcov + " ;")
                            else:
                                shocks_block.append(
                                    "var "
                                    + str(self.model.shocks[i])
                                    + ","
                                    + str(self.model.shocks[j])
                                    + " = "
                                    + tcov
                                    + " ;"
                                )
                shocks_block.append("end;")
        elif options["dest"] == "dynare++":
            shocks_block = []
            shocks_block.append("vcov = [")
            cov_shape = self.covariances.shape
            shocks_matrix = []
            for i in range(cov_shape[0]):
                shocks_matrix.append(" ".join(map(str, self.covariances[i, :])))
            shocks_block.append(";\n".join(shocks_matrix))
            shocks_block.append("];")

        initval_block = []
        if len(model.init_values) > 0:
            initval_block.append("initval;")
            for v in order:
                if v in model.init_values:
                    initval_block.append(str(v) + " = " + str(itd[v]).replace("**", "^") + ";")
                elif options["dest"] == "dynare++":
                    # dynare++ doesn't default to zero for non initialized variables
                    initval_block.append(str(v) + " = 0 ;")
            initval_block.append("end;")
        # else:
        # itd = self.get_init_dict()
        # initval_block = []
        # initval_block.append("initval;")
        # for v in self.model.variables:
        # if v in self.init_values:
        # initval_block.append(str(v) + " = " + str(itd[v]) +  ";")
        # initval_block.append("end;")
        model_text = ""
        model_text += "\n".join(init_block)
        model_text += "\n\n" + "\n".join(model_block)
        model_text += "\n\n" + "\n".join(shocks_block)
        model_text += "\n\n" + "\n".join(initval_block)

        if options["steady"] and options["dest"] == "dynare":
            model_text += "\n\nsteady;\n"

        if options["check"] and options["dest"] == "dynare":
            model_text += "\n\ncheck;\n"

        if options["dest"] == "dynare++":
            model_text += "\n\norder = " + str(options["order"]) + ";\n"

        model_text += "\n" + append

        if output_file == None:
            output_file = self.model.fname + ".mod"
        if output_file != False:
            f = file(output_file, "w")
            f.write(model_text)
            f.close()

        if return_text:
            return model_text
        else:
            return None
Пример #14
0
    def compute_main_file(self, omit_nnz=True):
        model = self.model

        # should be computed somewhere else
        all_symbols = set([])
        for eq in model.equations:
            all_symbols.update(eq.atoms())
        format_dict = dict()
        format_dict["fname"] = model.fname
        format_dict["maximum_lag"] = max([-v.lag for v in all_symbols if isinstance(v, TSymbol)])
        format_dict["maximum_lead"] = max([v.lag for v in all_symbols if isinstance(v, TSymbol)])
        format_dict["maximum_endo_lag"] = max([-v.lag for v in all_symbols if isinstance(v, Variable)])
        format_dict["maximum_endo_lead"] = max([v.lag for v in all_symbols if isinstance(v, Variable)])
        format_dict["maximum_exo_lag"] = max([-v.lag for v in all_symbols if isinstance(v, Shock)])
        format_dict["maximum_exo_lead"] = max([v.lag for v in all_symbols if isinstance(v, Shock)])
        format_dict["endo_nbr"] = len(model.variables)
        format_dict["exo_nbr"] = len(model.shocks)
        format_dict["param_nbr"] = len(model.parameters)

        output = """%
% Status : main Dynare file
%
% Warning : this file is generated automatically by Dolo for Dynare
%           from model file (.mod)

clear all
tic;
global M_ oo_ options_
global ys0_ ex0_ ct_
options_ = [];
M_.fname = '{fname}';
%
% Some global variables initialization
%
global_initialization;
diary off;
warning_old_state = warning;
warning off;
delete {fname}.log;
warning warning_old_state;
logname_ = '{fname}.log';
diary {fname}.log;
options_.model_mode = 0;
erase_compiled_function('{fname}_static');
erase_compiled_function('{fname}_dynamic');

M_.exo_det_nbr = 0;
M_.exo_nbr = {exo_nbr};
M_.endo_nbr = {endo_nbr};
M_.param_nbr = {param_nbr};
M_.Sigma_e = zeros({exo_nbr}, {exo_nbr});
M_.exo_names_orig_ord = [1:{exo_nbr}];
""".format(
            **format_dict
        )

        string_of_names = lambda l: str.join(" , ", ["'%s'" % str(v) for v in l])
        string_of_tex_names = lambda l: str.join(" , ", ["'%s'" % v._latex_() for v in l])
        output += "M_.exo_names = strvcat( {0} );\n".format(string_of_names(model.shocks))
        output += "M_.exo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.shocks))
        output += "M_.endo_names = strvcat( {0} );\n".format(string_of_names(model.variables))
        output += "M_.endo_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.variables))
        output += "M_.param_names = strvcat( {0} );\n".format(string_of_names(model.parameters))
        output += "M_.param_names_tex = strvcat( {0} );\n".format(string_of_tex_names(model.parameters))

        from dolo.misc.matlab import value_to_mat

        lli = value_to_mat(self.lead_lag_incidence_matrix())
        output += "M_.lead_lag_incidence = {0}';\n".format(lli)

        output += """M_.maximum_lag = {maximum_lag};
M_.maximum_lead = {maximum_lead};
M_.maximum_endo_lag = {maximum_endo_lag};
M_.maximum_endo_lead = {maximum_endo_lead};
M_.maximum_exo_lag = {maximum_exo_lag};
M_.maximum_exo_lead = {maximum_exo_lead};
oo_.steady_state = zeros({endo_nbr}, 1);
oo_.exo_steady_state = zeros({exo_nbr}, 1);
M_.params = repmat(NaN,{param_nbr}, 1);
""".format(
            **format_dict
        )

        # Now we add tags for equations
        tags_array_string = []
        for eq in model.equations:
            for k in eq.tags.keys():
                tags_array_string.append("{n}, '{key}', '{value}'".format(n=eq.n, key=k, value=eq.tags[k]))
        output += "M_.equations_tags = {{\n{0}\n}};\n".format(";\n".join(tags_array_string))

        if not omit_nnz:
            # we don't set the number of non zero derivatives yet
            order = max([ndt.depth() for ndt in self.dynamic_derivatives])
            output += "M_.NNZDerivatives = zeros({0}, 1); % parrot mode\n".format(order)
            output += "M_.NNZDerivatives(1) = {0}; % parrot mode\n".format(self.NNZDerivatives(1))
            output += "M_.NNZDerivatives(2) = {0}; % parrot mode\n".format(self.NNZDerivatives(2))
            output += "M_.NNZDerivatives(3) = {0}; % parrot mode\n".format(self.NNZDerivatives(3))

        idp = DicPrinter(self.static_substitution_list(y="oo_.steady_state", params="M_.params"))

        # BUG: how do we treat parameters absent from the model, but present in parameters_values ?

        from dolo.misc.triangular_solver import solve_triangular_system

        [junk, porder] = solve_triangular_system(model.parameters_values)
        porder = [p for p in porder if p in model.parameters]

        d = dict()
        d.update(model.parameters_values)
        d.update(model.init_values)

        [junk, vorder] = solve_triangular_system(model.init_values)
        vorder = [v for v in vorder if p in model.variables]

        for p in porder:
            i = model.parameters.index(p) + 1
            output += "M_.params({0}) = {1};\n".format(i, idp.doprint_matlab(model.parameters_values[p]))
            output += "{0} = M_.params({1});\n".format(p, i)

        output += """%
% INITVAL instructions
%
"""
        # idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params'))
        output += "options_.initval_file = 0; % parrot mode\n"
        for v in vorder:
            if v in self.model.variables:  # should be removed
                i = model.variables.index(v) + 1
                output += "oo_.steady_state({0}) = {1};\n".format(i, idp.doprint_matlab(model.init_values[v]))
        # we don't allow initialization of shocks to nonzero values
        output += "oo_.exo_steady_state = zeros({0},1);\n".format(len(model.shocks))
        output += """oo_.endo_simul=[oo_.steady_state*ones(1,M_.maximum_lag)];
if M_.exo_nbr > 0;
    oo_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];
end;
if M_.exo_det_nbr > 0;
    oo_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];
end;
"""
        # output += '''steady;
        output += """
%
% SHOCKS instructions
%
make_ex_;
M_.exo_det_length = 0; % parrot
"""

        for i in range(model.covariances.shape[0]):
            for j in range(model.covariances.shape[1]):
                expr = model.covariances[i, j]
                if expr != 0:
                    v = str(expr).replace("**", "^")
                    # if (v != 0) and not isinstance(v,sympy.core.numbers.Zero):
                    output += "M_.Sigma_e({0}, {1}) = {2};\n".format(i + 1, j + 1, v)

        # This results from the stoch_simul(
        #        output += '''options_.drop = 200;
        # options_.order = 3;
        # var_list_=[];
        # info = stoch_simul(var_list_);
        #'''
        #
        #        output += '''save('example2_results.mat', 'oo_', 'M_', 'options_');
        # diary off
        #
        # disp(['Total computing time : ' dynsec2hms(toc) ]);'''

        f = file(model.fname + ".m", "w")
        f.write(output)
        f.close()

        return output
Пример #15
0
    def compute_main_file(self, omit_nnz=True):
        model = self.model

        # should be computed somewhere else
        all_symbols = set([])
        for eq in model.equations:
            all_symbols.update(eq.atoms())
        format_dict = dict()
        format_dict['fname'] = model.fname
        format_dict['maximum_lag'] = max(
            [-v.lag for v in all_symbols if isinstance(v, TSymbol)])
        format_dict['maximum_lead'] = max(
            [v.lag for v in all_symbols if isinstance(v, TSymbol)])
        format_dict['maximum_endo_lag'] = max(
            [-v.lag for v in all_symbols if isinstance(v, Variable)])
        format_dict['maximum_endo_lead'] = max(
            [v.lag for v in all_symbols if isinstance(v, Variable)])
        format_dict['maximum_exo_lag'] = max(
            [-v.lag for v in all_symbols if isinstance(v, Shock)])
        format_dict['maximum_exo_lead'] = max(
            [v.lag for v in all_symbols if isinstance(v, Shock)])
        format_dict['endo_nbr'] = len(model.variables)
        format_dict['exo_nbr'] = len(model.shocks)
        format_dict['param_nbr'] = len(model.parameters)

        output = """%
% Status : main Dynare file
%
% Warning : this file is generated automatically by Dolo for Dynare
%           from model file (.mod)

clear all
tic;
global M_ oo_ options_
global ys0_ ex0_ ct_
options_ = [];
M_.fname = '{fname}';
%
% Some global variables initialization
%
global_initialization;
diary off;
warning_old_state = warning;
warning off;
delete {fname}.log;
warning warning_old_state;
logname_ = '{fname}.log';
diary {fname}.log;
options_.model_mode = 0;
erase_compiled_function('{fname}_static');
erase_compiled_function('{fname}_dynamic');

M_.exo_det_nbr = 0;
M_.exo_nbr = {exo_nbr};
M_.endo_nbr = {endo_nbr};
M_.param_nbr = {param_nbr};
M_.Sigma_e = zeros({exo_nbr}, {exo_nbr});
M_.exo_names_orig_ord = [1:{exo_nbr}];
""".format(**format_dict)

        string_of_names = lambda l: str.join(' , ',
                                             ["'%s'" % str(v) for v in l])
        string_of_tex_names = lambda l: str.join(
            ' , ', ["'%s'" % v._latex_() for v in l])
        output += "M_.exo_names = strvcat( {0} );\n".format(
            string_of_names(model.shocks))
        output += "M_.exo_names_tex = strvcat( {0} );\n".format(
            string_of_tex_names(model.shocks))
        output += "M_.endo_names = strvcat( {0} );\n".format(
            string_of_names(model.variables))
        output += "M_.endo_names_tex = strvcat( {0} );\n".format(
            string_of_tex_names(model.variables))
        output += "M_.param_names = strvcat( {0} );\n".format(
            string_of_names(model.parameters))
        output += "M_.param_names_tex = strvcat( {0} );\n".format(
            string_of_tex_names(model.parameters))

        from dolo.misc.matlab import value_to_mat
        lli = value_to_mat(self.lead_lag_incidence_matrix())
        output += "M_.lead_lag_incidence = {0}';\n".format(lli)

        output += """M_.maximum_lag = {maximum_lag};
M_.maximum_lead = {maximum_lead};
M_.maximum_endo_lag = {maximum_endo_lag};
M_.maximum_endo_lead = {maximum_endo_lead};
M_.maximum_exo_lag = {maximum_exo_lag};
M_.maximum_exo_lead = {maximum_exo_lead};
oo_.steady_state = zeros({endo_nbr}, 1);
oo_.exo_steady_state = zeros({exo_nbr}, 1);
M_.params = repmat(NaN,{param_nbr}, 1);
""".format(**format_dict)

        # Now we add tags for equations
        tags_array_string = []
        for eq in model.equations:
            for k in eq.tags.keys():
                tags_array_string.append("{n}, '{key}', '{value}'".format(
                    n=eq.n, key=k, value=eq.tags[k]))
        output += "M_.equations_tags = {{\n{0}\n}};\n".format(
            ";\n".join(tags_array_string))

        if not omit_nnz:
            # we don't set the number of non zero derivatives yet
            order = max([ndt.depth() for ndt in self.dynamic_derivatives])
            output += "M_.NNZDerivatives = zeros({0}, 1); % parrot mode\n".format(
                order)
            output += "M_.NNZDerivatives(1) = {0}; % parrot mode\n".format(
                self.NNZDerivatives(1))
            output += "M_.NNZDerivatives(2) = {0}; % parrot mode\n".format(
                self.NNZDerivatives(2))
            output += "M_.NNZDerivatives(3) = {0}; % parrot mode\n".format(
                self.NNZDerivatives(3))

        idp = DicPrinter(
            self.static_substitution_list(y='oo_.steady_state',
                                          params='M_.params'))

        # BUG: how do we treat parameters absent from the model, but present in parameters_values ?

        from dolo.misc.triangular_solver import solve_triangular_system

        [junk, porder] = solve_triangular_system(model.parameters_values)
        porder = [p for p in porder if p in model.parameters]

        d = dict()
        d.update(model.parameters_values)
        d.update(model.init_values)

        [junk, vorder] = solve_triangular_system(model.init_values)
        vorder = [v for v in vorder if p in model.variables]

        for p in porder:
            i = model.parameters.index(p) + 1
            output += "M_.params({0}) = {1};\n".format(
                i, idp.doprint_matlab(model.parameters_values[p]))
            output += "{0} = M_.params({1});\n".format(p, i)

        output += '''%
% INITVAL instructions
%
'''
        #idp = DicPrinter(self.static_substitution_list(y='oo_.steady_state',params='M_.params'))
        output += "options_.initval_file = 0; % parrot mode\n"
        for v in vorder:
            if v in self.model.variables:  # should be removed
                i = model.variables.index(v) + 1
                output += "oo_.steady_state({0}) = {1};\n".format(
                    i, idp.doprint_matlab(model.init_values[v]))
        # we don't allow initialization of shocks to nonzero values
        output += "oo_.exo_steady_state = zeros({0},1);\n".format(
            len(model.shocks))
        output += '''oo_.endo_simul=[oo_.steady_state*ones(1,M_.maximum_lag)];
if M_.exo_nbr > 0;
    oo_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];
end;
if M_.exo_det_nbr > 0;
    oo_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];
end;
'''
        #output += '''steady;
        output += """
%
% SHOCKS instructions
%
make_ex_;
M_.exo_det_length = 0; % parrot
"""

        for i in range(model.covariances.shape[0]):
            for j in range(model.covariances.shape[1]):
                expr = model.covariances[i, j]
                if expr != 0:
                    v = str(expr).replace("**", "^")
                    #if (v != 0) and not isinstance(v,sympy.core.numbers.Zero):
                    output += "M_.Sigma_e({0}, {1}) = {2};\n".format(
                        i + 1, j + 1, v)

        # This results from the stoch_simul(


#        output += '''options_.drop = 200;
#options_.order = 3;
#var_list_=[];
#info = stoch_simul(var_list_);
#'''
#
#        output += '''save('example2_results.mat', 'oo_', 'M_', 'options_');
#diary off
#
#disp(['Total computing time : ' dynsec2hms(toc) ]);'''

        f = file(model.fname + '.m', 'w')
        f.write(output)
        f.close()

        return output
Пример #16
0
    def export_to_modfile(self,
                          output_file=None,
                          return_text=False,
                          options={},
                          append="",
                          comments="",
                          solve_init_state=False):

        model = self.model
        #init_state = self.get_init_dict()

        default = {
            'steady': False,
            'check': False,
            'dest': 'dynare',
            'order': 1,
            'use_dll': False
        }  #default options
        for o in default:
            if not o in options:
                options[o] = default[o]

        init_block = ["// Generated by Dolo"]
        init_block.append("// Model basename : " + self.model.fname)
        init_block.append(comments)
        init_block.append("")
        init_block.append("var " +
                          str.join(",", map(str, self.model.variables)) + ";")
        init_block.append("")
        init_block.append("varexo " +
                          str.join(",", map(str, self.model.shocks)) + ";")
        init_block.append("")
        init_block.append("parameters " +
                          str.join(",", map(str, self.model.parameters)) + ";")

        init_state = model.parameters_values.copy()
        init_state.update(model.init_values.copy())

        from dolo.misc.triangular_solver import solve_triangular_system
        if not solve_init_state:
            itd = model.init_values
            order = solve_triangular_system(init_state, return_order=True)
        else:
            itd, order = solve_triangular_system(init_state)

        for p in order:
            if p in model.parameters:
                #init_block.append(p.name + " = " + str(init_state[p]) + ";")
                if p in model.parameters_values:
                    init_block.append(
                        p.name + " = " +
                        str(model.parameters_values[p]).replace('**', '^') +
                        ";")

        printer = CustomPrinter()
        model_block = []
        if options['use_dll']:
            model_block.append("model(use_dll);")
        else:
            model_block.append("model;")
        for eq in self.model.equations:
            s = printer.doprint(eq)
            s = s.replace("==", "=")
            s = s.replace("**", "^")
            #            s = s.replace("_b1","(-1)") # this should allow lags more than 1
            #            s = s.replace("_f1","(+1)") # this should allow lags more than 1
            model_block += "\n"
            if 'name' in eq.tags:
                model_block.append("// eq %s : %s" %
                                   (eq.n, eq.tags.get('name')))
            else:
                model_block.append("// eq %s" % (eq.n))
            if len(eq.tags) > 0:
                model_block.append("[ {0} ]".format(" , ".join(
                    ["{0} = '{1}'".format(k, eq.tags[k]) for k in eq.tags])))
            model_block.append(s + ";")
        model_block.append("end;")

        if options['dest'] == 'dynare':
            shocks_block = []
            if model.covariances != None:
                shocks_block.append("shocks;")
                cov_shape = model.covariances.shape
                for i in range(cov_shape[0]):
                    for j in range(i, cov_shape[1]):
                        cov = model.covariances[i, j]
                        if cov != 0:
                            tcov = str(cov).replace('**', '^')
                            if i == j:
                                shocks_block.append("var " +
                                                    str(self.model.shocks[i]) +
                                                    " = " + tcov + " ;")
                            else:
                                shocks_block.append("var " +
                                                    str(self.model.shocks[i]) +
                                                    "," +
                                                    str(self.model.shocks[j]) +
                                                    " = " + tcov + " ;")
                shocks_block.append("end;")
        elif options['dest'] == 'dynare++':
            shocks_block = []
            shocks_block.append("vcov = [")
            cov_shape = self.covariances.shape
            shocks_matrix = []
            for i in range(cov_shape[0]):
                shocks_matrix.append(" ".join(map(str,
                                                  self.covariances[i, :])))
            shocks_block.append(";\n".join(shocks_matrix))
            shocks_block.append("];")

        initval_block = []
        if len(model.init_values) > 0:
            initval_block.append("initval;")
            for v in order:
                if v in model.init_values:
                    initval_block.append(
                        str(v) + " = " + str(itd[v]).replace('**', '^') + ";")
                elif options['dest'] == 'dynare++':
                    # dynare++ doesn't default to zero for non initialized variables
                    initval_block.append(str(v) + " = 0 ;")
            initval_block.append("end;")
        #else:
        #itd = self.get_init_dict()
        #initval_block = []
        #initval_block.append("initval;")
        #for v in self.model.variables:
        #if v in self.init_values:
        #initval_block.append(str(v) + " = " + str(itd[v]) +  ";")
        #initval_block.append("end;")
        model_text = ""
        model_text += "\n".join(init_block)
        model_text += "\n\n" + "\n".join(model_block)
        model_text += "\n\n" + "\n".join(shocks_block)
        model_text += "\n\n" + "\n".join(initval_block)

        if options['steady'] and options['dest'] == 'dynare':
            model_text += "\n\nsteady;\n"

        if options['check'] and options['dest'] == 'dynare':
            model_text += "\n\ncheck;\n"

        if options['dest'] == 'dynare++':
            model_text += "\n\norder = " + str(options['order']) + ";\n"

        model_text += "\n" + append

        if output_file == None:
            output_file = self.model.fname + '.mod'
        if output_file != False:
            f = file(output_file, 'w')
            f.write(model_text)
            f.close()

        if return_text:
            return (model_text)
        else:
            return None
Пример #17
0
def simple_global_representation(self, allow_future_shocks=True, solve_systems=False):


    resp = {}
    eq_g = self['equations_groups']
    v_g = self['variables_groups']
    if 'expectation' in eq_g:
        resp['f_eqs'] = [ eq.gap for eq in  eq_g['arbitrage'] + eq_g['expectation']] # TODO: complementarity conditions
        resp['controls'] = v_g['controls'] + v_g['expectations']
    else:
        resp['f_eqs'] = [ eq.gap for eq in  eq_g['arbitrage']] # TODO: complementarity conditions
        resp['controls'] = list( v_g['controls'] )

    resp['g_eqs'] = [eq.rhs for eq in  eq_g['transition'] ]


    if 'auxiliary' in eq_g:

        sdict = {}
        from dolo.symbolic.symbolic import timeshift
        auxies = list( eq_g['auxiliary'] )
        if 'auxiliary_2' in eq_g:
            auxies += list( eq_g['auxiliary_2'] )
        for eq in  auxies:
            sdict[eq.lhs] = eq.rhs
            sdict[eq.lhs(1)] = timeshift( eq.rhs, 1)
            sdict[eq.lhs(-1)] = timeshift( eq.rhs, -1)
        from dolo.misc.triangular_solver import solve_triangular_system
        sdict = solve_triangular_system(sdict)
        resp['a_eqs'] = [sdict[v] for v in v_g['auxiliary']]
        resp['auxiliaries'] = [v for v in v_g['auxiliary']]
        resp['f_eqs'] = [eq.subs(sdict) for eq in resp['f_eqs']]
        resp['g_eqs'] = [eq.subs(sdict) for eq in resp['g_eqs']]

    elif 'auxiliary_2' in eq_g:
        sdict = {}
        from dolo.misc.misc import timeshift
        auxies = eq_g['auxiliary_2']
        for eq in  auxies:
            sdict[eq.lhs] = eq.rhs
            sdict[eq.lhs(1)] = timeshift( eq.rhs, 1)
            sdict[eq.lhs(-1)] = timeshift( eq.rhs, -1)
        from dolo.misc.calculus import simple_triangular_solve
        sdict = simple_triangular_solve(sdict)
        resp['f_eqs'] = [eq.subs(sdict) for eq in resp['f_eqs']]
        resp['g_eqs'] = [eq.subs(sdict) for eq in resp['g_eqs']]


    if not allow_future_shocks:
        # future shocks are replaced by 0
        zero_shocks = {s(1):0 for s in self.shocks}
        resp['f_eqs'] = [ eq.subs(zero_shocks) for eq in resp['f_eqs'] ]

    if solve_systems:
        from dolo.misc.triangular_solver import solve_triangular_system
        system = {s: resp['g_eqs'][i] for i,s in enumerate(v_g['states'])}
        new_geqs = solve_triangular_system(system)
        resp['g_eqs'] = [new_geqs[s] for s in v_g['states']]

    resp['states'] = v_g['states']
    resp['shocks'] = self.shocks #['shocks_ordering'] # TODO: bad
    resp['parameters'] = self.parameters #['parameters_ordering']

    return resp
    ]

    from sympy import exp

    eqs = [
        x + y*k_2 + z*exp(x_1 + t),
        (y + z)**0.3,
        z,
        (k_1 + k_2)**0.3,
        k_2**x_1
    ]

    sdict = {s:eqs[i] for i,s in enumerate(vars) }

    from dolo.misc.triangular_solver import solve_triangular_system
    order = solve_triangular_system(sdict, return_order=True)

    ordered_vars  = [ v for v in order ]
    ordered_eqs = [ eqs[vars.index(v)] for v in order ]

    pprint(ordered_vars)
    pprint(ordered_eqs)



    #    f = create_fun()
    #
    #    test = f(s1,x1,p0)
    #    print(test)
    args_names = ['s','x']
    #