signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def obj_to_rst(self, file_path=None, deliminator='<STR_LIT:U+0020>', tab=None,<EOL>quote_numbers=True, quote_empty_str=False):
tab = self.tab if tab is None else tab<EOL>list_of_list, column_widths = self.get_data_and_shared_column_widths(<EOL>data_kwargs=dict(quote_numbers=quote_numbers,<EOL>quote_empty_str=quote_empty_str,<EOL>deliminator='<STR_LIT:U+0020>'),<EOL>width_kwargs=dict(padding=<NUM_LIT:0>, pad_last_column=True))<EOL>ret = [[cell....
This will return a str of a rst table. :param file_path: str of the path to the file :param keys: list of str of the order of keys to use :param tab: string of offset of the table :param quote_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True w...
f5033:c0:m20
def obj_to_psql(self, file_path=None, deliminator='<STR_LIT>', tab=None,<EOL>quote_numbers=True, quote_empty_str=False):
tab = self.tab if tab is None else tab<EOL>list_of_list, column_widths = self.get_data_and_shared_column_widths(<EOL>data_kwargs=dict(quote_numbers=quote_numbers,<EOL>quote_empty_str=quote_empty_str),<EOL>width_kwargs=dict(padding=<NUM_LIT:0>, pad_first_cell=<NUM_LIT:1>))<EOL>for row in list_of_list:<EOL><INDENT>row[<N...
This will return a str of a psql table. :param file_path: str of the path to the file :param deliminator: str of the bar separating columns :param keys: list of str of the order of keys to use :param tab: string of offset of the table :param quote_numbers: bool if True will quote numb...
f5033:c0:m21
def obj_to_json(self, file_path=None, indent=<NUM_LIT:2>, sort_keys=False,<EOL>quote_numbers=True):
data = [row.obj_to_ordered_dict(self.columns) for row in self]<EOL>if not quote_numbers:<EOL><INDENT>for row in data:<EOL><INDENT>for k, v in row.items():<EOL><INDENT>if isinstance(v, (bool, int, float)):<EOL><INDENT>row[k] = str(row[k])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>ret = json.dumps(data, indent=indent, sort_key...
This will return a str of a json list. :param file_path: path to data file, defaults to self's contents if left alone :param indent: int if set to 2 will indent to spaces and include line breaks. :param sort_keys: sorts columns as oppose to column order. :...
f5033:c0:m22
def obj_to_grid(self, file_path=None, delim=None, tab=None,<EOL>quote_numbers=True, quote_empty_str=False):
div_delims = {"<STR_LIT>": ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'],<EOL>"<STR_LIT>": ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'],<EOL>"<STR_LIT>": ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'],<EOL>"<STR_LIT>": ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']}<EOL>de...
This will return a str of a grid table. :param file_path: path to data file, defaults to self's contents if left alone :param delim: dict of deliminators, defaults to obj_to_str's method: :param tab: string of offset of the table :param quote_n...
f5033:c0:m23
def obj_to_csv(self, file_path=None, quote_everything=False,<EOL>space_columns=True, quote_numbers=True):
list_of_list, column_widths = self.get_data_and_shared_column_widths(<EOL>data_kwargs=dict(quote_numbers=quote_numbers,<EOL>quote_everything=quote_everything,<EOL>safe_str=self._excel_cell),<EOL>width_kwargs=dict(padding=<NUM_LIT:0>))<EOL>if space_columns:<EOL><INDENT>csv = ['<STR_LIT:U+002C>'.join([cell.ljust(column_w...
This will return a str of a csv text that is friendly to excel :param file_path: str to the path :param quote_everything: bool if True will quote everything if it needs it or not, this is so it looks pretty in excel. :param quote_numbers: bool if True will quote numbers that are ...
f5033:c0:m24
def obj_to_html(self, file_path=None, tab='<STR_LIT>', border=<NUM_LIT:1>, cell_padding=<NUM_LIT:5>,<EOL>cell_spacing=<NUM_LIT:1>, border_color='<STR_LIT>', align='<STR_LIT>',<EOL>row_span=None, quote_numbers=True, quote_empty_str=False):
html_table = self._html_link_cells()<EOL>html_table._html_row_respan(row_span)<EOL>data = [self._html_row(html_table.columns, tab + '<STR_LIT:U+0020>', '<STR_LIT>',<EOL>align=align, quote_numbers=quote_numbers)]<EOL>for i, row in enumerate(html_table):<EOL><INDENT>color = '<STR_LIT>' if i % <NUM_LIT:2> else None<EOL>ro...
This will return a str of an html table. :param file_path: str for path to the file :param tab: str to insert before each line e.g. ' ' :param border: int of the thickness of the table lines :param cell_padding: int of the padding for the cells :param cell_spacing: int of the spacing...
f5033:c0:m25
def share_column_widths(self, tables, shared_limit=None):
for table in tables:<EOL><INDENT>record = (table, shared_limit)<EOL>if not record in self.shared_tables and table is not self:<EOL><INDENT>self.shared_tables.append(record)<EOL><DEDENT><DEDENT>
To have this table use sync with the columns in tables Note, this will need to be called on the other tables to be fully synced. :param tables: list of SeabornTables to share column widths :param shared_limit: int if diff is greater than this than ignore it. :return: None
f5033:c0:m29
@key_on.setter<EOL><INDENT>def key_on(self, value):<DEDENT>
if isinstance(value, BASESTRING):<EOL><INDENT>value = (value,)<EOL><DEDENT>self._key_on = value<EOL>
:param value: str of which column to key the rows on like a dictionary :return: None
f5033:c0:m39
def map(self, func):
for row in self.table:<EOL><INDENT>for i, cell in enumerate(row):<EOL><INDENT>row[i] = func(cell)<EOL><DEDENT><DEDENT>
This will replace every cell in the function with func(cell) :param func: func to call :return: None
f5033:c0:m41
def naming_convention_columns(self, convention='<STR_LIT>',<EOL>remove_empty=True):
converter = getattr(self, '<STR_LIT>' % convention, None)<EOL>assert converter is not None,'<STR_LIT>' % convention<EOL>self.row_columns = [converter(col) for col in self.row_columns]<EOL>self._columns = [converter(col) for col in self._columns]<EOL>if remove_empty and '<STR_LIT>' in self.row_columns:<EOL><INDENT>self....
This will change the column names to a particular naming convention. underscore: lower case all letters and replaces spaces with _ title: uppercase first letter and replaces _ with spaces :param convention: str enum of "lowercase_underscore" :param remove_empty: bool if true will remove column header of value '...
f5033:c0:m43
def remove_column(self, key):
if isinstance(key, int):<EOL><INDENT>index = key<EOL>key = self.row_columns[key]<EOL><DEDENT>else:<EOL><INDENT>index = self._column_index[key]<EOL><DEDENT>for row in self.table:<EOL><INDENT>row.pop(index)<EOL><DEDENT>self.row_columns = self.row_columns[:index] + self.row_columns[<EOL>index + <NUM_LIT:1>:]<EOL>self.pop_...
:param key: str of the column to remove from every row in the table :return: None
f5033:c0:m44
def filter_by(self, **kwargs):
ret = self.__class__(<EOL>columns=self.columns, row_columns=self.row_columns, tab=self.tab,<EOL>key_on=self.key_on)<EOL>for row in self:<EOL><INDENT>if False not in [row[k] == v for k, v in kwargs.items()]:<EOL><INDENT>ret.append(row)<EOL><DEDENT><DEDENT>return ret<EOL>
:param kwargs: dict of column == value :return: SeabornTable
f5033:c0:m45
def filter(self, column, condition='<STR_LIT>', value=None):
ret = self.__class__(<EOL>columns=self.columns, row_columns=self.row_columns, tab=self.tab,<EOL>key_on=self.key_on)<EOL>for row in self:<EOL><INDENT>if getattr(row[column], condition, None):<EOL><INDENT>if eval('<STR_LIT>' % (condition, value)):<EOL><INDENT>ret.append(row)<EOL><DEDENT><DEDENT>if eval('<STR_LIT>' % cond...
:param column: str or index of the column :param condition: str of the python operator :param value: obj of the value to test for :return: SeabornTable
f5033:c0:m46
def append(self, row=None):
self.table.append(self._normalize_row(row))<EOL>return self.table[-<NUM_LIT:1>]<EOL>
This will add a row to the table :param row: obj, list, or dictionary :return: SeabornRow that was added to the table
f5033:c0:m47
@classmethod<EOL><INDENT>def pertibate_to_obj(cls, columns, pertibate_values,<EOL>generated_columns=None, filter_func=None,<EOL>max_size=None, deliminator=None, tab=None):<DEDENT>
table = cls(columns=columns, deliminator=deliminator, tab=tab)<EOL>table._parameters = pertibate_values.copy()<EOL>table._parameters.update(generated_columns or {})<EOL>table.pertibate(pertibate_values.keys(), filter_func, max_size)<EOL>return table<EOL>
This will create and add rows to the table by pertibating the parameters for the provided columns :param columns: list of str of columns in the table :param pertibate_values: dict of {'column': [values]} :param generated_columns: dict of {'column': func} :param filter_func: func to return False to filter out row :p...
f5033:c0:m49
def pertibate(self, pertibate_columns=None, filter_func=None,<EOL>max_size=<NUM_LIT:1000>):
pertibate_columns = pertibate_columns or self.columns<EOL>for c in pertibate_columns:<EOL><INDENT>assert c in self.columns, '<STR_LIT>' % c<EOL><DEDENT>column_size = [c in pertibate_columns and len(self._parameters[c]) or <NUM_LIT:1><EOL>for c in self.columns]<EOL>max_size = min(max_size, reduce(lambda x, y: x * y, col...
:param pertibate_columns: list of str fo columns to pertibate see DOE :param filter_func: func that takes a SeabornRow and return True if this row should be exist :param max_size: int of the max number of rows to try but some may be filtered out :return: None
f5033:c0:m50
def __getitem__(self, item):
if isinstance(item, (int, slice)):<EOL><INDENT>return self.table[item]<EOL><DEDENT>else:<EOL><INDENT>assert self.key_on<EOL>if not isinstance(item, (tuple, list)):<EOL><INDENT>item = [item]<EOL><DEDENT>for row in self.table:<EOL><INDENT>key = [row[k] for k in self.key_on]<EOL>if key == list(item):<EOL><INDENT>return ro...
This will return a row if item is an int or if key_on is set else it will return the column if column if it is in self._columns :param item: int or str of the row or column to get :return: list
f5033:c0:m65
def __setitem__(self, item, value):
if isinstance(item, int):<EOL><INDENT>self.table[item] = self._normalize_row(value)<EOL><DEDENT>else:<EOL><INDENT>assert self.key_on<EOL>if not isinstance(item, (tuple, list)):<EOL><INDENT>item = [item]<EOL><DEDENT>for i, row in enumerate(self.table):<EOL><INDENT>key = [row[k] for k in self.key_on]<EOL>if key == list(i...
This will set a row if item is an int or set the values of a column :param item: int or str of the row or column to set :param value: func or obj or list if it is a list then assign each row from this list :return: None
f5033:c0:m66
def pop_empty_columns(self, empty=None):
empty = ['<STR_LIT>', None] if empty is None else empty<EOL>if len(self) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>for col in list(self.columns):<EOL><INDENT>if self[<NUM_LIT:0>][col] in empty:<EOL><INDENT>if not [v for v in self.get_column(col) if v not in empty]:<EOL><INDENT>self.pop_column(col)<EOL><DEDENT><DED...
This will pop columns from the printed columns if they only contain '' or None :param empty: list of values to treat as empty
f5033:c0:m67
def insert(self, index, column, default_value='<STR_LIT>', values=None,<EOL>compute_value_func=None, compute_key=None):
for row in self.table:<EOL><INDENT>value = values.pop(<NUM_LIT:0>) if values else default_value<EOL>if compute_value_func is not None:<EOL><INDENT>value = compute_value_func(<EOL>row if compute_key is None else row[compute_key])<EOL><DEDENT>if index is None:<EOL><INDENT>row.append(value)<EOL><DEDENT>else:<EOL><INDENT>r...
This will insert a new column at index and then set the value unless compute_value is provided :param index: int index of where to insert the column :param column: str of the name of the column :param default_value: obj of the default value :param values: obj of the column values (length should equal table) :param ...
f5033:c0:m74
def sort_by_key(self, keys=None):
keys = keys or self.key_on<EOL>keys = keys if isinstance(keys, (list, tuple)) else [keys]<EOL>for key in reversed(keys):<EOL><INDENT>reverse, key = (True, key[<NUM_LIT:1>:]) if key[<NUM_LIT:0>] == '<STR_LIT:->' else (False, key)<EOL>self.table.sort(key=lambda row: row[key], reverse=reverse)<EOL><DEDENT>
:param keys: list of str to sort by, if name starts with - reverse order :return: None
f5033:c0:m76
def get_data_and_column_widths(self, data_kwargs, width_kwargs):
data_kwargs = data_kwargs.copy()<EOL>safe_str = data_kwargs.pop('<STR_LIT>', self._safe_str)<EOL>list_of_list = [[safe_str(col, _is_header=True, **data_kwargs)<EOL>for col in self.columns]]<EOL>list_of_list+= [[safe_str(row[col], **data_kwargs)<EOL>for col in self.columns] for row in self]<EOL>column_widths = self._get...
:param data_kwargs: kwargs used for converting data to strings :param width_kwargs: kwargs used for determining column widths :return: tuple(list of list of strings, list of int)
f5033:c0:m79
def get_data_and_shared_column_widths(self, data_kwargs, width_kwargs):
list_of_list, column_widths = self.get_data_and_column_widths(<EOL>data_kwargs, width_kwargs)<EOL>for table, shared_limit in self.shared_tables:<EOL><INDENT>_, widths = table.get_data_and_column_widths(<EOL>data_kwargs, width_kwargs)<EOL>for i, width in enumerate(widths[:len(column_widths)]):<EOL><INDENT>delta = width ...
:param data_kwargs: kwargs used for converting data to strings :param width_kwargs: kwargs used for determining column widths :return: tuple(list of list of strings, list of int)
f5033:c0:m80
@classmethod<EOL><INDENT>def _safe_str(cls, cell, quote_numbers=True, repr_line_break=False,<EOL>deliminator=None, quote_empty_str=False,<EOL>title_columns=False, _is_header=False):<DEDENT>
if cell is None:<EOL><INDENT>cell = '<STR_LIT>'<EOL><DEDENT>ret = str(cell) if not isinstance(cell, BASESTRING) else cell<EOL>if isinstance(cell, BASESTRING):<EOL><INDENT>if title_columns and _is_header:<EOL><INDENT>ret = cls._title_column(ret)<EOL><DEDENT>if quote_numbers and (ret.replace(u'<STR_LIT:.>', u'<STR_LIT>')...
:param cell: obj to turn in to a string :param quote_numbers: bool if True will quote numbers that are strings :param repr_line_break: if True will replace \n with \\n :param deliminator: if the deliminator is in the cell it will be quoted :param quote_empty_str: bool if True will quote empty strings
f5033:c0:m81
@classmethod<EOL><INDENT>def _excel_cell(cls, cell, quote_everything=False, quote_numbers=True,<EOL>_is_header=False):<DEDENT>
if cell is None:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT>if cell is True:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT>if cell is False:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT>ret = cell if isinstance(cell, BASESTRING) else UNICODE(cell)<EOL>if isinstance(cell, (int, float)) and not quote_everything:<EOL><INDEN...
This will return a text that excel interprets correctly when importing csv :param cell: obj to store in the cell :param quote_everything: bool to quote even if not necessary :param quote_numbers: bool if True will quote numbers that are strings :param _is_header: not used :...
f5033:c0:m82
@classmethod<EOL><INDENT>def _get_normalized_columns(cls, list_):<DEDENT>
ret = []<EOL>for row in list_:<EOL><INDENT>if len(row.keys()) > len(ret):<EOL><INDENT>ret = cls._ordered_keys(row)<EOL><DEDENT><DEDENT>for row in list_:<EOL><INDENT>for key in row.keys():<EOL><INDENT>if key not in ret:<EOL><INDENT>ret.append(key)<EOL>if not isinstance(row, OrderedDict):<EOL><INDENT>ret.sort()<EOL><DEDE...
:param list_: list of dict :return: list of string of every key in all the dictionaries
f5033:c0:m86
@staticmethod<EOL><INDENT>def _ordered_keys(dict_):<DEDENT>
return isinstance(dict_, OrderedDict) and dict_.keys() ordict_ and sorted(dict_.keys()) or []<EOL>
:param dict_: dict of OrderedDict to be processed :return: list of str of keys in the original order or in alphabetical order
f5033:c0:m87
@staticmethod<EOL><INDENT>def _key_on_columns(key_on, columns):<DEDENT>
if key_on is not None:<EOL><INDENT>if key_on in columns:<EOL><INDENT>columns.remove(key_on)<EOL><DEDENT>columns = [key_on] + columns<EOL><DEDENT>return columns<EOL>
:param key_on: str of column :param columns: list of str of columns :return: list of str with the key_on in the front of the list
f5033:c0:m88
@staticmethod<EOL><INDENT>def _index_iterator(column_size, max_size, mix_index=False):<DEDENT>
<EOL>indexes = [<NUM_LIT:0>] * len(column_size)<EOL>index_order = [<NUM_LIT:0>]<EOL>if mix_index:<EOL><INDENT>for i in range(<NUM_LIT:1>, max(column_size)):<EOL><INDENT>index_order += [-<NUM_LIT:1> * i, i]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>index_order += range(<NUM_LIT:1>, max(column_size))<EOL><DEDENT>for i in ran...
This will iterate over the indexes and return a list of indexes :param column_size: list of int of the size of each list :param max_size: int of the max number of iterations :param mix_index: bool if True will go first then last then middle :return: list of int of indexes
f5033:c0:m91
def _html_link_cells(self):
new_table = self.copy()<EOL>for row in new_table:<EOL><INDENT>for c in new_table.columns:<EOL><INDENT>link = '<STR_LIT>' % c<EOL>if row.get(link, None):<EOL><INDENT>row[c] = '<STR_LIT>' % (row[link], row[c])<EOL><DEDENT><DEDENT><DEDENT>new_table.columns = [c for c in self.columns if '<STR_LIT>' not in c]<EOL>return new...
This will return a new table with cell linked with their columns that have <Link> in the name :return:
f5033:c0:m94
def _column_width(self, index=None, name=None, max_width=<NUM_LIT>, **kwargs):
assert name is not None or index is not None<EOL>if name and name not in self._column_index:<EOL><INDENT>return min(max_width, name)<EOL><DEDENT>if index is not None:<EOL><INDENT>name = self.columns[index]<EOL><DEDENT>else:<EOL><INDENT>index = self._column_index[name]<EOL><DEDENT>values_width = [len(name)]<EOL>if isins...
:param index: int of the column index :param name: str of the name of the column :param max_width: int of the max size of characters in the width :return: int of the width of this column
f5033:c0:m98
def update(self, dict_):
for key, value in dict_.items():<EOL><INDENT>index = self.column_index.get(key, None)<EOL>if index is not None:<EOL><INDENT>list.__setitem__(self, index, value)<EOL><DEDENT><DEDENT>
This will update the row values if the columns exist :param dict_: dict of values to update :return: None
f5033:c1:m9
def qnwcheb(n, a=<NUM_LIT:1>, b=<NUM_LIT:1>):
return _make_multidim_func(_qnwcheb1, n, a, b)<EOL>
Computes multivariate Guass-Checbychev quadrature nodes and weights. 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, that constant is repeated d tim...
f5040:m2
def qnwequi(n, a, b, kind="<STR_LIT:N>", equidist_pp=None, random_state=None):
random_state = check_random_state(random_state)<EOL>if equidist_pp is None:<EOL><INDENT>import sympy as sym<EOL>equidist_pp = np.sqrt(np.array(list(sym.primerange(<NUM_LIT:0>, <NUM_LIT>))))<EOL><DEDENT>n, a, b = list(map(np.atleast_1d, list(map(np.asarray, [n, a, b]))))<EOL>d = max(list(map(len, [n, a, b])))<EOL>n = np...
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 of lower endpoints. If a scalar ...
f5040:m3
def qnwlege(n, a, b):
return _make_multidim_func(_qnwlege1, n, a, b)<EOL>
Computes multivariate Guass-Legendre quadrature nodes and weights. 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, that constant is repeated d time...
f5040:m4
def qnwnorm(n, mu=None, sig2=None, usesqrtm=False):
n = np.atleast_1d(n)<EOL>d = n.size<EOL>if mu is None:<EOL><INDENT>mu = np.zeros(d)<EOL><DEDENT>else:<EOL><INDENT>mu = np.atleast_1d(mu)<EOL><DEDENT>if sig2 is None:<EOL><INDENT>sig2 = np.eye(d)<EOL><DEDENT>else:<EOL><INDENT>sig2 = np.atleast_1d(sig2).reshape(d, d)<EOL><DEDENT>if all([x.size == <NUM_LIT:1> for x in [n,...
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 variable. If a scalar is gi...
f5040:m5
def qnwlogn(n, mu=None, sig2=None):
nodes, weights = qnwnorm(n, mu, sig2)<EOL>return np.exp(nodes), weights<EOL>
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 variable. If a scalar is...
f5040:m6
def qnwsimp(n, a, b):
return _make_multidim_func(_qnwsimp1, n, a, b)<EOL>
Computes multivariate Simpson quadrature nodes and weights. 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, that constant is repeated d times, where...
f5040:m7
def qnwtrap(n, a, b):
return _make_multidim_func(_qnwtrap1, n, a, b)<EOL>
Computes multivariate trapezoid rule quadrature nodes and weights. 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, that constant is repeated d times...
f5040:m8
def qnwunif(n, a, b):
n, a, b = list(map(np.asarray, [n, a, b]))<EOL>nodes, weights = qnwlege(n, a, b)<EOL>weights = weights / np.prod(b - a)<EOL>return nodes, weights<EOL>
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, that constant is repeate...
f5040:m9
def quadrect(f, n, a, b, kind='<STR_LIT>', *args, **kwargs):
if kind.lower() == "<STR_LIT>":<EOL><INDENT>nodes, weights = qnwlege(n, a, b)<EOL><DEDENT>elif kind.lower() == "<STR_LIT>":<EOL><INDENT>nodes, weights = qnwcheb(n, a, b)<EOL><DEDENT>elif kind.lower() == "<STR_LIT>":<EOL><INDENT>nodes, weights = qnwtrap(n, a, b)<EOL><DEDENT>elif kind.lower() == "<STR_LIT>":<EOL><INDENT>...
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 a matrix representing point...
f5040:m10
def qnwbeta(n, a=<NUM_LIT:1.0>, b=<NUM_LIT:1.0>):
return _make_multidim_func(_qnwbeta1, n, a, b)<EOL>
Computes nodes and weights for beta 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=1.0) A length-d b : array_like(float), optional(default=1.0) A d x d array representing the va...
f5040:m11
def qnwgamma(n, a=<NUM_LIT:1.0>, b=<NUM_LIT:1.0>, tol=<NUM_LIT>):
return _make_multidim_func(_qnwgamma1, n, a, b, tol)<EOL>
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 positive b : scalar or arr...
f5040:m12
def _make_multidim_func(one_d_func, n, *args):
_args = list(args)<EOL>n = np.atleast_1d(n)<EOL>args = list(map(np.atleast_1d, _args))<EOL>if all([x.size == <NUM_LIT:1> for x in [n] + args]):<EOL><INDENT>return one_d_func(n[<NUM_LIT:0>], *_args)<EOL><DEDENT>d = n.size<EOL>for i in range(len(args)):<EOL><INDENT>if args[i].size == <NUM_LIT:1>:<EOL><INDENT>args[i] = np...
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 through the appropriate 1d...
f5040:m13
@jit(nopython=True)<EOL>def _qnwcheb1(n, a, b):
nodes = (b+a)/<NUM_LIT:2> - (b-a)/<NUM_LIT:2> * np.cos(np.pi/n * np.linspace(<NUM_LIT:0.5>, n-<NUM_LIT:0.5>, n))<EOL>t1 = np.arange(<NUM_LIT:1>, n+<NUM_LIT:1>) - <NUM_LIT:0.5><EOL>t2 = np.arange(<NUM_LIT:0.0>, n, <NUM_LIT:2>)<EOL>t3 = np.concatenate((np.array([<NUM_LIT:1.0>]),<EOL>-<NUM_LIT>/(np.arange(<NUM_LIT:1.0>, n...
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 nodes : np.ndarray(dtype=float) An n element array...
f5040:m14
@jit(nopython=True)<EOL>def _qnwlege1(n, a, b):
<EOL>maxit = <NUM_LIT:100><EOL>m = int(fix((n + <NUM_LIT:1>) / <NUM_LIT>))<EOL>xm = <NUM_LIT:0.5> * (b + a)<EOL>xl = <NUM_LIT:0.5> * (b - a)<EOL>nodes = np.zeros(n)<EOL>weights = nodes.copy()<EOL>i = np.arange(m)<EOL>z = np.cos(np.pi * ((i + <NUM_LIT:1.0>) - <NUM_LIT>) / (n + <NUM_LIT:0.5>))<EOL>for its in range(maxit)...
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 nodes : np.ndarray(dtype=float) An n element array o...
f5040:m15
@jit(nopython=True)<EOL>def _qnwnorm1(n):
maxit = <NUM_LIT:100><EOL>pim4 = <NUM_LIT:1> / np.pi**(<NUM_LIT>)<EOL>m = int(fix((n + <NUM_LIT:1>) / <NUM_LIT:2>))<EOL>nodes = np.zeros(n)<EOL>weights = np.zeros(n)<EOL>for i in range(m):<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>z = np.sqrt(<NUM_LIT:2>*n+<NUM_LIT:1>) - <NUM_LIT> * ((<NUM_LIT:2> * n + <NUM_LIT:1>)*...
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 of weights Notes ----- Based of original fu...
f5040:m16
@jit(nopython=True)<EOL>def _qnwsimp1(n, a, b):
if n % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>")<EOL>n += <NUM_LIT:1><EOL><DEDENT>nodes = np.linspace(a, b, n)<EOL>dx = nodes[<NUM_LIT:1>] - nodes[<NUM_LIT:0>]<EOL>weights = np.kron(np.ones((n+<NUM_LIT:1>) // <NUM_LIT:2>), np.array([<NUM_LIT>, <NUM_LIT>]))<EOL>weights = weights[:n]<EOL>weights[<NUM_LIT...
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.ndarray(dtype=float) An n element array of weigh...
f5040:m17
@jit(nopython=True)<EOL>def _qnwtrap1(n, a, b):
if n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nodes = np.linspace(a, b, n)<EOL>dx = nodes[<NUM_LIT:1>] - nodes[<NUM_LIT:0>]<EOL>weights = dx * np.ones(n)<EOL>weights[<NUM_LIT:0>] *= <NUM_LIT:0.5><EOL>weights[-<NUM_LIT:1>] *= <NUM_LIT:0.5><EOL>return nodes, weights<EOL>
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 nodes : np.ndarray(dtype=float) An n element array o...
f5040:m18
@jit(nopython=True)<EOL>def _qnwbeta1(n, a=<NUM_LIT:1.0>, b=<NUM_LIT:1.0>):
<EOL>a = a - <NUM_LIT:1><EOL>b = b - <NUM_LIT:1><EOL>maxiter = <NUM_LIT><EOL>nodes = np.zeros(n)<EOL>weights = np.zeros(n)<EOL>for i in range(n):<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>an = a/n<EOL>bn = b/n<EOL>r1 = (<NUM_LIT:1>+a) * (<NUM_LIT>/(<NUM_LIT:4>+n*n) + <NUM_LIT>*an/n)<EOL>r2 = <NUM_LIT:1> + <NUM_LIT>*...
Computes nodes and weights for quadrature on the beta distribution. Default is a=b=1 which is just a uniform distribution NOTE: For now I am just following compecon; would be much better to find a different way since I don't know what they are doing. Parameters ---------- n : scalar : int The number of quadrature...
f5040:m19
@jit(nopython=True)<EOL>def _qnwgamma1(n, a=<NUM_LIT:1.0>, b=<NUM_LIT:1.0>, tol=<NUM_LIT>):
a -= <NUM_LIT:1><EOL>maxit = <NUM_LIT><EOL>factor = -math.exp(gammaln(a+n) - gammaln(n) - gammaln(a+<NUM_LIT:1>))<EOL>nodes = np.zeros(n)<EOL>weights = np.zeros(n)<EOL>for i in range(n):<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>z = (<NUM_LIT:1>+a) * (<NUM_LIT:3>+<NUM_LIT>*a) / (<NUM_LIT:1> + <NUM_LIT>*n + <NUM_LIT>...
1d quadrature weights and nodes for Gamma distributed random variable Parameters ---------- n : scalar : int The number of quadrature points a : scalar : float, optional(default=1.0) Shape parameter of the gamma distribution parameter. Must be positive b : scalar : float, optional(default=1.0) Scale para...
f5040:m20
def probvec(m, k, random_state=None, parallel=True):
if k == <NUM_LIT:1>:<EOL><INDENT>return np.ones((m, k))<EOL><DEDENT>random_state = check_random_state(random_state)<EOL>r = random_state.random_sample(size=(m, k-<NUM_LIT:1>))<EOL>x = np.empty((m, k))<EOL>if parallel:<EOL><INDENT>_probvec_parallel(r, x)<EOL><DEDENT>else:<EOL><INDENT>_probvec_cpu(r, x)<EOL><DEDENT>retur...
Return m randomly sampled probability vectors of dimension k. Parameters ---------- m : scalar(int) Number of probability vectors. k : scalar(int) Dimension of each probability vectors. random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set ...
f5043:m0
def _probvec(r, out):
n = r.shape[<NUM_LIT:0>]<EOL>r.sort()<EOL>out[<NUM_LIT:0>] = r[<NUM_LIT:0>]<EOL>for i in range(<NUM_LIT:1>, n):<EOL><INDENT>out[i] = r[i] - r[i-<NUM_LIT:1>]<EOL><DEDENT>out[n] = <NUM_LIT:1> - r[n-<NUM_LIT:1>]<EOL>
Fill `out` with randomly sampled probability vectors as rows. To be complied as a ufunc by guvectorize of Numba. The inputs must have the same shape except the last axis; the length of the last axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is k, then r.shape[-1] must be k-1. Parameters ---------- ...
f5043:m1
def sample_without_replacement(n, k, num_trials=None, random_state=None):
if n <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if k > n:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>size = k if num_trials is None else (num_trials, k)<EOL>random_state = check_random_state(random_state)<EOL>r = random_state.random_sample(size=size)<EOL>result = _sample_without_re...
Randomly choose k integers without replacement from 0, ..., n-1. Parameters ---------- n : scalar(int) Number of integers, 0, ..., n-1, to sample from. k : scalar(int) Number of integers to sample. num_trials : scalar(int), optional(default=None) Number of trials. random_state : int or np.random.RandomS...
f5043:m2
@guvectorize(['<STR_LIT>'], '<STR_LIT>', nopython=True, cache=True)<EOL>def _sample_without_replacement(n, r, out):
k = r.shape[<NUM_LIT:0>]<EOL>pool = np.arange(n)<EOL>for j in range(k):<EOL><INDENT>idx = int(np.floor(r[j] * (n-j))) <EOL>out[j] = pool[idx]<EOL>pool[idx] = pool[n-j-<NUM_LIT:1>]<EOL><DEDENT>
Main body of `sample_without_replacement`. To be complied as a ufunc by guvectorize of Numba.
f5043:m3
@generated_jit(nopython=True)<EOL>def draw(cdf, size=None):
if isinstance(size, types.Integer):<EOL><INDENT>def draw_impl(cdf, size):<EOL><INDENT>rs = np.random.random_sample(size)<EOL>out = np.empty(size, dtype=np.int_)<EOL>for i in range(size):<EOL><INDENT>out[i] = searchsorted(cdf, rs[i])<EOL><DEDENT>return out<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def draw_impl(cdf, size):<...
Generate a random sample according to the cumulative distribution given by `cdf`. Jit-complied by Numba in nopython mode. Parameters ---------- cdf : array_like(float, ndim=1) Array containing the cumulative distribution. size : scalar(int), optional(default=None) Size of the sample. If an integer is supplied...
f5043:m4
def __call__(self, y):
k = len(y)<EOL>v = self.p(self.X, y.reshape((<NUM_LIT:1>, k)))<EOL>psi_vals = np.mean(v, axis=<NUM_LIT:0>) <EOL>return psi_vals.flatten()<EOL>
A vectorized function that returns the value of the look ahead estimate at the values in the array y. Parameters ---------- y : array_like(float) A vector of points at which we wish to evaluate the look- ahead estimator Returns ------- psi_vals : array_like(float) The values of the density estimate at the...
f5045:c0:m3
@property<EOL><INDENT>def q(self):<DEDENT>
return self._q<EOL>
Getter method for q.
f5046:c0:m3
@q.setter<EOL><INDENT>def q(self, val):<DEDENT>
self._q = np.asarray(val)<EOL>self.Q = cumsum(val)<EOL>
Setter method for q.
f5046:c0:m4
def draw(self, k=<NUM_LIT:1>, random_state=None):
random_state = check_random_state(random_state)<EOL>return self.Q.searchsorted(random_state.uniform(<NUM_LIT:0>, <NUM_LIT:1>, size=k),<EOL>side='<STR_LIT:right>')<EOL>
Returns k draws from q. For each such draw, the value i is returned with probability q[i]. Parameters ----------- k : scalar(int), optional Number of draws to be returned random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set the initial state...
f5046:c0:m5
def lemke_howson(g, init_pivot=<NUM_LIT:0>, max_iter=<NUM_LIT:10>**<NUM_LIT:6>, capping=None,<EOL>full_output=False):
try:<EOL><INDENT>N = g.N<EOL><DEDENT>except:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if N != <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>payoff_matrices = g.payoff_arrays<EOL>nums_actions = g.nums_actions<EOL>total_num = sum(nums_actions)<EOL>msg = '<STR_LIT>' +'<STR_LIT>'.f...
Find one mixed-action Nash equilibrium of a 2-player normal form game by the Lemke-Howson algorithm [2]_, implemented with "complementary pivoting" (see, e.g., von Stengel [3]_ for details). Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. init_pivot : scalar(int), optional(default...
f5047:m0
@jit(nopython=True, cache=True)<EOL>def _lemke_howson_capping(payoff_matrices, tableaux, bases, init_pivot,<EOL>max_iter, capping):
m, n = tableaux[<NUM_LIT:1>].shape[<NUM_LIT:0>], tableaux[<NUM_LIT:0>].shape[<NUM_LIT:0>]<EOL>init_pivot_curr = init_pivot<EOL>max_iter_curr = max_iter<EOL>total_num_iter = <NUM_LIT:0><EOL>for k in range(m+n-<NUM_LIT:1>):<EOL><INDENT>capping_curr = min(max_iter_curr, capping)<EOL>_initialize_tableaux(payoff_matrices, t...
Execute the Lemke-Howson algorithm with the heuristics proposed by Codenotti et al. Parameters ---------- payoff_matrices : tuple(ndarray(ndim=2)) Tuple of two arrays representing payoff matrices, of shape (m, n) and (n, m), respectively. tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays to be ...
f5047:m1
@jit(nopython=True, cache=True)<EOL>def _initialize_tableaux(payoff_matrices, tableaux, bases):
nums_actions = payoff_matrices[<NUM_LIT:0>].shape<EOL>consts = np.zeros(<NUM_LIT:2>) <EOL>for pl in range(<NUM_LIT:2>):<EOL><INDENT>min_ = payoff_matrices[pl].min()<EOL>if min_ <= <NUM_LIT:0>:<EOL><INDENT>consts[pl] = min_ * (-<NUM_LIT:1>) + <NUM_LIT:1><EOL><DEDENT><DEDENT>for pl, (py_start, sl_start) in enumerate(zip...
Given a tuple of payoff matrices, initialize the tableau and basis arrays in place. For each player `i`, if `payoff_matrices[i].min()` is non-positive, then stored in the tableau are payoff values incremented by `abs(payoff_matrices[i].min()) + 1` (to ensure for the tableau not to have a negative entry or a column ide...
f5047:m2
@jit(nopython=True, cache=True)<EOL>def _lemke_howson_tbl(tableaux, bases, init_pivot, max_iter):
init_player = <NUM_LIT:0><EOL>for k in bases[<NUM_LIT:0>]:<EOL><INDENT>if k == init_pivot:<EOL><INDENT>init_player = <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>pls = [init_player, <NUM_LIT:1> - init_player]<EOL>pivot = init_pivot<EOL>m, n = tableaux[<NUM_LIT:1>].shape[<NUM_LIT:0>], tableaux[<NUM_LIT:0>].shape[<NUM_LIT:0...
Main body of the Lemke-Howson algorithm implementation. Perform the complementary pivoting. Modify `tablaux` and `bases` in place. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays containing the tableaux, of shape (n, m+n+1) and (m, m+n+1), respectively. Modified in place. b...
f5047:m3
@jit(nopython=True, cache=True)<EOL>def _pivoting(tableau, pivot, pivot_row):
nrows, ncols = tableau.shape<EOL>pivot_elt = tableau[pivot_row, pivot]<EOL>for j in range(ncols):<EOL><INDENT>tableau[pivot_row, j] /= pivot_elt<EOL><DEDENT>for i in range(nrows):<EOL><INDENT>if i == pivot_row:<EOL><INDENT>continue<EOL><DEDENT>multiplier = tableau[i, pivot]<EOL>if multiplier == <NUM_LIT:0>:<EOL><INDENT...
Perform a pivoting step. Modify `tableau` in place. Parameters ---------- tableau : ndarray(float, ndim=2) Array containing the tableau. pivot : scalar(int) Pivot. pivot_row : scalar(int) Pivot row index. Returns ------- tableau : ndarray(float, ndim=2) View to `tableau`.
f5047:m4
@jit(nopython=True, cache=True)<EOL>def _get_mixed_actions(tableaux, bases):
nums_actions = tableaux[<NUM_LIT:1>].shape[<NUM_LIT:0>], tableaux[<NUM_LIT:0>].shape[<NUM_LIT:0>]<EOL>num = nums_actions[<NUM_LIT:0>] + nums_actions[<NUM_LIT:1>]<EOL>out = np.zeros(num)<EOL>for pl, (start, stop) in enumerate(zip((<NUM_LIT:0>, nums_actions[<NUM_LIT:0>]),<EOL>(nums_actions[<NUM_LIT:0>], num))):<EOL><INDE...
From `tableaux` and `bases`, extract non-slack basic variables and return a tuple of the corresponding, normalized mixed actions. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays containing the tableaux, of shape (n, m+n+1) and (m, m+n+1), respectively. bases : tuple(ndarray(...
f5047:m7
def _equilibrium_payoffs_abreu_sannikov(rpg, tol=<NUM_LIT>, max_iter=<NUM_LIT>,<EOL>u_init=np.zeros(<NUM_LIT:2>)):
sg, delta = rpg.sg, rpg.delta<EOL>if sg.N != <NUM_LIT:2>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise NotImplementedError(msg)<EOL><DEDENT>best_dev_gains = _best_dev_gains(rpg)<EOL>IC = np.empty(<NUM_LIT:2>)<EOL>action_profile_payoff = np.empty(<NUM_LIT:2>)<EOL>extended_payoff = np.ones(<NUM_LIT:3>)<EOL>new_pts = np.empty(...
Using 'abreu_sannikov' algorithm to compute the set of payoff pairs of all pure-strategy subgame-perfect equilibria with public randomization for any repeated two-player games with perfect monitoring and discounting, following Abreu and Sannikov (2014). Parameters ---------- rpg : RepeatedGame Two player repeated ...
f5048:m0
def _best_dev_gains(rpg):
sg, delta = rpg.sg, rpg.delta<EOL>best_dev_gains = ((<NUM_LIT:1>-delta)/delta *<EOL>(np.max(sg.payoff_arrays[i], <NUM_LIT:0>) - sg.payoff_arrays[i])<EOL>for i in range(<NUM_LIT:2>))<EOL>return tuple(best_dev_gains)<EOL>
Calculate the normalized payoff gains from deviating from the current action to the best response for each player. Parameters ---------- rpg : RepeatedGame Two player repeated game. Returns ------- best_dev_gains : tuple(ndarray(float, ndim=2)) The normalized best deviation payoff gain arrays. best_dev_ga...
f5048:m1
@njit<EOL>def _R(delta, nums_actions, payoff_arrays, best_dev_gains, points,<EOL>vertices, equations, u, IC, action_profile_payoff,<EOL>extended_payoff, new_pts, W_new, tol=<NUM_LIT>):
n_new_pt = <NUM_LIT:0><EOL>for a0 in range(nums_actions[<NUM_LIT:0>]):<EOL><INDENT>for a1 in range(nums_actions[<NUM_LIT:1>]):<EOL><INDENT>action_profile_payoff[<NUM_LIT:0>] = payoff_arrays[<NUM_LIT:0>][a0, a1]<EOL>action_profile_payoff[<NUM_LIT:1>] = payoff_arrays[<NUM_LIT:1>][a1, a0]<EOL>IC[<NUM_LIT:0>] = u[<NUM_LIT:...
Updating the payoff convex hull by iterating all action pairs. Using the R operator proposed by Abreu and Sannikov 2014. Parameters ---------- delta : scalar(float) The common discount rate at which all players discount the future. nums_actions : tuple(int) Tuple of the numbers of actions, one for...
f5048:m2
@njit<EOL>def _find_C(C, points, vertices, equations, extended_payoff, IC, tol):
n = <NUM_LIT:0><EOL>weights = np.empty(<NUM_LIT:2>)<EOL>for i in range(len(vertices)-<NUM_LIT:1>):<EOL><INDENT>n = _intersect(C, n, weights, IC,<EOL>points[vertices[i]],<EOL>points[vertices[i+<NUM_LIT:1>]], tol)<EOL><DEDENT>n = _intersect(C, n, weights, IC,<EOL>points[vertices[-<NUM_LIT:1>]],<EOL>points[vertices[<NUM_L...
Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated potential extreme points of one action profile. One action profile can o...
f5048:m3
@njit<EOL>def _intersect(C, n, weights, IC, pt0, pt1, tol):
for i in range(<NUM_LIT:2>):<EOL><INDENT>if (abs(pt0[i] - pt1[i]) < tol):<EOL><INDENT>if (abs(pt1[i] - IC[i]) < tol):<EOL><INDENT>x = pt1[<NUM_LIT:1>-i]<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>weights[i] = (pt0[i] - IC[i]) / (pt0[i] - pt1[i])<EOL>if (<NUM_LIT:0> < weights[i] <= <NUM...
Find the intersection points of a half-closed simplex (pt0, pt1] and IC constraints. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated points of one action profile. One action profile can only generate at most 4 points. n : scalar(int) The number of intersecti...
f5048:m4
@njit<EOL>def _update_u(u, W):
for i in range(<NUM_LIT:2>):<EOL><INDENT>W_min = W[:, i].min()<EOL>if u[i] < W_min:<EOL><INDENT>u[i] = W_min<EOL><DEDENT><DEDENT>return u<EOL>
Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hull. Returns ------- u : ndarray(float, ndim=1) The update...
f5048:m5
def equilibrium_payoffs(self, method=None, options=None):
if method is None:<EOL><INDENT>method = '<STR_LIT>'<EOL><DEDENT>if options is None:<EOL><INDENT>options = {}<EOL><DEDENT>if method in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return _equilibrium_payoffs_abreu_sannikov(self, **options)<EOL><DEDENT>else:<EOL><INDENT>msg = f"<STR_LIT>"<EOL>raise NotImplementedError(msg)<EO...
Compute the set of payoff pairs of all pure-strategy subgame-perfect equilibria with public randomization for any repeated two-player games with perfect monitoring and discounting. Parameters ---------- method : str, optional The method for solving the equilibrium payoff set. options : dict, optional A dictio...
f5048:c0:m1
def vertex_enumeration(g, qhull_options=None):
return list(vertex_enumeration_gen(g, qhull_options=qhull_options))<EOL>
Compute mixed-action Nash equilibria of a 2-player normal form game by enumeration and matching of vertices of the best response polytopes. For a non-degenerate game input, these are all the Nash equilibria. Internally, `scipy.spatial.ConvexHull` is used to compute vertex enumeration of the best response polytopes, or...
f5049:m0
def vertex_enumeration_gen(g, qhull_options=None):
try:<EOL><INDENT>N = g.N<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if N != <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>brps = [_BestResponsePolytope(<EOL>g.players[<NUM_LIT:1>-i], idx=i, qhull_options=qhull_options<EOL>) for i in range(N)]<EO...
Generator version of `vertex_enumeration`. Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. qhull_options : str, optional(default=None) Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull manual <http://www.qhull.org>`_ for details. Yields ------- tuple(ndarray(...
f5049:m1
@jit(nopython=True)<EOL>def _vertex_enumeration_gen(labelings_bits_tup, equations_tup, trans_recips):
m, n = equations_tup[<NUM_LIT:0>].shape[<NUM_LIT:1>] - <NUM_LIT:1>, equations_tup[<NUM_LIT:1>].shape[<NUM_LIT:1>] - <NUM_LIT:1><EOL>num_vertices0, num_vertices1 =equations_tup[<NUM_LIT:0>].shape[<NUM_LIT:0>], equations_tup[<NUM_LIT:1>].shape[<NUM_LIT:0>]<EOL>ZERO_LABELING0_BITS = (np.uint64(<NUM_LIT:1>) << np.uint64(m)...
Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best response polytopes. equations_tup : tuple(ndarray(float, ndim=2)) Tuple of ndarrays containing the hyperplane...
f5049:m2
@guvectorize(['<STR_LIT>'], '<STR_LIT>', nopython=True, cache=True)<EOL>def _ints_arr_to_bits(ints_arr, out):
m = ints_arr.shape[<NUM_LIT:0>]<EOL>out[<NUM_LIT:0>] = <NUM_LIT:0><EOL>for i in range(m):<EOL><INDENT>out[<NUM_LIT:0>] |= np.uint64(<NUM_LIT:1>) << np.uint64(ints_arr[i])<EOL><DEDENT>
Convert an array of integers representing the set bits into the corresponding integer. Compiled as a ufunc by Numba's `@guvectorize`: if the input is a 2-dim array with shape[0]=K, the function returns a 1-dim array of K converted integers. Parameters ---------- ints_arr : ndarray(int32, ndim=1) Array of distinct...
f5049:m3
@jit(nopython=True, cache=True)<EOL>def _get_mixed_actions(labeling_bits, equation_tup, trans_recips):
m, n = equation_tup[<NUM_LIT:0>].shape[<NUM_LIT:0>] - <NUM_LIT:1>, equation_tup[<NUM_LIT:1>].shape[<NUM_LIT:0>] - <NUM_LIT:1><EOL>out = np.empty(m+n)<EOL>for pl, (start, stop, skip) in enumerate([(<NUM_LIT:0>, m, np.uint64(<NUM_LIT:1>)),<EOL>(m, m+n, np.uint64(<NUM_LIT:0>))]):<EOL><INDENT>sum_ = <NUM_LIT:0.><EOL>for i ...
From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- labeling_bits : scalar(np.uint64) Integer with set bits representing a labeling of a mixed a...
f5049:m4
def setUp(self):
coordination_game_matrix = [[<NUM_LIT:4>, <NUM_LIT:0>], [<NUM_LIT:3>, <NUM_LIT:2>]]<EOL>self.player = Player(coordination_game_matrix)<EOL>
Setup a Player instance
f5053:c0:m0
def setUp(self):
payoffs_2opponents = [[[<NUM_LIT:3>, <NUM_LIT:6>],<EOL>[<NUM_LIT:4>, <NUM_LIT:2>]],<EOL>[[<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:5>, <NUM_LIT:7>]]]<EOL>self.player = Player(payoffs_2opponents)<EOL>
Setup a Player instance
f5053:c1:m0
def setUp(self):
coordination_game_matrix = [[<NUM_LIT:4>, <NUM_LIT:0>], [<NUM_LIT:3>, <NUM_LIT:2>]]<EOL>self.g = NormalFormGame(coordination_game_matrix)<EOL>
Setup a NormalFormGame instance
f5053:c2:m0
def setUp(self):
self.BoS_bimatrix = np.array([[(<NUM_LIT:3>, <NUM_LIT:2>), (<NUM_LIT:1>, <NUM_LIT:1>)],<EOL>[(<NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:2>, <NUM_LIT:3>)]])<EOL>self.g = NormalFormGame(self.BoS_bimatrix)<EOL>
Setup a NormalFormGame instance
f5053:c3:m0
def setUp(self):
payoffs_2opponents = [[[<NUM_LIT:3>, <NUM_LIT:6>],<EOL>[<NUM_LIT:4>, <NUM_LIT:2>]],<EOL>[[<NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:5>, <NUM_LIT:7>]]]<EOL>player = Player(payoffs_2opponents)<EOL>self.g = NormalFormGame([player for i in range(<NUM_LIT:3>)])<EOL>
Setup a NormalFormGame instance
f5053:c4:m0
def setUp(self):
self.payoffs = [<NUM_LIT:0>, <NUM_LIT:1>, -<NUM_LIT:1>]<EOL>self.player = Player(self.payoffs)<EOL>self.best_response_action = <NUM_LIT:1><EOL>self.dominated_actions = [<NUM_LIT:0>, <NUM_LIT:2>]<EOL>
Setup a Player instance
f5053:c5:m0
def setUp(self):
data = [[<NUM_LIT:0>], [<NUM_LIT:1>], [<NUM_LIT:1>]]<EOL>self.g = NormalFormGame(data)<EOL>
Setup a NormalFormGame instance
f5053:c6:m0
def setUp(self):
self.payoffs = [[<NUM_LIT:0>, <NUM_LIT:1>]]<EOL>self.player = Player(self.payoffs)<EOL>
Setup a Player instance
f5053:c7:m0
def random_skew_sym(n, m=None, random_state=None):
if m is None:<EOL><INDENT>m = n<EOL><DEDENT>random_state = check_random_state(random_state)<EOL>B = random_state.random_sample((n, m))<EOL>A = np.empty((n+m, n+m))<EOL>A[:n, :n] = <NUM_LIT:0><EOL>A[n:, n:] = <NUM_LIT:0><EOL>A[:n, n:] = B<EOL>A[n:, :n] = -B.T<EOL>return NormalFormGame([Player(A) for i in range(<NUM_LIT:...
Generate a random skew symmetric zero-sum NormalFormGame of the form O B -B.T O where B is an n x m matrix.
f5054:m0
def blotto_game(h, t, rho, mu=<NUM_LIT:0>, random_state=None):
actions = simplex_grid(h, t)<EOL>n = actions.shape[<NUM_LIT:0>]<EOL>payoff_arrays = tuple(np.empty((n, n)) for i in range(<NUM_LIT:2>))<EOL>mean = np.array([mu, mu])<EOL>cov = np.array([[<NUM_LIT:1>, rho], [rho, <NUM_LIT:1>]])<EOL>random_state = check_random_state(random_state)<EOL>values = random_state.multivariate_no...
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)!)). Each player has...
f5059:m0
@jit(nopython=True)<EOL>def _populate_blotto_payoff_arrays(payoff_arrays, actions, values):
n, h = actions.shape<EOL>payoffs = np.empty(<NUM_LIT:2>)<EOL>for i in range(n):<EOL><INDENT>for j in range(n):<EOL><INDENT>payoffs[:] = <NUM_LIT:0><EOL>for k in range(h):<EOL><INDENT>if actions[i, k] == actions[j, k]:<EOL><INDENT>for p in range(<NUM_LIT:2>):<EOL><INDENT>payoffs[p] += values[k, p] / <NUM_LIT:2><EOL><DED...
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 : ndarray(int, ndim=2) ndarray o...
f5059:m1
def ranking_game(n, steps=<NUM_LIT:10>, random_state=None):
payoff_arrays = tuple(np.empty((n, n)) for i in range(<NUM_LIT:2>))<EOL>random_state = check_random_state(random_state)<EOL>scores = random_state.randint(<NUM_LIT:1>, steps+<NUM_LIT:1>, size=(<NUM_LIT:2>, n))<EOL>scores.cumsum(axis=<NUM_LIT:1>, out=scores)<EOL>costs = np.empty((<NUM_LIT:2>, n-<NUM_LIT:1>))<EOL>costs[:]...
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 prize, ...
f5059:m2
@jit(nopython=True)<EOL>def _populate_ranking_payoff_arrays(payoff_arrays, scores, costs):
n = payoff_arrays[<NUM_LIT:0>].shape[<NUM_LIT:0>]<EOL>for p, payoff_array in enumerate(payoff_arrays):<EOL><INDENT>payoff_array[<NUM_LIT:0>, :] = <NUM_LIT:0><EOL>for i in range(<NUM_LIT:1>, n):<EOL><INDENT>for j in range(n):<EOL><INDENT>payoff_array[i, j] = -costs[p, i-<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>prize = <...
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 (2, n) containing score valu...
f5059:m3
def sgc_game(k):
payoff_arrays = tuple(np.empty((<NUM_LIT:4>*k-<NUM_LIT:1>, <NUM_LIT:4>*k-<NUM_LIT:1>)) for i in range(<NUM_LIT:2>))<EOL>_populate_sgc_payoff_arrays(payoff_arrays)<EOL>g = NormalFormGame(<EOL>[Player(payoff_array) for payoff_array in payoff_arrays]<EOL>)<EOL>return g<EOL>
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. Paramete...
f5059:m4
@jit(nopython=True)<EOL>def _populate_sgc_payoff_arrays(payoff_arrays):
n = payoff_arrays[<NUM_LIT:0>].shape[<NUM_LIT:0>] <EOL>m = (n+<NUM_LIT:1>)//<NUM_LIT:2> - <NUM_LIT:1> <EOL>for payoff_array in payoff_arrays:<EOL><INDENT>for i in range(m):<EOL><INDENT>for j in range(m):<EOL><INDENT>payoff_array[i, j] = <NUM_LIT><EOL><DEDENT>for j in range(m, n):<EOL><INDENT>payoff_array[i, j] = <NUM...
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.
f5059:m5
def tournament_game(n, k, random_state=None):
m = scipy.special.comb(n, k, exact=True)<EOL>if m > np.iinfo(np.intp).max:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>payoff_arrays = tuple(np.zeros(shape) for shape in [(n, m), (m, n)])<EOL>tourn = random_tournament_graph(n, random_state=random_state)<EOL>indices, indptr = tourn.csgraph.indices, tourn.csgra...
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. Give...
f5059:m6
@jit(nopython=True)<EOL>def _populate_tournament_payoff_array0(payoff_array, k, indices, indptr):
n = payoff_array.shape[<NUM_LIT:0>]<EOL>X = np.empty(k, dtype=np.int_)<EOL>a = np.empty(k, dtype=np.int_)<EOL>for i in range(n):<EOL><INDENT>d = indptr[i+<NUM_LIT:1>] - indptr[i]<EOL>if d >= k:<EOL><INDENT>for j in range(k):<EOL><INDENT>a[j] = j<EOL><DEDENT>while a[-<NUM_LIT:1>] < d:<EOL><INDENT>for j in range(k):<EOL>...
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 : scalar(int) Size of the s...
f5059:m7
@jit(nopython=True)<EOL>def _populate_tournament_payoff_array1(payoff_array, k):
m = payoff_array.shape[<NUM_LIT:0>]<EOL>X = np.arange(k)<EOL>for j in range(m):<EOL><INDENT>for i in range(k):<EOL><INDENT>payoff_array[j, X[i]] = <NUM_LIT:1><EOL><DEDENT>X = next_k_array(X)<EOL><DEDENT>
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 nodes.
f5059:m8
def unit_vector_game(n, avoid_pure_nash=False, random_state=None):
random_state = check_random_state(random_state)<EOL>payoff_arrays = (np.zeros((n, n)), random_state.random_sample((n, n)))<EOL>if not avoid_pure_nash:<EOL><INDENT>ones_ind = random_state.randint(n, size=n)<EOL>payoff_arrays[<NUM_LIT:0>][ones_ind, np.arange(n)] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if n == <NUM_LI...
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) Number of actions. avoid_pure_nas...
f5059:m9
def mclennan_tourky(g, init=None, epsilon=<NUM_LIT>, max_iter=<NUM_LIT:200>,<EOL>full_output=False):
try:<EOL><INDENT>N = g.N<EOL><DEDENT>except:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if N < <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>if init is None:<EOL><INDENT>init = (<NUM_LIT:0>,) * N<EOL><DEDENT>try:<EOL><INDENT>l = len(init)<EOL><DEDENT>except TypeError:<EOL><INDENT...
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 ...
f5062:m0
def _best_response_selection(x, g, indptr=None):
N = g.N<EOL>if indptr is None:<EOL><INDENT>indptr = np.empty(N+<NUM_LIT:1>, dtype=int)<EOL>indptr[<NUM_LIT:0>] = <NUM_LIT:0><EOL>indptr[<NUM_LIT:1>:] = np.cumsum(g.nums_actions)<EOL><DEDENT>out = np.zeros(indptr[-<NUM_LIT:1>])<EOL>if N == <NUM_LIT:2>:<EOL><INDENT>for i in range(N):<EOL><INDENT>opponent_action = x[indpt...
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 length equal to n_0 + ...
f5062:m1
def _is_epsilon_nash(x, g, epsilon, indptr=None):
if indptr is None:<EOL><INDENT>indptr = np.empty(g.N+<NUM_LIT:1>, dtype=int)<EOL>indptr[<NUM_LIT:0>] = <NUM_LIT:0><EOL>indptr[<NUM_LIT:1>:] = np.cumsum(g.nums_actions)<EOL><DEDENT>action_profile = _get_action_profile(x, indptr)<EOL>return g.is_nash(action_profile, tol=epsilon)<EOL>
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 : NormalFormGame epsilon : scalar(float) ...
f5062:m2