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.ljust(column_widths[i]) for i, cell in enumerate(row)]<EOL>for row in list_of_list]<EOL>bar = deliminator.join(['<STR_LIT:=>' * width for width in column_widths])<EOL>ret = [deliminator.join(row) for row in ret]<EOL>ret = [bar, ret[<NUM_LIT:0>], bar] + ret[<NUM_LIT:1>:] + [bar]<EOL>ret = tab + (u'<STR_LIT:\n>' + tab).join(ret)<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
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 will quote empty strings :return: str of the converted markdown tables
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[<NUM_LIT:0>] = '<STR_LIT:U+0020>' + row[<NUM_LIT:0>]<EOL><DEDENT>if len(column_widths) > <NUM_LIT:1>:<EOL><INDENT>column_widths[-<NUM_LIT:1>] += <NUM_LIT:1><EOL><DEDENT>ret = [[cell.center(column_widths[i])<EOL>for i, cell in enumerate(list_of_list[<NUM_LIT:0>])]]<EOL>ret += [[cell.ljust(column_widths[i]) for i, cell in enumerate(row)]<EOL>for row in list_of_list[<NUM_LIT:1>:]]<EOL>column_widths = self._get_column_widths(ret, padding=<NUM_LIT:3>,<EOL>pad_last_column=True)<EOL>ret = [deliminator.join(row) for row in ret]<EOL>bar = ('<STR_LIT:+>'.join(['<STR_LIT:->' * (width - <NUM_LIT:1>) for width in column_widths]))[<NUM_LIT:1>:]<EOL>ret.insert(<NUM_LIT:1>, bar)<EOL>ret = tab + (u'<STR_LIT:\n>' + tab).join(ret)<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
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 numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: str of the converted markdown tables
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_keys=sort_keys)<EOL>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>ret = ret.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>self._save_file(file_path, ret)<EOL>return ret<EOL>
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. :param quote_numbers: bool if True will quote numbers that are strings :return: string representing the grid formation of the relevant data
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>delim = delim if delim else {}<EOL>for tag in self.FANCY.keys():<EOL><INDENT>delim[tag] = delim[tag] if tag in delim.keys()else self.FANCY[tag]<EOL><DEDENT>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_last_column=True))<EOL>ret = [[cell.ljust(column_widths[i]) for i, cell in enumerate(row)]<EOL>for row in list_of_list]<EOL>grid_row = {}<EOL>for key in div_delims.keys():<EOL><INDENT>draw = div_delims[key]<EOL>grid_row[key] = delim[draw[<NUM_LIT:0>]]<EOL>grid_row[key] += delim[draw[<NUM_LIT:1>]].join(<EOL>[delim[draw[<NUM_LIT:2>]] * width<EOL>for width in column_widths])<EOL>grid_row[key] += delim[draw[<NUM_LIT:3>]]<EOL><DEDENT>ret = [delim['<STR_LIT>'] + delim['<STR_LIT>'].join(row) +<EOL>delim['<STR_LIT>'] for row in ret]<EOL>header = [grid_row["<STR_LIT>"], ret[<NUM_LIT:0>], grid_row["<STR_LIT>"]]<EOL>body = [[row, grid_row["<STR_LIT>"]] for row in ret[<NUM_LIT:1>:]]<EOL>body = [item for pair in body for item in pair][:-<NUM_LIT:1>]<EOL>ret = header + body + [grid_row["<STR_LIT>"]]<EOL>ret = tab + (u'<STR_LIT:\n>' + tab).join(ret)<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
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_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: string representing the grid formation of the relevant data
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_widths[i])<EOL>for i, cell in enumerate(row)])<EOL>for row in list_of_list]<EOL><DEDENT>else:<EOL><INDENT>csv = ['<STR_LIT:U+002C>'.join(row) for row in list_of_list]<EOL><DEDENT>if os.name == '<STR_LIT>':<EOL><INDENT>ret = '<STR_LIT:\r\n>'.join(csv)<EOL><DEDENT>else:<EOL><INDENT>ret = '<STR_LIT:\n>'.join(csv)<EOL><DEDENT>self._save_file(file_path, ret)<EOL>return ret<EOL>
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 strings :param space_columns: bool if True it will align columns with spaces :return: str
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>row = [row[c] for c in html_table.columns]<EOL>data.append(self._html_row(row, tab + '<STR_LIT:U+0020>', color, align=align,<EOL>quote_numbers=quote_numbers))<EOL><DEDENT>ret = '''<STR_LIT>'''.strip().replace('<STR_LIT>', '<STR_LIT:\n>')<EOL>data = ('<STR_LIT>' % tab).join(data)<EOL>ret = (ret % (border, cell_padding, cell_spacing, border_color, data)<EOL>).replace('<STR_LIT:\n>', '<STR_LIT>' % tab)<EOL>self._save_file(file_path, ret)<EOL>return ret<EOL>
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 for hte cells :param border_color: str of the color for the border :param align: str for cell alignment, center, left, right :param row_span: list of rows to span :param quote_numbers: bool if True will quote numbers that are strings :param quote_empty_str: bool if True will quote empty strings :return: str of html code
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.remove_column('<STR_LIT>')<EOL><DEDENT>
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 '' :return: None
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_column(key)<EOL>
: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>' % condition):<EOL><INDENT>ret.append(row)<EOL><DEDENT><DEDENT>return ret<EOL>
: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 :param max_size: int of the max size of the table :param deliminator: str to use as a deliminator when making a str :param tab: str to include before every row :return: SeabornTable
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, column_size))<EOL>for indexes in self._index_iterator(column_size, max_size):<EOL><INDENT>row = SeabornRow(self._column_index,<EOL>[self._pertibate_value(indexes.pop(<NUM_LIT:0>), c) for<EOL>c in self.columns])<EOL>kwargs = row.obj_to_dict()<EOL>if filter_func is None or filter_func(_row_index=len(self.table),<EOL>**kwargs):<EOL><INDENT>self.table.append(row)<EOL><DEDENT><DEDENT>for c in self.columns: <EOL><INDENT>if hasattr(self._parameters.get(c, '<STR_LIT>'), '<STR_LIT>'):<EOL><INDENT>self.set_column(c, self._parameters[c])<EOL><DEDENT><DEDENT>
: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 row<EOL><DEDENT><DEDENT>row = self.append()<EOL>for i, key in enumerate(self.key_on):<EOL><INDENT>row[key] = item[i]<EOL><DEDENT>return row<EOL><DEDENT>
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(item):<EOL><INDENT>self.table[i] = value<EOL>return<EOL><DEDENT><DEDENT>row = self.append(value)<EOL>for i, key in enumerate(self.key_on):<EOL><INDENT>row[key] = item[i]<EOL><DEDENT><DEDENT>
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><DEDENT><DEDENT>
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>row.insert(index, value)<EOL><DEDENT><DEDENT>if index is None:<EOL><INDENT>self.row_columns += [column]<EOL>if self.row_columns is not self.columns andcolumn not in self.columns:<EOL><INDENT>self.columns.append(column)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.row_columns = self.row_columns[:index] + [column]+ self.row_columns[index:]<EOL>self.columns.insert(index, column)<EOL><DEDENT>self._parameters[column] = list(set(self.get_column(column)))<EOL>
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 compute_value_func: func to compute the value given the row :param compute_key: str of the column to send to computer_value_func instead of row :return: None
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_column_widths(list_of_list, **width_kwargs)<EOL>return list_of_list, column_widths<EOL>
: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 - column_widths[i]<EOL>if delta > <NUM_LIT:0> and (not shared_limit or delta <= shared_limit):<EOL><INDENT>column_widths[i] = width<EOL><DEDENT><DEDENT><DEDENT>return list_of_list, column_widths<EOL>
: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>').isdigit() or<EOL>ret in [u'<STR_LIT:False>', u'<STR_LIT:True>', '<STR_LIT:False>',<EOL>'<STR_LIT:True>']):<EOL><INDENT>ret = u'<STR_LIT>' % ret<EOL><DEDENT>elif u'<STR_LIT:">' in ret or (deliminator and deliminator in ret):<EOL><INDENT>ret = u'<STR_LIT>' % ret<EOL><DEDENT>elif quote_empty_str and cell == u'<STR_LIT>':<EOL><INDENT>ret = u'<STR_LIT>'<EOL><DEDENT><DEDENT>if repr_line_break:<EOL><INDENT>ret = ret.replace(u'<STR_LIT:\n>', u'<STR_LIT>')<EOL><DEDENT>return ret<EOL>
: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><INDENT>return ret<EOL><DEDENT>ret = ret.replace(u'<STR_LIT>', u"<STR_LIT:'>").replace(u'<STR_LIT>', u"<STR_LIT:'>")<EOL>ret = ret.replace(u'<STR_LIT>', u'<STR_LIT:">').replace(u'<STR_LIT>', u'<STR_LIT:">')<EOL>ret = ret.replace(u'<STR_LIT:\r>', u'<STR_LIT>')<EOL>ret = ret.replace(u'<STR_LIT:\n>', u'<STR_LIT:\r>')<EOL>ret = ret.replace(u'<STR_LIT:">', u'<STR_LIT>')<EOL>if ((ret.replace(u'<STR_LIT:.>', u'<STR_LIT>').isdigit() and quote_numbers) or<EOL>ret.startswith(u'<STR_LIT:U+0020>') or ret.endswith(u'<STR_LIT:U+0020>')):<EOL><INDENT>return u'<STR_LIT>' % ret<EOL><DEDENT>for special_char in [u'<STR_LIT:\r>', u'<STR_LIT:\t>', u'<STR_LIT:">', u'<STR_LIT:U+002C>', u"<STR_LIT:'>"]:<EOL><INDENT>if special_char in ret:<EOL><INDENT>return u'<STR_LIT>' % ret<EOL><DEDENT><DEDENT>return ret<EOL>
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 :return: str
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><DEDENT><DEDENT><DEDENT><DEDENT>return ret<EOL>
: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 range(max_size):<EOL><INDENT>yield [index_order[indexes[i]] for i in range(len(indexes))]<EOL>for index in range(len(column_size)):<EOL><INDENT>indexes[index] += <NUM_LIT:1><EOL>if indexes[index] < column_size[index]:<EOL><INDENT>break<EOL><DEDENT>indexes[index] = <NUM_LIT:0><EOL>if index == len(column_size) - <NUM_LIT:1>:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>raise StopIteration()<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
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_table<EOL>
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 isinstance(self._parameters.get(name, None), list):<EOL><INDENT>values_width += [len(self._safe_str(p, **kwargs))<EOL>for p in self._parameters[name]]<EOL><DEDENT>values_width += [len(self._safe_str(row[index], **kwargs))<EOL>for row in self.table]<EOL>ret = max(values_width)<EOL>return min(max_width, ret) if max_width else ret<EOL>
: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 times, where d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwcheb`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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.prod(n)<EOL>if a.size == <NUM_LIT:1>:<EOL><INDENT>a = np.repeat(a, d)<EOL><DEDENT>if b.size == <NUM_LIT:1>:<EOL><INDENT>b = np.repeat(b, d)<EOL><DEDENT>i = np.arange(<NUM_LIT:1>, n + <NUM_LIT:1>)<EOL>if kind.upper() == "<STR_LIT:N>": <EOL><INDENT>j = <NUM_LIT> ** (np.arange(<NUM_LIT:1>, d+<NUM_LIT:1>) / (d+<NUM_LIT:1>))<EOL>nodes = np.outer(i, j)<EOL>nodes = (nodes - fix(nodes)).squeeze()<EOL><DEDENT>elif kind.upper() == "<STR_LIT>": <EOL><INDENT>j = equidist_pp[:d]<EOL>nodes = np.outer(i, j)<EOL>nodes = (nodes - fix(nodes)).squeeze()<EOL><DEDENT>elif kind.upper() == "<STR_LIT:H>": <EOL><INDENT>j = equidist_pp[:d]<EOL>nodes = np.outer(i * (i+<NUM_LIT:1>) / <NUM_LIT:2>, j)<EOL>nodes = (nodes - fix(nodes)).squeeze()<EOL><DEDENT>elif kind.upper() == "<STR_LIT:R>": <EOL><INDENT>nodes = random_state.rand(n, d).squeeze()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>r = b - a<EOL>nodes = a + nodes * r<EOL>weights = (np.prod(r) / n) * np.ones(n)<EOL>return nodes, weights<EOL>
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 is given, that constant is repeated d times, where d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions kind : string, optional(default="N") One of the following: - N - Neiderreiter (default) - W - Weyl - H - Haber - R - pseudo Random equidist_pp : array_like, optional(default=None) TODO: I don't know what this does 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 reproducibility. If None, a randomly initialized RandomState is used. Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwequi`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 times, where d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwlege`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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, mu, sig2]]):<EOL><INDENT>nodes, weights = _qnwnorm1(n[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>nodes = []<EOL>weights = []<EOL>for i in range(d):<EOL><INDENT>_1d = _qnwnorm1(n[i])<EOL>nodes.append(_1d[<NUM_LIT:0>])<EOL>weights.append(_1d[<NUM_LIT:1>])<EOL><DEDENT>nodes = gridmake(*nodes)<EOL>weights = ckron(*weights[::-<NUM_LIT:1>])<EOL><DEDENT>if usesqrtm:<EOL><INDENT>new_sig2 = la.sqrtm(sig2)<EOL><DEDENT>else: <EOL><INDENT>new_sig2 = la.cholesky(sig2)<EOL><DEDENT>if d > <NUM_LIT:1>:<EOL><INDENT>nodes = nodes.dot(new_sig2) + mu <EOL><DEDENT>else: <EOL><INDENT>nodes = nodes * new_sig2 + mu<EOL><DEDENT>return nodes.squeeze(), weights<EOL>
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 given, that constant is repeated d times, where d is the number of dimensions sig2 : array_like(float), optional(default=eye(d)) A d x d array representing the variance-covariance matrix of the multivariate normal distribution. Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwnorm`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 given, that constant is repeated d times, where d is the number of dimensions sig2 : array_like(float), optional(default=eye(d)) A d x d array representing the variance-covariance matrix of the multivariate normal distribution. Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwlogn`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwsimp`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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, where d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwtrap`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 repeated d times, where d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwunif`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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>nodes, weights = qnwsimp(n, a, b)<EOL><DEDENT>else:<EOL><INDENT>nodes, weights = qnwequi(n, a, b, kind)<EOL><DEDENT>out = weights.dot(f(nodes, *args, **kwargs))<EOL>return out<EOL>
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 points along each dimension (each dimension is a column). Other arguments that need to be passed to the function are caught by `*args` and `**kwargs` 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 d is the number of dimensions b : scalar or array_like(float) A length-d iterable of upper endpoints. If a scalar is given, that constant is repeated d times, where d is the number of dimensions kind : string, optional(default='lege') Specifies which type of integration to perform. Valid values are: lege - Gauss-Legendre cheb - Gauss-Chebyshev trap - trapezoid rule simp - Simpson rule N - Neiderreiter equidistributed sequence W - Weyl equidistributed sequence H - Haber equidistributed sequence R - Monte Carlo *args, **kwargs : Other arguments passed to the function f Returns ------- out : scalar (float) The value of the integral on the region [a, b] Notes ----- Based of original function ``quadrect`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 variance-covariance matrix of the multivariate normal distribution. Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwbeta`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 array_like(float) : optional(default=ones(d)) Scale parameter of the gamma distribution parameter. Must be positive tol : scalar or array_like(float) : optional(default=ones(d) * 3e-14) Tolerance parameter for newton iterations for each node Returns ------- nodes : np.ndarray(dtype=float) Quadrature nodes weights : np.ndarray(dtype=float) Weights for quadrature nodes Notes ----- Based of original function ``qnwgamma`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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.repeat(args[i], d)<EOL><DEDENT><DEDENT>nodes = []<EOL>weights = []<EOL>for i in range(d):<EOL><INDENT>ai = [x[i] for x in args]<EOL>_1d = one_d_func(n[i], *ai)<EOL>nodes.append(_1d[<NUM_LIT:0>])<EOL>weights.append(_1d[<NUM_LIT:1>])<EOL><DEDENT>weights = ckron(*weights[::-<NUM_LIT:1>]) <EOL>nodes = gridmake(*nodes)<EOL>return nodes, weights<EOL>
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 function before using a tensor product to combine weights and nodes. Parameters ---------- one_d_func : function The 1d function to be called along each dimension n : int or array_like(float) A length-d iterable of the number of nodes in each dimension args : These are the arguments to various qnw____ functions. For the majority of the functions this is just a and b, but some differ. Returns ------- func : function The multi-dimensional version of the parameter ``one_d_func``
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-<NUM_LIT:1>, <NUM_LIT:2>)*np.arange(<NUM_LIT>, n+<NUM_LIT:1>, <NUM_LIT:2>))))<EOL>weights = ((b-a)/n)*np.cos(np.pi/n*np.outer(t1, t2)) @ t3<EOL>return nodes, weights<EOL>
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 of weights Notes ----- Based of original function ``qnwcheb1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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):<EOL><INDENT>p1 = np.ones_like(z)<EOL>p2 = np.zeros_like(z)<EOL>for j in range(<NUM_LIT:1>, n+<NUM_LIT:1>):<EOL><INDENT>p3 = p2<EOL>p2 = p1<EOL>p1 = ((<NUM_LIT:2> * j - <NUM_LIT:1>) * z * p2 - (j - <NUM_LIT:1>) * p3) / j<EOL><DEDENT>pp = n * (z * p1 - p2)/(z * z - <NUM_LIT:1.0>)<EOL>z1 = z.copy()<EOL>z = z1 - p1/pp<EOL>if np.all(np.abs(z - z1) < <NUM_LIT>):<EOL><INDENT>break<EOL><DEDENT><DEDENT>if its == maxit - <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nodes[i] = xm - xl * z<EOL>nodes[- i - <NUM_LIT:1>] = xm + xl * z<EOL>weights[i] = <NUM_LIT:2> * xl / ((<NUM_LIT:1> - z * z) * pp * pp)<EOL>weights[- i - <NUM_LIT:1>] = weights[i]<EOL>return nodes, weights<EOL>
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 of weights Notes ----- Based of original function ``qnwlege1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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>)**(-<NUM_LIT:1> / <NUM_LIT>))<EOL><DEDENT>elif i == <NUM_LIT:1>:<EOL><INDENT>z = z - <NUM_LIT> * (n ** <NUM_LIT>) / z<EOL><DEDENT>elif i == <NUM_LIT:2>:<EOL><INDENT>z = <NUM_LIT> * z + <NUM_LIT> * nodes[<NUM_LIT:0>]<EOL><DEDENT>elif i == <NUM_LIT:3>:<EOL><INDENT>z = <NUM_LIT> * z + <NUM_LIT> * nodes[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>z = <NUM_LIT:2> * z + nodes[i-<NUM_LIT:2>]<EOL><DEDENT>its = <NUM_LIT:0><EOL>while its < maxit:<EOL><INDENT>its += <NUM_LIT:1><EOL>p1 = pim4<EOL>p2 = <NUM_LIT:0><EOL>for j in range(<NUM_LIT:1>, n+<NUM_LIT:1>):<EOL><INDENT>p3 = p2<EOL>p2 = p1<EOL>p1 = z * math.sqrt(<NUM_LIT>/j) * p2 - math.sqrt((j - <NUM_LIT:1.0>) / j) * p3<EOL><DEDENT>pp = math.sqrt(<NUM_LIT:2> * n) * p2<EOL>z1 = z<EOL>z = z1 - p1/pp<EOL>if abs(z - z1) < <NUM_LIT>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if its == maxit:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nodes[n - <NUM_LIT:1> - i] = z<EOL>nodes[i] = -z<EOL>weights[i] = <NUM_LIT:2> / (pp*pp)<EOL>weights[n - <NUM_LIT:1> - i] = weights[i]<EOL><DEDENT>weights /= math.sqrt(math.pi)<EOL>nodes = nodes * math.sqrt(<NUM_LIT>)<EOL>return nodes, weights<EOL>
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 function ``qnwnorm1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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:0>] = weights[-<NUM_LIT:1>] = <NUM_LIT:1><EOL>weights = (dx / <NUM_LIT>) * weights<EOL>return nodes, weights<EOL>
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 weights Notes ----- Based of original function ``qnwsimp1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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 of weights Notes ----- Based of original function ``qnwtrap1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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>*an + <NUM_LIT>*bn + <NUM_LIT>*an*an + <NUM_LIT>*an*bn<EOL>z = <NUM_LIT:1> - r1/r2<EOL><DEDENT>elif i == <NUM_LIT:1>:<EOL><INDENT>r1 = (<NUM_LIT>+a) / ((<NUM_LIT:1>+a)*(<NUM_LIT:1>+<NUM_LIT>*a))<EOL>r2 = <NUM_LIT:1> + <NUM_LIT> * (n-<NUM_LIT:8>) * (<NUM_LIT:1>+<NUM_LIT>*a)/n<EOL>r3 = <NUM_LIT:1> + <NUM_LIT>*b * (<NUM_LIT:1>+<NUM_LIT>*abs(a))/n<EOL>z = z - (<NUM_LIT:1>-z) * r1 * r2 * r3<EOL><DEDENT>elif i == <NUM_LIT:2>:<EOL><INDENT>r1 = (<NUM_LIT>+<NUM_LIT>*a)/(<NUM_LIT:1>+<NUM_LIT>*a)<EOL>r2 = <NUM_LIT:1>+<NUM_LIT>*(n-<NUM_LIT:8>)/n<EOL>r3 = <NUM_LIT:1>+<NUM_LIT:8>*b/((<NUM_LIT>+b)*n*n)<EOL>z = z-(nodes[<NUM_LIT:0>]-z)*r1*r2*r3<EOL><DEDENT>elif i == n - <NUM_LIT:2>:<EOL><INDENT>r1 = (<NUM_LIT:1>+<NUM_LIT>*b)/(<NUM_LIT>+<NUM_LIT>*b)<EOL>r2 = <NUM_LIT:1>/(<NUM_LIT:1>+<NUM_LIT>*(n-<NUM_LIT:4>)/(<NUM_LIT:1>+<NUM_LIT>*(n-<NUM_LIT:4>)))<EOL>r3 = <NUM_LIT:1>/(<NUM_LIT:1>+<NUM_LIT:20>*a/((<NUM_LIT>+a)*n*n))<EOL>z = z+(z-nodes[-<NUM_LIT:4>])*r1*r2*r3<EOL><DEDENT>elif i == n - <NUM_LIT:1>:<EOL><INDENT>r1 = (<NUM_LIT:1>+<NUM_LIT>*b) / (<NUM_LIT>+<NUM_LIT>*b)<EOL>r2 = <NUM_LIT:1> / (<NUM_LIT:1>+<NUM_LIT>*(n-<NUM_LIT:8>)/n)<EOL>r3 = <NUM_LIT:1> / (<NUM_LIT:1>+<NUM_LIT:8>*a/((<NUM_LIT>+a)*n*n))<EOL>z = z+(z-nodes[-<NUM_LIT:3>])*r1*r2*r3<EOL><DEDENT>else:<EOL><INDENT>z = <NUM_LIT:3>*nodes[i-<NUM_LIT:1>] - <NUM_LIT:3>*nodes[i-<NUM_LIT:2>] + nodes[i-<NUM_LIT:3>]<EOL><DEDENT>ab = a+b<EOL>its = <NUM_LIT:0><EOL>z1 = -<NUM_LIT:100><EOL>while abs(z - z1) > <NUM_LIT> and its < maxiter:<EOL><INDENT>temp = <NUM_LIT:2> + ab<EOL>p1 = (a-b + temp*z)/<NUM_LIT:2><EOL>p2 = <NUM_LIT:1><EOL>for j in range(<NUM_LIT:2>, n+<NUM_LIT:1>):<EOL><INDENT>p3 = p2<EOL>p2 = p1<EOL>temp = <NUM_LIT:2>*j + ab<EOL>aa = <NUM_LIT:2>*j * (j+ab)*(temp-<NUM_LIT:2>)<EOL>bb = (temp-<NUM_LIT:1>) * (a*a - b*b + temp*(temp-<NUM_LIT:2>) * z)<EOL>c = <NUM_LIT:2> * (j - <NUM_LIT:1> + a) * (j - <NUM_LIT:1> + b) * temp<EOL>p1 = (bb*p2 - c*p3)/aa<EOL><DEDENT>pp = (n*(a-b-temp*z) * p1 + <NUM_LIT:2>*(n+a)*(n+b)*p2)/(temp*(<NUM_LIT:1> - z*z))<EOL>z1 = z<EOL>z = z1 - p1/pp<EOL>if abs(z - z1) < <NUM_LIT>:<EOL><INDENT>break<EOL><DEDENT>its += <NUM_LIT:1><EOL><DEDENT>if its == maxiter:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nodes[i] = z<EOL>weights[i] = temp/(pp*p2)<EOL><DEDENT>nodes = (<NUM_LIT:1>-nodes)/<NUM_LIT:2><EOL>weights = weights * math.exp(gammaln(a+n) + gammaln(b+n)<EOL>- gammaln(n+<NUM_LIT:1>) - gammaln(n+ab+<NUM_LIT:1>))<EOL>weights = weights / (<NUM_LIT:2>*math.exp(gammaln(a+<NUM_LIT:1>) + gammaln(b+<NUM_LIT:1>)<EOL>- gammaln(ab+<NUM_LIT:2>)))<EOL>return nodes, weights<EOL>
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 points a : scalar : float, optional(default=1) First Beta distribution parameter b : scalar : float, optional(default=1) Second Beta distribution parameter Returns ------- nodes : np.ndarray(dtype=float, ndim=1) The quadrature points weights : np.ndarray(dtype=float, ndim=1) The quadrature weights that correspond to nodes Notes ----- Based of original function ``_qnwbeta1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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>*a)<EOL><DEDENT>elif i == <NUM_LIT:1>:<EOL><INDENT>z = z + (<NUM_LIT:15> + <NUM_LIT>*a) / (<NUM_LIT:1> + <NUM_LIT>*a + <NUM_LIT>*n)<EOL><DEDENT>else:<EOL><INDENT>j = i-<NUM_LIT:1><EOL>z = z + ((<NUM_LIT:1> + <NUM_LIT>*j) / (<NUM_LIT>*j) + <NUM_LIT>*j*a / (<NUM_LIT:1> + <NUM_LIT>*j)) *(z - nodes[j-<NUM_LIT:1>]) / (<NUM_LIT:1> + <NUM_LIT>*a)<EOL><DEDENT>its = <NUM_LIT:0><EOL>z1 = -<NUM_LIT><EOL>while abs(z - z1) > tol and its < maxit:<EOL><INDENT>p1 = <NUM_LIT:1.0><EOL>p2 = <NUM_LIT:0.0><EOL>for j in range(<NUM_LIT:1>, n+<NUM_LIT:1>):<EOL><INDENT>p3 = p2<EOL>p2 = p1<EOL>p1 = ((<NUM_LIT:2>*j - <NUM_LIT:1> + a - z)*p2 - (j - <NUM_LIT:1> + a)*p3) / j<EOL><DEDENT>pp = (n*p1 - (n+a)*p2) / z<EOL>z1 = z<EOL>z = z1 - p1/pp<EOL>its += <NUM_LIT:1><EOL><DEDENT>if its == maxit:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>nodes[i] = z<EOL>weights[i] = factor / (pp*n*p2)<EOL><DEDENT>return nodes*b, weights<EOL>
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 parameter of the gamma distribution parameter. Must be positive tol : scalar : float, optional(default=3e-14) Tolerance parameter for newton iterations for each node Returns ------- nodes : np.ndarray(dtype=float, ndim=1) The quadrature points weights : np.ndarray(dtype=float, ndim=1) The quadrature weights that correspond to nodes Notes ----- Based of original function ``qnwgamma1`` in CompEcon toolbox by Miranda and Fackler References ---------- Miranda, Mario J, and Paul L Fackler. Applied Computational Economics and Finance, MIT Press, 2002.
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>return x<EOL>
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 the initial state of the random number generator for reproducibility. If None, a randomly initialized RandomState is used. parallel : bool(default=True) Whether to use multi-core CPU (parallel=True) or single-threaded CPU (parallel=False). (Internally the code is executed through Numba.guvectorize.) Returns ------- x : ndarray(float, ndim=2) Array of shape (m, k) containing probability vectors as rows. Examples -------- >>> qe.random.probvec(2, 3, random_state=1234) array([[ 0.19151945, 0.43058932, 0.37789123], [ 0.43772774, 0.34763084, 0.21464142]])
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 ---------- r : ndarray(float) Array containing random values in [0, 1). out : ndarray(float) Output array.
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_replacement(n, r)<EOL>return result<EOL>
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.RandomState, optional Random seed (integer) or np.random.RandomState instance to set the initial state of the random number generator for reproducibility. If None, a randomly initialized RandomState is used. Returns ------- result : ndarray(int, ndim=1 or 2) Array of shape (k,) if num_trials is None, or of shape (num_trials, k) otherwise, (each row of) which contains k unique random elements chosen from 0, ..., n-1. Examples -------- >>> qe.random.sample_without_replacement(5, 3, random_state=1234) array([0, 2, 1]) >>> qe.random.sample_without_replacement(5, 3, num_trials=4, ... random_state=1234) array([[0, 2, 1], [3, 4, 0], [1, 3, 2], [4, 1, 3]])
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):<EOL><INDENT>r = np.random.random_sample()<EOL>return searchsorted(cdf, r)<EOL><DEDENT><DEDENT>return draw_impl<EOL>
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, an ndarray of `size` independent draws is returned; otherwise, a single draw is returned as a scalar. Returns ------- scalar(int) or ndarray(int, ndim=1) Examples -------- >>> cdf = np.cumsum([0.4, 0.6]) >>> qe.random.draw(cdf) 1 >>> qe.random.draw(cdf, 10) array([1, 0, 1, 0, 1, 0, 0, 0, 1, 0])
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 points in y
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 of the random number generator for reproducibility. If None, a randomly initialized RandomState is used. Returns ------- array_like(int) An array of k independent draws from q
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>'.format(total_num)<EOL>if not isinstance(init_pivot, numbers.Integral):<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT>if not (<NUM_LIT:0> <= init_pivot < total_num):<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT>if capping is None:<EOL><INDENT>capping = max_iter<EOL><DEDENT>tableaux = tuple(<EOL>np.empty((nums_actions[<NUM_LIT:1>-i], total_num+<NUM_LIT:1>)) for i in range(N)<EOL>)<EOL>bases = tuple(np.empty(nums_actions[<NUM_LIT:1>-i], dtype=int) for i in range(N))<EOL>converged, num_iter, init_pivot_used =_lemke_howson_capping(payoff_matrices, tableaux, bases, init_pivot,<EOL>max_iter, capping)<EOL>NE = _get_mixed_actions(tableaux, bases)<EOL>if not full_output:<EOL><INDENT>return NE<EOL><DEDENT>res = NashResult(NE=NE,<EOL>converged=converged,<EOL>num_iter=num_iter,<EOL>max_iter=max_iter,<EOL>init=init_pivot_used)<EOL>return NE, res<EOL>
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=0) Initial pivot, an integer k such that 0 <= k < m+n, where integers 0, ..., m-1 and m, ..., m+n-1 correspond to the actions of players 0 and 1, respectively. max_iter : scalar(int), optional(default=10**6) Maximum number of pivoting steps. capping : scalar(int), optional(default=None) If supplied, the routine is executed with the heuristics proposed by Codenotti et al. [1]_; see Notes below for details. full_output : bool, optional(default=False) If False, only the computed Nash equilibrium is returned. If True, the return value is `(NE, res)`, where `NE` is the Nash equilibrium and `res` is a `NashResult` object. Returns ------- NE : tuple(ndarray(float, ndim=1)) Tuple of computed Nash equilibrium mixed actions. res : NashResult Object containing information about the computation. Returned only when `full_output` is True. See `NashResult` for details. Examples -------- Consider the following game from von Stengel [3]_: >>> np.set_printoptions(precision=4) # Reduce the digits printed >>> bimatrix = [[(3, 3), (3, 2)], ... [(2, 2), (5, 6)], ... [(0, 3), (6, 1)]] >>> g = NormalFormGame(bimatrix) Obtain a Nash equilibrium of this game by `lemke_howson` with player 0's action 1 (out of the three actions 0, 1, and 2) as the initial pivot: >>> lemke_howson(g, init_pivot=1) (array([ 0. , 0.3333, 0.6667]), array([ 0.3333, 0.6667])) >>> g.is_nash(_) True Additional information is returned if `full_output` is set True: >>> NE, res = lemke_howson(g, init_pivot=1, full_output=True) >>> res.converged # Whether the routine has converged True >>> res.num_iter # Number of pivoting steps performed 4 Notes ----- * This routine is implemented with floating point arithmetic and thus is subject to numerical instability. * If `capping` is set to a positive integer, the routine is executed with the heuristics proposed by [1]_: * For k = `init_pivot`, `init_pivot` + 1, ..., `init_pivot` + (m+n-2), (modulo m+n), the Lemke-Howson algorithm is executed with k as the initial pivot and `capping` as the maximum number of pivoting steps. If the algorithm converges during this loop, then the Nash equilibrium found is returned. * Otherwise, the Lemke-Howson algorithm is executed with `init_pivot` + (m+n-1) (modulo m+n) as the initial pivot, with a limit `max_iter` on the total number of pivoting steps. Accoding to the simulation results for *uniformly random games*, for medium- to large-size games this heuristics outperforms the basic Lemke-Howson algorithm with a fixed initial pivot, where [1]_ suggests that `capping` be set to 10. References ---------- .. [1] B. Codenotti, S. De Rossi, and M. Pagan, "An Experimental Analysis of Lemke-Howson Algorithm," arXiv:0811.3247, 2008. .. [2] C. E. Lemke and J. T. Howson, "Equilibrium Points of Bimatrix Games," Journal of the Society for Industrial and Applied Mathematics (1964), 413-423. .. [3] B. von Stengel, "Equilibrium Computation for Two-Player Games in Strategic and Extensive Form," Chapter 3, N. Nisan, T. Roughgarden, E. Tardos, and V. Vazirani eds., Algorithmic Game Theory, 2007.
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, tableaux, bases)<EOL>converged, num_iter =_lemke_howson_tbl(tableaux, bases, init_pivot_curr, capping_curr)<EOL>total_num_iter += num_iter<EOL>if converged or total_num_iter >= max_iter:<EOL><INDENT>return converged, total_num_iter, init_pivot_curr<EOL><DEDENT>init_pivot_curr += <NUM_LIT:1><EOL>if init_pivot_curr >= m + n:<EOL><INDENT>init_pivot_curr -= m + n<EOL><DEDENT>max_iter_curr -= num_iter<EOL><DEDENT>_initialize_tableaux(payoff_matrices, tableaux, bases)<EOL>converged, num_iter =_lemke_howson_tbl(tableaux, bases, init_pivot_curr, max_iter_curr)<EOL>total_num_iter += num_iter<EOL>return converged, total_num_iter, init_pivot_curr<EOL>
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 used to store the tableaux, of shape (n, m+n+1) and (m, m+n+1), respectively. Modified in place. bases : tuple(ndarray(int, ndim=1)) Tuple of two arrays to be used to store the bases, of shape (n,) and (m,), respectively. Modified in place. init_pivot : scalar(int) Integer k such that 0 <= k < m+n. max_iter : scalar(int) Maximum number of pivoting steps. capping : scalar(int) Value for capping. If set equal to `max_iter`, then the routine is equivalent to the standard Lemke-Howson algorithm.
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((<NUM_LIT:0>, nums_actions[<NUM_LIT:0>]),<EOL>(nums_actions[<NUM_LIT:0>], <NUM_LIT:0>))):<EOL><INDENT>for i in range(nums_actions[<NUM_LIT:1>-pl]):<EOL><INDENT>for j in range(nums_actions[pl]):<EOL><INDENT>tableaux[pl][i, py_start+j] =payoff_matrices[<NUM_LIT:1>-pl][i, j] + consts[<NUM_LIT:1>-pl]<EOL><DEDENT>for j in range(nums_actions[<NUM_LIT:1>-pl]):<EOL><INDENT>if j == i:<EOL><INDENT>tableaux[pl][i, sl_start+j] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>tableaux[pl][i, sl_start+j] = <NUM_LIT:0><EOL><DEDENT><DEDENT>tableaux[pl][i, -<NUM_LIT:1>] = <NUM_LIT:1><EOL><DEDENT>for i in range(nums_actions[<NUM_LIT:1>-pl]):<EOL><INDENT>bases[pl][i] = sl_start + i<EOL><DEDENT><DEDENT>return tableaux, bases<EOL>
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 identically zero). Suppose that the players 0 and 1 have m and n actions, respectively. * `tableaux[0]` has n rows and m+n+1 columns, where columns 0, ..., m-1 and m, ..., m+n-1 correspond to the non-slack and slack variables, respectively. * `tableaux[1]` has m rows and m+n+1 columns, where columns 0, ..., m-1 and m, ..., m+n-1 correspond to the slack and non-slack variables, respectively. * In each `tableaux[i]`, column m+n contains the values of the basic variables (which are initially 1). * `bases[0]` and `bases[1]` contain basic variable indices, which are initially m, ..., m+n-1 and 0, ..., m-1, respectively. 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 used to store the tableaux, of shape (n, m+n+1) and (m, m+n+1), respectively. Modified in place. bases : tuple(ndarray(int, ndim=1)) Tuple of two arrays to be used to store the bases, of shape (n,) and (m,), respectively. Modified in place. Returns ------- tableaux : tuple(ndarray(float, ndim=2)) View to `tableaux`. bases : tuple(ndarray(int, ndim=1)) View to `bases`. Examples -------- >>> A = np.array([[3, 3], [2, 5], [0, 6]]) >>> B = np.array([[3, 2, 3], [2, 6, 1]]) >>> m, n = A.shape >>> tableaux = (np.empty((n, m+n+1)), np.empty((m, m+n+1))) >>> bases = (np.empty(n, dtype=int), np.empty(m, dtype=int)) >>> tableaux, bases = _initialize_tableaux((A, B), tableaux, bases) >>> tableaux[0] array([[ 3., 2., 3., 1., 0., 1.], [ 2., 6., 1., 0., 1., 1.]]) >>> tableaux[1] array([[ 1., 0., 0., 4., 4., 1.], [ 0., 1., 0., 3., 6., 1.], [ 0., 0., 1., 1., 7., 1.]]) >>> bases (array([3, 4]), array([0, 1, 2]))
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>]<EOL>slack_starts = (m, <NUM_LIT:0>)<EOL>argmins = np.empty(max(m, n), dtype=np.int_)<EOL>converged = False<EOL>num_iter = <NUM_LIT:0><EOL>while True:<EOL><INDENT>for pl in pls:<EOL><INDENT>row_min = _lex_min_ratio_test(tableaux[pl], pivot,<EOL>slack_starts[pl], argmins)<EOL>_pivoting(tableaux[pl], pivot, row_min)<EOL>bases[pl][row_min], pivot = pivot, bases[pl][row_min]<EOL>num_iter += <NUM_LIT:1><EOL>if pivot == init_pivot:<EOL><INDENT>converged = True<EOL>break<EOL><DEDENT>if num_iter >= max_iter:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>break<EOL><DEDENT>return converged, num_iter<EOL>
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. bases : tuple(ndarray(int, ndim=1)) Tuple of two arrays containing the bases, of shape (n,) and (m,), respectively. Modified in place. init_pivot : scalar(int) Integer k such that 0 <= k < m+n. max_iter : scalar(int) Maximum number of pivoting steps. Returns ------- converged : bool Whether the pivoting terminated before `max_iter` was reached. num_iter : scalar(int) Number of pivoting steps performed. Examples -------- >>> np.set_printoptions(precision=4) # Reduce the digits printed >>> A = np.array([[3, 3], [2, 5], [0, 6]]) >>> B = np.array([[3, 2, 3], [2, 6, 1]]) >>> m, n = A.shape >>> tableaux = (np.empty((n, m+n+1)), np.empty((m, m+n+1))) >>> bases = (np.empty(n, dtype=int), np.empty(m, dtype=int)) >>> tableaux, bases = _initialize_tableaux((A, B), tableaux, bases) >>> _lemke_howson_tbl(tableaux, bases, 1, 10) (True, 4) >>> tableaux[0] array([[ 0.875 , 0. , 1. , 0.375 , -0.125 , 0.25 ], [ 0.1875, 1. , 0. , -0.0625, 0.1875, 0.125 ]]) >>> tableaux[1] array([[ 1. , -1.6 , 0.8 , 0. , 0. , 0.2 ], [ 0. , 0.4667, -0.4 , 1. , 0. , 0.0667], [ 0. , -0.0667, 0.2 , 0. , 1. , 0.1333]]) >>> bases (array([2, 1]), array([0, 3, 4])) The outputs indicate that in the Nash equilibrium obtained, player 0's mixed action plays actions 2 and 1 with positive weights 0.25 and 0.125, while player 1's mixed action plays actions 0 and 1 (labeled as 3 and 4) with positive weights 0.0667 and 0.1333.
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>continue<EOL><DEDENT>for j in range(ncols):<EOL><INDENT>tableau[i, j] -= tableau[pivot_row, j] * multiplier<EOL><DEDENT><DEDENT>return tableau<EOL>
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><INDENT>sum_ = <NUM_LIT:0.><EOL>for i in range(nums_actions[<NUM_LIT:1>-pl]):<EOL><INDENT>k = bases[pl][i]<EOL>if start <= k < stop:<EOL><INDENT>out[k] = tableaux[pl][i, -<NUM_LIT:1>]<EOL>sum_ += tableaux[pl][i, -<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if sum_ != <NUM_LIT:0>:<EOL><INDENT>out[start:stop] /= sum_<EOL><DEDENT><DEDENT>return out[:nums_actions[<NUM_LIT:0>]], out[nums_actions[<NUM_LIT:0>]:]<EOL>
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(int, ndim=1)) Tuple of two arrays containing the bases, of shape (n,) and (m,), respectively. Returns ------- tuple(ndarray(float, ndim=1)) Tuple of mixed actions as given by the non-slack basic variables in the tableaux.
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((<NUM_LIT:4>, <NUM_LIT:2>))<EOL>W_new = np.empty((np.prod(sg.nums_actions)*<NUM_LIT:4>, <NUM_LIT:2>))<EOL>W_old = np.empty((np.prod(sg.nums_actions)*<NUM_LIT:4>, <NUM_LIT:2>))<EOL>n_new_pt = <NUM_LIT:0><EOL>u = np.copy(u_init)<EOL>payoff_pts =sg.payoff_profile_array.reshape(np.prod(sg.nums_actions), <NUM_LIT:2>)<EOL>W_new[:np.prod(sg.nums_actions)] = payoff_pts<EOL>n_new_pt = np.prod(sg.nums_actions)<EOL>n_iter = <NUM_LIT:0><EOL>while True:<EOL><INDENT>W_old[:n_new_pt] = W_new[:n_new_pt]<EOL>n_old_pt = n_new_pt<EOL>hull = ConvexHull(W_old[:n_old_pt])<EOL>W_new, n_new_pt =_R(delta, sg.nums_actions, sg.payoff_arrays,<EOL>best_dev_gains, hull.points, hull.vertices,<EOL>hull.equations, u, IC, action_profile_payoff,<EOL>extended_payoff, new_pts, W_new)<EOL>n_iter += <NUM_LIT:1><EOL>if n_iter >= max_iter:<EOL><INDENT>break<EOL><DEDENT>if n_new_pt == n_old_pt:<EOL><INDENT>if np.linalg.norm(W_new[:n_new_pt] - W_old[:n_new_pt]) < tol:<EOL><INDENT>break<EOL><DEDENT><DEDENT>_update_u(u, W_new[:n_new_pt])<EOL><DEDENT>hull = ConvexHull(W_new[:n_new_pt])<EOL>return hull<EOL>
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 game. tol : scalar(float), optional(default=1e-12) Tolerance for convergence checking. max_iter : scalar(int), optional(default=500) Maximum number of iterations. u_init : ndarray(float, ndim=1), optional(default=np.zeros(2)) The initial guess of threat points. Returns ------- hull : scipy.spatial.ConvexHull The convex hull of equilibrium payoff pairs. References ---------- .. [1] Abreu, Dilip, and Yuliy Sannikov. "An algorithm for two‐player repeated games with perfect monitoring." Theoretical Economics 9.2 (2014): 313-338.
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_gains[i][ai, a-i] is normalized payoff gain player i can get if originally players are choosing ai and a-i, and player i deviates to the best response action.
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:0>] + best_dev_gains[<NUM_LIT:0>][a0, a1]<EOL>IC[<NUM_LIT:1>] = u[<NUM_LIT:1>] + best_dev_gains[<NUM_LIT:1>][a1, a0]<EOL>if (action_profile_payoff >= IC).all():<EOL><INDENT>extended_payoff[:<NUM_LIT:2>] = action_profile_payoff<EOL>if (np.dot(equations, extended_payoff) <= tol).all():<EOL><INDENT>W_new[n_new_pt] = action_profile_payoff<EOL>n_new_pt += <NUM_LIT:1><EOL>continue<EOL><DEDENT><DEDENT>new_pts, n = _find_C(new_pts, points, vertices, equations,<EOL>extended_payoff, IC, tol)<EOL>for i in range(n):<EOL><INDENT>W_new[n_new_pt] =delta * new_pts[i] + (<NUM_LIT:1>-delta) * action_profile_payoff<EOL>n_new_pt += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return W_new, n_new_pt<EOL>
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 each player. payoff_arrays : tuple(ndarray(float, ndim=2)) Tuple of the payoff arrays, one for each player. best_dev_gains : tuple(ndarray(float, ndim=2)) Tuple of the normalized best deviation payoff gain arrays. best_dev_gains[i][ai, a-i] is payoff gain player i can get if originally players are choosing ai and a-i, and player i deviates to the best response action. points : ndarray(float, ndim=2) Coordinates of the points in the W, which construct a feasible payoff convex hull. vertices : ndarray(float, ndim=1) Indices of points forming the vertices of the convex hull, which are in counterclockwise order. equations : ndarray(float, ndim=2) [normal, offset] forming the hyperplane equation of the facet u : ndarray(float, ndim=1) The threat points. IC : ndarray(float, ndim=1) The minimum IC continuation values. action_profile_payoff : ndarray(float, ndim=1) Array of payoff for one action profile. extended_payoff : ndarray(float, ndim=2) The array [payoff0, payoff1, 1] for checking if [payoff0, payoff1] is in the feasible payoff convex hull. new_pts : ndarray(float, ndim=1) The 4 by 2 array for storing the generated potential extreme points of one action profile. One action profile can only generate at most 4 points. W_new : ndarray(float, ndim=2) Array for storing the coordinates of the generated potential extreme points that construct a new feasible payoff convex hull. tol: scalar(float), optional(default=1e-10) The tolerance for checking if two values are equal. Returns ------- W_new : ndarray(float, ndim=2) The coordinates of the generated potential extreme points that construct a new feasible payoff convex hull. n_new_pt : scalar(int) The number of points in W_new that construct the feasible payoff convex hull.
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_LIT:0>]], tol)<EOL>extended_payoff[:<NUM_LIT:2>] = IC<EOL>if (np.dot(equations, extended_payoff) <= tol).all():<EOL><INDENT>C[n, :] = IC<EOL>n += <NUM_LIT:1><EOL><DEDENT>return C, n<EOL>
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 only generate at most 4 points. points : ndarray(float, ndim=2) Coordinates of the points in the W, which construct a feasible payoff convex hull. vertices : ndarray(float, ndim=1) Indices of points forming the vertices of the convex hull, which are in counterclockwise order. equations : ndarray(float, ndim=2) [normal, offset] forming the hyperplane equation of the facet extended_payoff : ndarray(float, ndim=1) The array [payoff0, payoff1, 1] for checking if [payoff0, payoff1] is in the feasible payoff convex hull. IC : ndarray(float, ndim=1) The minimum IC continuation values. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- C : ndarray(float, ndim=2) The generated potential extreme points. n : scalar(int) The number of found intersection points.
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_LIT:1>):<EOL><INDENT>x = (<NUM_LIT:1> - weights[i]) * pt0[<NUM_LIT:1>-i] + weights[i] * pt1[<NUM_LIT:1>-i]<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if x - IC[<NUM_LIT:1>-i] > tol:<EOL><INDENT>C[n, i] = IC[i]<EOL>C[n, <NUM_LIT:1>-i] = x<EOL>n += <NUM_LIT:1><EOL><DEDENT>elif x - IC[<NUM_LIT:1>-i] > -tol:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return n<EOL>
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 intersection points that have been found. weights : ndarray(float, ndim=1) The size 2 array for storing the weights when calculate the intersection point of simplex and IC constraints. IC : ndarray(float, ndim=1) The minimum IC continuation values. pt0 : ndarray(float, ndim=1) Coordinates of the starting point of the simplex. pt1 : ndarray(float, ndim=1) Coordinates of the ending point of the simplex. tol : scalar(float) The tolerance for checking if two values are equal. Returns ------- n : scalar(int) The updated number of found intersection points.
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 updated threat points.
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)<EOL><DEDENT>
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 dictionary of method options. For example, 'abreu_sannikov' method accepts the following options: tol : scalar(float) Tolerance for convergence checking. max_iter : scalar(int) Maximum number of iterations. u_init : ndarray(float, ndim=1) The initial guess of threat points. Notes ----- Here lists all the implemented methods. The default method is 'abreu_sannikov'. 1. 'abreu_sannikov'
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 equivalently, facet enumeration of their polar polytopes. Then, for each vertex of the polytope for player 0, vertices of the polytope for player 1 are searched to find a completely labeled pair. 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. Returns ------- list(tuple(ndarray(float, ndim=1))) List containing tuples of Nash equilibrium mixed actions.
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)]<EOL>labelings_bits_tup =tuple(_ints_arr_to_bits(brps[i].labelings) for i in range(N))<EOL>equations_tup = tuple(brps[i].equations for i in range(N))<EOL>trans_recips = tuple(brps[i].trans_recip for i in range(N))<EOL>return _vertex_enumeration_gen(labelings_bits_tup, equations_tup,<EOL>trans_recips)<EOL>
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(float, ndim=1)) Tuple of Nash equilibrium mixed actions.
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)) - np.uint64(<NUM_LIT:1>)<EOL>COMPLETE_LABELING_BITS = (np.uint64(<NUM_LIT:1>) << np.uint64(m+n)) - np.uint64(<NUM_LIT:1>)<EOL>for i in range(num_vertices0):<EOL><INDENT>if labelings_bits_tup[<NUM_LIT:0>][i] == ZERO_LABELING0_BITS:<EOL><INDENT>continue<EOL><DEDENT>for j in range(num_vertices1):<EOL><INDENT>xor = labelings_bits_tup[<NUM_LIT:0>][i] ^ labelings_bits_tup[<NUM_LIT:1>][j]<EOL>if xor == COMPLETE_LABELING_BITS:<EOL><INDENT>yield _get_mixed_actions(<EOL>labelings_bits_tup[<NUM_LIT:0>][i],<EOL>(equations_tup[<NUM_LIT:0>][i], equations_tup[<NUM_LIT:1>][j]),<EOL>trans_recips<EOL>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>
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 equations of the polar polytopes. trans_recips : tuple(scalar(float)) Tuple of the reciprocals of the translations.
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 integers from 0, ..., 63. Returns ------- np.uint64 Integer with set bits represented by the input integers. Examples -------- >>> ints_arr = np.array([0, 1, 2], dtype=np.int32) >>> _ints_arr_to_bits(ints_arr) 7 >>> ints_arr2d = np.array([[0, 1, 2], [3, 0, 1]], dtype=np.int32) >>> _ints_arr_to_bits(ints_arr2d) array([ 7, 11], dtype=uint64)
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 in range(start, stop):<EOL><INDENT>if (labeling_bits & np.uint64(<NUM_LIT:1>)) == skip:<EOL><INDENT>out[i] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>out[i] = equation_tup[pl][i-start] * trans_recips[pl] -equation_tup[pl][-<NUM_LIT:1>]<EOL>sum_ += out[i]<EOL><DEDENT>labeling_bits = labeling_bits >> np.uint64(<NUM_LIT:1>)<EOL><DEDENT>if sum_ != <NUM_LIT:0>:<EOL><INDENT>out[start:stop] /= sum_<EOL><DEDENT><DEDENT>return out[:m], out[m:]<EOL>
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 action of player 0. equation_tup : tuple(ndarray(float, ndim=1)) Tuple of hyperplane equations of the polar polytopes. trans_recips : tuple(scalar(float)) Tuple of the reciprocals of the translations. Returns ------- tuple(ndarray(float, ndim=1)) Tuple of mixed actions.
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:2>)])<EOL>
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_normal(mean, cov, h)<EOL>_populate_blotto_payoff_arrays(payoff_arrays, actions, values)<EOL>g = NormalFormGame(<EOL>[Player(payoff_array) for payoff_array in payoff_arrays]<EOL>)<EOL>return g<EOL>
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 a value for each hill that he receives if he assigns strictly more troops to the hill than his opponent (ties are broken uniformly at random), where the values are drawn from a multivariate normal distribution with covariance `rho`. Each player’s payoff is the sum of the values of the hills won by that player. Parameters ---------- h : scalar(int) Number of hills. t : scalar(int) Number of troops. rho : scalar(float) Covariance of the players' values of each hill. Must be in [-1, 1]. mu : scalar(float), optional(default=0) Mean of the players' values of each hill. 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 reproducibility. If None, a randomly initialized RandomState is used. Returns ------- g : NormalFormGame Examples -------- >>> g = blotto_game(2, 3, 0.5, random_state=1234) >>> g.players[0] Player([[-0.44861083, -1.08443468, -1.08443468, -1.08443468], [ 0.18721302, -0.44861083, -1.08443468, -1.08443468], [ 0.18721302, 0.18721302, -0.44861083, -1.08443468], [ 0.18721302, 0.18721302, 0.18721302, -0.44861083]]) >>> g.players[1] Player([[-1.20042463, -1.39708658, -1.39708658, -1.39708658], [-1.00376268, -1.20042463, -1.39708658, -1.39708658], [-1.00376268, -1.00376268, -1.20042463, -1.39708658], [-1.00376268, -1.00376268, -1.00376268, -1.20042463]])
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><DEDENT><DEDENT>else:<EOL><INDENT>winner = np.int(actions[i, k] < actions[j, k])<EOL>payoffs[winner] += values[k, winner]<EOL><DEDENT><DEDENT>payoff_arrays[<NUM_LIT:0>][i, j], payoff_arrays[<NUM_LIT:1>][j, i] = payoffs<EOL><DEDENT><DEDENT>
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 of shape (n, h) containing all possible actions, i.e., h-part compositions of t. values : ndarray(float, ndim=2) ndarray of shape (h, 2), where `values[k, :]` contains the players' values of hill `k`.
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[:] = random_state.randint(<NUM_LIT:1>, steps+<NUM_LIT:1>, size=(<NUM_LIT:2>, n-<NUM_LIT:1>))<EOL>costs.cumsum(axis=<NUM_LIT:1>, out=costs)<EOL>costs[:] /= (n * steps)<EOL>_populate_ranking_payoff_arrays(payoff_arrays, scores, costs)<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 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, whose value is 1, and the other player obtains the "second prize" of value 0; in the case of a tie, the first prize is split and each player receives a value of 0.5. The payoff of a player is given by the value of the prize minus the cost of the effort. Parameters ---------- n : scalar(int) Number of actions, i.e, number of possible effort levels. steps : scalar(int), optional(default=10) Parameter determining the upper bound for the size of the random steps for the scores and costs for each player: The step sizes for the scores are drawn from `1`, ..., `steps`, while those for the costs are multiples of `1/(n*steps)`, where the cost of effort level `0` is 0, and the maximum possible cost of effort level `n-1` is less than or equal to 1. 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 reproducibility. If None, a randomly initialized RandomState is used. Returns ------- g : NormalFormGame Examples -------- >>> g = ranking_game(5, random_state=1234) >>> g.players[0] Player([[ 0. , 0. , 0. , 0. , 0. ], [ 0.82, -0.18, -0.18, -0.18, -0.18], [ 0.8 , 0.8 , -0.2 , -0.2 , -0.2 ], [ 0.68, 0.68, 0.68, -0.32, -0.32], [ 0.66, 0.66, 0.66, 0.66, -0.34]]) >>> g.players[1] Player([[ 1. , 0. , 0. , 0. , 0. ], [ 0.8 , 0.8 , -0.2 , -0.2 , -0.2 ], [ 0.66, 0.66, 0.66, -0.34, -0.34], [ 0.6 , 0.6 , 0.6 , 0.6 , -0.4 ], [ 0.58, 0.58, 0.58, 0.58, 0.58]])
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 = <NUM_LIT:1.><EOL>for i in range(n):<EOL><INDENT>for j in range(n):<EOL><INDENT>if scores[<NUM_LIT:0>, i] > scores[<NUM_LIT:1>, j]:<EOL><INDENT>payoff_arrays[<NUM_LIT:0>][i, j] += prize<EOL><DEDENT>elif scores[<NUM_LIT:0>, i] < scores[<NUM_LIT:1>, j]:<EOL><INDENT>payoff_arrays[<NUM_LIT:1>][j, i] += prize<EOL><DEDENT>else:<EOL><INDENT>payoff_arrays[<NUM_LIT:0>][i, j] += prize / <NUM_LIT:2><EOL>payoff_arrays[<NUM_LIT:1>][j, i] += prize / <NUM_LIT:2><EOL><DEDENT><DEDENT><DEDENT>
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 values corresponding to the effort levels for the two players. costs : ndarray(float, ndim=2) ndarray of shape (2, n-1) containing cost values corresponding to the n-1 positive effort levels for the two players, with the assumption that the cost of the zero effort action is zero.
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. Parameters ---------- k : scalar(int) Positive integer determining the number of actions. The returned game will have `4*k-1` actions for each player. Returns ------- g : NormalFormGame Examples -------- >>> g = sgc_game(2) >>> g.players[0] Player([[ 0.75, 0.5 , 1. , 0.5 , 0.5 , 0.5 , 0.5 ], [ 1. , 0.75, 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ], [ 0.5 , 1. , 0.75, 0.5 , 0.5 , 0.5 , 0.5 ], [ 0. , 0. , 0. , 0.75, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0.75, 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0.75, 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0.75]]) >>> g.players[1] Player([[ 0.75, 0.5 , 1. , 0.5 , 0.5 , 0.5 , 0.5 ], [ 1. , 0.75, 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ], [ 0.5 , 1. , 0.75, 0.5 , 0.5 , 0.5 , 0.5 ], [ 0. , 0. , 0. , 0. , 0.75, 0. , 0. ], [ 0. , 0. , 0. , 0.75, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0.75], [ 0. , 0. , 0. , 0. , 0. , 0.75, 0. ]])
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_LIT:0.5><EOL><DEDENT><DEDENT>for i in range(m, n):<EOL><INDENT>for j in range(n):<EOL><INDENT>payoff_array[i, j] = <NUM_LIT:0><EOL><DEDENT><DEDENT>payoff_array[<NUM_LIT:0>, m-<NUM_LIT:1>] = <NUM_LIT:1><EOL>payoff_array[<NUM_LIT:0>, <NUM_LIT:1>] = <NUM_LIT:0.5><EOL>for i in range(<NUM_LIT:1>, m-<NUM_LIT:1>):<EOL><INDENT>payoff_array[i, i-<NUM_LIT:1>] = <NUM_LIT:1><EOL>payoff_array[i, i+<NUM_LIT:1>] = <NUM_LIT:0.5><EOL><DEDENT>payoff_array[m-<NUM_LIT:1>, m-<NUM_LIT:2>] = <NUM_LIT:1><EOL>payoff_array[m-<NUM_LIT:1>, <NUM_LIT:0>] = <NUM_LIT:0.5><EOL><DEDENT>k = (m+<NUM_LIT:1>)//<NUM_LIT:2><EOL>for h in range(k):<EOL><INDENT>i, j = m + <NUM_LIT:2>*h, m + <NUM_LIT:2>*h<EOL>payoff_arrays[<NUM_LIT:0>][i, j] = <NUM_LIT><EOL>payoff_arrays[<NUM_LIT:0>][i+<NUM_LIT:1>, j+<NUM_LIT:1>] = <NUM_LIT><EOL>payoff_arrays[<NUM_LIT:1>][j, i+<NUM_LIT:1>] = <NUM_LIT><EOL>payoff_arrays[<NUM_LIT:1>][j+<NUM_LIT:1>, i] = <NUM_LIT><EOL><DEDENT>
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.csgraph.indptr<EOL>_populate_tournament_payoff_array0(payoff_arrays[<NUM_LIT:0>], k, indices, indptr)<EOL>_populate_tournament_payoff_array1(payoff_arrays[<NUM_LIT:1>], k)<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 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. Given a randomly generated tournament graph on the n nodes, the payoff for player 0 is 1 if, in the tournament, the node chosen by player 0 dominates all the nodes in the k-subset chosen by player 1. The payoff for player 1 is 1 if player 1's k-subset contains player 0's chosen node. Parameters ---------- n : scalar(int) Number of nodes in the tournament graph. k : scalar(int) Size of subsets of nodes in the tournament graph. 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 reproducibility. If None, a randomly initialized RandomState is used. Returns ------- g : NormalFormGame Notes ----- The actions of player 1 are ordered according to the combinatorial number system [1]_, which is different from the order used in the original library in C. Examples -------- >>> g = tournament_game(5, 2, random_state=1234) >>> g.players[0] Player([[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 1., 0., 1., 0., 1., 0., 0., 0., 0.]]) >>> g.players[1] Player([[ 1., 1., 0., 0., 0.], [ 1., 0., 1., 0., 0.], [ 0., 1., 1., 0., 0.], [ 1., 0., 0., 1., 0.], [ 0., 1., 0., 1., 0.], [ 0., 0., 1., 1., 0.], [ 1., 0., 0., 0., 1.], [ 0., 1., 0., 0., 1.], [ 0., 0., 1., 0., 1.], [ 0., 0., 0., 1., 1.]]) References ---------- .. [1] `Combinatorial number system <https://en.wikipedia.org/wiki/Combinatorial_number_system>`_, Wikipedia.
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><INDENT>X[j] = indices[indptr[i]+a[j]]<EOL><DEDENT>payoff_array[i, k_array_rank_jit(X)] = <NUM_LIT:1><EOL>a = next_k_array(a)<EOL><DEDENT><DEDENT><DEDENT>
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 subsets of nodes. indices : ndarray(int, ndim=1) CSR format index array of the adjacency matrix of the tournament graph. indptr : ndarray(int, ndim=1) CSR format index pointer array of the adjacency matrix of the tournament graph.
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_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>maxes = payoff_arrays[<NUM_LIT:1>].max(axis=<NUM_LIT:0>)<EOL>is_suboptimal = payoff_arrays[<NUM_LIT:1>] < maxes<EOL>nums_suboptimal = is_suboptimal.sum(axis=<NUM_LIT:1>)<EOL>while (nums_suboptimal==<NUM_LIT:0>).any():<EOL><INDENT>payoff_arrays[<NUM_LIT:1>][:] = random_state.random_sample((n, n))<EOL>payoff_arrays[<NUM_LIT:1>].max(axis=<NUM_LIT:0>, out=maxes)<EOL>np.less(payoff_arrays[<NUM_LIT:1>], maxes, out=is_suboptimal)<EOL>is_suboptimal.sum(axis=<NUM_LIT:1>, out=nums_suboptimal)<EOL><DEDENT>for i in range(n):<EOL><INDENT>one_ind = random_state.randint(n)<EOL>while not is_suboptimal[i, one_ind]:<EOL><INDENT>one_ind = random_state.randint(n)<EOL><DEDENT>payoff_arrays[<NUM_LIT:0>][one_ind, i] = <NUM_LIT:1><EOL><DEDENT><DEDENT>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 "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_nash : bool, optional(default=False) If True, player 0's payoffs will be placed in order to avoid pure Nash equilibria. (If necessary, the payoffs for player 1 are redrawn so as not to have a dominant action.) 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 reproducibility. If None, a randomly initialized RandomState is used. Returns ------- g : NormalFormGame Examples -------- >>> g = unit_vector_game(4, random_state=1234) >>> g.players[0] Player([[ 1., 0., 1., 0.], [ 0., 0., 0., 1.], [ 0., 0., 0., 0.], [ 0., 1., 0., 0.]]) >>> g.players[1] Player([[ 0.19151945, 0.62210877, 0.43772774, 0.78535858], [ 0.77997581, 0.27259261, 0.27646426, 0.80187218], [ 0.95813935, 0.87593263, 0.35781727, 0.50099513], [ 0.68346294, 0.71270203, 0.37025075, 0.56119619]]) With `avoid_pure_nash=True`: >>> g = unit_vector_game(4, avoid_pure_nash=True, random_state=1234) >>> g.players[0] Player([[ 1., 1., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 1., 1.], [ 0., 0., 0., 0.]]) >>> g.players[1] Player([[ 0.19151945, 0.62210877, 0.43772774, 0.78535858], [ 0.77997581, 0.27259261, 0.27646426, 0.80187218], [ 0.95813935, 0.87593263, 0.35781727, 0.50099513], [ 0.68346294, 0.71270203, 0.37025075, 0.56119619]]) >>> pure_nash_brute(g) []
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>raise TypeError('<STR_LIT>')<EOL><DEDENT>if l != N:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(N=N)<EOL>)<EOL><DEDENT>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>x_init = _flatten_action_profile(init, indptr)<EOL>is_approx_fp = lambda x: _is_epsilon_nash(x, g, epsilon, indptr)<EOL>x_star, converged, num_iter =_compute_fixed_point_ig(_best_response_selection, x_init, max_iter,<EOL>verbose=<NUM_LIT:0>, print_skip=<NUM_LIT:1>,<EOL>is_approx_fp=is_approx_fp,<EOL>g=g, indptr=indptr)<EOL>NE = _get_action_profile(x_star, indptr)<EOL>if not full_output:<EOL><INDENT>return NE<EOL><DEDENT>res = NashResult(NE=NE,<EOL>converged=converged,<EOL>num_iter=num_iter,<EOL>max_iter=max_iter,<EOL>init=init,<EOL>epsilon=epsilon)<EOL>return NE, res<EOL>
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 Initial action profile, an array of N objects, where each object must be an iteger (pure action) or an array of floats (mixed action). If None, default to an array of zeros (the zero-th action for each player). epsilon : scalar(float), optional(default=1e-3) Value of epsilon-optimality. max_iter : scalar(int), optional(default=100) Maximum number of iterations. full_output : bool, optional(default=False) If False, only the computed Nash equilibrium is returned. If True, the return value is `(NE, res)`, where `NE` is the Nash equilibrium and `res` is a `NashResult` object. Returns ------- NE : tuple(ndarray(float, ndim=1)) Tuple of computed Nash equilibrium mixed actions. res : NashResult Object containing information about the computation. Returned only when `full_output` is True. See `NashResult` for details. Examples -------- Consider the following version of 3-player "anti-coordination" game, where action 0 is a safe action which yields payoff 1, while action 1 yields payoff :math:`v` if no other player plays 1 and payoff 0 otherwise: >>> N = 3 >>> v = 2 >>> payoff_array = np.empty((2,)*n) >>> payoff_array[0, :] = 1 >>> payoff_array[1, :] = 0 >>> payoff_array[1].flat[0] = v >>> g = NormalFormGame((Player(payoff_array),)*N) >>> print(g) 3-player NormalFormGame with payoff profile array: [[[[ 1., 1., 1.], [ 1., 1., 2.]], [[ 1., 2., 1.], [ 1., 0., 0.]]], [[[ 2., 1., 1.], [ 0., 1., 0.]], [[ 0., 0., 1.], [ 0., 0., 0.]]]] This game has a unique symmetric Nash equilibrium, where the equilibrium action is given by :math:`(p^*, 1-p^*)` with :math:`p^* = 1/v^{1/(N-1)}`: >>> p_star = 1/(v**(1/(N-1))) >>> [p_star, 1 - p_star] [0.7071067811865475, 0.29289321881345254] Obtain an approximate Nash equilibrium of this game by `mclennan_tourky`: >>> epsilon = 1e-5 # Value of epsilon-optimality >>> NE = mclennan_tourky(g, epsilon=epsilon) >>> print(NE[0], NE[1], NE[2], sep='\n') [ 0.70710754 0.29289246] [ 0.70710754 0.29289246] [ 0.70710754 0.29289246] >>> g.is_nash(NE, tol=epsilon) True Additional information is returned if `full_output` is set True: >>> NE, res = mclennan_tourky(g, epsilon=epsilon, full_output=True) >>> res.converged True >>> res.num_iter 18 References ---------- .. [1] A. McLennan and R. Tourky, "From Imitation Games to Kakutani," 2006.
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[indptr[<NUM_LIT:1>-i]:indptr[<NUM_LIT:1>-i+<NUM_LIT:1>]]<EOL>pure_br = g.players[i].best_response(opponent_action)<EOL>out[indptr[i]+pure_br] = <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(N):<EOL><INDENT>opponent_actions = tuple(<EOL>x[indptr[(i+j)%N]:indptr[(i+j)%N+<NUM_LIT:1>]] for j in range(<NUM_LIT:1>, N)<EOL>)<EOL>pure_br = g.players[i].best_response(opponent_actions)<EOL>out[indptr[i]+pure_br] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return out<EOL>
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 + ... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains player i's mixed action. g : NormalFormGame indptr : array_like(int, ndim=1), optional(default=None) Array of index pointers of length N+1, where `indptr[0] = 0` and `indptr[i+1] = indptr[i] + n_i`. Created internally if None. Returns ------- out : ndarray(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 representation of his pure best response.
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) indptr : array_like(int, ndim=1), optional(default=None) Array of index pointers of length N+1, where `indptr[0] = 0` and `indptr[i+1] = indptr[i] + n_i`. Created internally if None. Returns ------- bool
f5062:m2