Beispiel #1
0
def solve_something(name, args):

    from dolo.misc.yamlfile import yaml_import
    from dolo.numeric.global_solve import global_solve
    model = yaml_import('examples/global_models/{}.yaml'.format(name))
    dr = global_solve(model, **args)
    return dr
Beispiel #2
0
    def test_omega_errors(self):

        from dolo.misc.yamlfile import yaml_import
        from dolo.numeric.global_solve import global_solve

        model = yaml_import('examples/global_models/rbc.yaml')
        from dolo.compiler.converter import GModel_fg_from_fga
        model = GModel_fg_from_fga( model )

        from dolo.numeric.perturbations_to_states import approximate_controls

        dr = approximate_controls(model)
        dr_global = global_solve(model, smolyak_order=4, verbose=False, pert_order=1, method='newton', polish=True)


        sigma = model.calibration['covariances']

        # cmodel = CModel(model)

        model.sigma = sigma

        s_0 = dr.S_bar

        from dolo.numeric.error_measures import  omega
        res = omega( dr, model, dr_global.bounds, [10,10], time_weight=[50, 0.96,s_0])
Beispiel #3
0
def solve_something(name, args):

    from dolo.misc.yamlfile import yaml_import
    from dolo.numeric.global_solve import global_solve
    model = yaml_import('examples/global_models/{}.yaml'.format(name))
    dr = global_solve(model, **args)
    return dr
Beispiel #4
0
    def test_denhaan_errors(self):

        from dolo.misc.yamlfile import yaml_import
        from dolo.numeric.global_solve import global_solve

        model = yaml_import('examples/global_models/rbc.yaml')


        from dolo.compiler.compiler_global import CModel
        from dolo.numeric.perturbations_to_states import approximate_controls

        dr = approximate_controls(model)
        dr_global = global_solve(model, smolyak_order=4, verbose=False, pert_order=1, method='newton', polish=True)


        sigma = model.calibration['covariances']

        model.sigma = sigma

        s_0 = dr.S_bar

        from dolo.numeric.error_measures import denhaanerrors

        [error_1, error_2] = denhaanerrors(model, dr, s_0)
        [error_1_glob, error_2_glob] = denhaanerrors(model, dr_global, s_0)

        print(error_1)
        print(error_1_glob)
        assert( max(error_1_glob) < 10-7) # errors with solyak colocations at order 4 are very small
        assert( max(error_2_glob) < 10-7)
Beispiel #5
0
    def test_omega_errors(self):

        from dolo.misc.yamlfile import yaml_import
        from dolo.numeric.global_solve import global_solve

        model = yaml_import('examples/global_models/rbc.yaml')
        from dolo.compiler.converter import GModel_fg_from_fga
        model = GModel_fg_from_fga(model)

        from dolo.numeric.perturbations_to_states import approximate_controls

        dr = approximate_controls(model)
        dr_global = global_solve(model,
                                 smolyak_order=4,
                                 verbose=False,
                                 pert_order=1,
                                 method='newton',
                                 polish=True)

        sigma = model.calibration['covariances']

        # cmodel = CModel(model)

        model.sigma = sigma

        s_0 = dr.S_bar

        from dolo.numeric.error_measures import omega
        res = omega(dr,
                    model,
                    dr_global.bounds, [10, 10],
                    time_weight=[50, 0.96, s_0])
    def test_second_order_accuracy(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('examples/global_models/rbc.yaml', compiler=None)


        from dolo.numeric.perturbations import solve_decision_rule
        from dolo.numeric.perturbations_to_states import approximate_controls


        coeffs = approximate_controls(model,order=2, return_dr=False)
        state_perturb = coeffs[0]

        dr = solve_decision_rule(model)
        statefree_perturb = dr['ys'] + dr['g_ss']/2.0
        ctls = model.symbols_s['controls']
        ctls_ind = [model.variables.index(v) for v in ctls]

        # the two methods should yield exactly the same result

        from numpy.testing import assert_almost_equal
        A = statefree_perturb[ctls_ind]
        B = state_perturb

        assert_almost_equal(A, B)  # we compare the risk-adjusted constants
Beispiel #7
0
    def test_denhaan_errors(self):

        from dolo.misc.yamlfile import yaml_import
        from dolo.numeric.global_solve import global_solve

        model = yaml_import('examples/global_models/rbc.yaml')

        from dolo.compiler.compiler_global import CModel
        from dolo.numeric.perturbations_to_states import approximate_controls

        dr = approximate_controls(model)
        dr_global = global_solve(model,
                                 smolyak_order=4,
                                 verbose=False,
                                 pert_order=1,
                                 method='newton',
                                 polish=True)

        sigma = model.calibration['covariances']

        model.sigma = sigma

        s_0 = dr.S_bar

        from dolo.numeric.error_measures import denhaanerrors

        [error_1, error_2] = denhaanerrors(model, dr, s_0)
        [error_1_glob, error_2_glob] = denhaanerrors(model, dr_global, s_0)

        print(error_1)
        print(error_1_glob)
        assert (max(error_1_glob) < 10 - 7
                )  # errors with solyak colocations at order 4 are very small
        assert (max(error_2_glob) < 10 - 7)
    def test_perturbation(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('../examples/global_models/optimal_growth.yaml')

        from dolo.numeric.perturbations_to_states import approximate_controls

        [Xbar, X_s,X_ss]  = approximate_controls(model,2)
        state_perturb = Xbar


        from dolo.numeric.perturbations import solve_decision_rule
        dr = solve_decision_rule(model)
        statefree_perturb = dr['ys'] + dr['g_ss']/2.0
        ctls = model['variables_groups']['controls'] + model['variables_groups']['expectations']
        ctls_ind = [model.variables.index(v) for v in ctls]

        # the two methods should yield exactly the same result

        from numpy.testing import assert_almost_equal
        A = statefree_perturb[ctls_ind]
        B = state_perturb

        assert_almost_equal(A, B)
Beispiel #9
0
    def test_perturbation(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('../examples/global_models/optimal_growth.yaml')

        from dolo.numeric.perturbations_to_states import approximate_controls

        [Xbar, X_s, X_ss] = approximate_controls(model, 2)
        state_perturb = Xbar

        from dolo.numeric.perturbations import solve_decision_rule
        dr = solve_decision_rule(model)
        statefree_perturb = dr['ys'] + dr['g_ss'] / 2.0
        ctls = model['variables_groups']['controls'] + model[
            'variables_groups']['expectations']
        ctls_ind = [model.variables.index(v) for v in ctls]

        # the two methods should yield exactly the same result

        from numpy.testing import assert_almost_equal
        A = statefree_perturb[ctls_ind]
        B = state_perturb

        assert_almost_equal(A, B)
Beispiel #10
0
    def test_second_order_accuracy(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('examples/global_models/rbc.yaml', compiler=None)

        from dolo.numeric.perturbations import solve_decision_rule
        from dolo.numeric.perturbations_to_states import approximate_controls

        coeffs = approximate_controls(model, order=2, return_dr=False)
        state_perturb = coeffs[0]

        dr = solve_decision_rule(model)
        statefree_perturb = dr['ys'] + dr['g_ss'] / 2.0
        ctls = model.symbols_s['controls']
        ctls_ind = [model.variables.index(v) for v in ctls]

        # the two methods should yield exactly the same result

        from numpy.testing import assert_almost_equal
        A = statefree_perturb[ctls_ind]
        B = state_perturb

        assert_almost_equal(A, B)  # we compare the risk-adjusted constants
Beispiel #11
0
    def test_higher_order_perturbation(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('../examples/global_models/optimal_growth.yaml')

        from dolo.numeric.perturbations_to_states import approximate_controls

        [Xbar, X_s, X_ss, X_sss] = approximate_controls(model, 3)
    def test_higher_order_perturbation(self):

        # This solves the optimal growth example at second order
        # and computes the second order correction to the steady-state
        # We test that both the statefree method and the perturbation to states
        # yield the same result.

        from dolo.misc.yamlfile import yaml_import
        model = yaml_import('../examples/global_models/optimal_growth.yaml')

        from dolo.numeric.perturbations_to_states import approximate_controls

        [Xbar,X_s,X_ss,X_sss]  = approximate_controls(model,3)
Beispiel #13
0
    # model2 = model.copy()
    #
    # print( model2 == model )
    # print(model.symbols)
    # print(model)

    # filename = '../../examples/dynare_modfiles/example1.mod'
    # filename = '/home/pablo/Documents/Research/CGR/revival/CKM.mod'

    filename = '../../examples/global_models/rbc.yaml'

    # from dolo.misc.modfile import dynare_import
    # model = dynare_import(filename)

    from dolo.misc.yamlfile import yaml_import
    model = yaml_import(filename)


    from dolo import global_solve
    dr = global_solve(model)

    from dolo.numeric.perturbations import solve_decision_rule

    print(model)

    model2 = model.copy()

    model2.set_calibration({'beta':0.95})

    print(model.calibration)
    print(model2.calibration)
Beispiel #14
0
 def test_perturbation_3(self):
     from dolo.misc.yamlfile import yaml_import
     from dolo.numeric.perturbations_to_states import approximate_controls
     model = yaml_import('examples/global_models/rbc.yaml')
     dr = approximate_controls(model, order=3)
 def test_perturbation_3(self):
     from dolo.misc.yamlfile import yaml_import
     from dolo.numeric.perturbations_to_states import approximate_controls
     model = yaml_import('examples/global_models/rbc.yaml')
     dr = approximate_controls(model,order=3)
Beispiel #16
0
    def main(argv):
        if len(argv) < 1:
            print("Not enough arguments.")
            print('')
            usage()

            sys.exit(2)

        # Read options
        options = {
            "check": False,
            "ramsey": False,
            "dynare": False,
            "output": False,
            "static-order": 2,
            "dynamic-order": 1,
            "mirfac": False,
            'target': 'recs',
            'solve': False
        }
        short_arg_dict = "hcdrom"
        long_arg_dict = [
            "help", "check", "dynare", "static-order=", "dynamic-order=",
            "output=", "ramsey", "mirfac", "target=", 'solve'
        ]
        try:
            opts, args = getopt.getopt(argv, short_arg_dict, long_arg_dict)
        except getopt.GetoptError:
            usage()
            sys.exit(2)
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                usage()
                sys.exit()
            if opt in ("-d", "--dynare"):
                options["dynare"] = True
            if opt in ("-c", "--check"):
                options["check"] = True
            if opt in ("-r", "--ramsey"):
                options["ramsey"] = True
            if opt in ("-o", "--output"):
                options["output"] = True
            if opt in ("--dynare", ):
                options["dynare"]
            if opt in ("--static-order", ):
                options["static-order"] = int(arg)
            if opt in ("--dynamic-order", ):
                options["dynamic-order"] = int(arg)
            if opt in ("--mirfac", '-m'):
                options["mirfac"] = True
            if opt in ("--target"):
                options["target"] = arg
            if opt in ("--solve"):
                options["solve"] = True
                print arg

        if args == []:
            print("File argument missing")
            sys.exit()
        else:
            filename = args[0]

        # determine filename type
        regex_mod = re.compile("(.*)\.mod")
        regex_mod_match = re.match(regex_mod, filename)
        if regex_mod_match:
            filetype = "mod"
            filename_trunc = regex_mod_match.groups()[0]

        regex_yaml = re.compile("(.*)\.yaml")
        regex_yaml_match = re.match(regex_yaml, filename)
        if regex_yaml_match:
            filetype = "yaml"
            filename_trunc = regex_yaml_match.groups()[0]

        current_dir = os.getcwd()
        filename_trunc = current_dir + '/' + filename_trunc

        if filetype == "":
            print("Unknown filetype")
            sys.exit(2)

        # Import the model
        if filetype == "mod":
            model = dynare_import(filename)

        elif filetype == "yaml":
            from dolo.misc.yamlfile import yaml_import
            model = yaml_import(filename)

        model.check_consistency(verbose=True)

        #elif filetype == "xml":
        #    import_xmlfile(filename_trunc,options)

        # Process the model
        if options['ramsey']:
            from dolo.symbolic.ramsey import RamseyModel
            #dynare_model.introduce_auxiliary_variables()
            model.check()

            rmodel = RamseyModel(dynare_model)
            rmodel.check(verbose=True)
            options['output'] = True
            dynare_model = rmodel

        if options['output']:
            from dolo.compiler.compiler_dynare import DynareCompiler
            comp = DynareCompiler(model)
            comp.export_to_modfile()

        if options['dynare']:
            from dolo.compiler.compiler_dynare import DynareCompiler

            comp = DynareCompiler(model)

            write_file(
                model.fname + '_dynamic.m',
                comp.compute_dynamic_mfile(max_order=options["dynamic-order"]))
            write_file(
                model.fname + '_static.m',
                comp.compute_static_mfile(max_order=options["static-order"]))
            write_file(model.fname + '.m', comp.compute_main_file())

        if options['mirfac']:
            from dolo.compiler.compiler_mirfac import MirFacCompiler

            mirfac_target = options['target']
            comp = MirFacCompiler(model)

            if mirfac_target == 'recs':
                out_txt = comp.process_output_matlab(
                    mirfac_target,
                    with_parameters_values=True,
                    with_solution=options['solve'])
            else:
                out_txt = comp.process_output_matlab_old(
                    mirfac_target,
                    with_parameters_values=True,
                    with_solution=options['solve'])

            write_file('{0}_{1}.m'.format(model.fname, mirfac_target), out_txt)
Beispiel #17
0
    def sigma(self):
        return self.model.read_covariances()

    @property
    def parameters(self):
        return self.model.read_calibration()[2]


if __name__  == '__main__':

    from dolo.misc.yamlfile import yaml_import
    from dolo.numeric.perturbations_to_states import approximate_controls
    from dolo.numeric.global_solve import global_solve


    model = yaml_import( 'examples/global_models/rbc_fgah.yaml')
    model_bis = yaml_import( 'examples/global_models/rbc.yaml')

    print(model)
    print(model)

    dr_pert = approximate_controls(model_bis)

    cm = CModel_fgah(model)


    cm_fg = cm.as_type('fg')


    import time
Beispiel #18
0
    #
    # print( model2 == model )
    # print(model.symbols)
    # print(model)

    # filename = '../../examples/dynare_modfiles/example1.mod'
    # filename = '/home/pablo/Documents/Research/CGR/revival/CKM.mod'

    filename = "../../examples/global_models/rbc.yaml"

    # from dolo.misc.modfile import dynare_import
    # model = dynare_import(filename)

    from dolo.misc.yamlfile import yaml_import

    model = yaml_import(filename)

    from dolo import global_solve

    dr = global_solve(model)

    from dolo.numeric.perturbations import solve_decision_rule

    print(model)

    model2 = model.copy()

    model2.set_calibration({"beta": 0.95})

    print(model.calibration)
    print(model2.calibration)
Beispiel #19
0
######

input_file = args.input
if args.output:
    output_filename = args.output
    output_rad = output_filename.strip('.m')
else:  # we should determine some good output name in case none has been specified
    output_rad = input_file.strip('.yaml') + '_model'
    output_filename = output_rad + '.m'

######

from dolo.misc.yamlfile import yaml_import

model = yaml_import(input_file)

import os
import re

basename = os.path.basename(output_filename)
fname = re.compile('(.*)\.m').match(basename).group(1)
model['name'] = fname

# check steady-state
if args.print_residuals:
    from dolo.symbolic.model import print_residuals
    print_residuals(model)

from dolo.compiler.compiler_matlab import CompilerMatlab
comp = CompilerMatlab(model)