def test_eval_splines_2(): import time [a, b, orders, raw_vals, coeffs] = test_splines_filter() fine_grid = mlinspace(a, b, [10000, 10000]) # print(output.flags) N = fine_grid.shape[0] output = numpy.zeros((N, 1)) cc = numpy.ascontiguousarray(coeffs[None,:,:]) import time t1 = time.time() vec_eval_cubic_multi_spline(a, b, orders, cc, fine_grid, output) t2 = time.time() print(t2-t1) t1 = time.time() vec_eval_cubic_multi_spline(a, b, orders, cc, fine_grid, output) t2 = time.time() print(t2-t1)
def __init__(self, min, max, n=[]): self.min = np.array(min, dtype=float) self.max = np.array(max, dtype=float) if len(n) == 0: self.n = np.zeros(n, dtype=int) + 20 else: self.n = np.array(n, dtype=int) self.__nodes__ = mlinspace(self.min, self.max, self.n)
def __init__(self,a,b,orders): self.d = len(a) self.a = a self.b = b self.bounds = np.row_stack( [a,b] ) self.orders = numpy.array(orders, dtype=int) nodes = [np.linspace(a[i], b[i], orders[i]) for i in range(len(orders))] self.nodes = nodes self.grid = mlinspace(a,b,orders)
def __init__(self, min, max, n=[]): self.d = len(min) # this should be a tuple self.min = np.array(min, dtype=float) self.max = np.array(max, dtype=float) if len(n) == 0: self.n = np.zeros(n, dtype=int) + 20 else: self.n = np.array(n, dtype=int) # this should be done only on request. self.__nodes__ = mlinspace(self.min, self.max, self.n)
def test_eval_splines_3(): import time [a, b, orders, raw_vals, coeffs] = test_splines_filter() mvals = raw_vals[None, :] csp = MultivariateCubicSplines(a, b, orders) csp.set_mvalues(mvals) fine_grid = mlinspace(a, b, [10, 10]) values = csp(fine_grid)
def test_eval_splines_2(): import time [a, b, orders, raw_vals, coeffs] = test_splines_filter() fine_grid = mlinspace(a, b, [10, 10]) N = fine_grid.shape[0] output = numpy.zeros((N, 1)) cc = coeffs[None, :, :] vec_eval_cubic_multi_spline(a, b, orders, cc, fine_grid, output)
def test_splines_filter(): a = numpy.array([0.0, 0.0]) b = numpy.array([1.0, 1.0]) orders = numpy.array([10, 10]) grid = mlinspace(a, b, orders) fun = lambda x, y: numpy.sin(x ** 2 + y ** 2) raw_vals = fun(grid[:, 0], grid[:, 1]) raw_vals = raw_vals[:, None] coeffs = filter_coeffs(a, b, orders, raw_vals) return [a, b, orders, raw_vals, coeffs]
def fine_grid(model, Nf): ''' Construct evenly spaced fine grids for state variables. For endogenous variables use a uniform grid with the upper and lower bounds as specified in the yaml file. For exogenous variables, use grids from the discretization of the AR(1) process via Rouwenhorst. Parameters ---------- model : NumericModel "dtcscc" model to be solved Nf : array Number of points on a fine grid for each endogeneous state variable, for use in computing the stationary distribution. Returns ------- grid : array Fine grid for state variables. Note, exogenous ordered first, then endogenous. Later variables are "fastest" moving, earlier variables are "slowest" moving. ''' # HACK: trick to get number of exogenous states Nexo = len(model.calibration['exogenous']) Nend = len(model.calibration['states']) - Nexo # ENDOGENOUS VARIABLES grid = model.get_grid() a = grid.min b = grid.max sgrid = mlinspace(a[Nexo:], b[Nexo:], Nf[Nexo:]) mgrid, Qm = exog_grid_trans(model, Nf) # Put endogenous and exogenous grids together gridf = np.hstack([ np.repeat(mgrid, sgrid.shape[0], axis=0), np.tile(sgrid, (mgrid.shape[0], 1)) ]) return gridf
def pea(model, maxit=100, tol=1e-8, initial_dr=None, verbose=False): t1 = time.time() g = model.functions['transition'] d = model.functions['direct_response'] h = model.functions['expectation'] p = model.calibration['parameters'] if initial_dr is None: drp = approximate_controls(model) else: drp = approximate_controls(model) nodes, weights = gauss_hermite_nodes([5], model.covariances) ap = model.options['approximation_space'] a = ap['a'] b = ap['b'] orders = ap['orders'] grid = mlinspace(a,b,orders) dr = MultivariateCubicSplines(a,b,orders) N = grid.shape[0] z = np.zeros((N,len(model.symbols['expectations']))) x_0 = drp(grid) it = 0 err = 10 err_0 = 10 if verbose: headline = '|{0:^4} | {1:10} | {2:8} | {3:8} |' headline = headline.format('N', ' Error', 'Gain', 'Time') stars = '-'*len(headline) print(stars) print(headline) print(stars) # format string for within loop fmt_str = '|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |' while err>tol and it<=maxit: t_start = time.time() dr.set_values(x_0) z[...] = 0 for i in range(weights.shape[0]): e = nodes[i,:] S = g(grid, x_0, e, p) # evaluate future controls X = dr(S) z += weights[i]*h(S,X,p) # TODO: check that control is admissible new_x = d(grid, z, p) # check whether they differ from the preceding guess err = (abs(new_x - x_0).max()) x_0 = new_x if verbose: # update error and print if `verbose` err_SA = err/err_0 err_0 = err t_finish = time.time() elapsed = t_finish - t_start if verbose: print(fmt_str.format(it, err, err_SA, elapsed)) if it == maxit: import warnings warnings.warn(UserWarning("Maximum number of iterations reached")) # compute final fime and do final printout if `verbose` t2 = time.time() if verbose: print(stars) print('Elapsed: {} seconds.'.format(t2 - t1)) print(stars) return dr
def grid(self): if self.__grid__ is None: from dolo.numeric.misc import mlinspace self.__grid__ = mlinspace(self.a, self.b, self.orders) return self.__grid__
def pea(model, maxit=100, tol=1e-8, initial_dr=None, verbose=False): t1 = time.time() g = model.functions['transition'] d = model.functions['direct_response'] h = model.functions['expectation'] p = model.calibration['parameters'] if initial_dr is None: drp = approximate_controls(model) else: drp = approximate_controls(model) nodes, weights = gauss_hermite_nodes([5], model.covariances) ap = model.options['approximation_space'] a = ap['a'] b = ap['b'] orders = ap['orders'] grid = mlinspace(a, b, orders) dr = MultivariateCubicSplines(a, b, orders) N = grid.shape[0] z = np.zeros((N, len(model.symbols['expectations']))) x_0 = drp(grid) it = 0 err = 10 err_0 = 10 if verbose: headline = '|{0:^4} | {1:10} | {2:8} | {3:8} |' headline = headline.format('N', ' Error', 'Gain', 'Time') stars = '-' * len(headline) print(stars) print(headline) print(stars) # format string for within loop fmt_str = '|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |' while err > tol and it <= maxit: t_start = time.time() dr.set_values(x_0) z[...] = 0 for i in range(weights.shape[0]): e = nodes[i, :] S = g(grid, x_0, e, p) # evaluate future controls X = dr(S) z += weights[i] * h(S, X, p) # TODO: check that control is admissible new_x = d(grid, z, p) # check whether they differ from the preceding guess err = (abs(new_x - x_0).max()) x_0 = new_x if verbose: # update error and print if `verbose` err_SA = err / err_0 err_0 = err t_finish = time.time() elapsed = t_finish - t_start if verbose: print(fmt_str.format(it, err, err_SA, elapsed)) if it == maxit: import warnings warnings.warn(UserWarning("Maximum number of iterations reached")) # compute final fime and do final printout if `verbose` t2 = time.time() if verbose: print(stars) print('Elapsed: {} seconds.'.format(t2 - t1)) print(stars) return dr
def grid(self): if self.__grid__ is None: self.__grid__ = mlinspace(self.smin, self.smax, self.orders) return self.__grid__