text
stringlengths
81
112k
Save a GeoDataFrame of place shapes or footprints as an ESRI shapefile. Parameters ---------- gdf : GeoDataFrame the gdf to be saved filename : string what to call the shapefile (file extensions are added automatically) folder : string where to save the shapefile, if non...
Save graph nodes and edges as ESRI shapefiles to disk. Parameters ---------- G : networkx multidigraph filename : string the name of the shapefiles (not including file extensions) folder : string the folder to contain the shapefiles, if None, use default data folder encoding : s...
Save a graph as an OSM XML formatted file. NOTE: for very large networks this method can take upwards of 30+ minutes to finish. Parameters __________ G : networkx multidigraph or multigraph filename : string the name of the osm file (including file extension) folder : string the...
Save graph as GraphML file to disk. Parameters ---------- G : networkx multidigraph filename : string the name of the graphml file (including file extension) folder : string the folder to contain the file, if None, use default data folder gephi : bool if True, give each ...
Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string the name of the graphml file (including file extension) folder : string the folder containing the file, if None, use default data folder node_type : ...
Check if two edge data dictionaries are the same based on OSM ID and geometry. Parameters ---------- data : dict the first edge's data data_other : dict the second edge's data Returns ------- is_dupe : bool def is_duplicate_edge(data, data_other): """ Check if ...
Check if LineString geometries in two edges are the same, in normal or reversed order of points. Parameters ---------- ls1 : LineString the first edge's geometry ls2 : LineString the second edge's geometry Returns ------- bool def is_same_geometry(ls1, ls2): """ ...
Update the keys of edges that share a u, v with another edge but differ in geometry. For example, two one-way streets from u to v that bow away from each other as separate streets, rather than opposite direction edges of a single street. Parameters ---------- G : networkx multidigraph ...
Convert a directed graph to an undirected graph that maintains parallel edges if geometries differ. Parameters ---------- G : networkx multidigraph Returns ------- networkx multigraph def get_undirected(G): """ Convert a directed graph to an undirected graph that maintains paralle...
Convert a graph into node and/or edge GeoDataFrames Parameters ---------- G : networkx multidigraph nodes : bool if True, convert graph nodes to a GeoDataFrame and return it edges : bool if True, convert graph edges to a GeoDataFrame and return it node_geometry : bool if...
Convert node and edge GeoDataFrames into a graph Parameters ---------- gdf_nodes : GeoDataFrame gdf_edges : GeoDataFrame Returns ------- networkx multidigraph def gdfs_to_graph(gdf_nodes, gdf_edges): """ Convert node and edge GeoDataFrames into a graph Parameters --------...
Create a filename string in a consistent format from a place name string. Parameters ---------- place_name : string place name to convert into a filename Returns ------- string def make_shp_filename(place_name): """ Create a filename string in a consistent format from a place ...
Calculate basic descriptive metric and topological stats for a graph. For an unprojected lat-lng graph, tolerance and graph units should be in degrees, and circuity_dist should be 'gc'. For a projected graph, tolerance and graph units should be in meters (or similar) and circuity_dist should be 'euclid...
Calculate extended topological stats and metrics for a graph. Many of these algorithms have an inherently high time complexity. Global topological analysis of large complex networks is extremely time consuming and may exhaust computer memory. Consider using function arguments to not run metrics that re...
r""" Solve by backward induction a :math:`T`-period finite horizon discrete dynamic program with stationary reward and transition probability functions :math:`r` and :math:`q` and discount factor :math:`\beta \in [0, 1]`. The optimal value functions :math:`v^*_0, \ldots, v^*_T` and policy funct...
Check whether `s_indices` and `a_indices` are sorted in lexicographic order. Parameters ---------- s_indices, a_indices : ndarray(ndim=1) Returns ------- bool Whether `s_indices` and `a_indices` are sorted. def _has_sorted_sa_indices(s_indices, a_indices): """ Check whethe...
Generate `a_indptr`; stored in `out`. `s_indices` is assumed to be in sorted order. Parameters ---------- num_states : scalar(int) s_indices : ndarray(int, ndim=1) out : ndarray(int, ndim=1) Length must be num_states+1. def _generate_a_indptr(num_states, s_indices, out): """ ...
Check that for every state, reward is finite for some action, and for the case sa_pair is True, that for every state, there is some action available. def _check_action_feasibility(self): """ Check that for every state, reward is finite for some action, and for the case sa_pair i...
Convert this instance of `DiscreteDP` to SA-pair form Parameters ---------- sparse : bool, optional(default=True) Should the `Q` matrix be stored as a sparse matrix? If true the CSR format is used Returns ------- ddp_sa : DiscreteDP T...
Convert this instance of `DiscreteDP` to the "product" form. The product form uses the version of the init method taking `R`, `Q` and `beta`. Parameters ---------- Returns ------- ddp_sa : DiscreteDP The correspnoding DiscreteDP instance in product ...
Given a policy `sigma`, return the reward vector `R_sigma` and the transition probability matrix `Q_sigma`. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- R_sigma : ndarray(float, ndim=1) ...
The Bellman operator, which computes and returns the updated value function `Tv` for a value function `v`. Parameters ---------- v : array_like(float, ndim=1) Value function vector, of length n. Tv : ndarray(float, ndim=1), optional(default=None) Optiona...
Given a policy `sigma`, return the T_sigma operator. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- callable The T_sigma operator. def T_sigma(self, sigma): """ Given a policy `s...
Compute the v-greedy policy. Parameters ---------- v : array_like(float, ndim=1) Value function vector, of length n. sigma : ndarray(int, ndim=1), optional(default=None) Optional output array for `sigma`. Returns ------- sigma : ndarray(...
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 length n. def evaluate_policy(self, sigma): """...
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`. Parameters ---------- T : c...
Solve the dynamic programming problem. Parameters ---------- method : str, optinal(default='policy_iteration') Solution method, str in {'value_iteration', 'vi', 'policy_iteration', 'pi', 'modified_policy_iteration', 'mpi'}. v_init : array_like(float,...
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 NotImp...
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 NotImplementedErr...
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` me...
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 Markov chain. def controlled_mc(self, sigma): "...
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 giving the length of the window. Defaults to 7. window...
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 frequences :math:`w_j` in :math:`[0, \pi]` and corresp...
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. Parameters ---------- x : ...
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. def support_enumeration_gen(g): """ Generator version of `...
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, ndim=1)) Tuple of Nash equilibrium mixed actions, ...
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`, ...
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 corresponding mixed action. Returns ------- ndar...
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) to `opponent_mixed_action` under `payoff_matrix`. Parameters ---------- ...
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 : scalar(int) or array_like(int) Integer or array like of int...
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 : ndarray(float, ndim=1) An array representing the play...
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, or an array of floats representing a mixed action. opponents_actions...
Return the best response action(s) to `opponents_actions`. Parameters ---------- opponents_actions : scalar(int) or array_like A profile of N-1 opponents' actions, represented by either scalar(int), array_like(float), array_like(int), or array_like(array_like...
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 np.random.RandomState, optional Random seed (integer) or np.random....
Determine whether `action` is strictly dominated by some mixed action. Parameters ---------- action : scalar(int) Integer representing a pure action. tol : scalar(float), optional(default=None) Tolerance level used in determining domination. If 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, default to the value of the `tol` attribute. method : s...
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_idx : scalar(int) Index of the player to delete actio...
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) or an array of floats (mixed action). tol : scalar(float)...
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 : NormalFormGame NormalFormGame instance. init : array_like(int or array_like(float, ndim=1)), optional ...
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, ndim=1) Array of flattened mixed action profile of le...
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]]` contains player i's mixed action. g : NormalFormGa...
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 player i's mixed action. indptr : array...
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 (array_like of floats of length n_i). indptr : array_l...
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!*(h-1)!))....
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), where n = (t+h-1)!/ (t!*(h-1)!). Modified in place. actions : ndarra...
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 t...
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). Modified in place. scores : ndarray(int, ndim=2) ndarray of shape ...
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, respect...
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. def _populate_sgc_payoff_arrays(payoff_arrays): """ Populate the ndarrays...
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 ...
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, m), where m = n choose k, prefilled with zeros. Modified in place. k : s...
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. Modified in place. k : scalar(int) Size of the subsets of node...
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. Parameters ---------- n : scalar(int) Numbe...
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 entries are all nonnegative) `A`, this routine solves ...
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) Output array in which to place the stationar...
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] ...
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 the initial state of the random number generator for ...
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 of nodes. r : ndarray(float, ndim=1) ndarray of length ...
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_proj`` is a list of length `n` that assign...
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_strongl...
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._conde...
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. def _compute_period(self): """ Set ``self._period`` and ``self._cyclic_components_proj``. ...
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 representing the subgraph. def subgraph(self, ...
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. A 1-D array with length n will be treated...
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, ...
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. Returns ------- s_indices : ndarray(int,...
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 transition. init_states : array_like(int, ndim=1) Array containing th...
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_cdfs1d : ndarray(float, ndim=1) 1D array containing the CDFs of the state transition. indices : ndarray(int, ndim=1) CSR f...
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 : array_like(float ndim=1) or scalar(int), optional(default=0) If init i...
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) Index of `value` if `value` is a single state v...
Return the index of the given value in `state_values`. Parameters ---------- value Value to get the index for. Returns ------- idx : int Index of `value`. def _get_index(self, value): """ Return the index of the given value in `s...
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_...
Simulate time series of state transitions, where state indices are returned. Parameters ---------- ts_length : scalar(int) Length of each simulation. init : int or array_like(int, ndim=1), optional Initial state(s). If None, the initial state is randomly...
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 of each simulation. init : scalar or array_like, optional(default=None) Init...
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 :math:`d_t` with :math:`P_{t-1}` and :mat...
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 = - Fx`. Computation is via the solution algorithm as specified...
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)`. Parameters ---------- x0 : array_like(float) The initial state, a vector of length n ...
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`. Yields ------ out : tuple(int) ...
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 sequence points a : scalar or array_like(float) A length-d iterable ...
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=zeros(d)) The means of each dimension of the random variabl...
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)) The means of each dimension of the random vari...
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 endpoints. If a scalar is given, ...
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. This should be a function that accepts as its first argument...
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 parameter of the gamma distribution parameter. Must be pos...
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...
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...
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...
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 ...
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....
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...