INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Computes the non - stochastic steady - state of the economy.
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
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
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
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.
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 matrix_eqn. solve_discrete_riccat...
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.
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 ).
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.
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.
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.
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.
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.
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
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
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
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
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
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
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.
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.
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.
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.
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
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
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.
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 ] _.
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.
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 error check is made for the inputs....
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...
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.
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...
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) ...
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...
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)
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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
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
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
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 information see the docstring of that m...
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.
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.
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
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
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
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
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
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
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 ).
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
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
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
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 ).
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.
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 ...
mean
def mean(self): "mean" n, a, b = self.n, self.a, self.b return n * a / (a + b)
Variance
def var(self): "Variance" n, a, b = self.n, self.a, self.b top = n*a*b * (a + b + n) btm = (a+b)**2.0 * (a+b+1.0) return top / btm
skewness
def skew(self): "skewness" n, a, b = self.n, self.a, self.b t1 = (a+b+2*n) * (b - a) / (a+b+2) t2 = sqrt((1+a+b) / (n*a*b * (n+a+b))) return t1 * t2
r Generate the vector of probabilities for the Beta - binomial ( n a b ) distribution.
def pdf(self): r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = ...
Using abreu_sannikov algorithm to compute the set of payoff pairs of all pure - strategy subgame - perfect equilibria with public randomization for any repeated two - player games with perfect monitoring and discounting following Abreu and Sannikov ( 2014 ).
def _equilibrium_payoffs_abreu_sannikov(rpg, tol=1e-12, max_iter=500, u_init=np.zeros(2)): """ Using 'abreu_sannikov' algorithm to compute the set of payoff pairs of all pure-strategy subgame-perfect equilibria with public randomization for any repeated two-player...
Calculate the normalized payoff gains from deviating from the current action to the best response for each player.
def _best_dev_gains(rpg): """ Calculate the normalized payoff gains from deviating from the current action to the best response for each player. Parameters ---------- rpg : RepeatedGame Two player repeated game. Returns ------- best_dev_gains : tuple(ndarray(float, ndim=2))...
Updating the payoff convex hull by iterating all action pairs. Using the R operator proposed by Abreu and Sannikov 2014.
def _R(delta, nums_actions, payoff_arrays, best_dev_gains, points, vertices, equations, u, IC, action_profile_payoff, extended_payoff, new_pts, W_new, tol=1e-10): """ Updating the payoff convex hull by iterating all action pairs. Using the R operator proposed by Abreu and Sannikov 2014. P...
Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise.
def _find_C(C, points, vertices, equations, extended_payoff, IC, tol): """ Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array...
Find the intersection points of a half - closed simplex ( pt0 pt1 ] and IC constraints.
def _intersect(C, n, weights, IC, pt0, pt1, tol): """ Find the intersection points of a half-closed simplex (pt0, pt1] and IC constraints. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated points of one action profile. One action profile...
Update the threat points if it not feasible in the new W by the minimum of new feasible payoffs.
def _update_u(u, W): """ Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hul...
Compute the set of payoff pairs of all pure - strategy subgame - perfect equilibria with public randomization for any repeated two - player games with perfect monitoring and discounting.
def equilibrium_payoffs(self, method=None, options=None): """ Compute the set of payoff pairs of all pure-strategy subgame-perfect equilibria with public randomization for any repeated two-player games with perfect monitoring and discounting. Parameters ---------- ...
Return a random NormalFormGame instance where the payoffs are drawn independently from the uniform distribution on [ 0 1 ).
def random_game(nums_actions, random_state=None): """ Return a random NormalFormGame instance where the payoffs are drawn independently from the uniform distribution on [0, 1). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. ran...
Return a random NormalFormGame instance where the payoff profiles are drawn independently from the standard multi - normal with the covariance of any pair of payoffs equal to rho as studied in [ 1 ] _.
def covariance_game(nums_actions, rho, random_state=None): """ Return a random NormalFormGame instance where the payoff profiles are drawn independently from the standard multi-normal with the covariance of any pair of payoffs equal to `rho`, as studied in [1]_. Parameters ---------- nu...
Return a tuple of random pure actions ( integers ).
def random_pure_actions(nums_actions, random_state=None): """ Return a tuple of random pure actions (integers). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random see...
Return a tuple of random mixed actions ( vectors of floats ).
def random_mixed_actions(nums_actions, random_state=None): """ Return a tuple of random mixed actions (vectors of floats). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional ...
Retrieve raw files from QuantEcon. notebooks or other Github repo Parameters ---------- file_list list or dict A list of files to specify a collection of filenames A dict of dir: list ( files ) to specify a directory repo str optional ( default = REPO ) raw str optional ( defualt = RAW ) This is here in case github cha...
def fetch_nb_dependencies(files, repo=REPO, raw=RAW, branch=BRANCH, folder=FOLDER, overwrite=False, verbose=True): """ Retrieve raw files from QuantEcon.notebooks or other Github repo Parameters ---------- file_list list or dict A list of files to specify a collection of filen...
r Compute the limit of a Nash linear quadratic dynamic game. In this problem player i minimizes
def nnash(A, B1, B2, R1, R2, Q1, Q2, S1, S2, W1, W2, M1, M2, beta=1.0, tol=1e-8, max_iter=1000, random_state=None): r""" Compute the limit of a Nash linear quadratic dynamic game. In this problem, player i minimizes .. math:: \sum_{t=0}^{\infty} \left\{ x_t' r_i x_...
r Select from a tuple of ( root funccalls iterations flag )
def _results(r): r"""Select from a tuple of(root, funccalls, iterations, flag)""" x, funcalls, iterations, flag = r return results(x, funcalls, iterations, flag == 0)
Find a zero from the Newton - Raphson method using the jitted version of Scipy s newton for scalars. Note that this does not provide an alternative method such as secant. Thus it is important that fprime can be provided.
def newton(func, x0, fprime, args=(), tol=1.48e-8, maxiter=50, disp=True): """ Find a zero from the Newton-Raphson method using the jitted version of Scipy's newton for scalars. Note that this does not provide an alternative method such as secant. Thus, it is important that `fprime` can be pr...
Find a zero from the secant method using the jitted version of Scipy s secant method.
def newton_secant(func, x0, args=(), tol=1.48e-8, maxiter=50, disp=True): """ Find a zero from the secant method using the jitted version of Scipy's secant method. Note that `func` must be jitted via Numba. Parameters ---------- func : callable and jitted The func...
Conditional checks for intervals in methods involving bisection
def _bisect_interval(a, b, fa, fb): """Conditional checks for intervals in methods involving bisection""" if fa*fb > 0: raise ValueError("f(a) and f(b) must have different signs") root = 0.0 status = _ECONVERR # Root found at either end of [a,b] if fa == 0: root = a stat...
Find root of a function within an interval adapted from Scipy s bisect.
def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): """ Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same sig...
Find a root of a function in a bracketing interval using Brent s method adapted from Scipy s brentq.
def brentq(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): """ Find a root of a function in a bracketing interval using Brent's method adapted from Scipy's brentq. Uses the classic Brent's method to find a zero of the function `f` on the sign changing interval [a , b...
r Computes and returns an approximate fixed point of the function T.
def compute_fixed_point(T, v, error_tol=1e-3, max_iter=50, verbose=2, print_skip=5, method='iteration', *args, **kwargs): r""" Computes and returns an approximate fixed point of the function `T`. The default method `'iteration'` simply iterates the function given an initial cond...
Implement the imitation game algorithm by McLennan and Tourky ( 2006 ) for computing an approximate fixed point of T.
def _compute_fixed_point_ig(T, v, max_iter, verbose, print_skip, is_approx_fp, *args, **kwargs): """ Implement the imitation game algorithm by McLennan and Tourky (2006) for computing an approximate fixed point of `T`. Parameters ---------- is_approx_fp : callable ...
Given sequences X and Y of ndarrays initialize the tableau and basis arrays in place for the geometric imitation game as defined in McLennan and Tourky ( 2006 ) to be passed to _lemke_howson_tbl.
def _initialize_tableaux_ig(X, Y, tableaux, bases): """ Given sequences `X` and `Y` of ndarrays, initialize the tableau and basis arrays in place for the "geometric" imitation game as defined in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`. Parameters ---------- X, Y : nd...
Return an iterable with the active participants in a room.
def get_participants(self, namespace, room): """Return an iterable with the active participants in a room.""" for sid, active in six.iteritems(self.rooms[namespace][room].copy()): yield sid
Register a client connection to a namespace.
def connect(self, sid, namespace): """Register a client connection to a namespace.""" self.enter_room(sid, namespace, None) self.enter_room(sid, namespace, sid)
Put the client in the to - be - disconnected list.
def pre_disconnect(self, sid, namespace): """Put the client in the to-be-disconnected list. This allows the client data structures to be present while the disconnect handler is invoked, but still recognize the fact that the client is soon going away. """ if namespace not...
Register a client disconnect from a namespace.
def disconnect(self, sid, namespace): """Register a client disconnect from a namespace.""" if namespace not in self.rooms: return rooms = [] for room_name, room in six.iteritems(self.rooms[namespace].copy()): if sid in room: rooms.append(room_name)...