INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get footprint data from OSM then assemble it into a GeoDataFrame. Parameters ---------- polygon : shapely Polygon or MultiPolygon geographic shape to fetch the footprints within north : float northern latitude of bounding box south : float southern latitude of bounding box ...
def create_footprints_gdf(polygon=None, north=None, south=None, east=None, west=None, footprint_type='building', retain_invalid=False): """ Get footprint data from OSM then assemble it into a GeoDataFrame. Parameters ---------- polygon : shapely Polygon or MultiPolygon ...
Get footprints within some distance north, south, east, and west of a lat-long point. Parameters ---------- point : tuple a lat-long point distance : numeric distance in meters footprint_type : string type of footprint to be downloaded. OSM tag key e.g. 'building', 'land...
def footprints_from_point(point, distance, footprint_type='building', retain_invalid=False): """ Get footprints within some distance north, south, east, and west of a lat-long point. Parameters ---------- point : tuple a lat-long point distance : numeric distance in meters ...
Get footprints within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric distance in meters footprint_type : string type of footprint to be downloaded. OSM tag key...
def footprints_from_address(address, distance, footprint_type='building', retain_invalid=False): """ Get footprints within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric ...
Get footprints within some polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get data within. coordinates should be in units of latitude-longitude degrees. footprint_type : string type of footprint to be downloaded. OSM tag key e.g. 'building'...
def footprints_from_polygon(polygon, footprint_type='building', retain_invalid=False): """ Get footprints within some polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get data within. coordinates should be in units of latitude-longitude degrees. ...
Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its footprints using the footprints_from_address function, which geocodes the place name to a ...
def footprints_from_place(place, footprint_type='building', retain_invalid=False): """ Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its...
Plot a GeoDataFrame of footprints. Parameters ---------- gdf : GeoDataFrame footprints fig : figure ax : axis figsize : tuple color : string the color of the footprints bgcolor : string the background color of the plot set_bounds : bool if True, set b...
def plot_footprints(gdf, fig=None, ax=None, figsize=None, color='#333333', bgcolor='w', set_bounds=True, bbox=None, save=False, show=True, close=False, filename='image', file_format='png', dpi=600): """ Plot a GeoDataFrame of footprints. Parameters ---------- ...
Get the elevation (meters) of each node in the network and add it to the node as an attribute. Parameters ---------- G : networkx multidigraph api_key : string your google maps elevation API key max_locations_per_batch : int max number of coordinate pairs to submit in each API c...
def add_node_elevations(G, api_key, max_locations_per_batch=350, pause_duration=0.02): # pragma: no cover """ Get the elevation (meters) of each node in the network and add it to the node as an attribute. Parameters ---------- G : networkx multidigraph api_key : stri...
Get the directed grade (ie, rise over run) for each edge in the network and add it to the edge as an attribute. Nodes must have elevation attributes to use this function. Parameters ---------- G : networkx multidigraph add_absolute : bool if True, also add the absolute value of the grad...
def add_edge_grades(G, add_absolute=True): # pragma: no cover """ Get the directed grade (ie, rise over run) for each edge in the network and add it to the edge as an attribute. Nodes must have elevation attributes to use this function. Parameters ---------- G : networkx multidigraph ad...
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...
def save_gdf_shapefile(gdf, filename=None, folder=None): """ 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 automatic...
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...
def save_graph_shapefile(G, filename='graph', folder=None, encoding='utf-8'): """ 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 ...
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...
def save_graph_osm(G, node_tags=settings.osm_xml_node_tags, node_attrs=settings.osm_xml_node_attrs, edge_tags=settings.osm_xml_way_tags, edge_attrs=settings.osm_xml_way_attrs, oneway=True, filename='graph.osm', folder=None): ...
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 ...
def save_graphml(G, filename='graph.graphml', folder=None, gephi=False): """ 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 th...
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 : ...
def load_graphml(filename, folder=None, node_type=int): """ 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 co...
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 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 """ ...
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): """ 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...
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 ...
def update_edge_keys(G): """ 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 --------...
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 parallel edges if geometries differ. Parameters ---------- G : networkx multidigraph Returns ------- networkx multigraph """ start_time = time.time() # set from/to nodes before m...
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...
def graph_to_gdfs(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True): """ 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 ...
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 ---------- gdf_nodes : GeoDataFrame gdf_edges : GeoDataFrame Returns ------- networkx multidigraph """ G = nx.MultiDiGraph() G.graph['crs'] = gdf_nodes.crs G.gr...
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 name string. Parameters ---------- place_name : string place name to convert into a filename Returns ------- string """ name_pieces = list(reversed(place_name.split(', ')...
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...
def basic_stats(G, area=None, clean_intersects=False, tolerance=15, circuity_dist='gc'): """ 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 pr...
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...
def extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False): """ 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 ...
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...
def backward_induction(ddp, T, v_term=None): 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 ...
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 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. """ ...
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 is True, that for every state, there is some action available. """ # Check that for every state, reward is finite for some action R_max...
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): """ 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. ...
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...
def to_sa_pair_form(self, sparse=True): """ 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 Retur...
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 ...
def to_product_form(self): """ 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 Th...
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) ...
def RQ_sigma(self, sigma): """ 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 ------- ...
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...
def bellman_operator(self, v, Tv=None, sigma=None): """ 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. ...
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 `sigma`, return the T_sigma operator. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- callable The T_sigma operator. """ ...
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(...
def compute_greedy(self, v, sigma=None): """ 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 `sigm...
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): """ 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`. Parameters ---------- T : c...
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. 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,...
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`. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- mc : MarkovChain Controlled Markov chain.
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. 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...
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 .. 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...
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. Parameters ---------- x : ...
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`. 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 `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`. 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, ...
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`, ...
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. 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...
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). Return the best response action (with the smallest index if more than one) to `opponent_mixed_action` under `payoff_matrix`. Parameters ---------- ...
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. Parameters ---------- action : scalar(int) or array_like(int) Integer or array like of int...
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. Parameters ---------- opponents_actions : see `best_response`. Returns ------- payoff_vector : ndarray(float, ndim=1) An array representing the play...
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`. 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...
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`. 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...
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`. 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....
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...
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...
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, ...
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, ...
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 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...
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. 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)...
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]_. Parameters ---------- g : NormalFormGame NormalFormGame instance. init : array_like(int or array_like(float, ndim=1)), optional ...
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. Parameters ---------- x : array_like(float, ndim=1) Array of flattened mixed action profile of le...
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`. 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...
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. 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...
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. 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...
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!*(h-1)!))....
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. 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...
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 t...
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`. 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 ...
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, respect...
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. 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 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...
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...
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. 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...
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. Parameters ---------- n : scalar(int) Numbe...
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`. More generally, given a Metzler matrix (square matrix whose off-diagonal entries are all nonnegative) `A`, this routine solves ...
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. 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...
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. 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 ...
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. Parameters ---------- n : scalar(int) Number of nodes. r : ndarray(float, ndim=1) ndarray of length ...
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 ``self._scc_proj`` is a list of length `n` that assign...
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``. 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``. 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. Parameters ---------- nodes : array_like(int, ndim=1) Array of node indices. Returns ------- DiGraph A DiGraph representing the subgraph.
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. 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...
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, ...
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 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...
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. 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...
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}}. 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...
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`. 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...
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`. 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 `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. 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...
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). Parameters ---------- ts_length : scalar(int) Length of each simulation. init : scalar or array_like, optional(default=None) Init...
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 .. 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...
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 .. 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...
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)`. Parameters ---------- x0 : array_like(float) The initial state, a vector of length n ...
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`. 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) ...
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. Parameters ---------- n : int Number of sequence points a : scalar or array_like(float) A length-d iterable ...
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 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...
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 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...
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 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, ...
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. Parameters ---------- f : function The function to integrate over. This should be a function that accepts as its first argument...
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 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...
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...