INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Compute the value of a policy.
def evaluate_policy(self, sigma): """ Compute the value of a policy. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- v_sigma : ndarray(float, ndim=1) Value vector of `sigma`, of le...
Iteratively apply the operator T to v. Modify v in - place. Iteration is performed for at most a number max_iter of times. If tol is specified it is terminated once the distance of T ( v ) from v ( in the max norm ) is less than tol.
def operator_iteration(self, T, v, max_iter, tol=None, *args, **kwargs): """ Iteratively apply the operator `T` to `v`. Modify `v` in-place. Iteration is performed for at most a number `max_iter` of times. If `tol` is specified, it is terminated once the distance of `T(v)` from `...
Solve the dynamic programming problem.
def solve(self, method='policy_iteration', v_init=None, epsilon=None, max_iter=None, k=20): """ Solve the dynamic programming problem. Parameters ---------- method : str, optinal(default='policy_iteration') Solution method, str in {'value_iteration', 'v...
Solve the optimization problem by value iteration. See the solve method.
def value_iteration(self, v_init=None, epsilon=None, max_iter=None): """ Solve the optimization problem by value iteration. See the `solve` method. """ if self.beta == 1: raise NotImplementedError(self._error_msg_no_discounting) if max_iter is None: ...
Solve the optimization problem by policy iteration. See the solve method.
def policy_iteration(self, v_init=None, max_iter=None): """ Solve the optimization problem by policy iteration. See the `solve` method. """ if self.beta == 1: raise NotImplementedError(self._error_msg_no_discounting) if max_iter is None: max_iter...
Solve the optimization problem by modified policy iteration. See the solve method.
def modified_policy_iteration(self, v_init=None, epsilon=None, max_iter=None, k=20): """ Solve the optimization problem by modified policy iteration. See the `solve` method. """ if self.beta == 1: raise NotImplementedError(self._erro...
Returns the controlled Markov chain for a given policy sigma.
def controlled_mc(self, sigma): """ Returns the controlled Markov chain for a given policy `sigma`. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- mc : MarkovChain Controlled Mark...
Smooth the data in x using convolution with a window of requested size and type.
def smooth(x, window_len=7, window='hanning'): """ Smooth the data in x using convolution with a window of requested size and type. Parameters ---------- x : array_like(float) A flat NumPy array containing the data to smooth window_len : scalar(int), optional An odd integer ...
r Computes the periodogram
def periodogram(x, window=None, window_len=7): r""" Computes the periodogram .. math:: I(w) = \frac{1}{n} \Big[ \sum_{t=0}^{n-1} x_t e^{itw} \Big] ^2 at the Fourier frequences :math:`w_j := \frac{2 \pi j}{n}`, :math:`j = 0, \dots, n - 1`, using the fast Fourier transform. Only the fre...
Compute periodogram from data x using prewhitening smoothing and recoloring. The data is fitted to an AR ( 1 ) model for prewhitening and the residuals are used to compute a first - pass periodogram with smoothing. The fitted coefficients are then used for recoloring.
def ar_periodogram(x, window='hanning', window_len=7): """ Compute periodogram from data x, using prewhitening, smoothing and recoloring. The data is fitted to an AR(1) model for prewhitening, and the residuals are used to compute a first-pass periodogram with smoothing. The fitted coefficients ar...
Generator version of support_enumeration.
def support_enumeration_gen(g): """ Generator version of `support_enumeration`. Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. Yields ------- tuple(ndarray(float, ndim=1)) Tuple of Nash equilibrium mixed actions. """ try: ...
Main body of support_enumeration_gen.
def _support_enumeration_gen(payoff_matrices): """ Main body of `support_enumeration_gen`. Parameters ---------- payoff_matrices : tuple(ndarray(float, ndim=2)) Tuple of payoff matrices, of shapes (m, n) and (n, m), respectively. Yields ------ out : tuple(ndarray(float,...
Given a player s payoff matrix payoff_matrix an array own_supp of this player s actions and an array opp_supp of the opponent s actions each of length k compute the opponent s mixed action whose support equals opp_supp and for which the player is indifferent among the actions in own_supp if any such exists. Return True...
def _indiff_mixed_action(payoff_matrix, own_supp, opp_supp, A, out): """ Given a player's payoff matrix `payoff_matrix`, an array `own_supp` of this player's actions, and an array `opp_supp` of the opponent's actions, each of length k, compute the opponent's mixed action whose support equals `opp_su...
Convert a pure action to the corresponding mixed action.
def pure2mixed(num_actions, action): """ Convert a pure action to the corresponding mixed action. Parameters ---------- num_actions : scalar(int) The number of the pure actions (= the length of a mixed action). action : scalar(int) The pure action to convert to the correspondin...
Numba - optimized version of Player. best_response compilied in nopython mode specialized for 2 - player games ( where there is only one opponent ).
def best_response_2p(payoff_matrix, opponent_mixed_action, tol=1e-8): """ Numba-optimized version of `Player.best_response` compilied in nopython mode, specialized for 2-player games (where there is only one opponent). Return the best response action (with the smallest index if more than one) t...
Return a new Player instance with the action ( s ) specified by action deleted from the action set of the player specified by player_idx. Deletion is not performed in place.
def delete_action(self, action, player_idx=0): """ Return a new `Player` instance with the action(s) specified by `action` deleted from the action set of the player specified by `player_idx`. Deletion is not performed in place. Parameters ---------- action : scal...
Return an array of payoff values one for each own action given a profile of the opponents actions.
def payoff_vector(self, opponents_actions): """ Return an array of payoff values, one for each own action, given a profile of the opponents' actions. Parameters ---------- opponents_actions : see `best_response`. Returns ------- payoff_vector : n...
Return True if own_action is a best response to opponents_actions.
def is_best_response(self, own_action, opponents_actions, tol=None): """ Return True if `own_action` is a best response to `opponents_actions`. Parameters ---------- own_action : scalar(int) or array_like(float, ndim=1) An integer representing a pure action, ...
Return the best response action ( s ) to opponents_actions.
def best_response(self, opponents_actions, tie_breaking='smallest', payoff_perturbation=None, tol=None, random_state=None): """ Return the best response action(s) to `opponents_actions`. Parameters ---------- opponents_actions : scalar(int) or array_like ...
Return a pure action chosen randomly from actions.
def random_choice(self, actions=None, random_state=None): """ Return a pure action chosen randomly from `actions`. Parameters ---------- actions : array_like(int), optional(default=None) An array of integers representing pure actions. random_state : int or n...
Determine whether action is strictly dominated by some mixed action.
def is_dominated(self, action, tol=None, method=None): """ Determine whether `action` is strictly dominated by some mixed action. Parameters ---------- action : scalar(int) Integer representing a pure action. tol : scalar(float), optional(default=Non...
Return a list of actions that are strictly dominated by some mixed actions.
def dominated_actions(self, tol=None, method=None): """ Return a list of actions that are strictly dominated by some mixed actions. Parameters ---------- tol : scalar(float), optional(default=None) Tolerance level used in determining domination. If None, ...
Return a new NormalFormGame instance with the action ( s ) specified by action deleted from the action set of the player specified by player_idx. Deletion is not performed in place.
def delete_action(self, player_idx, action): """ Return a new `NormalFormGame` instance with the action(s) specified by `action` deleted from the action set of the player specified by `player_idx`. Deletion is not performed in place. Parameters ---------- player_...
Return True if action_profile is a Nash equilibrium.
def is_nash(self, action_profile, tol=None): """ Return True if `action_profile` is a Nash equilibrium. Parameters ---------- action_profile : array_like(int or array_like(float)) An array of N objects, where each object must be an integer (pure action) o...
r Find one mixed - action epsilon - Nash equilibrium of an N - player normal form game by the fixed point computation algorithm by McLennan and Tourky [ 1 ] _.
def mclennan_tourky(g, init=None, epsilon=1e-3, max_iter=200, full_output=False): r""" Find one mixed-action epsilon-Nash equilibrium of an N-player normal form game by the fixed point computation algorithm by McLennan and Tourky [1]_. Parameters ---------- g : NormalFor...
Selection of the best response correspondence of g that selects the best response action with the smallest index when there are ties where the input and output are flattened action profiles.
def _best_response_selection(x, g, indptr=None): """ Selection of the best response correspondence of `g` that selects the best response action with the smallest index when there are ties, where the input and output are flattened action profiles. Parameters ---------- x : array_like(float, ...
Determine whether x is an epsilon - Nash equilibrium of g.
def _is_epsilon_nash(x, g, epsilon, indptr=None): """ Determine whether `x` is an `epsilon`-Nash equilibrium of `g`. Parameters ---------- x : array_like(float, ndim=1) Array of flattened mixed action profile of length equal to n_0 + ... + n_N-1, where `out[indptr[i]:indptr[i+1]]` c...
Obtain a tuple of mixed actions from a flattened action profile.
def _get_action_profile(x, indptr): """ Obtain a tuple of mixed actions from a flattened action profile. Parameters ---------- x : array_like(float, ndim=1) Array of flattened mixed action profile of length equal to n_0 + ... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains play...
Flatten the given action profile.
def _flatten_action_profile(action_profile, indptr): """ Flatten the given action profile. Parameters ---------- action_profile : array_like(int or array_like(float, ndim=1)) Profile of actions of the N players, where each player i' action is a pure action (int) or a mixed action (a...
Return a NormalFormGame instance of a 2 - player non - zero sum Colonel Blotto game ( Hortala - Vallve and Llorente - Saguer 2012 ) where the players have an equal number t of troops to assign to h hills ( so that the number of actions for each player is equal to ( t + h - 1 ) choose ( h - 1 ) = ( t + h - 1 ) !/ ( t! *...
def blotto_game(h, t, rho, mu=0, random_state=None): """ Return a NormalFormGame instance of a 2-player non-zero sum Colonel Blotto game (Hortala-Vallve and Llorente-Saguer, 2012), where the players have an equal number `t` of troops to assign to `h` hills (so that the number of actions for each pla...
Populate the ndarrays in payoff_arrays with the payoff values of the Blotto game with h hills and t troops.
def _populate_blotto_payoff_arrays(payoff_arrays, actions, values): """ Populate the ndarrays in `payoff_arrays` with the payoff values of the Blotto game with h hills and t troops. Parameters ---------- payoff_arrays : tuple(ndarray(float, ndim=2)) Tuple of 2 ndarrays of shape (n, n), ...
Return a NormalFormGame instance of ( the 2 - player version of ) the ranking game studied by Goldberg et al. ( 2013 ) where each player chooses an effort level associated with a score and a cost which are both increasing functions with randomly generated step sizes. The player with the higher score wins the first priz...
def ranking_game(n, steps=10, random_state=None): """ Return a NormalFormGame instance of (the 2-player version of) the "ranking game" studied by Goldberg et al. (2013), where each player chooses an effort level associated with a score and a cost which are both increasing functions with randomly gen...
Populate the ndarrays in payoff_arrays with the payoff values of the ranking game given scores and costs.
def _populate_ranking_payoff_arrays(payoff_arrays, scores, costs): """ Populate the ndarrays in `payoff_arrays` with the payoff values of the ranking game given `scores` and `costs`. Parameters ---------- payoff_arrays : tuple(ndarray(float, ndim=2)) Tuple of 2 ndarrays of shape (n, n)....
Return a NormalFormGame instance of the 2 - player game introduced by Sandholm Gilpin and Conitzer ( 2005 ) which has a unique Nash equilibrium where each player plays half of the actions with positive probabilities. Payoffs are normalized so that the minimum and the maximum payoffs are 0 and 1 respectively.
def sgc_game(k): """ Return a NormalFormGame instance of the 2-player game introduced by Sandholm, Gilpin, and Conitzer (2005), which has a unique Nash equilibrium, where each player plays half of the actions with positive probabilities. Payoffs are normalized so that the minimum and the maximum...
Populate the ndarrays in payoff_arrays with the payoff values of the SGC game.
def _populate_sgc_payoff_arrays(payoff_arrays): """ Populate the ndarrays in `payoff_arrays` with the payoff values of the SGC game. Parameters ---------- payoff_arrays : tuple(ndarray(float, ndim=2)) Tuple of 2 ndarrays of shape (4*k-1, 4*k-1). Modified in place. """ n = payof...
Return a NormalFormGame instance of the 2 - player win - lose game whose payoffs are either 0 or 1 introduced by Anbalagan et al. ( 2013 ). Player 0 has n actions which constitute the set of nodes { 0... n - 1 } while player 1 has n choose k actions each corresponding to a subset of k elements of the set of n nodes. Gi...
def tournament_game(n, k, random_state=None): """ Return a NormalFormGame instance of the 2-player win-lose game, whose payoffs are either 0 or 1, introduced by Anbalagan et al. (2013). Player 0 has n actions, which constitute the set of nodes {0, ..., n-1}, while player 1 has n choose k actions, ea...
Populate payoff_array with the payoff values for player 0 in the tournament game given a random tournament graph in CSR format.
def _populate_tournament_payoff_array0(payoff_array, k, indices, indptr): """ Populate `payoff_array` with the payoff values for player 0 in the tournament game given a random tournament graph in CSR format. Parameters ---------- payoff_array : ndarray(float, ndim=2) ndarray of shape (n...
Populate payoff_array with the payoff values for player 1 in the tournament game.
def _populate_tournament_payoff_array1(payoff_array, k): """ Populate `payoff_array` with the payoff values for player 1 in the tournament game. Parameters ---------- payoff_array : ndarray(float, ndim=2) ndarray of shape (m, n), where m = n choose k, prefilled with zeros. Modif...
Return a NormalFormGame instance of the 2 - player game unit vector game ( Savani and von Stengel 2016 ). Payoffs for player 1 are chosen randomly from the [ 0 1 ) range. For player 0 each column contains exactly one 1 payoff and the rest is 0.
def unit_vector_game(n, avoid_pure_nash=False, random_state=None): """ Return a NormalFormGame instance of the 2-player game "unit vector game" (Savani and von Stengel, 2016). Payoffs for player 1 are chosen randomly from the [0, 1) range. For player 0, each column contains exactly one 1 payoff and ...
r This routine computes the stationary distribution of an irreducible Markov transition matrix ( stochastic matrix ) or transition rate matrix ( generator matrix ) A.
def gth_solve(A, overwrite=False, use_jit=True): r""" This routine computes the stationary distribution of an irreducible Markov transition matrix (stochastic matrix) or transition rate matrix (generator matrix) `A`. More generally, given a Metzler matrix (square matrix whose off-diagonal entri...
JIT complied version of the main routine of gth_solve.
def _gth_solve_jit(A, out): """ JIT complied version of the main routine of gth_solve. Parameters ---------- A : numpy.ndarray(float, ndim=2) Stochastic matrix or generator matrix. Must be of shape n x n. Data will be overwritten. out : numpy.ndarray(float, ndim=1) Outp...
Generate the indices of nonzero entries of a csr_matrix S
def _csr_matrix_indices(S): """ Generate the indices of nonzero entries of a csr_matrix S """ m, n = S.shape for i in range(m): for j in range(S.indptr[i], S.indptr[i+1]): row_index, col_index = i, S.indices[j] yield row_index, col_index
Return a random tournament graph [ 1 ] _ with n nodes.
def random_tournament_graph(n, random_state=None): """ Return a random tournament graph [1]_ with n nodes. Parameters ---------- n : scalar(int) Number of nodes. random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set...
Populate ndarrays row and col with directed edge indices determined by random numbers in r for a tournament graph with n nodes which has num_edges = n * ( n - 1 )// 2 edges.
def _populate_random_tournament_row_col(n, r, row, col): """ Populate ndarrays `row` and `col` with directed edge indices determined by random numbers in `r` for a tournament graph with n nodes, which has num_edges = n * (n-1) // 2 edges. Parameters ---------- n : scalar(int) Number...
Set self. _num_scc and self. _scc_proj by calling scipy. sparse. csgraph. connected_components: * docs. scipy. org/ doc/ scipy/ reference/ sparse. csgraph. html * github. com/ scipy/ scipy/ blob/ master/ scipy/ sparse/ csgraph/ _traversal. pyx
def _find_scc(self): """ Set ``self._num_scc`` and ``self._scc_proj`` by calling ``scipy.sparse.csgraph.connected_components``: * docs.scipy.org/doc/scipy/reference/sparse.csgraph.html * github.com/scipy/scipy/blob/master/scipy/sparse/csgraph/_traversal.pyx ``self._scc_p...
Return the sparse matrix representation of the condensation digraph in lil format.
def _condensation_lil(self): """ Return the sparse matrix representation of the condensation digraph in lil format. """ condensation_lil = sparse.lil_matrix( (self.num_strongly_connected_components, self.num_strongly_connected_components), dtype=bool ...
Set self. _sink_scc_labels which is a list containing the labels of the strongly connected components.
def _find_sink_scc(self): """ Set self._sink_scc_labels, which is a list containing the labels of the strongly connected components. """ condensation_lil = self._condensation_lil() # A sink SCC is a SCC such that none of its members is strongly # connected to no...
Set self. _period and self. _cyclic_components_proj.
def _compute_period(self): """ Set ``self._period`` and ``self._cyclic_components_proj``. Use the algorithm described in: J. P. Jarvis and D. R. Shier, "Graph-Theoretic Analysis of Finite Markov Chains," 1996. """ # Degenerate graph with a single node (which is ...
Return the subgraph consisting of the given nodes and edges between thses nodes.
def subgraph(self, nodes): """ Return the subgraph consisting of the given nodes and edges between thses nodes. Parameters ---------- nodes : array_like(int, ndim=1) Array of node indices. Returns ------- DiGraph A DiGraph ...
Estimate the rank ( i. e. the dimension of the nullspace ) of a matrix.
def rank_est(A, atol=1e-13, rtol=0): """ Estimate the rank (i.e. the dimension of the nullspace) of a matrix. The algorithm used by this function is based on the singular value decomposition of `A`. Parameters ---------- A : array_like(float, ndim=1 or 2) A should be at most 2-D. ...
r This function applies Hamilton filter to the data http:// econweb. ucsd. edu/ ~jhamilto/ hp. pdf Parameters ---------- data: arrray or dataframe h: integer Time horizon that we are likely to predict incorrectly. Original paper recommends 2 for annual data 8 for quarterly data 24 for monthly data. * args: integer If s...
def hamilton_filter(data, h, *args): r""" This function applies "Hamilton filter" to the data http://econweb.ucsd.edu/~jhamilto/hp.pdf Parameters ---------- data : arrray or dataframe h : integer Time horizon that we are likely to predict incorrectly. Ori...
Generate s_indices and a_indices for DiscreteDP for the case where all the actions are feasible at every state.
def sa_indices(num_states, num_actions): """ Generate `s_indices` and `a_indices` for `DiscreteDP`, for the case where all the actions are feasible at every state. Parameters ---------- num_states : scalar(int) Number of states. num_actions : scalar(int) Number of actions. ...
Generate num_reps sample paths of length ts_length where num_reps = out. shape [ 0 ] and ts_length = out. shape [ 1 ].
def _generate_sample_paths(P_cdfs, init_states, random_values, out): """ Generate num_reps sample paths of length ts_length, where num_reps = out.shape[0] and ts_length = out.shape[1]. Parameters ---------- P_cdfs : ndarray(float, ndim=2) Array containing as rows the CDFs of the state t...
For sparse matrix.
def _generate_sample_paths_sparse(P_cdfs1d, indices, indptr, init_states, random_values, out): """ For sparse matrix. Generate num_reps sample paths of length ts_length, where num_reps = out.shape[0] and ts_length = out.shape[1]. Parameters ---------- P_cd...
Generates one sample path from the Markov chain represented by ( n x n ) transition matrix P on state space S = {{ 0... n - 1 }}.
def mc_sample_path(P, init=0, sample_size=1000, random_state=None): """ Generates one sample path from the Markov chain represented by (n x n) transition matrix P on state space S = {{0,...,n-1}}. Parameters ---------- P : array_like(float, ndim=2) A Markov transition matrix. init ...
Return the index ( or indices ) of the given value ( or values ) in state_values.
def get_index(self, value): """ Return the index (or indices) of the given value (or values) in `state_values`. Parameters ---------- value Value(s) to get the index (indices) for. Returns ------- idx : int or ndarray(int) ...
Return the index of the given value in state_values.
def _get_index(self, value): """ Return the index of the given value in `state_values`. Parameters ---------- value Value to get the index for. Returns ------- idx : int Index of `value`. """ error_msg = 'value {0...
Store the stationary distributions in self. _stationary_distributions.
def _compute_stationary(self): """ Store the stationary distributions in self._stationary_distributions. """ if self.is_irreducible: if not self.is_sparse: # Dense stationary_dists = gth_solve(self.P).reshape(1, self.n) else: # Sparse ...
Simulate time series of state transitions where state indices are returned.
def simulate_indices(self, ts_length, init=None, num_reps=None, random_state=None): """ Simulate time series of state transitions, where state indices are returned. Parameters ---------- ts_length : scalar(int) Length of each simulati...
Simulate time series of state transitions where the states are annotated with their values ( if state_values is not None ).
def simulate(self, ts_length, init=None, num_reps=None, random_state=None): """ Simulate time series of state transitions, where the states are annotated with their values (if `state_values` is not None). Parameters ---------- ts_length : scalar(int) Length o...
This method is for updating in the finite horizon case. It shifts the current value function
def update_values(self): """ This method is for updating in the finite horizon case. It shifts the current value function .. math:: V_t(x) = x' P_t x + d_t and the optimal policy :math:`F_t` one step *back* in time, replacing the pair :math:`P_t` and :mat...
Computes the matrix: math: P and scalar: math: d that represent the value function
def stationary_values(self, method='doubling'): """ Computes the matrix :math:`P` and scalar :math:`d` that represent the value function .. math:: V(x) = x' P x + d in the infinite horizon case. Also computes the control matrix :math:`F` from :math:`u = -...
Compute and return the optimal state and control sequences: math: x_0... x_T and: math: u_0... u_T under the assumption that: math: { w_t } is iid and: math: N ( 0 1 ).
def compute_sequence(self, x0, ts_length=None, method='doubling', random_state=None): """ Compute and return the optimal state and control sequences :math:`x_0, ..., x_T` and :math:`u_0,..., u_T` under the assumption that :math:`{w_t}` is iid and :math:`N(0, 1)`...
Generator version of pure_nash_brute.
def pure_nash_brute_gen(g, tol=None): """ Generator version of `pure_nash_brute`. Parameters ---------- g : NormalFormGame tol : scalar(float), optional(default=None) Tolerance level used in determining best responses. If None, default to the value of the `tol` attribute of `g`....
Generates equidistributed sequences with property that averages value of integrable function evaluated over the sequence converges to the integral as n goes to infinity.
def qnwequi(n, a, b, kind="N", equidist_pp=None, random_state=None): """ Generates equidistributed sequences with property that averages value of integrable function evaluated over the sequence converges to the integral as n goes to infinity. Parameters ---------- n : int Number of ...
Computes nodes and weights for multivariate normal distribution
def qnwnorm(n, mu=None, sig2=None, usesqrtm=False): """ Computes nodes and weights for multivariate normal distribution Parameters ---------- n : int or array_like(float) A length-d iterable of the number of nodes in each dimension mu : scalar or array_like(float), optional(default=zer...
Computes nodes and weights for multivariate lognormal distribution
def qnwlogn(n, mu=None, sig2=None): """ Computes nodes and weights for multivariate lognormal distribution Parameters ---------- n : int or array_like(float) A length-d iterable of the number of nodes in each dimension mu : scalar or array_like(float), optional(default=zeros(d)) ...
Computes quadrature nodes and weights for multivariate uniform distribution
def qnwunif(n, a, b): """ Computes quadrature nodes and weights for multivariate uniform distribution Parameters ---------- n : int or array_like(float) A length-d iterable of the number of nodes in each dimension a : scalar or array_like(float) A length-d iterable of lower...
Integrate the d - dimensional function f on a rectangle with lower and upper bound for dimension i defined by a [ i ] and b [ i ] respectively ; using n [ i ] points.
def quadrect(f, n, a, b, kind='lege', *args, **kwargs): """ Integrate the d-dimensional function f on a rectangle with lower and upper bound for dimension i defined by a[i] and b[i], respectively; using n[i] points. Parameters ---------- f : function The function to integrate over. ...
Computes nodes and weights for gamma distribution
def qnwgamma(n, a=1.0, b=1.0, tol=3e-14): """ Computes nodes and weights for gamma distribution Parameters ---------- n : int or array_like(float) A length-d iterable of the number of nodes in each dimension a : scalar or array_like(float) : optional(default=ones(d)) Shape para...
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.
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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
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 = ( n ...
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 \ }.
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 ).
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
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.
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
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.
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.
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...