Ejemplo n.º 1
0
def deterministic_solve(model, start_s, T=500):

    # simulation is assumed to return to steady-state

    dr = approximate_controls(model, order=1,   )

    final_s = model.calibration['states'].copy()
    final_x = model.calibration['controls'].copy()
    start_x = dr( numpy.atleast_2d( start_s.ravel()).T ).flatten()

    final = numpy.concatenate( [final_s, final_x])
    start = numpy.concatenate( [start_s, start_x])

    print(final)
    print(start)

    n_s = len(final_s)
    n_x = len(final_x)

    initial_guess = numpy.concatenate( [start*(1-l) + final*l for l in linspace(0.0,1.0,T+1)] )

    initial_guess = initial_guess.reshape( (-1, n_s + n_x)).T

    # initial_guess = initial_guess[n_s:-n_x]



    res = det_residual(model, initial_guess, start_s, final_x)

    print(abs(res).max())

    sh = initial_guess.shape


    sh = initial_guess.shape

    fobj = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x).ravel()

    res = fobj( initial_guess.ravel() )
    from scipy.optimize import newton_krylov, fsolve

    import time
    t = time.time()
    sol = fsolve(fobj, initial_guess.ravel() )
    sol = sol.reshape(sh)

    print(fobj(sol))
    # sol = newton_krylov(fobj, initial_guess)

    s = time.time()
    print('Elapsed : {}'.format(s-t))

    return sol
Ejemplo n.º 2
0
def deterministic_solve(model, start_s, T=500):

    # simulation is assumed to return to steady-state

    dr = approximate_controls(model, order=1)

    final_s = model.calibration["states"].copy()
    final_x = model.calibration["controls"].copy()
    start_x = dr(numpy.atleast_2d(start_s.ravel()).T).flatten()

    final = numpy.concatenate([final_s, final_x])
    start = numpy.concatenate([start_s, start_x])

    print(final)
    print(start)

    n_s = len(final_s)
    n_x = len(final_x)

    initial_guess = numpy.concatenate([start * (1 - l) + final * l for l in linspace(0.0, 1.0, T + 1)])

    initial_guess = initial_guess.reshape((-1, n_s + n_x)).T

    # initial_guess = initial_guess[n_s:-n_x]

    res = det_residual(model, initial_guess, start_s, final_x)

    print(abs(res).max())

    sh = initial_guess.shape

    sh = initial_guess.shape

    fobj = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x).ravel()

    res = fobj(initial_guess.ravel())
    from scipy.optimize import newton_krylov, fsolve

    import time

    t = time.time()
    sol = fsolve(fobj, initial_guess.ravel())
    sol = sol.reshape(sh)

    print(fobj(sol))
    # sol = newton_krylov(fobj, initial_guess)

    s = time.time()
    print("Elapsed : {}".format(s - t))

    return sol
Ejemplo n.º 3
0
def test_eval_formula():

    from dolo.compiler.eval_formula import eval_formula
    from dolo import yaml_import, approximate_controls, simulate

    model = yaml_import('examples/models/rbc.yaml')
    dr = approximate_controls(model)
    sim = simulate(model, dr)

    rr = eval_formula("delta*k-i", sim, context=model.calibration)
    rr = eval_formula("y(1) - y", sim, context=model.calibration)

    sim['diff'] = model.eval_formula("delta*k-i", sim)
    model.eval_formula("y(1) - y", sim)
    sim['ddiff'] = model.eval_formula("diff(1)-diff(-1)", sim)
Ejemplo n.º 4
0
def test_simulations():

    from dolo import yaml_import, approximate_controls
    model = yaml_import('../../examples/models/rbc.yaml')

    dr = approximate_controls(model)

    parms = model.calibration['parameters']
    sigma = model.covariances

    import numpy

    s0 = dr.S_bar

    horizon = 50

    import time
    t1 = time.time()
    simul = simulate(model, dr, s0, sigma, n_exp=1000, parms=parms, seed=1, horizon=horizon)
    t2 = time.time()

    print("Took: {}".format(t2-t1))


    from dolo.numeric.discretization import gauss_hermite_nodes
    N = 80
    [x,w] = gauss_hermite_nodes(N, sigma)


    t3 = time.time()
    simul_2 = simulate(model, dr, s0, sigma, n_exp=1000, parms=parms, horizon=horizon, seed=1, solve_expectations=True, nodes=x, weights=w)
    t4 = time.time()

    print("Took: {}".format(t4-t3))

    from matplotlib.pyplot import hist, show, figure, plot, title


    timevec = numpy.array(range(simul.shape[2]))


    figure()
    for k in range(10):
        plot(simul[:,k,0] - simul_2[:,k,0])
    title("Productivity")
    show()

    figure()
    for k in range(10):
        plot(simul[:,k,1] - simul_2[:,k,1])
    title("Investment")
    show()

#
#    figure()
#    plot(simul[0,0,:])
#    plot(simul_2[0,0,:])
#    show()

    figure()
    for i in range( horizon ):
        hist( simul[i,:,0], bins=50 )

    show()
Ejemplo n.º 5
0
def deterministic_solve_comp(model, start_s, T=10):

    # simulation is assumed to return to steady-state

    dr = approximate_controls(model, order=1,   )

    final_s = model.calibration['states'].copy()
    final_x = model.calibration['controls'].copy()
    start_x = dr( numpy.atleast_2d( start_s.ravel()).T ).flatten()

    final = numpy.concatenate( [final_s, final_x])
    start = numpy.concatenate( [start_s, start_x])

    print(final)
    print(start)

    n_s = len(final_s)
    n_x = len(final_x)

    initial_guess = numpy.concatenate( [start*(1-l) + final*l for l in linspace(0.0,1.0,T+1)] )

    initial_guess = initial_guess.reshape( (-1, n_s + n_x)).T
    N = initial_guess.shape[1]

    initial_guess = numpy.row_stack( [initial_guess, numpy.zeros( (n_x, N) ), numpy.zeros( (n_x, N) )] )

    # initial_guess = initial_guess[n_s:-n_x]

    lower_bound = initial_guess*0
    lower_bound[:n_s+n_x,:] = -big_number
    lower_bound[:,-1] = -big_number

    upper_bound = lower_bound*0 + big_number

    print( sum( (upper_bound - initial_guess)<=0 ) )
    print( sum( (lower_bound - initial_guess)>0 ) )


    res = det_residual_comp(model, initial_guess, start_s, final_x)

    print(abs(res).max())

    sh = initial_guess.shape

    fobj = lambda vec: det_residual_comp(model, vec, start_s, final_x)
    fobj = lambda vec: det_residual_comp(model, vec.reshape(sh), start_s, final_x).ravel()

    from dolo.numeric.solver import MyJacobian
    #
    dres = MyJacobian(fobj)(initial_guess.ravel())
    #
    # print(dres.shape)
    # print(numpy.linalg.matrix_rank(dres))

    f = lambda x: [fobj(x), MyJacobian(fobj)(x)]

    import time
    t = time.time()

    initial_guess = initial_guess.ravel()
    lower_bound = lower_bound.ravel()
    upper_bound = upper_bound.ravel()

    from dolo.numeric.ncpsolve import ncpsolve
    sol = ncpsolve( f, lower_bound, upper_bound, initial_guess, verbose=True)
    # from dolo.numeric.solver import solver
    # sol = solver(fobj, initial_guess, lb=lower_bound, ub=upper_bound, serial_problem=False, method='ncpsolve', verbose=True)

    print(sol.shape)

    s = time.time()
    print('Elapsed : {}'.format(s-t))

    return sol[:n_s+n_x,:]
Ejemplo n.º 6
0
        if isinstance(plot_controls, str):
            i = controls_names.index(plot_controls)
            pyplot.plot(values, xvec[i, :], **kwargs)
        else:
            for cn in plot_controls:
                i = controls_names.index(cn)
                pyplot.plot(values, xvec[i, :], label=cn)
            pyplot.legend()
        pyplot.xlabel(state)


if __name__ == '__main__':
    from dolo import yaml_import, approximate_controls
    model = yaml_import('../../examples/global_models/capital.yaml')

    dr = approximate_controls(model)

    [y, x, parms] = model.read_calibration()
    sigma = model.read_covariances()

    from dolo.compiler.compiler_global import CModel

    import numpy
    cmodel = CModel(model)
    s0 = numpy.atleast_2d(dr.S_bar).T
    horizon = 50

    simul = simulate(cmodel,
                     dr,
                     s0,
                     sigma,
Ejemplo n.º 7
0
            i = controls_names.index(plot_controls)
            pyplot.plot(values, xvec[i,:], **kwargs)
        else:
            for cn in  plot_controls:
                i = controls_names.index(cn)
                pyplot.plot(values, xvec[i,:], label=cn)
            pyplot.legend()
        pyplot.xlabel(state)



if __name__ == '__main__':
    from dolo import yaml_import, approximate_controls
    model = yaml_import('../../examples/global_models/capital.yaml')

    dr = approximate_controls(model)

    [y,x,parms] = model.read_calibration()
    sigma = model.read_covariances()

    from dolo.compiler.compiler_global import CModel

    import numpy
    cmodel = CModel(model)
    s0 = numpy.atleast_2d( dr.S_bar ).T
    horizon = 50

    simul = simulate(cmodel, dr, s0, sigma, n_exp=500, parms=parms, seed=1, horizon=horizon)


Ejemplo n.º 8
0
def deterministic_solve_comp(model, start_s, T=10):

    # simulation is assumed to return to steady-state

    dr = approximate_controls(model, order=1)

    final_s = model.calibration["states"].copy()
    final_x = model.calibration["controls"].copy()
    start_x = dr(numpy.atleast_2d(start_s.ravel()).T).flatten()

    final = numpy.concatenate([final_s, final_x])
    start = numpy.concatenate([start_s, start_x])

    print(final)
    print(start)

    n_s = len(final_s)
    n_x = len(final_x)

    initial_guess = numpy.concatenate([start * (1 - l) + final * l for l in linspace(0.0, 1.0, T + 1)])

    initial_guess = initial_guess.reshape((-1, n_s + n_x)).T
    N = initial_guess.shape[1]

    initial_guess = numpy.row_stack([initial_guess, numpy.zeros((n_x, N)), numpy.zeros((n_x, N))])

    # initial_guess = initial_guess[n_s:-n_x]

    lower_bound = initial_guess * 0
    lower_bound[: n_s + n_x, :] = -big_number
    lower_bound[:, -1] = -big_number

    upper_bound = lower_bound * 0 + big_number

    print(sum((upper_bound - initial_guess) <= 0))
    print(sum((lower_bound - initial_guess) > 0))

    res = det_residual_comp(model, initial_guess, start_s, final_x)

    print(abs(res).max())

    sh = initial_guess.shape

    fobj = lambda vec: det_residual_comp(model, vec, start_s, final_x)
    fobj = lambda vec: det_residual_comp(model, vec.reshape(sh), start_s, final_x).ravel()

    from dolo.numeric.solver import MyJacobian

    #
    dres = MyJacobian(fobj)(initial_guess.ravel())
    #
    # print(dres.shape)
    # print(numpy.linalg.matrix_rank(dres))

    f = lambda x: [fobj(x), MyJacobian(fobj)(x)]

    import time

    t = time.time()

    initial_guess = initial_guess.ravel()
    lower_bound = lower_bound.ravel()
    upper_bound = upper_bound.ravel()

    from dolo.numeric.ncpsolve import ncpsolve

    sol = ncpsolve(f, lower_bound, upper_bound, initial_guess, verbose=True)
    # from dolo.numeric.solver import solver
    # sol = solver(fobj, initial_guess, lb=lower_bound, ub=upper_bound, serial_problem=False, method='ncpsolve', verbose=True)

    print(sol.shape)

    s = time.time()
    print("Elapsed : {}".format(s - t))

    return sol[: n_s + n_x, :]
Ejemplo n.º 9
0
def test_simulations():

    import time
    from matplotlib.pyplot import hist, show, figure, plot, title
    from dolo import yaml_import, approximate_controls
    from dolo.numeric.discretization import gauss_hermite_nodes
    model = yaml_import('../../examples/models/rbc.yaml')

    dr = approximate_controls(model)

    parms = model.calibration['parameters']
    sigma = model.get_calibration().sigma

    s0 = dr.S_bar

    horizon = 50

    t1 = time.time()
    simul = simulate(model,
                     dr,
                     s0,
                     sigma,
                     n_exp=1000,
                     parms=parms,
                     seed=1,
                     horizon=horizon)
    t2 = time.time()

    print("Took: {}".format(t2 - t1))

    N = 80
    [x, w] = gauss_hermite_nodes(N, sigma)

    t3 = time.time()
    simul_2 = simulate(model,
                       dr,
                       s0,
                       sigma,
                       n_exp=1000,
                       parms=parms,
                       horizon=horizon,
                       seed=1,
                       solve_expectations=True,
                       nodes=x,
                       weights=w)
    t4 = time.time()

    print("Took: {}".format(t4 - t3))

    timevec = numpy.array(range(simul.shape[2]))

    figure()
    for k in range(10):
        plot(simul[:, k, 0] - simul_2[:, k, 0])
    title("Productivity")
    show()

    figure()
    for k in range(10):
        plot(simul[:, k, 1] - simul_2[:, k, 1])
    title("Investment")
    show()

    #
    #    figure()
    #    plot(simul[0,0,:])
    #    plot(simul_2[0,0,:])
    #    show()

    figure()
    for i in range(horizon):
        hist(simul[i, :, 0], bins=50)

    show()