INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
A helper function to cut down on code repetition. Almost all of the code in qnwcheb, qnwlege, qnwsimp, qnwtrap is just dealing various forms of input arguments and then shelling out to the corresponding 1d version of the function. This routine does all the argument checking and passes things throug...
def _make_multidim_func(one_d_func, n, *args): """ A helper function to cut down on code repetition. Almost all of the code in qnwcheb, qnwlege, qnwsimp, qnwtrap is just dealing various forms of input arguments and then shelling out to the corresponding 1d version of the function. This routine ...
Compute univariate Guass-Checbychev quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes no...
def _qnwcheb1(n, a, b): """ Compute univariate Guass-Checbychev quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) ...
Compute univariate Guass-Legendre quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes node...
def _qnwlege1(n, a, b): """ Compute univariate Guass-Legendre quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) A...
Compute nodes and weights for quadrature of univariate standard normal distribution Parameters ---------- n : int The number of nodes Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes nodes : np.ndarray(dtype=float) An n element array ...
def _qnwnorm1(n): """ Compute nodes and weights for quadrature of univariate standard normal distribution Parameters ---------- n : int The number of nodes Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes nodes : np.ndarray(dtype=floa...
Compute univariate Simpson quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes nodes : np....
def _qnwsimp1(n, a, b): """ Compute univariate Simpson quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n ele...
Compute univariate trapezoid rule quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n element array of nodes node...
def _qnwtrap1(n, a, b): """ Compute univariate trapezoid rule quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) A...
Computes nodes and weights for quadrature on the beta distribution. Default is a=b=1 which is just a uniform distribution NOTE: For now I am just following compecon; would be much better to find a different way since I don't know what they are doing. Parameters ---------- n : scalar : int ...
def _qnwbeta1(n, a=1.0, b=1.0): """ Computes nodes and weights for quadrature on the beta distribution. Default is a=b=1 which is just a uniform distribution NOTE: For now I am just following compecon; would be much better to find a different way since I don't know what they are doing. Paramet...
1d quadrature weights and nodes for Gamma distributed random variable Parameters ---------- n : scalar : int The number of quadrature points a : scalar : float, optional(default=1.0) Shape parameter of the gamma distribution parameter. Must be positive b : scalar : float, optional...
def _qnwgamma1(n, a=1.0, b=1.0, tol=3e-14): """ 1d quadrature weights and nodes for Gamma distributed random variable Parameters ---------- n : scalar : int The number of quadrature points a : scalar : float, optional(default=1.0) Shape parameter of the gamma distribution param...
Generator version of `vertex_enumeration`. Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. qhull_options : str, optional(default=None) Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull manual <http://www.qhull.org>`_ for details. ...
def vertex_enumeration_gen(g, qhull_options=None): """ Generator version of `vertex_enumeration`. Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. qhull_options : str, optional(default=None) Options to pass to `scipy.spatial.ConvexHull`. See the ...
Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best response polytopes. equations_tup : tuple(ndarray(float, ndim=2)) Tuple of ndarra...
def _vertex_enumeration_gen(labelings_bits_tup, equations_tup, trans_recips): """ Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best resp...
Convert an array of integers representing the set bits into the corresponding integer. Compiled as a ufunc by Numba's `@guvectorize`: if the input is a 2-dim array with shape[0]=K, the function returns a 1-dim array of K converted integers. Parameters ---------- ints_arr : ndarray(int32, n...
def _ints_arr_to_bits(ints_arr, out): """ Convert an array of integers representing the set bits into the corresponding integer. Compiled as a ufunc by Numba's `@guvectorize`: if the input is a 2-dim array with shape[0]=K, the function returns a 1-dim array of K converted integers. Paramet...
From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- labeling_bits : scalar(np.uint64) Integer with set bits representing...
def _get_mixed_actions(labeling_bits, equation_tup, trans_recips): """ From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- ...
Expands one or more vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- *arrays : tuple/list of np.ndarray Tuple/list of...
def gridmake(*arrays): """ Expands one or more vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- *arrays : tuple/list of np....
Expands two vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- x1 : np.ndarray First vector to be expanded. x2 : np.nda...
def _gridmake2(x1, x2): """ Expands two vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- x1 : np.ndarray First vec...
Return m randomly sampled probability vectors of dimension k. Parameters ---------- m : scalar(int) Number of probability vectors. k : scalar(int) Dimension of each probability vectors. random_state : int or np.random.RandomState, optional Random seed (integer) or np.rando...
def probvec(m, k, random_state=None, parallel=True): """ Return m randomly sampled probability vectors of dimension k. Parameters ---------- m : scalar(int) Number of probability vectors. k : scalar(int) Dimension of each probability vectors. random_state : int or np.rando...
Fill `out` with randomly sampled probability vectors as rows. To be complied as a ufunc by guvectorize of Numba. The inputs must have the same shape except the last axis; the length of the last axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is k, then r.shape[-1] must be k-1. Pa...
def _probvec(r, out): """ Fill `out` with randomly sampled probability vectors as rows. To be complied as a ufunc by guvectorize of Numba. The inputs must have the same shape except the last axis; the length of the last axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is k, the...
Randomly choose k integers without replacement from 0, ..., n-1. Parameters ---------- n : scalar(int) Number of integers, 0, ..., n-1, to sample from. k : scalar(int) Number of integers to sample. num_trials : scalar(int), optional(default=None) Number of trials. ran...
def sample_without_replacement(n, k, num_trials=None, random_state=None): """ Randomly choose k integers without replacement from 0, ..., n-1. Parameters ---------- n : scalar(int) Number of integers, 0, ..., n-1, to sample from. k : scalar(int) Number of integers to sample. ...
Main body of `sample_without_replacement`. To be complied as a ufunc by guvectorize of Numba.
def _sample_without_replacement(n, r, out): """ Main body of `sample_without_replacement`. To be complied as a ufunc by guvectorize of Numba. """ k = r.shape[0] # Logic taken from random.sample in the standard library pool = np.arange(n) for j in range(k): idx = int(np.floor(r[...
Generate a random sample according to the cumulative distribution given by `cdf`. Jit-complied by Numba in nopython mode. Parameters ---------- cdf : array_like(float, ndim=1) Array containing the cumulative distribution. size : scalar(int), optional(default=None) Size of the sampl...
def draw(cdf, size=None): """ Generate a random sample according to the cumulative distribution given by `cdf`. Jit-complied by Numba in nopython mode. Parameters ---------- cdf : array_like(float, ndim=1) Array containing the cumulative distribution. size : scalar(int), optional(d...
Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each line corresponds to one point of the product spa...
def cartesian(nodes, order='C'): ''' Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each lin...
Constructs a regular cartesian grid Parameters ---------- a : array_like(ndim=1) lower bounds in each dimension b : array_like(ndim=1) upper bounds in each dimension nums : array_like(ndim=1) number of nodes along each dimension order : str, optional(default='C') ...
def mlinspace(a, b, nums, order='C'): ''' Constructs a regular cartesian grid Parameters ---------- a : array_like(ndim=1) lower bounds in each dimension b : array_like(ndim=1) upper bounds in each dimension nums : array_like(ndim=1) number of nodes along each dime...
Repeats each element of a vector many times and repeats the whole result many times Parameters ---------- x : ndarray(ndim=1) vector to be repeated K : scalar(int) number of times each element of x is repeated (inner iterations) out : ndarray(ndim=1) placeholder for th...
def _repeat_1d(x, K, out): ''' Repeats each element of a vector many times and repeats the whole result many times Parameters ---------- x : ndarray(ndim=1) vector to be repeated K : scalar(int) number of times each element of x is repeated (inner iterations) out : nda...
r""" Construct an array consisting of the integer points in the (m-1)-dimensional simplex :math:`\{x \mid x_0 + \cdots + x_{m-1} = n \}`, or equivalently, the m-part compositions of n, which are listed in lexicographic order. The total number of the points (hence the length of the output array) is L...
def simplex_grid(m, n): r""" Construct an array consisting of the integer points in the (m-1)-dimensional simplex :math:`\{x \mid x_0 + \cdots + x_{m-1} = n \}`, or equivalently, the m-part compositions of n, which are listed in lexicographic order. The total number of the points (hence the leng...
r""" Return the index of the point x in the lexicographic order of the integer points of the (m-1)-dimensional simplex :math:`\{x \mid x_0 + \cdots + x_{m-1} = n\}`. Parameters ---------- x : array_like(int, ndim=1) Integer point in the simplex, i.e., an array of m nonnegative i...
def simplex_index(x, m, n): r""" Return the index of the point x in the lexicographic order of the integer points of the (m-1)-dimensional simplex :math:`\{x \mid x_0 + \cdots + x_{m-1} = n\}`. Parameters ---------- x : array_like(int, ndim=1) Integer point in the simplex, i.e., an ...
The total number of m-part compositions of n, which is equal to (n+m-1) choose (m-1). Parameters ---------- m : scalar(int) Number of parts of composition. n : scalar(int) Integer to decompose. Returns ------- scalar(int) Total number of m-part compositions of ...
def num_compositions(m, n): """ The total number of m-part compositions of n, which is equal to (n+m-1) choose (m-1). Parameters ---------- m : scalar(int) Number of parts of composition. n : scalar(int) Integer to decompose. Returns ------- scalar(int) ...
r""" Internally, scipy.signal works with systems of the form .. math:: ar_{poly}(L) X_t = ma_{poly}(L) \epsilon_t where L is the lag operator. To match this, we set .. math:: ar_{poly} = (1, -\phi_1, -\phi_2,..., -\phi_p) ma_{poly} = (1, \theta_1...
def set_params(self): r""" Internally, scipy.signal works with systems of the form .. math:: ar_{poly}(L) X_t = ma_{poly}(L) \epsilon_t where L is the lag operator. To match this, we set .. math:: ar_{poly} = (1, -\phi_1, -\phi_2,..., -\phi_p) ...
Get the impulse response corresponding to our model. Returns ------- psi : array_like(float) psi[j] is the response at lag j of the impulse response. We take psi[0] as unity.
def impulse_response(self, impulse_length=30): """ Get the impulse response corresponding to our model. Returns ------- psi : array_like(float) psi[j] is the response at lag j of the impulse response. We take psi[0] as unity. """ from sci...
r""" Compute the spectral density function. The spectral density is the discrete time Fourier transform of the autocovariance function. In particular, .. math:: f(w) = \sum_k \gamma(k) \exp(-ikw) where gamma is the autocovariance function and the sum is over ...
def spectral_density(self, two_pi=True, res=1200): r""" Compute the spectral density function. The spectral density is the discrete time Fourier transform of the autocovariance function. In particular, .. math:: f(w) = \sum_k \gamma(k) \exp(-ikw) where ga...
Compute the autocovariance function from the ARMA parameters over the integers range(num_autocov) using the spectral density and the inverse Fourier transform. Parameters ---------- num_autocov : scalar(int), optional(default=16) The number of autocovariances to calc...
def autocovariance(self, num_autocov=16): """ Compute the autocovariance function from the ARMA parameters over the integers range(num_autocov) using the spectral density and the inverse Fourier transform. Parameters ---------- num_autocov : scalar(int), optional...
Compute a simulated sample path assuming Gaussian shocks. Parameters ---------- ts_length : scalar(int), optional(default=90) Number of periods to simulate for random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState i...
def simulation(self, ts_length=90, random_state=None): """ Compute a simulated sample path assuming Gaussian shocks. Parameters ---------- ts_length : scalar(int), optional(default=90) Number of periods to simulate for random_state : int or np.random.RandomS...
Computes the non-stochastic steady-state of the economy. Parameters ---------- nnc : array_like(float) nnc is the location of the constant in the state vector x_t
def compute_steadystate(self, nnc=2): """ Computes the non-stochastic steady-state of the economy. Parameters ---------- nnc : array_like(float) nnc is the location of the constant in the state vector x_t """ zx = np.eye(self.A0.shape[0])-self.A0 ...
Simulate quantities and prices for the economy Parameters ---------- x0 : array_like(float) The initial state ts_length : scalar(int) Length of the simulation Pay : array_like(float) Vector to price an asset whose payout is Pay*xt
def compute_sequence(self, x0, ts_length=None, Pay=None): """ Simulate quantities and prices for the economy Parameters ---------- x0 : array_like(float) The initial state ts_length : scalar(int) Length of the simulation Pay : array_like...
Create Impulse Response Functions Parameters ---------- ts_length : scalar(int) Number of periods to calculate IRF Shock : array_like(float) Vector of shocks to calculate IRF to. Default is first element of w
def irf(self, ts_length=100, shock=None): """ Create Impulse Response Functions Parameters ---------- ts_length : scalar(int) Number of periods to calculate IRF Shock : array_like(float) Vector of shocks to calculate IRF to. Default is first ele...
Compute canonical preference representation Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology
def canonical(self): """ Compute canonical preference representation Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology """ Ac1 = np.hstack((self.deltah,...
r""" This function takes the linear state space system that is an input to the Kalman class and it converts that system to the time-invariant whitener represenation given by .. math:: \tilde{x}_{t+1}^* = \tilde{A} \tilde{x} + \tilde{C} v a = \tilde{G} \t...
def whitener_lss(self): r""" This function takes the linear state space system that is an input to the Kalman class and it converts that system to the time-invariant whitener represenation given by .. math:: \tilde{x}_{t+1}^* = \tilde{A} \tilde{x} + \tilde{C...
r""" Updates the moments (x_hat, Sigma) of the time t prior to the time t filtering distribution, using current measurement :math:`y_t`. The updates are according to .. math:: \hat{x}^F = \hat{x} + \Sigma G' (G \Sigma G' + R)^{-1} (y - G \hat{x}) ...
def prior_to_filtered(self, y): r""" Updates the moments (x_hat, Sigma) of the time t prior to the time t filtering distribution, using current measurement :math:`y_t`. The updates are according to .. math:: \hat{x}^F = \hat{x} + \Sigma G' (G \Sigma G' + R)^{-1} ...
Updates the moments of the time t filtering distribution to the moments of the predictive distribution, which becomes the time t+1 prior
def filtered_to_forecast(self): """ Updates the moments of the time t filtering distribution to the moments of the predictive distribution, which becomes the time t+1 prior """ # === simplify notation === # A, C = self.ss.A, self.ss.C Q = np.dot(C, C.T) ...
Computes the limit of :math:`\Sigma_t` as t goes to infinity by solving the associated Riccati equation. The outputs are stored in the attributes `K_infinity` and `Sigma_infinity`. Computation is via the doubling algorithm (default) or a QZ decomposition method (see the documentation in ...
def stationary_values(self, method='doubling'): """ Computes the limit of :math:`\Sigma_t` as t goes to infinity by solving the associated Riccati equation. The outputs are stored in the attributes `K_infinity` and `Sigma_infinity`. Computation is via the doubling algorithm (defa...
Wold representation moving average or VAR coefficients for the steady state Kalman filter. Parameters ---------- j : int The lag length coeff_type : string, either 'ma' or 'var' (default='ma') The type of coefficent sequence to compute. Either 'ma' for ...
def stationary_coefficients(self, j, coeff_type='ma'): """ Wold representation moving average or VAR coefficients for the steady state Kalman filter. Parameters ---------- j : int The lag length coeff_type : string, either 'ma' or 'var' (default='ma')...
Find one mixed-action Nash equilibrium of a 2-player normal form game by the Lemke-Howson algorithm [2]_, implemented with "complementary pivoting" (see, e.g., von Stengel [3]_ for details). Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. init_pivot : s...
def lemke_howson(g, init_pivot=0, max_iter=10**6, capping=None, full_output=False): """ Find one mixed-action Nash equilibrium of a 2-player normal form game by the Lemke-Howson algorithm [2]_, implemented with "complementary pivoting" (see, e.g., von Stengel [3]_ for details). Par...
Execute the Lemke-Howson algorithm with the heuristics proposed by Codenotti et al. Parameters ---------- payoff_matrices : tuple(ndarray(ndim=2)) Tuple of two arrays representing payoff matrices, of shape (m, n) and (n, m), respectively. tableaux : tuple(ndarray(float, ndim=2)) ...
def _lemke_howson_capping(payoff_matrices, tableaux, bases, init_pivot, max_iter, capping): """ Execute the Lemke-Howson algorithm with the heuristics proposed by Codenotti et al. Parameters ---------- payoff_matrices : tuple(ndarray(ndim=2)) Tuple of two array...
Given a tuple of payoff matrices, initialize the tableau and basis arrays in place. For each player `i`, if `payoff_matrices[i].min()` is non-positive, then stored in the tableau are payoff values incremented by `abs(payoff_matrices[i].min()) + 1` (to ensure for the tableau not to have a negative e...
def _initialize_tableaux(payoff_matrices, tableaux, bases): """ Given a tuple of payoff matrices, initialize the tableau and basis arrays in place. For each player `i`, if `payoff_matrices[i].min()` is non-positive, then stored in the tableau are payoff values incremented by `abs(payoff_matrice...
Main body of the Lemke-Howson algorithm implementation. Perform the complementary pivoting. Modify `tablaux` and `bases` in place. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays containing the tableaux, of shape (n, m+n+1) and (m, m+n+1), respect...
def _lemke_howson_tbl(tableaux, bases, init_pivot, max_iter): """ Main body of the Lemke-Howson algorithm implementation. Perform the complementary pivoting. Modify `tablaux` and `bases` in place. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays co...
Perform a pivoting step. Modify `tableau` in place. Parameters ---------- tableau : ndarray(float, ndim=2) Array containing the tableau. pivot : scalar(int) Pivot. pivot_row : scalar(int) Pivot row index. Returns ------- tableau : ndarray(float, ndim=2) ...
def _pivoting(tableau, pivot, pivot_row): """ Perform a pivoting step. Modify `tableau` in place. Parameters ---------- tableau : ndarray(float, ndim=2) Array containing the tableau. pivot : scalar(int) Pivot. pivot_row : scalar(int) Pivot row index. Returns ...
From `tableaux` and `bases`, extract non-slack basic variables and return a tuple of the corresponding, normalized mixed actions. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays containing the tableaux, of shape (n, m+n+1) and (m, m+n+1), respectively....
def _get_mixed_actions(tableaux, bases): """ From `tableaux` and `bases`, extract non-slack basic variables and return a tuple of the corresponding, normalized mixed actions. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays containing the tableaux, of s...
r""" Computes the expected discounted quadratic sum .. math:: q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big] Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t` with :math:`{x_t}` standard normal and :math:`x_0` the initial condition. Parameters ...
def var_quadratic_sum(A, C, H, beta, x0): r""" Computes the expected discounted quadratic sum .. math:: q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big] Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t` with :math:`{x_t}` standard normal and :math...
r""" Computes the quadratic sum .. math:: V = \sum_{j=0}^{\infty} A^j B A^{j'} V is computed by solving the corresponding discrete lyapunov equation using the doubling algorithm. See the documentation of `util.solve_discrete_lyapunov` for more information. Parameters ---------- ...
def m_quadratic_sum(A, B, max_it=50): r""" Computes the quadratic sum .. math:: V = \sum_{j=0}^{\infty} A^j B A^{j'} V is computed by solving the corresponding discrete lyapunov equation using the doubling algorithm. See the documentation of `util.solve_discrete_lyapunov` for more in...
r""" Takes as inputs n, p, q, psi. It will then construct a markov chain that estimates an AR(1) process of: :math:`y_t = \bar{y} + \rho y_{t-1} + \varepsilon_t` where :math:`\varepsilon_t` is i.i.d. normal of mean 0, std dev of sigma The Rouwenhorst approximation uses the following recursive defin...
def rouwenhorst(n, ybar, sigma, rho): r""" Takes as inputs n, p, q, psi. It will then construct a markov chain that estimates an AR(1) process of: :math:`y_t = \bar{y} + \rho y_{t-1} + \varepsilon_t` where :math:`\varepsilon_t` is i.i.d. normal of mean 0, std dev of sigma The Rouwenhorst approx...
r""" Computes a Markov chain associated with a discretized version of the linear Gaussian AR(1) process .. math:: y_{t+1} = \rho y_t + u_{t+1} using Tauchen's method. Here :math:`{u_t}` is an i.i.d. Gaussian process with zero mean. Parameters ---------- rho : scalar(float) ...
def tauchen(rho, sigma_u, m=3, n=7): r""" Computes a Markov chain associated with a discretized version of the linear Gaussian AR(1) process .. math:: y_{t+1} = \rho y_t + u_{t+1} using Tauchen's method. Here :math:`{u_t}` is an i.i.d. Gaussian process with zero mean. Parameters ...
.. highlight:: none Maximize a scalar-valued function with one or more variables using the Nelder-Mead method. This function is JIT-compiled in `nopython` mode using Numba. Parameters ---------- fun : callable The objective function to be maximized: `fun(x, *args) -> float` wh...
def nelder_mead(fun, x0, bounds=np.array([[], []]).T, args=(), tol_f=1e-10, tol_x=1e-10, max_iter=1000): """ .. highlight:: none Maximize a scalar-valued function with one or more variables using the Nelder-Mead method. This function is JIT-compiled in `nopython` mode using Numba. ...
.. highlight:: none Implements the Nelder-Mead algorithm described in Lagarias et al. (1998) modified to maximize instead of minimizing. JIT-compiled in `nopython` mode using Numba. Parameters ---------- fun : callable The objective function to be maximized. `fun(x, *args) ...
def _nelder_mead_algorithm(fun, vertices, bounds=np.array([[], []]).T, args=(), ρ=1., χ=2., γ=0.5, σ=0.5, tol_f=1e-8, tol_x=1e-8, max_iter=1000): """ .. highlight:: none Implements the Nelder-Mead algorithm described in Lagarias et al. (1998) modifi...
Generates an initial simplex for the Nelder-Mead method. JIT-compiled in `nopython` mode using Numba. Parameters ---------- x0 : ndarray(float, ndim=1) Initial guess. Array of real elements of size (n,), where ‘n’ is the number of independent variables. bounds: ndarray(float, ndim=...
def _initialize_simplex(x0, bounds): """ Generates an initial simplex for the Nelder-Mead method. JIT-compiled in `nopython` mode using Numba. Parameters ---------- x0 : ndarray(float, ndim=1) Initial guess. Array of real elements of size (n,), where ‘n’ is the number of indepen...
Checks whether the parameters for the Nelder-Mead algorithm are valid. JIT-compiled in `nopython` mode using Numba. Parameters ---------- ρ : scalar(float) Reflection parameter. Must be strictly greater than 0. χ : scalar(float) Expansion parameter. Must be strictly greater than ma...
def _check_params(ρ, χ, γ, σ, bounds, n): """ Checks whether the parameters for the Nelder-Mead algorithm are valid. JIT-compiled in `nopython` mode using Numba. Parameters ---------- ρ : scalar(float) Reflection parameter. Must be strictly greater than 0. χ : scalar(float) ...
Checks whether `x` is within `bounds`. JIT-compiled in `nopython` mode using Numba. Parameters ---------- x : ndarray(float, ndim=1) 1-D array with shape (n,) of independent variables. bounds: ndarray(float, ndim=2) Sequence of (min, max) pairs for each element in x. Returns ...
def _check_bounds(x, bounds): """ Checks whether `x` is within `bounds`. JIT-compiled in `nopython` mode using Numba. Parameters ---------- x : ndarray(float, ndim=1) 1-D array with shape (n,) of independent variables. bounds: ndarray(float, ndim=2) Sequence of (min, max) p...
Wrapper for bounding and taking the negative of `fun` for the Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba. Parameters ---------- fun : callable The objective function to be minimized. `fun(x, *args) -> float` where x is an 1-D array with shape (n,) and...
def _neg_bounded_fun(fun, bounds, x, args=()): """ Wrapper for bounding and taking the negative of `fun` for the Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba. Parameters ---------- fun : callable The objective function to be minimized. `fun(x, *args) ->...
r""" Computes the solution to the discrete lyapunov equation .. math:: AXA' - X + B = 0 :math:`X` is computed by using a doubling algorithm. In particular, we iterate to convergence on :math:`X_j` with the following recursions for :math:`j = 1, 2, \dots` starting from :math:`X_0 = B`, :ma...
def solve_discrete_lyapunov(A, B, max_it=50, method="doubling"): r""" Computes the solution to the discrete lyapunov equation .. math:: AXA' - X + B = 0 :math:`X` is computed by using a doubling algorithm. In particular, we iterate to convergence on :math:`X_j` with the following recursio...
Solves the discrete-time algebraic Riccati equation .. math:: X = A'XA - (N + B'XA)'(B'XB + R)^{-1}(N + B'XA) + Q Computation is via a modified structured doubling algorithm, an explanation of which can be found in the reference below, if `method="doubling"` (default), and via a QZ decomposit...
def solve_discrete_riccati(A, B, Q, R, N=None, tolerance=1e-10, max_iter=500, method="doubling"): """ Solves the discrete-time algebraic Riccati equation .. math:: X = A'XA - (N + B'XA)'(B'XB + R)^{-1}(N + B'XA) + Q Computation is via a modified structured doubling ...
Given an array `a` of k distinct nonnegative integers, sorted in ascending order, return the next k-array in the lexicographic ordering of the descending sequences of the elements [1]_. `a` is modified in place. Parameters ---------- a : ndarray(int, ndim=1) Array of length k. Retu...
def next_k_array(a): """ Given an array `a` of k distinct nonnegative integers, sorted in ascending order, return the next k-array in the lexicographic ordering of the descending sequences of the elements [1]_. `a` is modified in place. Parameters ---------- a : ndarray(int, ndim=1) ...
Given an array `a` of k distinct nonnegative integers, sorted in ascending order, return its ranking in the lexicographic ordering of the descending sequences of the elements [1]_. Parameters ---------- a : ndarray(int, ndim=1) Array of length k. Returns ------- idx : scalar(in...
def k_array_rank(a): """ Given an array `a` of k distinct nonnegative integers, sorted in ascending order, return its ranking in the lexicographic ordering of the descending sequences of the elements [1]_. Parameters ---------- a : ndarray(int, ndim=1) Array of length k. Return...
Numba jit version of `k_array_rank`. Notes ----- An incorrect value will be returned without warning or error if overflow occurs during the computation. It is the user's responsibility to ensure that the rank of the input array fits within the range of possible values of `np.intp`; a sufficient...
def k_array_rank_jit(a): """ Numba jit version of `k_array_rank`. Notes ----- An incorrect value will be returned without warning or error if overflow occurs during the computation. It is the user's responsibility to ensure that the rank of the input array fits within the range of possi...
Solve the linear equation ax = b directly calling a Numba internal function. The data in `a` and `b` are interpreted in Fortran order, and dtype of `a` and `b` must be the same, one of {float32, float64, complex64, complex128}. `a` and `b` are modified in place, and the solution is stored in `b`. *No er...
def _numba_linalg_solve(a, b): """ Solve the linear equation ax = b directly calling a Numba internal function. The data in `a` and `b` are interpreted in Fortran order, and dtype of `a` and `b` must be the same, one of {float32, float64, complex64, complex128}. `a` and `b` are modified in place, an...
Generates a solution trajectory of fixed length.
def _integrate_fixed_trajectory(self, h, T, step, relax): """Generates a solution trajectory of fixed length.""" # initialize the solution using initial condition solution = np.hstack((self.t, self.y)) while self.successful(): self.integrate(self.t + h, step, relax) ...
Numba jitted function that computes N choose k. Return `0` if the outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0, or k > N. Parameters ---------- N : scalar(int) k : scalar(int) Returns ------- val : scalar(int)
def comb_jit(N, k): """ Numba jitted function that computes N choose k. Return `0` if the outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0, or k > N. Parameters ---------- N : scalar(int) k : scalar(int) Returns ------- val : scalar(int) """ # Fro...
Initializes the integrator prior to integration.
def _initialize_integrator(self, t0, y0, integrator, **kwargs): """Initializes the integrator prior to integration.""" # set the initial condition self.set_initial_value(y0, t0) # select the integrator self.set_integrator(integrator, **kwargs)
Generates a solution trajectory of variable length.
def _integrate_variable_trajectory(self, h, g, tol, step, relax): """Generates a solution trajectory of variable length.""" # initialize the solution using initial condition solution = np.hstack((self.t, self.y)) while self.successful(): self.integrate(self.t + h, step, rel...
r""" The residual is the difference between the derivative of the B-spline approximation of the solution trajectory and the right-hand side of the original ODE evaluated along the approximated solution trajectory. Parameters ---------- traj : array_like (float) ...
def compute_residual(self, traj, ti, k=3, ext=2): r""" The residual is the difference between the derivative of the B-spline approximation of the solution trajectory and the right-hand side of the original ODE evaluated along the approximated solution trajectory. Parameters ...
r""" Solve the IVP by integrating the ODE given some initial condition. Parameters ---------- t0 : float Initial condition for the independent variable. y0 : array_like (float, shape=(n,)) Initial condition for the dependent variables. h : float, ...
def solve(self, t0, y0, h=1.0, T=None, g=None, tol=None, integrator='dopri5', step=False, relax=False, **kwargs): r""" Solve the IVP by integrating the ODE given some initial condition. Parameters ---------- t0 : float Initial condition for the independ...
r""" Parametric B-spline interpolation in N-dimensions. Parameters ---------- traj : array_like (float) Solution trajectory providing the data points for constructing the B-spline representation. ti : array_like (float) Array of values for the...
def interpolate(self, traj, ti, k=3, der=0, ext=2): r""" Parametric B-spline interpolation in N-dimensions. Parameters ---------- traj : array_like (float) Solution trajectory providing the data points for constructing the B-spline representation. ...
Calculates the Lorenz Curve, a graphical representation of the distribution of income or wealth. It returns the cumulative share of people (x-axis) and the cumulative share of income earned Parameters ---------- y : array_like(float or int, ndim=1) Array of income/wealth for each individua...
def lorenz_curve(y): """ Calculates the Lorenz Curve, a graphical representation of the distribution of income or wealth. It returns the cumulative share of people (x-axis) and the cumulative share of income earned Parameters ---------- y : array_like(float or int, ndim=1) Array of...
r""" Implements the Gini inequality index Parameters ----------- y : array_like(float) Array of income/wealth for each individual. Ordered or unordered is fine Returns ------- Gini index: float The gini index describing the inequality of the array of income/wealth Refe...
def gini_coefficient(y): r""" Implements the Gini inequality index Parameters ----------- y : array_like(float) Array of income/wealth for each individual. Ordered or unordered is fine Returns ------- Gini index: float The gini index describing the inequality of the arr...
r""" Implements Shorrocks mobility index Parameters ----------- A : array_like(float) Square matrix with transition probabilities (mobility matrix) of dimension m Returns -------- Shorrocks index: float The Shorrocks mobility index calculated as .. math:: ...
def shorrocks_index(A): r""" Implements Shorrocks mobility index Parameters ----------- A : array_like(float) Square matrix with transition probabilities (mobility matrix) of dimension m Returns -------- Shorrocks index: float The Shorrocks mobility index calcul...
Setter method for q.
def q(self, val): """ Setter method for q. """ self._q = np.asarray(val) self.Q = cumsum(val)
Returns k draws from q. For each such draw, the value i is returned with probability q[i]. Parameters ----------- k : scalar(int), optional Number of draws to be returned random_state : int or np.random.RandomState, optional Random seed (integer...
def draw(self, k=1, random_state=None): """ Returns k draws from q. For each such draw, the value i is returned with probability q[i]. Parameters ----------- k : scalar(int), optional Number of draws to be returned random_state : int or np.r...
Return a randomly sampled MarkovChain instance with n states, where each state has k states with positive transition probability. Parameters ---------- n : scalar(int) Number of states. k : scalar(int), optional(default=None) Number of states that may be reached from each state wit...
def random_markov_chain(n, k=None, sparse=False, random_state=None): """ Return a randomly sampled MarkovChain instance with n states, where each state has k states with positive transition probability. Parameters ---------- n : scalar(int) Number of states. k : scalar(int), option...
Return a randomly sampled n x n stochastic matrix with k nonzero entries for each row. Parameters ---------- n : scalar(int) Number of states. k : scalar(int), optional(default=None) Number of nonzero entries in each row of the matrix. Set to n if not specified. sparse...
def random_stochastic_matrix(n, k=None, sparse=False, format='csr', random_state=None): """ Return a randomly sampled n x n stochastic matrix with k nonzero entries for each row. Parameters ---------- n : scalar(int) Number of states. k : scalar(int), o...
Generate a "non-square stochastic matrix" of shape (m, n), which contains as rows m probability vectors of length n with k nonzero entries. For other parameters, see `random_stochastic_matrix`.
def _random_stochastic_matrix(m, n, k=None, sparse=False, format='csr', random_state=None): """ Generate a "non-square stochastic matrix" of shape (m, n), which contains as rows m probability vectors of length n with k nonzero entries. For other parameters, see `random...
Generate a DiscreteDP randomly. The reward values are drawn from the normal distribution with mean 0 and standard deviation `scale`. Parameters ---------- num_states : scalar(int) Number of states. num_actions : scalar(int) Number of actions. beta : scalar(float), optional(def...
def random_discrete_dp(num_states, num_actions, beta=None, k=None, scale=1, sparse=False, sa_pair=False, random_state=None): """ Generate a DiscreteDP randomly. The reward values are drawn from the normal distribution with mean 0 and standard deviation `scale`. Parameters ...
r""" The D operator, mapping P into .. math:: D(P) := P + PC(\theta I - C'PC)^{-1} C'P. Parameters ---------- P : array_like(float, ndim=2) A matrix that should be n x n Returns ------- dP : array_like(float, ndim=2) ...
def d_operator(self, P): r""" The D operator, mapping P into .. math:: D(P) := P + PC(\theta I - C'PC)^{-1} C'P. Parameters ---------- P : array_like(float, ndim=2) A matrix that should be n x n Returns ------- dP : arra...
r""" The B operator, mapping P into .. math:: B(P) := R - \beta^2 A'PB(Q + \beta B'PB)^{-1}B'PA + \beta A'PA and also returning .. math:: F := (Q + \beta B'PB)^{-1} \beta B'PA Parameters ---------- P : array_like(float, ndim=2) ...
def b_operator(self, P): r""" The B operator, mapping P into .. math:: B(P) := R - \beta^2 A'PB(Q + \beta B'PB)^{-1}B'PA + \beta A'PA and also returning .. math:: F := (Q + \beta B'PB)^{-1} \beta B'PA Parameters ---------- P :...
This method solves the robust control problem by tricking it into a stacked LQ problem, as described in chapter 2 of Hansen- Sargent's text "Robustness." The optimal control with observed state is .. math:: u_t = - F x_t And the value function is :math:`-x'Px` ...
def robust_rule(self, method='doubling'): """ This method solves the robust control problem by tricking it into a stacked LQ problem, as described in chapter 2 of Hansen- Sargent's text "Robustness." The optimal control with observed state is .. math:: u_t ...
A simple algorithm for computing the robust policy F and the corresponding value function P, based around straightforward iteration with the robust Bellman operator. This function is easier to understand but one or two orders of magnitude slower than self.robust_rule(). For more inform...
def robust_rule_simple(self, P_init=None, max_iter=80, tol=1e-8): """ A simple algorithm for computing the robust policy F and the corresponding value function P, based around straightforward iteration with the robust Bellman operator. This function is easier to understand but o...
Compute agent 2's best cost-minimizing response K, given F. Parameters ---------- F : array_like(float, ndim=2) A k x n array method : str, optional(default='doubling') Solution method used in solving the associated Riccati equation, str in {'doubling...
def F_to_K(self, F, method='doubling'): """ Compute agent 2's best cost-minimizing response K, given F. Parameters ---------- F : array_like(float, ndim=2) A k x n array method : str, optional(default='doubling') Solution method used in solving th...
Compute agent 1's best value-maximizing response F, given K. Parameters ---------- K : array_like(float, ndim=2) A j x n array method : str, optional(default='doubling') Solution method used in solving the associated Riccati equation, str in {'doublin...
def K_to_F(self, K, method='doubling'): """ Compute agent 1's best value-maximizing response F, given K. Parameters ---------- K : array_like(float, ndim=2) A j x n array method : str, optional(default='doubling') Solution method used in solving t...
r""" Given K and F, compute the value of deterministic entropy, which is .. math:: \sum_t \beta^t x_t' K'K x_t` with .. math:: x_{t+1} = (A - BF + CK) x_t Parameters ---------- F : array_like(float, ndim=2) The po...
def compute_deterministic_entropy(self, F, K, x0): r""" Given K and F, compute the value of deterministic entropy, which is .. math:: \sum_t \beta^t x_t' K'K x_t` with .. math:: x_{t+1} = (A - BF + CK) x_t Parameters --------...
Given a fixed policy F, with the interpretation :math:`u = -F x`, this function computes the matrix :math:`P_F` and constant :math:`d_F` associated with discounted cost :math:`J_F(x) = x' P_F x + d_F` Parameters ---------- F : array_like(float, ndim=2) The policy fun...
def evaluate_F(self, F): """ Given a fixed policy F, with the interpretation :math:`u = -F x`, this function computes the matrix :math:`P_F` and constant :math:`d_F` associated with discounted cost :math:`J_F(x) = x' P_F x + d_F` Parameters ---------- F : array_l...
process the input, capturing stdout
def process_input_line(self, line, store_history=True): """process the input, capturing stdout""" #print "input='%s'"%self.input stdout = sys.stdout splitter = self.IP.input_splitter try: sys.stdout = self.cout splitter.push(line) more = splitt...
# build out an image directive like # .. image:: somefile.png # :width 4in # # from an input like # savefig somefile.png width=4in
def process_image(self, decorator): """ # build out an image directive like # .. image:: somefile.png # :width 4in # # from an input like # savefig somefile.png width=4in """ savefig_dir = self.savefig_dir source_dir = self.source_dir ...
Process data block for INPUT token.
def process_input(self, data, input_prompt, lineno): """Process data block for INPUT token.""" decorator, input, rest = data image_file = None image_directive = None #print 'INPUT:', data # dbg is_verbatim = decorator=='@verbatim' or self.is_verbatim is_doctest =...
Process data block for OUTPUT token.
def process_output(self, data, output_prompt, input_lines, output, is_doctest, image_file): """Process data block for OUTPUT token.""" if is_doctest: submitted = data.strip() found = output if found is not None: found = found.str...
content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code
def process_pure_python(self, content): """ content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code ...
content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code
def process_pure_python2(self, content): """ content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code ...
r""" This is a separate function for simulating a vector linear system of the form .. math:: x_{t+1} = A x_t + v_t given :math:`x_0` = x0 Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n. The purpose of separating this functionality out is to target it for ...
def simulate_linear_model(A, x0, v, ts_length): r""" This is a separate function for simulating a vector linear system of the form .. math:: x_{t+1} = A x_t + v_t given :math:`x_0` = x0 Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n. The purpose of separa...
r""" Simulate a time series of length ts_length, first drawing .. math:: x_0 \sim N(\mu_0, \Sigma_0) Parameters ---------- ts_length : scalar(int), optional(default=100) The length of the simulation random_state : int or np.random.RandomState, o...
def simulate(self, ts_length=100, random_state=None): r""" Simulate a time series of length ts_length, first drawing .. math:: x_0 \sim N(\mu_0, \Sigma_0) Parameters ---------- ts_length : scalar(int), optional(default=100) The length of the sim...
r""" Simulate num_reps observations of :math:`x_T` and :math:`y_T` given :math:`x_0 \sim N(\mu_0, \Sigma_0)`. Parameters ---------- T : scalar(int), optional(default=10) The period that we want to replicate values for num_reps : scalar(int), optional(default=...
def replicate(self, T=10, num_reps=100, random_state=None): r""" Simulate num_reps observations of :math:`x_T` and :math:`y_T` given :math:`x_0 \sim N(\mu_0, \Sigma_0)`. Parameters ---------- T : scalar(int), optional(default=10) The period that we want to re...
r""" Create a generator to calculate the population mean and variance-convariance matrix for both :math:`x_t` and :math:`y_t` starting at the initial condition (self.mu_0, self.Sigma_0). Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x, Sigma_y) for the next period...
def moment_sequence(self): r""" Create a generator to calculate the population mean and variance-convariance matrix for both :math:`x_t` and :math:`y_t` starting at the initial condition (self.mu_0, self.Sigma_0). Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x, ...
r""" Compute the moments of the stationary distributions of :math:`x_t` and :math:`y_t` if possible. Computation is by iteration, starting from the initial conditions self.mu_0 and self.Sigma_0 Parameters ---------- max_iter : scalar(int), optional(default=200) ...
def stationary_distributions(self, max_iter=200, tol=1e-5): r""" Compute the moments of the stationary distributions of :math:`x_t` and :math:`y_t` if possible. Computation is by iteration, starting from the initial conditions self.mu_0 and self.Sigma_0 Parameters -----...
r""" Forecast the geometric sums .. math:: S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big] S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big] Parameters ---------- beta : scalar(float) Discount factor, in [0, 1) ...
def geometric_sums(self, beta, x_t): r""" Forecast the geometric sums .. math:: S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big] S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big] Parameters ---------- beta : scalar(fl...
r""" Pulls off the imuplse response coefficients to a shock in :math:`w_{t}` for :math:`x` and :math:`y` Important to note: We are uninterested in the shocks to v for this method * :math:`x` coefficients are :math:`C, AC, A^2 C...` * :math:`y` coefficients are :math:`GC...
def impulse_response(self, j=5): r""" Pulls off the imuplse response coefficients to a shock in :math:`w_{t}` for :math:`x` and :math:`y` Important to note: We are uninterested in the shocks to v for this method * :math:`x` coefficients are :math:`C, AC, A^2 C...` ...
Custom version of np.searchsorted. Return the largest index `i` such that `a[i-1] <= v < a[i]` (for `i = 0`, `v < a[0]`); if `v[n-1] <= v`, return `n`, where `n = len(a)`. Parameters ---------- a : ndarray(float, ndim=1) Input array. Must be sorted in ascending order. v : scalar(float)...
def searchsorted(a, v): """ Custom version of np.searchsorted. Return the largest index `i` such that `a[i-1] <= v < a[i]` (for `i = 0`, `v < a[0]`); if `v[n-1] <= v`, return `n`, where `n = len(a)`. Parameters ---------- a : ndarray(float, ndim=1) Input array. Must be sorted in asc...
Uses a jitted version of the maximization routine from SciPy's fminbound. The algorithm is identical except that it's been switched to maximization rather than minimization, and the tests for convergence have been stripped out to allow for jit compilation. Note that the input function `func` must be ji...
def brent_max(func, a, b, args=(), xtol=1e-5, maxiter=500): """ Uses a jitted version of the maximization routine from SciPy's fminbound. The algorithm is identical except that it's been switched to maximization rather than minimization, and the tests for convergence have been stripped out to allow ...