repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
robmcmullen/atrcopy
atrcopy/segments.py
get_style_bits
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0): """ Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region...
python
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0): """ Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region...
[ "def", "get_style_bits", "(", "match", "=", "False", ",", "comment", "=", "False", ",", "selected", "=", "False", ",", "data", "=", "False", ",", "diff", "=", "False", ",", "user", "=", "0", ")", ":", "style_bits", "=", "0", "if", "user", ":", "sty...
Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region data: labeled in the disassembler as a data region (i.e. not disassembled)
[ "Return", "an", "int", "value", "that", "contains", "the", "specified", "style", "bits", "set", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L22-L45
robmcmullen/atrcopy
atrcopy/segments.py
get_style_mask
def get_style_mask(**kwargs): """Get the bit mask that, when anded with data, will turn off the selected bits """ bits = get_style_bits(**kwargs) if 'user' in kwargs and kwargs['user']: bits |= user_bit_mask else: bits &= (0xff ^ user_bit_mask) return 0xff ^ bits
python
def get_style_mask(**kwargs): """Get the bit mask that, when anded with data, will turn off the selected bits """ bits = get_style_bits(**kwargs) if 'user' in kwargs and kwargs['user']: bits |= user_bit_mask else: bits &= (0xff ^ user_bit_mask) return 0xff ^ bits
[ "def", "get_style_mask", "(", "*", "*", "kwargs", ")", ":", "bits", "=", "get_style_bits", "(", "*", "*", "kwargs", ")", "if", "'user'", "in", "kwargs", "and", "kwargs", "[", "'user'", "]", ":", "bits", "|=", "user_bit_mask", "else", ":", "bits", "&=",...
Get the bit mask that, when anded with data, will turn off the selected bits
[ "Get", "the", "bit", "mask", "that", "when", "anded", "with", "data", "will", "turn", "off", "the", "selected", "bits" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L48-L57
robmcmullen/atrcopy
atrcopy/segments.py
SegmentData.byte_bounds_offset
def byte_bounds_offset(self): """Return start and end offsets of this segment's data into the base array's data. This ignores the byte order index. Arrays using the byte order index will have the entire base array's raw data. """ if self.data.base is None: if...
python
def byte_bounds_offset(self): """Return start and end offsets of this segment's data into the base array's data. This ignores the byte order index. Arrays using the byte order index will have the entire base array's raw data. """ if self.data.base is None: if...
[ "def", "byte_bounds_offset", "(", "self", ")", ":", "if", "self", ".", "data", ".", "base", "is", "None", ":", "if", "self", ".", "is_indexed", ":", "basearray", "=", "self", ".", "data", ".", "np_data", "else", ":", "basearray", "=", "self", ".", "d...
Return start and end offsets of this segment's data into the base array's data. This ignores the byte order index. Arrays using the byte order index will have the entire base array's raw data.
[ "Return", "start", "and", "end", "offsets", "of", "this", "segment", "s", "data", "into", "the", "base", "array", "s", "data", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L268-L281
robmcmullen/atrcopy
atrcopy/segments.py
SegmentData.get_raw_index
def get_raw_index(self, i): """Get index into base array's raw data, given the index into this segment """ if self.is_indexed: return int(self.order[i]) if self.data.base is None: return int(i) return int(self.data_start - self.base_start + i)
python
def get_raw_index(self, i): """Get index into base array's raw data, given the index into this segment """ if self.is_indexed: return int(self.order[i]) if self.data.base is None: return int(i) return int(self.data_start - self.base_start + i)
[ "def", "get_raw_index", "(", "self", ",", "i", ")", ":", "if", "self", ".", "is_indexed", ":", "return", "int", "(", "self", ".", "order", "[", "i", "]", ")", "if", "self", ".", "data", ".", "base", "is", "None", ":", "return", "int", "(", "i", ...
Get index into base array's raw data, given the index into this segment
[ "Get", "index", "into", "base", "array", "s", "raw", "data", "given", "the", "index", "into", "this", "segment" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L283-L291
robmcmullen/atrcopy
atrcopy/segments.py
SegmentData.get_indexes_from_base
def get_indexes_from_base(self): """Get array of indexes from the base array, as if this raw data were indexed. """ if self.is_indexed: return np.copy(self.order[i]) if self.data.base is None: i = 0 else: i = self.get_raw_index(0) ...
python
def get_indexes_from_base(self): """Get array of indexes from the base array, as if this raw data were indexed. """ if self.is_indexed: return np.copy(self.order[i]) if self.data.base is None: i = 0 else: i = self.get_raw_index(0) ...
[ "def", "get_indexes_from_base", "(", "self", ")", ":", "if", "self", ".", "is_indexed", ":", "return", "np", ".", "copy", "(", "self", ".", "order", "[", "i", "]", ")", "if", "self", ".", "data", ".", "base", "is", "None", ":", "i", "=", "0", "el...
Get array of indexes from the base array, as if this raw data were indexed.
[ "Get", "array", "of", "indexes", "from", "the", "base", "array", "as", "if", "this", "raw", "data", "were", "indexed", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L293-L303
robmcmullen/atrcopy
atrcopy/segments.py
SegmentData.reverse_index_mapping
def reverse_index_mapping(self): """Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array """ if self._reverse_index_mapp...
python
def reverse_index_mapping(self): """Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array """ if self._reverse_index_mapp...
[ "def", "reverse_index_mapping", "(", "self", ")", ":", "if", "self", ".", "_reverse_index_mapping", "is", "None", ":", "if", "self", ".", "is_indexed", ":", "# Initialize array to out of range", "r", "=", "np", ".", "zeros", "(", "self", ".", "base_length", ",...
Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array
[ "Get", "mapping", "from", "this", "segment", "s", "indexes", "to", "the", "indexes", "of", "the", "base", "array", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L358-L377
robmcmullen/atrcopy
atrcopy/segments.py
SegmentData.get_reverse_index
def get_reverse_index(self, base_index): """Get index into this segment's data given the index into the base data Raises IndexError if the base index doesn't map to anything in this segment's data """ r = self.reverse_index_mapping[base_index] if r < 0: raise...
python
def get_reverse_index(self, base_index): """Get index into this segment's data given the index into the base data Raises IndexError if the base index doesn't map to anything in this segment's data """ r = self.reverse_index_mapping[base_index] if r < 0: raise...
[ "def", "get_reverse_index", "(", "self", ",", "base_index", ")", ":", "r", "=", "self", ".", "reverse_index_mapping", "[", "base_index", "]", "if", "r", "<", "0", ":", "raise", "IndexError", "(", "\"index %d not mapped in this segment\"", "%", "base_index", ")",...
Get index into this segment's data given the index into the base data Raises IndexError if the base index doesn't map to anything in this segment's data
[ "Get", "index", "into", "this", "segment", "s", "data", "given", "the", "index", "into", "the", "base", "data" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L379-L388
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.resize
def resize(self, newsize, zeros=True): """ Resize the data arrays. This can only be performed on the container segment. Child segments must adjust their rawdata to point to the correct place. Since segments don't keep references to other segments, it is the user's responsibilit...
python
def resize(self, newsize, zeros=True): """ Resize the data arrays. This can only be performed on the container segment. Child segments must adjust their rawdata to point to the correct place. Since segments don't keep references to other segments, it is the user's responsibilit...
[ "def", "resize", "(", "self", ",", "newsize", ",", "zeros", "=", "True", ")", ":", "if", "not", "self", ".", "can_resize", ":", "raise", "ValueError", "(", "\"Segment %s can't be resized\"", "%", "str", "(", "self", ")", ")", "# only makes sense for the contai...
Resize the data arrays. This can only be performed on the container segment. Child segments must adjust their rawdata to point to the correct place. Since segments don't keep references to other segments, it is the user's responsibility to update any child segments that point to this ...
[ "Resize", "the", "data", "arrays", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L430-L458
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.restore_renamed_serializable_attributes
def restore_renamed_serializable_attributes(self): """Hook for the future if attributes have been renamed. The old attribute names will have been restored in the __dict__.update in __setstate__, so this routine should move attribute values to their new names. """ if hasat...
python
def restore_renamed_serializable_attributes(self): """Hook for the future if attributes have been renamed. The old attribute names will have been restored in the __dict__.update in __setstate__, so this routine should move attribute values to their new names. """ if hasat...
[ "def", "restore_renamed_serializable_attributes", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'start_addr'", ")", ":", "self", ".", "origin", "=", "self", ".", "start_addr", "log", ".", "debug", "(", "f\"moving start_addr to origin: {self.start_addr}\...
Hook for the future if attributes have been renamed. The old attribute names will have been restored in the __dict__.update in __setstate__, so this routine should move attribute values to their new names.
[ "Hook", "for", "the", "future", "if", "attributes", "have", "been", "renamed", ".", "The", "old", "attribute", "names", "will", "have", "been", "restored", "in", "the", "__dict__", ".", "update", "in", "__setstate__", "so", "this", "routine", "should", "move...
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L518-L527
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.reconstruct_raw
def reconstruct_raw(self, rawdata): """Reconstruct the pointers to the parent data arrays Each segment is a view into the primary segment's data, so those pointers and the order must be restored in the child segments. """ start, end = self._rawdata_bounds r = rawdata[sta...
python
def reconstruct_raw(self, rawdata): """Reconstruct the pointers to the parent data arrays Each segment is a view into the primary segment's data, so those pointers and the order must be restored in the child segments. """ start, end = self._rawdata_bounds r = rawdata[sta...
[ "def", "reconstruct_raw", "(", "self", ",", "rawdata", ")", ":", "start", ",", "end", "=", "self", ".", "_rawdata_bounds", "r", "=", "rawdata", "[", "start", ":", "end", "]", "delattr", "(", "self", ",", "'_rawdata_bounds'", ")", "try", ":", "if", "sel...
Reconstruct the pointers to the parent data arrays Each segment is a view into the primary segment's data, so those pointers and the order must be restored in the child segments.
[ "Reconstruct", "the", "pointers", "to", "the", "parent", "data", "arrays" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L529-L545
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_parallel_raw_data
def get_parallel_raw_data(self, other): """ Get the raw data that is similar to the specified other segment """ start, end = other.byte_bounds_offset() r = self.rawdata[start:end] if other.rawdata.is_indexed: r = r.get_indexed[other.order] return r
python
def get_parallel_raw_data(self, other): """ Get the raw data that is similar to the specified other segment """ start, end = other.byte_bounds_offset() r = self.rawdata[start:end] if other.rawdata.is_indexed: r = r.get_indexed[other.order] return r
[ "def", "get_parallel_raw_data", "(", "self", ",", "other", ")", ":", "start", ",", "end", "=", "other", ".", "byte_bounds_offset", "(", ")", "r", "=", "self", ".", "rawdata", "[", "start", ":", "end", "]", "if", "other", ".", "rawdata", ".", "is_indexe...
Get the raw data that is similar to the specified other segment
[ "Get", "the", "raw", "data", "that", "is", "similar", "to", "the", "specified", "other", "segment" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L547-L554
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.serialize_session
def serialize_session(self, mdict): """Save extra metadata to a dict so that it can be serialized This is not saved by __getstate__ because child segments will point to the same data and this allows it to only be saved for the base segment. As well as allowing it to be pulled out of the...
python
def serialize_session(self, mdict): """Save extra metadata to a dict so that it can be serialized This is not saved by __getstate__ because child segments will point to the same data and this allows it to only be saved for the base segment. As well as allowing it to be pulled out of the...
[ "def", "serialize_session", "(", "self", ",", "mdict", ")", ":", "mdict", "[", "\"comment ranges\"", "]", "=", "[", "list", "(", "a", ")", "for", "a", "in", "self", ".", "get_style_ranges", "(", "comment", "=", "True", ")", "]", "mdict", "[", "\"data r...
Save extra metadata to a dict so that it can be serialized This is not saved by __getstate__ because child segments will point to the same data and this allows it to only be saved for the base segment. As well as allowing it to be pulled out of the main json so that it can be more easil...
[ "Save", "extra", "metadata", "to", "a", "dict", "so", "that", "it", "can", "be", "serialized" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L556-L574
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_index_from_base_index
def get_index_from_base_index(self, base_index): """Get index into this array's data given the index into the base array """ r = self.rawdata try: index = r.get_reverse_index(base_index) except IndexError: raise IndexError("index %d not in this segment" % ...
python
def get_index_from_base_index(self, base_index): """Get index into this array's data given the index into the base array """ r = self.rawdata try: index = r.get_reverse_index(base_index) except IndexError: raise IndexError("index %d not in this segment" % ...
[ "def", "get_index_from_base_index", "(", "self", ",", "base_index", ")", ":", "r", "=", "self", ".", "rawdata", "try", ":", "index", "=", "r", ".", "get_reverse_index", "(", "base_index", ")", "except", "IndexError", ":", "raise", "IndexError", "(", "\"index...
Get index into this array's data given the index into the base array
[ "Get", "index", "into", "this", "array", "s", "data", "given", "the", "index", "into", "the", "base", "array" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L652-L662
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_style_ranges
def get_style_ranges(self, **kwargs): """Return a list of start, end pairs that match the specified style """ style_bits = self.get_style_bits(**kwargs) matches = (self.style & style_bits) == style_bits return self.bool_to_ranges(matches)
python
def get_style_ranges(self, **kwargs): """Return a list of start, end pairs that match the specified style """ style_bits = self.get_style_bits(**kwargs) matches = (self.style & style_bits) == style_bits return self.bool_to_ranges(matches)
[ "def", "get_style_ranges", "(", "self", ",", "*", "*", "kwargs", ")", ":", "style_bits", "=", "self", ".", "get_style_bits", "(", "*", "*", "kwargs", ")", "matches", "=", "(", "self", ".", "style", "&", "style_bits", ")", "==", "style_bits", "return", ...
Return a list of start, end pairs that match the specified style
[ "Return", "a", "list", "of", "start", "end", "pairs", "that", "match", "the", "specified", "style" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L689-L694
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.fixup_comments
def fixup_comments(self): """Remove any style bytes that are marked as commented but have no comment, and add any style bytes where there's a comment but it isn't marked in the style data. This happens on the base data, so only need to do this on one segment that uses this base ...
python
def fixup_comments(self): """Remove any style bytes that are marked as commented but have no comment, and add any style bytes where there's a comment but it isn't marked in the style data. This happens on the base data, so only need to do this on one segment that uses this base ...
[ "def", "fixup_comments", "(", "self", ")", ":", "style_base", "=", "self", ".", "rawdata", ".", "style_base", "comment_text_indexes", "=", "np", ".", "asarray", "(", "list", "(", "self", ".", "rawdata", ".", "extra", ".", "comments", ".", "keys", "(", ")...
Remove any style bytes that are marked as commented but have no comment, and add any style bytes where there's a comment but it isn't marked in the style data. This happens on the base data, so only need to do this on one segment that uses this base data.
[ "Remove", "any", "style", "bytes", "that", "are", "marked", "as", "commented", "but", "have", "no", "comment", "and", "add", "any", "style", "bytes", "where", "there", "s", "a", "comment", "but", "it", "isn", "t", "marked", "in", "the", "style", "data", ...
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L696-L712
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_entire_style_ranges
def get_entire_style_ranges(self, split_comments=None, **kwargs): """Find sections of the segment that have the same style value. The arguments to this function are used as a mask for the style to determine where to split the styles. Style bits that aren't included in the list will be i...
python
def get_entire_style_ranges(self, split_comments=None, **kwargs): """Find sections of the segment that have the same style value. The arguments to this function are used as a mask for the style to determine where to split the styles. Style bits that aren't included in the list will be i...
[ "def", "get_entire_style_ranges", "(", "self", ",", "split_comments", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style_bits", "=", "self", ".", "get_style_bits", "(", "*", "*", "kwargs", ")", "matches", "=", "self", ".", "get_comment_locations", "(", ...
Find sections of the segment that have the same style value. The arguments to this function are used as a mask for the style to determine where to split the styles. Style bits that aren't included in the list will be ignored when splitting. The returned list covers the entire length of ...
[ "Find", "sections", "of", "the", "segment", "that", "have", "the", "same", "style", "value", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L725-L775
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_comments_at_indexes
def get_comments_at_indexes(self, indexes): """Get a list of comments at specified indexes""" s = self.style[indexes] has_comments = np.where(s & comment_bit_mask > 0)[0] comments = [] for where_index in has_comments: raw = self.get_raw_index(indexes[where_index]) ...
python
def get_comments_at_indexes(self, indexes): """Get a list of comments at specified indexes""" s = self.style[indexes] has_comments = np.where(s & comment_bit_mask > 0)[0] comments = [] for where_index in has_comments: raw = self.get_raw_index(indexes[where_index]) ...
[ "def", "get_comments_at_indexes", "(", "self", ",", "indexes", ")", ":", "s", "=", "self", ".", "style", "[", "indexes", "]", "has_comments", "=", "np", ".", "where", "(", "s", "&", "comment_bit_mask", ">", "0", ")", "[", "0", "]", "comments", "=", "...
Get a list of comments at specified indexes
[ "Get", "a", "list", "of", "comments", "at", "specified", "indexes" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L947-L959
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_comment_restore_data
def get_comment_restore_data(self, ranges): """Get a chunk of data (designed to be opaque) containing comments, styles & locations that can be used to recreate the comments on an undo """ restore_data = [] for start, end in ranges: log.debug("range: %d-%d" % (start, e...
python
def get_comment_restore_data(self, ranges): """Get a chunk of data (designed to be opaque) containing comments, styles & locations that can be used to recreate the comments on an undo """ restore_data = [] for start, end in ranges: log.debug("range: %d-%d" % (start, e...
[ "def", "get_comment_restore_data", "(", "self", ",", "ranges", ")", ":", "restore_data", "=", "[", "]", "for", "start", ",", "end", "in", "ranges", ":", "log", ".", "debug", "(", "\"range: %d-%d\"", "%", "(", "start", ",", "end", ")", ")", "styles", "=...
Get a chunk of data (designed to be opaque) containing comments, styles & locations that can be used to recreate the comments on an undo
[ "Get", "a", "chunk", "of", "data", "(", "designed", "to", "be", "opaque", ")", "containing", "comments", "styles", "&", "locations", "that", "can", "be", "used", "to", "recreate", "the", "comments", "on", "an", "undo" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L961-L981
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.restore_comments
def restore_comments(self, restore_data): """Restore comment styles and data """ for start, end, styles, items in restore_data: log.debug("range: %d-%d" % (start, end)) self.style[start:end] = styles for i in range(start, end): rawindex, commen...
python
def restore_comments(self, restore_data): """Restore comment styles and data """ for start, end, styles, items in restore_data: log.debug("range: %d-%d" % (start, end)) self.style[start:end] = styles for i in range(start, end): rawindex, commen...
[ "def", "restore_comments", "(", "self", ",", "restore_data", ")", ":", "for", "start", ",", "end", ",", "styles", ",", "items", "in", "restore_data", ":", "log", ".", "debug", "(", "\"range: %d-%d\"", "%", "(", "start", ",", "end", ")", ")", "self", "....
Restore comment styles and data
[ "Restore", "comment", "styles", "and", "data" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L983-L1001
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.get_comments_in_range
def get_comments_in_range(self, start, end): """Get a list of comments at specified indexes""" comments = {} # Naive way, but maybe it's fast enough: loop over all comments # gathering those within the bounds for rawindex, comment in self.rawdata.extra.comments.items(): ...
python
def get_comments_in_range(self, start, end): """Get a list of comments at specified indexes""" comments = {} # Naive way, but maybe it's fast enough: loop over all comments # gathering those within the bounds for rawindex, comment in self.rawdata.extra.comments.items(): ...
[ "def", "get_comments_in_range", "(", "self", ",", "start", ",", "end", ")", ":", "comments", "=", "{", "}", "# Naive way, but maybe it's fast enough: loop over all comments", "# gathering those within the bounds", "for", "rawindex", ",", "comment", "in", "self", ".", "r...
Get a list of comments at specified indexes
[ "Get", "a", "list", "of", "comments", "at", "specified", "indexes" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L1003-L1016
robmcmullen/atrcopy
atrcopy/segments.py
DefaultSegment.copy_user_data
def copy_user_data(self, source, index_offset=0): """Copy comments and other user data from the source segment to this segment. The index offset is the offset into self based on the index of source. """ for index, comment in source.iter_comments_in_segment(): self.se...
python
def copy_user_data(self, source, index_offset=0): """Copy comments and other user data from the source segment to this segment. The index offset is the offset into self based on the index of source. """ for index, comment in source.iter_comments_in_segment(): self.se...
[ "def", "copy_user_data", "(", "self", ",", "source", ",", "index_offset", "=", "0", ")", ":", "for", "index", ",", "comment", "in", "source", ".", "iter_comments_in_segment", "(", ")", ":", "self", ".", "set_comment_at", "(", "index", "+", "index_offset", ...
Copy comments and other user data from the source segment to this segment. The index offset is the offset into self based on the index of source.
[ "Copy", "comments", "and", "other", "user", "data", "from", "the", "source", "segment", "to", "this", "segment", "." ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L1062-L1069
openstax/cnx-archive
cnxarchive/views/xpath.py
xpath_book
def xpath_book(request, uuid, version, return_json=True): """ Given a request, book UUID and version: returns a JSON object or HTML list of results, each result containing: module_name, module_uuid, xpath_results, an array of strings, each an individual xpath result. """ xpath_string =...
python
def xpath_book(request, uuid, version, return_json=True): """ Given a request, book UUID and version: returns a JSON object or HTML list of results, each result containing: module_name, module_uuid, xpath_results, an array of strings, each an individual xpath result. """ xpath_string =...
[ "def", "xpath_book", "(", "request", ",", "uuid", ",", "version", ",", "return_json", "=", "True", ")", ":", "xpath_string", "=", "request", ".", "params", ".", "get", "(", "'q'", ")", "results", "=", "execute_xpath", "(", "xpath_string", ",", "'xpath'", ...
Given a request, book UUID and version: returns a JSON object or HTML list of results, each result containing: module_name, module_uuid, xpath_results, an array of strings, each an individual xpath result.
[ "Given", "a", "request", "book", "UUID", "and", "version", ":" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/xpath.py#L44-L59
openstax/cnx-archive
cnxarchive/views/xpath.py
xpath_page
def xpath_page(request, uuid, version): """Given a page UUID (and optional version), returns a JSON object of results, as in xpath_book()""" xpath_string = request.params.get('q') return execute_xpath(xpath_string, 'xpath-module', uuid, version)
python
def xpath_page(request, uuid, version): """Given a page UUID (and optional version), returns a JSON object of results, as in xpath_book()""" xpath_string = request.params.get('q') return execute_xpath(xpath_string, 'xpath-module', uuid, version)
[ "def", "xpath_page", "(", "request", ",", "uuid", ",", "version", ")", ":", "xpath_string", "=", "request", ".", "params", ".", "get", "(", "'q'", ")", "return", "execute_xpath", "(", "xpath_string", ",", "'xpath-module'", ",", "uuid", ",", "version", ")" ...
Given a page UUID (and optional version), returns a JSON object of results, as in xpath_book()
[ "Given", "a", "page", "UUID", "(", "and", "optional", "version", ")", "returns", "a", "JSON", "object", "of", "results", "as", "in", "xpath_book", "()" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/xpath.py#L116-L120
openstax/cnx-archive
cnxarchive/views/xpath.py
execute_xpath
def execute_xpath(xpath_string, sql_function, uuid, version): """Executes either xpath or xpath-module SQL function with given input params.""" settings = get_current_registry().settings with db_connect() as db_connection: with db_connection.cursor() as cursor: try: ...
python
def execute_xpath(xpath_string, sql_function, uuid, version): """Executes either xpath or xpath-module SQL function with given input params.""" settings = get_current_registry().settings with db_connect() as db_connection: with db_connection.cursor() as cursor: try: ...
[ "def", "execute_xpath", "(", "xpath_string", ",", "sql_function", ",", "uuid", ",", "version", ")", ":", "settings", "=", "get_current_registry", "(", ")", ".", "settings", "with", "db_connect", "(", ")", "as", "db_connection", ":", "with", "db_connection", "....
Executes either xpath or xpath-module SQL function with given input params.
[ "Executes", "either", "xpath", "or", "xpath", "-", "module", "SQL", "function", "with", "given", "input", "params", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/xpath.py#L123-L144
openstax/cnx-archive
cnxarchive/views/xpath.py
xpath
def xpath(request): """View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.""" ident_hash = request.params.get('id') xpath_string = request.params.get('q') if not ident_hash or not xpath_...
python
def xpath(request): """View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.""" ident_hash = request.params.get('id') xpath_string = request.params.get('q') if not ident_hash or not xpath_...
[ "def", "xpath", "(", "request", ")", ":", "ident_hash", "=", "request", ".", "params", ".", "get", "(", "'id'", ")", "xpath_string", "=", "request", ".", "params", ".", "get", "(", "'q'", ")", "if", "not", "ident_hash", "or", "not", "xpath_string", ":"...
View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.
[ "View", "for", "the", "route", ".", "Determines", "UUID", "and", "version", "from", "input", "request", "and", "determines", "the", "type", "of", "UUID", "(", "collection", "or", "module", ")", "and", "executes", "the", "corresponding", "method", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/xpath.py#L156-L203
openstax/cnx-archive
cnxarchive/views/content.py
tree_to_html
def tree_to_html(tree): """Return html list version of book tree.""" ul = etree.Element('ul') html_listify([tree], ul) return HTML_WRAPPER.format(etree.tostring(ul))
python
def tree_to_html(tree): """Return html list version of book tree.""" ul = etree.Element('ul') html_listify([tree], ul) return HTML_WRAPPER.format(etree.tostring(ul))
[ "def", "tree_to_html", "(", "tree", ")", ":", "ul", "=", "etree", ".", "Element", "(", "'ul'", ")", "html_listify", "(", "[", "tree", "]", ",", "ul", ")", "return", "HTML_WRAPPER", ".", "format", "(", "etree", ".", "tostring", "(", "ul", ")", ")" ]
Return html list version of book tree.
[ "Return", "html", "list", "version", "of", "book", "tree", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L48-L52
openstax/cnx-archive
cnxarchive/views/content.py
_get_content_json
def _get_content_json(ident_hash=None): """Return a content as a dict from its ident-hash (uuid@version).""" request = get_current_request() routing_args = request and request.matchdict or {} if not ident_hash: ident_hash = routing_args['ident_hash'] as_collated = asbool(request.GET.get('as...
python
def _get_content_json(ident_hash=None): """Return a content as a dict from its ident-hash (uuid@version).""" request = get_current_request() routing_args = request and request.matchdict or {} if not ident_hash: ident_hash = routing_args['ident_hash'] as_collated = asbool(request.GET.get('as...
[ "def", "_get_content_json", "(", "ident_hash", "=", "None", ")", ":", "request", "=", "get_current_request", "(", ")", "routing_args", "=", "request", "and", "request", ".", "matchdict", "or", "{", "}", "if", "not", "ident_hash", ":", "ident_hash", "=", "rou...
Return a content as a dict from its ident-hash (uuid@version).
[ "Return", "a", "content", "as", "a", "dict", "from", "its", "ident", "-", "hash", "(", "uuid" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L55-L137
openstax/cnx-archive
cnxarchive/views/content.py
get_content_json
def get_content_json(request): """Retrieve content as JSON using the ident-hash (uuid@version).""" result = _get_content_json() resp = request.response resp.status = "200 OK" resp.content_type = 'application/json' resp.body = json.dumps(result) return result, resp
python
def get_content_json(request): """Retrieve content as JSON using the ident-hash (uuid@version).""" result = _get_content_json() resp = request.response resp.status = "200 OK" resp.content_type = 'application/json' resp.body = json.dumps(result) return result, resp
[ "def", "get_content_json", "(", "request", ")", ":", "result", "=", "_get_content_json", "(", ")", "resp", "=", "request", ".", "response", "resp", ".", "status", "=", "\"200 OK\"", "resp", ".", "content_type", "=", "'application/json'", "resp", ".", "body", ...
Retrieve content as JSON using the ident-hash (uuid@version).
[ "Retrieve", "content", "as", "JSON", "using", "the", "ident", "-", "hash", "(", "uuid" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L140-L148
openstax/cnx-archive
cnxarchive/views/content.py
get_content_html
def get_content_html(request): """Retrieve content as HTML using the ident-hash (uuid@version).""" result = _get_content_json() media_type = result['mediaType'] if media_type == COLLECTION_MIMETYPE: content = tree_to_html(result['tree']) else: content = result['content'] resp =...
python
def get_content_html(request): """Retrieve content as HTML using the ident-hash (uuid@version).""" result = _get_content_json() media_type = result['mediaType'] if media_type == COLLECTION_MIMETYPE: content = tree_to_html(result['tree']) else: content = result['content'] resp =...
[ "def", "get_content_html", "(", "request", ")", ":", "result", "=", "_get_content_json", "(", ")", "media_type", "=", "result", "[", "'mediaType'", "]", "if", "media_type", "==", "COLLECTION_MIMETYPE", ":", "content", "=", "tree_to_html", "(", "result", "[", "...
Retrieve content as HTML using the ident-hash (uuid@version).
[ "Retrieve", "content", "as", "HTML", "using", "the", "ident", "-", "hash", "(", "uuid" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L151-L165
openstax/cnx-archive
cnxarchive/views/content.py
html_listify
def html_listify(tree, root_ul_element, parent_id=None): """Recursively construct HTML nested list version of book tree. The original caller should not call this function with the `parent_id` defined. """ request = get_current_request() is_first_node = parent_id is None if is_first_node: ...
python
def html_listify(tree, root_ul_element, parent_id=None): """Recursively construct HTML nested list version of book tree. The original caller should not call this function with the `parent_id` defined. """ request = get_current_request() is_first_node = parent_id is None if is_first_node: ...
[ "def", "html_listify", "(", "tree", ",", "root_ul_element", ",", "parent_id", "=", "None", ")", ":", "request", "=", "get_current_request", "(", ")", "is_first_node", "=", "parent_id", "is", "None", "if", "is_first_node", ":", "parent_id", "=", "tree", "[", ...
Recursively construct HTML nested list version of book tree. The original caller should not call this function with the `parent_id` defined.
[ "Recursively", "construct", "HTML", "nested", "list", "version", "of", "book", "tree", ".", "The", "original", "caller", "should", "not", "call", "this", "function", "with", "the", "parent_id", "defined", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L168-L195
openstax/cnx-archive
cnxarchive/views/content.py
get_export_allowable_types
def get_export_allowable_types(cursor, exports_dirs, id, version): """Return export types.""" request = get_current_request() type_settings = request.registry.settings['_type_info'] type_names = [k for k, v in type_settings] type_infos = [v for k, v in type_settings] # We took the type_names dir...
python
def get_export_allowable_types(cursor, exports_dirs, id, version): """Return export types.""" request = get_current_request() type_settings = request.registry.settings['_type_info'] type_names = [k for k, v in type_settings] type_infos = [v for k, v in type_settings] # We took the type_names dir...
[ "def", "get_export_allowable_types", "(", "cursor", ",", "exports_dirs", ",", "id", ",", "version", ")", ":", "request", "=", "get_current_request", "(", ")", "type_settings", "=", "request", ".", "registry", ".", "settings", "[", "'_type_info'", "]", "type_name...
Return export types.
[ "Return", "export", "types", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L222-L247
openstax/cnx-archive
cnxarchive/views/content.py
get_book_info
def get_book_info(cursor, real_dict_cursor, book_id, book_version, page_id, page_version): """Return information about a given book. Return the book's title, id, shortId, authors and revised date. Raise HTTPNotFound if the page is not in the book. """ book_ident_hash = join_ident_...
python
def get_book_info(cursor, real_dict_cursor, book_id, book_version, page_id, page_version): """Return information about a given book. Return the book's title, id, shortId, authors and revised date. Raise HTTPNotFound if the page is not in the book. """ book_ident_hash = join_ident_...
[ "def", "get_book_info", "(", "cursor", ",", "real_dict_cursor", ",", "book_id", ",", "book_version", ",", "page_id", ",", "page_version", ")", ":", "book_ident_hash", "=", "join_ident_hash", "(", "book_id", ",", "book_version", ")", "page_ident_hash", "=", "join_i...
Return information about a given book. Return the book's title, id, shortId, authors and revised date. Raise HTTPNotFound if the page is not in the book.
[ "Return", "information", "about", "a", "given", "book", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L251-L286
openstax/cnx-archive
cnxarchive/views/content.py
get_portal_type
def get_portal_type(cursor, id, version): """Return the module's portal_type.""" args = join_ident_hash(id, version) sql_statement = """ SELECT m.portal_type FROM modules as m WHERE ident_hash(uuid, major_version, minor_version) = %s """ cursor.execute(sql_statement, vars=(args,)) r...
python
def get_portal_type(cursor, id, version): """Return the module's portal_type.""" args = join_ident_hash(id, version) sql_statement = """ SELECT m.portal_type FROM modules as m WHERE ident_hash(uuid, major_version, minor_version) = %s """ cursor.execute(sql_statement, vars=(args,)) r...
[ "def", "get_portal_type", "(", "cursor", ",", "id", ",", "version", ")", ":", "args", "=", "join_ident_hash", "(", "id", ",", "version", ")", "sql_statement", "=", "\"\"\"\n SELECT m.portal_type\n FROM modules as m\n WHERE ident_hash(uuid, major_version, minor_versio...
Return the module's portal_type.
[ "Return", "the", "module", "s", "portal_type", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L290-L304
openstax/cnx-archive
cnxarchive/views/content.py
get_books_containing_page
def get_books_containing_page(cursor, uuid, version, context_uuid=None, context_version=None): """Return a list of book names and UUIDs that contain a given module UUID.""" with db_connect() as db_connection: # Uses a RealDictCursor instead of the regular cursor ...
python
def get_books_containing_page(cursor, uuid, version, context_uuid=None, context_version=None): """Return a list of book names and UUIDs that contain a given module UUID.""" with db_connect() as db_connection: # Uses a RealDictCursor instead of the regular cursor ...
[ "def", "get_books_containing_page", "(", "cursor", ",", "uuid", ",", "version", ",", "context_uuid", "=", "None", ",", "context_version", "=", "None", ")", ":", "with", "db_connect", "(", ")", "as", "db_connection", ":", "# Uses a RealDictCursor instead of the regul...
Return a list of book names and UUIDs that contain a given module UUID.
[ "Return", "a", "list", "of", "book", "names", "and", "UUIDs", "that", "contain", "a", "given", "module", "UUID", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L307-L330
openstax/cnx-archive
cnxarchive/views/content.py
get_canonical_url
def get_canonical_url(metadata, request): """Builds canonical in book url from a pages metadata.""" slug_title = u'/{}'.format('-'.join(metadata['title'].split())) settings = get_current_registry().settings canon_host = settings.get('canonical-hostname', re.sub('archive.',...
python
def get_canonical_url(metadata, request): """Builds canonical in book url from a pages metadata.""" slug_title = u'/{}'.format('-'.join(metadata['title'].split())) settings = get_current_registry().settings canon_host = settings.get('canonical-hostname', re.sub('archive.',...
[ "def", "get_canonical_url", "(", "metadata", ",", "request", ")", ":", "slug_title", "=", "u'/{}'", ".", "format", "(", "'-'", ".", "join", "(", "metadata", "[", "'title'", "]", ".", "split", "(", ")", ")", ")", "settings", "=", "get_current_registry", "...
Builds canonical in book url from a pages metadata.
[ "Builds", "canonical", "in", "book", "url", "from", "a", "pages", "metadata", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L333-L353
openstax/cnx-archive
cnxarchive/views/content.py
get_content
def get_content(request): """Retrieve content using the ident-hash (uuid@version). Depending on extension or HTTP_ACCEPT header return HTML or JSON. """ ext = request.matchdict.get('ext') accept = request.headers.get('ACCEPT', '') if not ext: if ('application/xhtml+xml' in accept): ...
python
def get_content(request): """Retrieve content using the ident-hash (uuid@version). Depending on extension or HTTP_ACCEPT header return HTML or JSON. """ ext = request.matchdict.get('ext') accept = request.headers.get('ACCEPT', '') if not ext: if ('application/xhtml+xml' in accept): ...
[ "def", "get_content", "(", "request", ")", ":", "ext", "=", "request", ".", "matchdict", ".", "get", "(", "'ext'", ")", "accept", "=", "request", ".", "headers", ".", "get", "(", "'ACCEPT'", ",", "''", ")", "if", "not", "ext", ":", "if", "(", "'app...
Retrieve content using the ident-hash (uuid@version). Depending on extension or HTTP_ACCEPT header return HTML or JSON.
[ "Retrieve", "content", "using", "the", "ident", "-", "hash", "(", "uuid@version", ")", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L362-L395
openstax/cnx-archive
cnxarchive/views/content.py
get_extra
def get_extra(request): """Return information about a module / collection that cannot be cached.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict if args['page_ident_hash']: context_id, context_version = split_ident...
python
def get_extra(request): """Return information about a module / collection that cannot be cached.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict if args['page_ident_hash']: context_id, context_version = split_ident...
[ "def", "get_extra", "(", "request", ")", ":", "settings", "=", "get_current_registry", "(", ")", ".", "settings", "exports_dirs", "=", "settings", "[", "'exports-directories'", "]", ".", "split", "(", ")", "args", "=", "request", ".", "matchdict", "if", "arg...
Return information about a module / collection that cannot be cached.
[ "Return", "information", "about", "a", "module", "/", "collection", "that", "cannot", "be", "cached", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/content.py#L400-L439
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
map_indices_child2parent
def map_indices_child2parent(child, child_indices): """Map child RTDCBase event indices to parent RTDCBase Parameters ---------- child: RTDC_Hierarchy hierarchy child with `child_indices` child_indices: 1d ndarray child indices to map Returns ------- parent_indices: 1d ...
python
def map_indices_child2parent(child, child_indices): """Map child RTDCBase event indices to parent RTDCBase Parameters ---------- child: RTDC_Hierarchy hierarchy child with `child_indices` child_indices: 1d ndarray child indices to map Returns ------- parent_indices: 1d ...
[ "def", "map_indices_child2parent", "(", "child", ",", "child_indices", ")", ":", "parent", "=", "child", ".", "hparent", "# filters", "pf", "=", "parent", ".", "filter", ".", "all", "# indices corresponding to all child events", "idx", "=", "np", ".", "where", "...
Map child RTDCBase event indices to parent RTDCBase Parameters ---------- child: RTDC_Hierarchy hierarchy child with `child_indices` child_indices: 1d ndarray child indices to map Returns ------- parent_indices: 1d ndarray hierarchy parent indices
[ "Map", "child", "RTDCBase", "event", "indices", "to", "parent", "RTDCBase" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L310-L332
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
map_indices_child2root
def map_indices_child2root(child, child_indices): """Map RTDC_Hierarchy event indices to root RTDCBase Parameters ---------- child: RTDC_Hierarchy RTDCBase hierarchy child child_indices: 1d ndarray child indices to map Returns ------- root_indices: 1d ndarray hi...
python
def map_indices_child2root(child, child_indices): """Map RTDC_Hierarchy event indices to root RTDCBase Parameters ---------- child: RTDC_Hierarchy RTDCBase hierarchy child child_indices: 1d ndarray child indices to map Returns ------- root_indices: 1d ndarray hi...
[ "def", "map_indices_child2root", "(", "child", ",", "child_indices", ")", ":", "while", "True", ":", "indices", "=", "map_indices_child2parent", "(", "child", "=", "child", ",", "child_indices", "=", "child_indices", ")", "if", "isinstance", "(", "child", ".", ...
Map RTDC_Hierarchy event indices to root RTDCBase Parameters ---------- child: RTDC_Hierarchy RTDCBase hierarchy child child_indices: 1d ndarray child indices to map Returns ------- root_indices: 1d ndarray hierarchy root indices (not necessarily the indices...
[ "Map", "RTDC_Hierarchy", "event", "indices", "to", "root", "RTDCBase" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L335-L359
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
map_indices_parent2child
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
python
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
[ "def", "map_indices_parent2child", "(", "child", ",", "parent_indices", ")", ":", "parent", "=", "child", ".", "hparent", "# filters", "pf", "=", "parent", ".", "filter", ".", "all", "# indices in child", "child_indices", "=", "[", "]", "count", "=", "0", "f...
Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_indices: 1d ndarray child indices
[ "Map", "parent", "RTDCBase", "event", "indices", "to", "RTDC_Hierarchy" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L362-L392
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
map_indices_root2child
def map_indices_root2child(child, root_indices): """Map root RTDCBase event indices to child RTDCBase Parameters ---------- parent: RTDCBase hierarchy parent of `child`. root_indices: 1d ndarray hierarchy root indices to map (not necessarily the indices of `parent`) Ret...
python
def map_indices_root2child(child, root_indices): """Map root RTDCBase event indices to child RTDCBase Parameters ---------- parent: RTDCBase hierarchy parent of `child`. root_indices: 1d ndarray hierarchy root indices to map (not necessarily the indices of `parent`) Ret...
[ "def", "map_indices_root2child", "(", "child", ",", "root_indices", ")", ":", "# construct hierarchy tree containing only RTDC_Hierarchy instances", "hierarchy", "=", "[", "child", "]", "while", "True", ":", "if", "isinstance", "(", "child", ".", "hparent", ",", "RTDC...
Map root RTDCBase event indices to child RTDCBase Parameters ---------- parent: RTDCBase hierarchy parent of `child`. root_indices: 1d ndarray hierarchy root indices to map (not necessarily the indices of `parent`) Returns ------- child_indices: 1d ndarray c...
[ "Map", "root", "RTDCBase", "event", "indices", "to", "child", "RTDCBase" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L395-L427
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
HierarchyFilter.apply_manual_indices
def apply_manual_indices(self, manual_indices): """Write to `self.manual` Write `manual_indices` to the boolean array `self.manual` and also store the indices as `self._man_root_ids`. Notes ----- If `self.parent_changed` is `True`, i.e. the parent applied a filt...
python
def apply_manual_indices(self, manual_indices): """Write to `self.manual` Write `manual_indices` to the boolean array `self.manual` and also store the indices as `self._man_root_ids`. Notes ----- If `self.parent_changed` is `True`, i.e. the parent applied a filt...
[ "def", "apply_manual_indices", "(", "self", ",", "manual_indices", ")", ":", "if", "self", ".", "parent_changed", ":", "msg", "=", "\"Cannot apply filter, because parent changed: \"", "+", "\"dataset {}. \"", ".", "format", "(", "self", ".", "rtdc_ds", ")", "+", "...
Write to `self.manual` Write `manual_indices` to the boolean array `self.manual` and also store the indices as `self._man_root_ids`. Notes ----- If `self.parent_changed` is `True`, i.e. the parent applied a filter and the child did not yet hear about this, then ...
[ "Write", "to", "self", ".", "manual" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L93-L118
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
HierarchyFilter.retrieve_manual_indices
def retrieve_manual_indices(self): """Read from self.manual Read from the boolean array `self.manual`, index all occurences of `False` and find the corresponding indices in the root hierarchy parent, return those and store them in `self._man_root_ids` as well. Notes ...
python
def retrieve_manual_indices(self): """Read from self.manual Read from the boolean array `self.manual`, index all occurences of `False` and find the corresponding indices in the root hierarchy parent, return those and store them in `self._man_root_ids` as well. Notes ...
[ "def", "retrieve_manual_indices", "(", "self", ")", ":", "if", "self", ".", "parent_changed", ":", "# ignore", "pass", "else", ":", "# indices from boolean array", "pbool", "=", "map_indices_child2root", "(", "child", "=", "self", ".", "rtdc_ds", ",", "child_indic...
Read from self.manual Read from the boolean array `self.manual`, index all occurences of `False` and find the corresponding indices in the root hierarchy parent, return those and store them in `self._man_root_ids` as well. Notes ----- This method also retrieves ...
[ "Read", "from", "self", ".", "manual" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L120-L175
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
RTDC_Hierarchy.apply_filter
def apply_filter(self, *args, **kwargs): """Overridden `apply_filter` to perform tasks for hierarchy child""" if self.filter is not None: # make sure self.filter knows about root manual indices self.filter.retrieve_manual_indices() # Copy event data from hierarchy parent...
python
def apply_filter(self, *args, **kwargs): """Overridden `apply_filter` to perform tasks for hierarchy child""" if self.filter is not None: # make sure self.filter knows about root manual indices self.filter.retrieve_manual_indices() # Copy event data from hierarchy parent...
[ "def", "apply_filter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "filter", "is", "not", "None", ":", "# make sure self.filter knows about root manual indices", "self", ".", "filter", ".", "retrieve_manual_indices", "(",...
Overridden `apply_filter` to perform tasks for hierarchy child
[ "Overridden", "apply_filter", "to", "perform", "tasks", "for", "hierarchy", "child" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L269-L298
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
RTDC_Hierarchy.hash
def hash(self): """Hashes of a hierarchy child changes if the parent changes""" # Do not apply filters here (speed) hph = self.hparent.hash hpfilt = hashobj(self.hparent._filter) dhash = hashobj(hph + hpfilt) return dhash
python
def hash(self): """Hashes of a hierarchy child changes if the parent changes""" # Do not apply filters here (speed) hph = self.hparent.hash hpfilt = hashobj(self.hparent._filter) dhash = hashobj(hph + hpfilt) return dhash
[ "def", "hash", "(", "self", ")", ":", "# Do not apply filters here (speed)", "hph", "=", "self", ".", "hparent", ".", "hash", "hpfilt", "=", "hashobj", "(", "self", ".", "hparent", ".", "_filter", ")", "dhash", "=", "hashobj", "(", "hph", "+", "hpfilt", ...
Hashes of a hierarchy child changes if the parent changes
[ "Hashes", "of", "a", "hierarchy", "child", "changes", "if", "the", "parent", "changes" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L301-L307
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_tdms/event_image.py
ImageColumn.find_video_file
def find_video_file(rtdc_dataset): """Tries to find a video file that belongs to an RTDC dataset Returns None if no video file is found. """ video = None if rtdc_dataset._fdir.exists(): # Cell images (video) videos = [v.name for v in rtdc_dataset._fdir.rg...
python
def find_video_file(rtdc_dataset): """Tries to find a video file that belongs to an RTDC dataset Returns None if no video file is found. """ video = None if rtdc_dataset._fdir.exists(): # Cell images (video) videos = [v.name for v in rtdc_dataset._fdir.rg...
[ "def", "find_video_file", "(", "rtdc_dataset", ")", ":", "video", "=", "None", "if", "rtdc_dataset", ".", "_fdir", ".", "exists", "(", ")", ":", "# Cell images (video)", "videos", "=", "[", "v", ".", "name", "for", "v", "in", "rtdc_dataset", ".", "_fdir", ...
Tries to find a video file that belongs to an RTDC dataset Returns None if no video file is found.
[ "Tries", "to", "find", "a", "video", "file", "that", "belongs", "to", "an", "RTDC", "dataset" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_image.py#L66-L95
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_tdms/event_image.py
ImageMap._get_image_workaround_seek
def _get_image_workaround_seek(self, idx): """Same as __getitem__ but seek through the video beforehand This is a workaround for an all-zero image returned by `imageio`. """ warnings.warn("imageio workaround used!") cap = self.video_handle mult = 50 for ii in ran...
python
def _get_image_workaround_seek(self, idx): """Same as __getitem__ but seek through the video beforehand This is a workaround for an all-zero image returned by `imageio`. """ warnings.warn("imageio workaround used!") cap = self.video_handle mult = 50 for ii in ran...
[ "def", "_get_image_workaround_seek", "(", "self", ",", "idx", ")", ":", "warnings", ".", "warn", "(", "\"imageio workaround used!\"", ")", "cap", "=", "self", ".", "video_handle", "mult", "=", "50", "for", "ii", "in", "range", "(", "idx", "//", "mult", ")"...
Same as __getitem__ but seek through the video beforehand This is a workaround for an all-zero image returned by `imageio`.
[ "Same", "as", "__getitem__", "but", "seek", "through", "the", "video", "beforehand" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_image.py#L146-L157
mhostetter/nhl
nhl/list.py
List.select
def select(self, attr, default=None): """ Select a given attribute (or chain or attributes) from the objects within the list. Args: attr (str): attributes to be selected (with initial `.` omitted) default (any): value to return if given element in list doesn't co...
python
def select(self, attr, default=None): """ Select a given attribute (or chain or attributes) from the objects within the list. Args: attr (str): attributes to be selected (with initial `.` omitted) default (any): value to return if given element in list doesn't co...
[ "def", "select", "(", "self", ",", "attr", ",", "default", "=", "None", ")", ":", "return", "List", "(", "[", "_select", "(", "item", ",", "attr", ",", "default", ")", "for", "item", "in", "self", "]", ")" ]
Select a given attribute (or chain or attributes) from the objects within the list. Args: attr (str): attributes to be selected (with initial `.` omitted) default (any): value to return if given element in list doesn't contain desired attribute Returns: ...
[ "Select", "a", "given", "attribute", "(", "or", "chain", "or", "attributes", ")", "from", "the", "objects", "within", "the", "list", "." ]
train
https://github.com/mhostetter/nhl/blob/32c91cc392826e9de728563d57ab527421734ee1/nhl/list.py#L44-L57
mhostetter/nhl
nhl/list.py
List.filter
def filter(self, attr, value, compare="=="): """ Filter list by a comparison of a given attribute (or chain or attributes). Args: attr (str): attributes to be compared (with initial `.` omitted) value (any): value to compare attr against compare (str): compar...
python
def filter(self, attr, value, compare="=="): """ Filter list by a comparison of a given attribute (or chain or attributes). Args: attr (str): attributes to be compared (with initial `.` omitted) value (any): value to compare attr against compare (str): compar...
[ "def", "filter", "(", "self", ",", "attr", ",", "value", ",", "compare", "=", "\"==\"", ")", ":", "return", "List", "(", "[", "item", "for", "item", "in", "self", "if", "_filter", "(", "_select", "(", "item", ",", "attr", ")", ",", "value", ",", ...
Filter list by a comparison of a given attribute (or chain or attributes). Args: attr (str): attributes to be compared (with initial `.` omitted) value (any): value to compare attr against compare (str): comparison type "=": `attr == value` "=...
[ "Filter", "list", "by", "a", "comparison", "of", "a", "given", "attribute", "(", "or", "chain", "or", "attributes", ")", "." ]
train
https://github.com/mhostetter/nhl/blob/32c91cc392826e9de728563d57ab527421734ee1/nhl/list.py#L59-L79
robmcmullen/atrcopy
atrcopy/ataridos.py
AtariDosDiskImage.as_new_format
def as_new_format(self, format="ATR"): """ Create a new disk image in the specified format """ first_data = len(self.header) raw = self.rawdata[first_data:] data = add_atr_header(raw) newraw = SegmentData(data) image = self.__class__(newraw) return image
python
def as_new_format(self, format="ATR"): """ Create a new disk image in the specified format """ first_data = len(self.header) raw = self.rawdata[first_data:] data = add_atr_header(raw) newraw = SegmentData(data) image = self.__class__(newraw) return image
[ "def", "as_new_format", "(", "self", ",", "format", "=", "\"ATR\"", ")", ":", "first_data", "=", "len", "(", "self", ".", "header", ")", "raw", "=", "self", ".", "rawdata", "[", "first_data", ":", "]", "data", "=", "add_atr_header", "(", "raw", ")", ...
Create a new disk image in the specified format
[ "Create", "a", "new", "disk", "image", "in", "the", "specified", "format" ]
train
https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/ataridos.py#L489-L497
simse/pymitv
pymitv/tv.py
TV.set_source
def set_source(self, source): """Selects and saves source.""" route = Navigator(source=self.source).navigate_to_source(source) # Save new source self.source = source return self._send_keystroke(route, wait=True)
python
def set_source(self, source): """Selects and saves source.""" route = Navigator(source=self.source).navigate_to_source(source) # Save new source self.source = source return self._send_keystroke(route, wait=True)
[ "def", "set_source", "(", "self", ",", "source", ")", ":", "route", "=", "Navigator", "(", "source", "=", "self", ".", "source", ")", ".", "navigate_to_source", "(", "source", ")", "# Save new source\r", "self", ".", "source", "=", "source", "return", "sel...
Selects and saves source.
[ "Selects", "and", "saves", "source", "." ]
train
https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/tv.py#L100-L107
openstax/cnx-archive
cnxarchive/__init__.py
find_migrations_directory
def find_migrations_directory(): """Finds and returns the location of the database migrations directory. This function is used from a setuptools entry-point for db-migrator. """ here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, 'sql/migrations')
python
def find_migrations_directory(): """Finds and returns the location of the database migrations directory. This function is used from a setuptools entry-point for db-migrator. """ here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, 'sql/migrations')
[ "def", "find_migrations_directory", "(", ")", ":", "here", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "return", "os", ".", "path", ".", "join", "(", "here", ",", "'sql/migrations'", ")" ]
Finds and returns the location of the database migrations directory. This function is used from a setuptools entry-point for db-migrator.
[ "Finds", "and", "returns", "the", "location", "of", "the", "database", "migrations", "directory", ".", "This", "function", "is", "used", "from", "a", "setuptools", "entry", "-", "point", "for", "db", "-", "migrator", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/__init__.py#L34-L39
openstax/cnx-archive
cnxarchive/__init__.py
declare_api_routes
def declare_api_routes(config): """Declare routes, with a custom pregenerator.""" # The pregenerator makes sure we can generate a path using # request.route_path even if we don't have all the variables. # # For example, instead of having to do this: # request.route_path('resource', hash=hash...
python
def declare_api_routes(config): """Declare routes, with a custom pregenerator.""" # The pregenerator makes sure we can generate a path using # request.route_path even if we don't have all the variables. # # For example, instead of having to do this: # request.route_path('resource', hash=hash...
[ "def", "declare_api_routes", "(", "config", ")", ":", "# The pregenerator makes sure we can generate a path using", "# request.route_path even if we don't have all the variables.", "#", "# For example, instead of having to do this:", "# request.route_path('resource', hash=hash, ignore='')", ...
Declare routes, with a custom pregenerator.
[ "Declare", "routes", "with", "a", "custom", "pregenerator", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/__init__.py#L42-L82
openstax/cnx-archive
cnxarchive/__init__.py
declare_type_info
def declare_type_info(config): """Lookup type info from app configuration.""" settings = config.registry.settings settings['_type_info'] = [] for line in settings['exports-allowable-types'].splitlines(): if not line.strip(): continue type_name, type_info = line.strip().split(...
python
def declare_type_info(config): """Lookup type info from app configuration.""" settings = config.registry.settings settings['_type_info'] = [] for line in settings['exports-allowable-types'].splitlines(): if not line.strip(): continue type_name, type_info = line.strip().split(...
[ "def", "declare_type_info", "(", "config", ")", ":", "settings", "=", "config", ".", "registry", ".", "settings", "settings", "[", "'_type_info'", "]", "=", "[", "]", "for", "line", "in", "settings", "[", "'exports-allowable-types'", "]", ".", "splitlines", ...
Lookup type info from app configuration.
[ "Lookup", "type", "info", "from", "app", "configuration", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/__init__.py#L85-L100
openstax/cnx-archive
cnxarchive/__init__.py
main
def main(global_config, **settings): """Main WSGI application factory.""" initialize_sentry_integration() config = Configurator(settings=settings) declare_api_routes(config) declare_type_info(config) # allowing the pyramid templates to render rss and xml config.include('pyramid_jinja2') ...
python
def main(global_config, **settings): """Main WSGI application factory.""" initialize_sentry_integration() config = Configurator(settings=settings) declare_api_routes(config) declare_type_info(config) # allowing the pyramid templates to render rss and xml config.include('pyramid_jinja2') ...
[ "def", "main", "(", "global_config", ",", "*", "*", "settings", ")", ":", "initialize_sentry_integration", "(", ")", "config", "=", "Configurator", "(", "settings", "=", "settings", ")", "declare_api_routes", "(", "config", ")", "declare_type_info", "(", "config...
Main WSGI application factory.
[ "Main", "WSGI", "application", "factory", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/__init__.py#L137-L159
lucasmaystre/choix
choix/lsr.py
_init_lsr
def _init_lsr(n_items, alpha, initial_params): """Initialize the LSR Markov chain and the weights.""" if initial_params is None: weights = np.ones(n_items) else: weights = exp_transform(initial_params) chain = alpha * np.ones((n_items, n_items), dtype=float) return weights, chain
python
def _init_lsr(n_items, alpha, initial_params): """Initialize the LSR Markov chain and the weights.""" if initial_params is None: weights = np.ones(n_items) else: weights = exp_transform(initial_params) chain = alpha * np.ones((n_items, n_items), dtype=float) return weights, chain
[ "def", "_init_lsr", "(", "n_items", ",", "alpha", ",", "initial_params", ")", ":", "if", "initial_params", "is", "None", ":", "weights", "=", "np", ".", "ones", "(", "n_items", ")", "else", ":", "weights", "=", "exp_transform", "(", "initial_params", ")", ...
Initialize the LSR Markov chain and the weights.
[ "Initialize", "the", "LSR", "Markov", "chain", "and", "the", "weights", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L10-L17
lucasmaystre/choix
choix/lsr.py
_ilsr
def _ilsr(fun, params, max_iter, tol): """Iteratively refine LSR estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ converged = NormOfDifferenceTest(tol, order=1) for _ in range(max_iter): params = fu...
python
def _ilsr(fun, params, max_iter, tol): """Iteratively refine LSR estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ converged = NormOfDifferenceTest(tol, order=1) for _ in range(max_iter): params = fu...
[ "def", "_ilsr", "(", "fun", ",", "params", ",", "max_iter", ",", "tol", ")", ":", "converged", "=", "NormOfDifferenceTest", "(", "tol", ",", "order", "=", "1", ")", "for", "_", "in", "range", "(", "max_iter", ")", ":", "params", "=", "fun", "(", "i...
Iteratively refine LSR estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations.
[ "Iteratively", "refine", "LSR", "estimates", "until", "convergence", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L20-L33
lucasmaystre/choix
choix/lsr.py
lsr_pairwise
def lsr_pairwise(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for pairwise-comparison data (see :ref:`data-pairwise`). The argument ``initial_params`` can be used to itera...
python
def lsr_pairwise(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for pairwise-comparison data (see :ref:`data-pairwise`). The argument ``initial_params`` can be used to itera...
[ "def", "lsr_pairwise", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ")", ":", "weights", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "initial_params", ")", "for", "winner", ",", "loser"...
Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for pairwise-comparison data (see :ref:`data-pairwise`). The argument ``initial_params`` can be used to iteratively refine an existing parameter estimate (see the implementation...
[ "Compute", "the", "LSR", "estimate", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L36-L71
lucasmaystre/choix
choix/lsr.py
ilsr_pairwise
def ilsr_pairwise( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pairwise`), using ...
python
def ilsr_pairwise( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pairwise`), using ...
[ "def", "ilsr_pairwise", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ",", "max_iter", "=", "100", ",", "tol", "=", "1e-8", ")", ":", "fun", "=", "functools", ".", "partial", "(", "lsr_pairwise", ",", "n_ite...
Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pairwise`), using the iterative Luce Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain ...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "I", "-", "LSR", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L74-L109
lucasmaystre/choix
choix/lsr.py
lsr_pairwise_dense
def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters given dense data. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for dense pairwise-comparison data. The data is described by a pairwise-comparison matrix `...
python
def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters given dense data. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for dense pairwise-comparison data. The data is described by a pairwise-comparison matrix `...
[ "def", "lsr_pairwise_dense", "(", "comp_mat", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ")", ":", "n_items", "=", "comp_mat", ".", "shape", "[", "0", "]", "ws", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "ini...
Compute the LSR estimate of model parameters given dense data. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for dense pairwise-comparison data. The data is described by a pairwise-comparison matrix ``comp_mat`` such that ``comp_mat[i,j]`` contains the number of times ...
[ "Compute", "the", "LSR", "estimate", "of", "model", "parameters", "given", "dense", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L112-L154
lucasmaystre/choix
choix/lsr.py
ilsr_pairwise_dense
def ilsr_pairwise_dense( comp_mat, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters given dense data. This function computes the maximum-likelihood (ML) estimate of model parameters given dense pairwise-comparison data. The data is describ...
python
def ilsr_pairwise_dense( comp_mat, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters given dense data. This function computes the maximum-likelihood (ML) estimate of model parameters given dense pairwise-comparison data. The data is describ...
[ "def", "ilsr_pairwise_dense", "(", "comp_mat", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ",", "max_iter", "=", "100", ",", "tol", "=", "1e-8", ")", ":", "fun", "=", "functools", ".", "partial", "(", "lsr_pairwise_dense", ",", "comp_mat"...
Compute the ML estimate of model parameters given dense data. This function computes the maximum-likelihood (ML) estimate of model parameters given dense pairwise-comparison data. The data is described by a pairwise-comparison matrix ``comp_mat`` such that ``comp_mat[i,j]`` contains the number of time...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "given", "dense", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L157-L197
lucasmaystre/choix
choix/lsr.py
rank_centrality
def rank_centrality(n_items, data, alpha=0.0): """Compute the Rank Centrality estimate of model parameters. This function implements Negahban et al.'s Rank Centrality algorithm [NOS12]_. The algorithm is similar to :func:`~choix.ilsr_pairwise`, but considers the *ratio* of wins for each pair (instead o...
python
def rank_centrality(n_items, data, alpha=0.0): """Compute the Rank Centrality estimate of model parameters. This function implements Negahban et al.'s Rank Centrality algorithm [NOS12]_. The algorithm is similar to :func:`~choix.ilsr_pairwise`, but considers the *ratio* of wins for each pair (instead o...
[ "def", "rank_centrality", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ")", ":", "_", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "None", ")", "for", "winner", ",", "loser", "in", "data", ":", "chain", "[", "loser", ...
Compute the Rank Centrality estimate of model parameters. This function implements Negahban et al.'s Rank Centrality algorithm [NOS12]_. The algorithm is similar to :func:`~choix.ilsr_pairwise`, but considers the *ratio* of wins for each pair (instead of the total count). The transition rates of the R...
[ "Compute", "the", "Rank", "Centrality", "estimate", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L200-L233
lucasmaystre/choix
choix/lsr.py
lsr_rankings
def lsr_rankings(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for ranking data (see :ref:`data-rankings`). The argument ``initial_params`` can be used to iteratively refin...
python
def lsr_rankings(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for ranking data (see :ref:`data-rankings`). The argument ``initial_params`` can be used to iteratively refin...
[ "def", "lsr_rankings", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ")", ":", "weights", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "initial_params", ")", "for", "ranking", "in", "data...
Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for ranking data (see :ref:`data-rankings`). The argument ``initial_params`` can be used to iteratively refine an existing parameter estimate (see the implementation of :fun...
[ "Compute", "the", "LSR", "estimate", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L236-L276
lucasmaystre/choix
choix/lsr.py
ilsr_rankings
def ilsr_rankings( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the iterati...
python
def ilsr_rankings( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the iterati...
[ "def", "ilsr_rankings", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ",", "max_iter", "=", "100", ",", "tol", "=", "1e-8", ")", ":", "fun", "=", "functools", ".", "partial", "(", "lsr_rankings", ",", "n_ite...
Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the iterative Luce Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain are initiali...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "I", "-", "LSR", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L279-L314
lucasmaystre/choix
choix/lsr.py
lsr_top1
def lsr_top1(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for top-1 data (see :ref:`data-top1`). The argument ``initial_params`` can be used to iteratively refine an e...
python
def lsr_top1(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for top-1 data (see :ref:`data-top1`). The argument ``initial_params`` can be used to iteratively refine an e...
[ "def", "lsr_top1", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ")", ":", "weights", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "initial_params", ")", "for", "winner", ",", "losers", ...
Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for top-1 data (see :ref:`data-top1`). The argument ``initial_params`` can be used to iteratively refine an existing parameter estimate (see the implementation of :func:`~ch...
[ "Compute", "the", "LSR", "estimate", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L317-L354
lucasmaystre/choix
choix/lsr.py
ilsr_top1
def ilsr_top1( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the iterative Luce Sp...
python
def ilsr_top1( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the iterative Luce Sp...
[ "def", "ilsr_top1", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ",", "max_iter", "=", "100", ",", "tol", "=", "1e-8", ")", ":", "fun", "=", "functools", ".", "partial", "(", "lsr_top1", ",", "n_items", "...
Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the iterative Luce Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain are initialized wi...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "I", "-", "LSR", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/lsr.py#L357-L391
lucasmaystre/choix
choix/ep.py
ep_pairwise
def ep_pairwise(n_items, data, alpha, model="logit", max_iter=100, initial_state=None): """Compute a distribution of model parameters using the EP algorithm. This function computes an approximate Bayesian posterior probability distribution over model parameters, given pairwise-comparison data (see ...
python
def ep_pairwise(n_items, data, alpha, model="logit", max_iter=100, initial_state=None): """Compute a distribution of model parameters using the EP algorithm. This function computes an approximate Bayesian posterior probability distribution over model parameters, given pairwise-comparison data (see ...
[ "def", "ep_pairwise", "(", "n_items", ",", "data", ",", "alpha", ",", "model", "=", "\"logit\"", ",", "max_iter", "=", "100", ",", "initial_state", "=", "None", ")", ":", "if", "model", "==", "\"logit\"", ":", "match_moments", "=", "_match_moments_logit", ...
Compute a distribution of model parameters using the EP algorithm. This function computes an approximate Bayesian posterior probability distribution over model parameters, given pairwise-comparison data (see :ref:`data-pairwise`). It uses the expectation propagation algorithm, as presented, e.g., in [C...
[ "Compute", "a", "distribution", "of", "model", "parameters", "using", "the", "EP", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/ep.py#L32-L83
lucasmaystre/choix
choix/ep.py
_ep_pairwise
def _ep_pairwise( n_items, comparisons, alpha, match_moments, max_iter, initial_state): """Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ # Static variable that a...
python
def _ep_pairwise( n_items, comparisons, alpha, match_moments, max_iter, initial_state): """Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ # Static variable that a...
[ "def", "_ep_pairwise", "(", "n_items", ",", "comparisons", ",", "alpha", ",", "match_moments", ",", "max_iter", ",", "initial_state", ")", ":", "# Static variable that allows to check the # of iterations after the call.", "_ep_pairwise", ".", "iterations", "=", "0", "m", ...
Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations.
[ "Compute", "a", "distribution", "of", "model", "parameters", "using", "the", "EP", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/ep.py#L86-L154
lucasmaystre/choix
choix/ep.py
_log_phi
def _log_phi(z): """Stable computation of the log of the Normal CDF and its derivative.""" # Adapted from the GPML function `logphi.m`. if z * z < 0.0492: # First case: z close to zero. coef = -z / SQRT2PI val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0) res = -...
python
def _log_phi(z): """Stable computation of the log of the Normal CDF and its derivative.""" # Adapted from the GPML function `logphi.m`. if z * z < 0.0492: # First case: z close to zero. coef = -z / SQRT2PI val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0) res = -...
[ "def", "_log_phi", "(", "z", ")", ":", "# Adapted from the GPML function `logphi.m`.", "if", "z", "*", "z", "<", "0.0492", ":", "# First case: z close to zero.", "coef", "=", "-", "z", "/", "SQRT2PI", "val", "=", "functools", ".", "reduce", "(", "lambda", "acc...
Stable computation of the log of the Normal CDF and its derivative.
[ "Stable", "computation", "of", "the", "log", "of", "the", "Normal", "CDF", "and", "its", "derivative", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/ep.py#L157-L176
lucasmaystre/choix
choix/ep.py
_init_ws
def _init_ws(n_items, comparisons, prior_inv, tau, nu): """Initialize parameters in the weight space.""" prec = np.zeros((n_items, n_items)) xs = np.zeros(n_items) for i, (a, b) in enumerate(comparisons): prec[(a, a, b, b), (a, b, a, b)] += tau[i] * MAT_ONE_FLAT xs[a] += nu[i] x...
python
def _init_ws(n_items, comparisons, prior_inv, tau, nu): """Initialize parameters in the weight space.""" prec = np.zeros((n_items, n_items)) xs = np.zeros(n_items) for i, (a, b) in enumerate(comparisons): prec[(a, a, b, b), (a, b, a, b)] += tau[i] * MAT_ONE_FLAT xs[a] += nu[i] x...
[ "def", "_init_ws", "(", "n_items", ",", "comparisons", ",", "prior_inv", ",", "tau", ",", "nu", ")", ":", "prec", "=", "np", ".", "zeros", "(", "(", "n_items", ",", "n_items", ")", ")", "xs", "=", "np", ".", "zeros", "(", "n_items", ")", "for", "...
Initialize parameters in the weight space.
[ "Initialize", "parameters", "in", "the", "weight", "space", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/ep.py#L227-L237
lucasmaystre/choix
choix/utils.py
exp_transform
def exp_transform(params): """Transform parameters into exp-scale weights.""" weights = np.exp(np.asarray(params) - np.mean(params)) return (len(weights) / weights.sum()) * weights
python
def exp_transform(params): """Transform parameters into exp-scale weights.""" weights = np.exp(np.asarray(params) - np.mean(params)) return (len(weights) / weights.sum()) * weights
[ "def", "exp_transform", "(", "params", ")", ":", "weights", "=", "np", ".", "exp", "(", "np", ".", "asarray", "(", "params", ")", "-", "np", ".", "mean", "(", "params", ")", ")", "return", "(", "len", "(", "weights", ")", "/", "weights", ".", "su...
Transform parameters into exp-scale weights.
[ "Transform", "parameters", "into", "exp", "-", "scale", "weights", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L22-L25
lucasmaystre/choix
choix/utils.py
softmax
def softmax(xs): """Stable implementation of the softmax function.""" ys = xs - np.max(xs) exps = np.exp(ys) return exps / exps.sum(axis=0)
python
def softmax(xs): """Stable implementation of the softmax function.""" ys = xs - np.max(xs) exps = np.exp(ys) return exps / exps.sum(axis=0)
[ "def", "softmax", "(", "xs", ")", ":", "ys", "=", "xs", "-", "np", ".", "max", "(", "xs", ")", "exps", "=", "np", ".", "exp", "(", "ys", ")", "return", "exps", "/", "exps", ".", "sum", "(", "axis", "=", "0", ")" ]
Stable implementation of the softmax function.
[ "Stable", "implementation", "of", "the", "softmax", "function", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L28-L32
lucasmaystre/choix
choix/utils.py
inv_posdef
def inv_posdef(mat): """Stable inverse of a positive definite matrix.""" # See: # - http://www.seas.ucla.edu/~vandenbe/103/lectures/chol.pdf # - http://scicomp.stackexchange.com/questions/3188 chol = np.linalg.cholesky(mat) ident = np.eye(mat.shape[0]) res = solve_triangular(chol, ident, low...
python
def inv_posdef(mat): """Stable inverse of a positive definite matrix.""" # See: # - http://www.seas.ucla.edu/~vandenbe/103/lectures/chol.pdf # - http://scicomp.stackexchange.com/questions/3188 chol = np.linalg.cholesky(mat) ident = np.eye(mat.shape[0]) res = solve_triangular(chol, ident, low...
[ "def", "inv_posdef", "(", "mat", ")", ":", "# See:", "# - http://www.seas.ucla.edu/~vandenbe/103/lectures/chol.pdf", "# - http://scicomp.stackexchange.com/questions/3188", "chol", "=", "np", ".", "linalg", ".", "cholesky", "(", "mat", ")", "ident", "=", "np", ".", "eye"...
Stable inverse of a positive definite matrix.
[ "Stable", "inverse", "of", "a", "positive", "definite", "matrix", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L46-L54
lucasmaystre/choix
choix/utils.py
footrule_dist
def footrule_dist(params1, params2=None): r"""Compute Spearman's footrule distance between two models. This function computes Spearman's footrule distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :ma...
python
def footrule_dist(params1, params2=None): r"""Compute Spearman's footrule distance between two models. This function computes Spearman's footrule distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :ma...
[ "def", "footrule_dist", "(", "params1", ",", "params2", "=", "None", ")", ":", "assert", "params2", "is", "None", "or", "len", "(", "params1", ")", "==", "len", "(", "params2", ")", "ranks1", "=", "rankdata", "(", "params1", ",", "method", "=", "\"aver...
r"""Compute Spearman's footrule distance between two models. This function computes Spearman's footrule distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :math:`\tau_i` be its rank in the model descr...
[ "r", "Compute", "Spearman", "s", "footrule", "distance", "between", "two", "models", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L57-L95
lucasmaystre/choix
choix/utils.py
kendalltau_dist
def kendalltau_dist(params1, params2=None): r"""Compute the Kendall tau distance between two models. This function computes the Kendall tau distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :math:`\t...
python
def kendalltau_dist(params1, params2=None): r"""Compute the Kendall tau distance between two models. This function computes the Kendall tau distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :math:`\t...
[ "def", "kendalltau_dist", "(", "params1", ",", "params2", "=", "None", ")", ":", "assert", "params2", "is", "None", "or", "len", "(", "params1", ")", "==", "len", "(", "params2", ")", "ranks1", "=", "rankdata", "(", "params1", ",", "method", "=", "\"or...
r"""Compute the Kendall tau distance between two models. This function computes the Kendall tau distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :math:`\tau_i` be its rank in the model described by ...
[ "r", "Compute", "the", "Kendall", "tau", "distance", "between", "two", "models", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L98-L143
lucasmaystre/choix
choix/utils.py
rmse
def rmse(params1, params2): r"""Compute the root-mean-squared error between two models. Parameters ---------- params1 : array_like Parameters of the first model. params2 : array_like Parameters of the second model. Returns ------- error : float Root-mean-squared...
python
def rmse(params1, params2): r"""Compute the root-mean-squared error between two models. Parameters ---------- params1 : array_like Parameters of the first model. params2 : array_like Parameters of the second model. Returns ------- error : float Root-mean-squared...
[ "def", "rmse", "(", "params1", ",", "params2", ")", ":", "assert", "len", "(", "params1", ")", "==", "len", "(", "params2", ")", "params1", "=", "np", ".", "asarray", "(", "params1", ")", "-", "np", ".", "mean", "(", "params1", ")", "params2", "=",...
r"""Compute the root-mean-squared error between two models. Parameters ---------- params1 : array_like Parameters of the first model. params2 : array_like Parameters of the second model. Returns ------- error : float Root-mean-squared error.
[ "r", "Compute", "the", "root", "-", "mean", "-", "squared", "error", "between", "two", "models", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L146-L165
lucasmaystre/choix
choix/utils.py
log_likelihood_pairwise
def log_likelihood_pairwise(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 for winner, loser in data: loglik -= np.logaddexp(0, -(params[winner] - params[loser])) return loglik
python
def log_likelihood_pairwise(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 for winner, loser in data: loglik -= np.logaddexp(0, -(params[winner] - params[loser])) return loglik
[ "def", "log_likelihood_pairwise", "(", "data", ",", "params", ")", ":", "loglik", "=", "0", "for", "winner", ",", "loser", "in", "data", ":", "loglik", "-=", "np", ".", "logaddexp", "(", "0", ",", "-", "(", "params", "[", "winner", "]", "-", "params"...
Compute the log-likelihood of model parameters.
[ "Compute", "the", "log", "-", "likelihood", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L168-L173
lucasmaystre/choix
choix/utils.py
log_likelihood_rankings
def log_likelihood_rankings(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for ranking in data: for i, winner in enumerate(ranking[:-1]): loglik -= logsumexp(params.take(ranking[i:]) - params[winner]) return loglik
python
def log_likelihood_rankings(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for ranking in data: for i, winner in enumerate(ranking[:-1]): loglik -= logsumexp(params.take(ranking[i:]) - params[winner]) return loglik
[ "def", "log_likelihood_rankings", "(", "data", ",", "params", ")", ":", "loglik", "=", "0", "params", "=", "np", ".", "asarray", "(", "params", ")", "for", "ranking", "in", "data", ":", "for", "i", ",", "winner", "in", "enumerate", "(", "ranking", "[",...
Compute the log-likelihood of model parameters.
[ "Compute", "the", "log", "-", "likelihood", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L176-L183
lucasmaystre/choix
choix/utils.py
log_likelihood_top1
def log_likelihood_top1(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for winner, losers in data: idx = np.append(winner, losers) loglik -= logsumexp(params.take(idx) - params[winner]) return loglik
python
def log_likelihood_top1(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for winner, losers in data: idx = np.append(winner, losers) loglik -= logsumexp(params.take(idx) - params[winner]) return loglik
[ "def", "log_likelihood_top1", "(", "data", ",", "params", ")", ":", "loglik", "=", "0", "params", "=", "np", ".", "asarray", "(", "params", ")", "for", "winner", ",", "losers", "in", "data", ":", "idx", "=", "np", ".", "append", "(", "winner", ",", ...
Compute the log-likelihood of model parameters.
[ "Compute", "the", "log", "-", "likelihood", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L186-L193
lucasmaystre/choix
choix/utils.py
log_likelihood_network
def log_likelihood_network( digraph, traffic_in, traffic_out, params, weight=None): """ Compute the log-likelihood of model parameters. If ``weight`` is not ``None``, the log-likelihood is correct only up to a constant (independent of the parameters). """ loglik = 0 for i in range(l...
python
def log_likelihood_network( digraph, traffic_in, traffic_out, params, weight=None): """ Compute the log-likelihood of model parameters. If ``weight`` is not ``None``, the log-likelihood is correct only up to a constant (independent of the parameters). """ loglik = 0 for i in range(l...
[ "def", "log_likelihood_network", "(", "digraph", ",", "traffic_in", ",", "traffic_out", ",", "params", ",", "weight", "=", "None", ")", ":", "loglik", "=", "0", "for", "i", "in", "range", "(", "len", "(", "traffic_in", ")", ")", ":", "loglik", "+=", "t...
Compute the log-likelihood of model parameters. If ``weight`` is not ``None``, the log-likelihood is correct only up to a constant (independent of the parameters).
[ "Compute", "the", "log", "-", "likelihood", "of", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L196-L215
lucasmaystre/choix
choix/utils.py
statdist
def statdist(generator): """Compute the stationary distribution of a Markov chain. Parameters ---------- generator : array_like Infinitesimal generator matrix of the Markov chain. Returns ------- dist : numpy.ndarray The unnormalized stationary distribution of the Markov ch...
python
def statdist(generator): """Compute the stationary distribution of a Markov chain. Parameters ---------- generator : array_like Infinitesimal generator matrix of the Markov chain. Returns ------- dist : numpy.ndarray The unnormalized stationary distribution of the Markov ch...
[ "def", "statdist", "(", "generator", ")", ":", "generator", "=", "np", ".", "asarray", "(", "generator", ")", "n", "=", "generator", ".", "shape", "[", "0", "]", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "# The LU decomposition raises a warni...
Compute the stationary distribution of a Markov chain. Parameters ---------- generator : array_like Infinitesimal generator matrix of the Markov chain. Returns ------- dist : numpy.ndarray The unnormalized stationary distribution of the Markov chain. Raises ------ ...
[ "Compute", "the", "stationary", "distribution", "of", "a", "Markov", "chain", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L218-L257
lucasmaystre/choix
choix/utils.py
generate_params
def generate_params(n_items, interval=5.0, ordered=False): r"""Generate random model parameters. This function samples a parameter independently and uniformly for each item. ``interval`` defines the width of the uniform distribution. Parameters ---------- n_items : int Number of distin...
python
def generate_params(n_items, interval=5.0, ordered=False): r"""Generate random model parameters. This function samples a parameter independently and uniformly for each item. ``interval`` defines the width of the uniform distribution. Parameters ---------- n_items : int Number of distin...
[ "def", "generate_params", "(", "n_items", ",", "interval", "=", "5.0", ",", "ordered", "=", "False", ")", ":", "params", "=", "np", ".", "random", ".", "uniform", "(", "low", "=", "0", ",", "high", "=", "interval", ",", "size", "=", "n_items", ")", ...
r"""Generate random model parameters. This function samples a parameter independently and uniformly for each item. ``interval`` defines the width of the uniform distribution. Parameters ---------- n_items : int Number of distinct items. interval : float Sampling interval. o...
[ "r", "Generate", "random", "model", "parameters", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L260-L283
lucasmaystre/choix
choix/utils.py
generate_pairwise
def generate_pairwise(params, n_comparisons=10): """Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes from a Bradley-...
python
def generate_pairwise(params, n_comparisons=10): """Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes from a Bradley-...
[ "def", "generate_pairwise", "(", "params", ",", "n_comparisons", "=", "10", ")", ":", "n", "=", "len", "(", "params", ")", "items", "=", "tuple", "(", "range", "(", "n", ")", ")", "params", "=", "np", ".", "asarray", "(", "params", ")", "data", "="...
Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes from a Bradley--Terry model parametrized by ``params``. Parame...
[ "Generate", "pairwise", "comparisons", "from", "a", "Bradley", "--", "Terry", "model", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L286-L317
lucasmaystre/choix
choix/utils.py
generate_rankings
def generate_rankings(params, n_rankings, size=3): """Generate rankings according to a Plackett--Luce model. This function samples subsets of items (of size ``size``) independently and uniformly at random, and samples the correspoding partial ranking from a Plackett--Luce model parametrized by ``params...
python
def generate_rankings(params, n_rankings, size=3): """Generate rankings according to a Plackett--Luce model. This function samples subsets of items (of size ``size``) independently and uniformly at random, and samples the correspoding partial ranking from a Plackett--Luce model parametrized by ``params...
[ "def", "generate_rankings", "(", "params", ",", "n_rankings", ",", "size", "=", "3", ")", ":", "n", "=", "len", "(", "params", ")", "items", "=", "tuple", "(", "range", "(", "n", ")", ")", "params", "=", "np", ".", "asarray", "(", "params", ")", ...
Generate rankings according to a Plackett--Luce model. This function samples subsets of items (of size ``size``) independently and uniformly at random, and samples the correspoding partial ranking from a Plackett--Luce model parametrized by ``params``. Parameters ---------- params : array_like...
[ "Generate", "rankings", "according", "to", "a", "Plackett", "--", "Luce", "model", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L320-L351
lucasmaystre/choix
choix/utils.py
compare
def compare(items, params, rank=False): """Generate a comparison outcome that follows Luce's axiom. This function samples an outcome for the comparison of a subset of items, from a model parametrized by ``params``. If ``rank`` is True, it returns a ranking over the items, otherwise it returns a single ...
python
def compare(items, params, rank=False): """Generate a comparison outcome that follows Luce's axiom. This function samples an outcome for the comparison of a subset of items, from a model parametrized by ``params``. If ``rank`` is True, it returns a ranking over the items, otherwise it returns a single ...
[ "def", "compare", "(", "items", ",", "params", ",", "rank", "=", "False", ")", ":", "probs", "=", "probabilities", "(", "items", ",", "params", ")", "if", "rank", ":", "return", "np", ".", "random", ".", "choice", "(", "items", ",", "size", "=", "l...
Generate a comparison outcome that follows Luce's axiom. This function samples an outcome for the comparison of a subset of items, from a model parametrized by ``params``. If ``rank`` is True, it returns a ranking over the items, otherwise it returns a single item. Parameters ---------- items ...
[ "Generate", "a", "comparison", "outcome", "that", "follows", "Luce", "s", "axiom", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L354-L379
lucasmaystre/choix
choix/utils.py
probabilities
def probabilities(items, params): """Compute the comparison outcome probabilities given a subset of items. This function computes, for each item in ``items``, the probability that it would win (i.e., be chosen) in a comparison involving the items, given model parameters. Parameters ---------- ...
python
def probabilities(items, params): """Compute the comparison outcome probabilities given a subset of items. This function computes, for each item in ``items``, the probability that it would win (i.e., be chosen) in a comparison involving the items, given model parameters. Parameters ---------- ...
[ "def", "probabilities", "(", "items", ",", "params", ")", ":", "params", "=", "np", ".", "asarray", "(", "params", ")", "return", "softmax", "(", "params", ".", "take", "(", "items", ")", ")" ]
Compute the comparison outcome probabilities given a subset of items. This function computes, for each item in ``items``, the probability that it would win (i.e., be chosen) in a comparison involving the items, given model parameters. Parameters ---------- items : list Subset of items ...
[ "Compute", "the", "comparison", "outcome", "probabilities", "given", "a", "subset", "of", "items", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L382-L402
lucasmaystre/choix
choix/opt.py
opt_pairwise
def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given pairwise-comparison data (see :ref...
python
def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given pairwise-comparison data (see :ref...
[ "def", "opt_pairwise", "(", "n_items", ",", "data", ",", "alpha", "=", "1e-6", ",", "method", "=", "\"Newton-CG\"", ",", "initial_params", "=", "None", ",", "max_iter", "=", "None", ",", "tol", "=", "1e-5", ")", ":", "fcts", "=", "PairwiseFcts", "(", "...
Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given pairwise-comparison data (see :ref:`data-pairwise`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "scipy", ".", "optimize", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L126-L166
lucasmaystre/choix
choix/opt.py
opt_rankings
def opt_rankings(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given ranking data (see :ref:`data-ranki...
python
def opt_rankings(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given ranking data (see :ref:`data-ranki...
[ "def", "opt_rankings", "(", "n_items", ",", "data", ",", "alpha", "=", "1e-6", ",", "method", "=", "\"Newton-CG\"", ",", "initial_params", "=", "None", ",", "max_iter", "=", "None", ",", "tol", "=", "1e-5", ")", ":", "fcts", "=", "Top1Fcts", ".", "from...
Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given ranking data (see :ref:`data-rankings`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns the maximum...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "scipy", ".", "optimize", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L169-L209
lucasmaystre/choix
choix/opt.py
opt_top1
def opt_top1(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given top-1 data (see :ref:`data-top1`), usi...
python
def opt_top1(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given top-1 data (see :ref:`data-top1`), usi...
[ "def", "opt_top1", "(", "n_items", ",", "data", ",", "alpha", "=", "1e-6", ",", "method", "=", "\"Newton-CG\"", ",", "initial_params", "=", "None", ",", "max_iter", "=", "None", ",", "tol", "=", "1e-5", ")", ":", "fcts", "=", "Top1Fcts", "(", "data", ...
Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given top-1 data (see :ref:`data-top1`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns the maximum a-pos...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "scipy", ".", "optimize", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L212-L252
lucasmaystre/choix
choix/opt.py
PairwiseFcts.objective
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for win, los in self._data: val += np.logaddexp(0, -(params[win] - params[los])) return val
python
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for win, los in self._data: val += np.logaddexp(0, -(params[win] - params[los])) return val
[ "def", "objective", "(", "self", ",", "params", ")", ":", "val", "=", "self", ".", "_penalty", "*", "np", ".", "sum", "(", "params", "**", "2", ")", "for", "win", ",", "los", "in", "self", ".", "_data", ":", "val", "+=", "np", ".", "logaddexp", ...
Compute the negative penalized log-likelihood.
[ "Compute", "the", "negative", "penalized", "log", "-", "likelihood", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L28-L33
lucasmaystre/choix
choix/opt.py
Top1Fcts.from_rankings
def from_rankings(cls, data, penalty): """Alternative constructor for ranking data.""" top1 = list() for ranking in data: for i, winner in enumerate(ranking[:-1]): top1.append((winner, ranking[i+1:])) return cls(top1, penalty)
python
def from_rankings(cls, data, penalty): """Alternative constructor for ranking data.""" top1 = list() for ranking in data: for i, winner in enumerate(ranking[:-1]): top1.append((winner, ranking[i+1:])) return cls(top1, penalty)
[ "def", "from_rankings", "(", "cls", ",", "data", ",", "penalty", ")", ":", "top1", "=", "list", "(", ")", "for", "ranking", "in", "data", ":", "for", "i", ",", "winner", "in", "enumerate", "(", "ranking", "[", ":", "-", "1", "]", ")", ":", "top1"...
Alternative constructor for ranking data.
[ "Alternative", "constructor", "for", "ranking", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L69-L75
lucasmaystre/choix
choix/opt.py
Top1Fcts.objective
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for winner, losers in self._data: idx = np.append(winner, losers) val += logsumexp(params.take(idx) - params[winner]) return val
python
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for winner, losers in self._data: idx = np.append(winner, losers) val += logsumexp(params.take(idx) - params[winner]) return val
[ "def", "objective", "(", "self", ",", "params", ")", ":", "val", "=", "self", ".", "_penalty", "*", "np", ".", "sum", "(", "params", "**", "2", ")", "for", "winner", ",", "losers", "in", "self", ".", "_data", ":", "idx", "=", "np", ".", "append",...
Compute the negative penalized log-likelihood.
[ "Compute", "the", "negative", "penalized", "log", "-", "likelihood", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/opt.py#L77-L83
lucasmaystre/choix
choix/mm.py
_mm
def _mm(n_items, data, initial_params, alpha, max_iter, tol, mm_fun): """ Iteratively refine MM estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after `max_iter` iterations. """ if initial_params is None: params = np.zeros(n_items) ...
python
def _mm(n_items, data, initial_params, alpha, max_iter, tol, mm_fun): """ Iteratively refine MM estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after `max_iter` iterations. """ if initial_params is None: params = np.zeros(n_items) ...
[ "def", "_mm", "(", "n_items", ",", "data", ",", "initial_params", ",", "alpha", ",", "max_iter", ",", "tol", ",", "mm_fun", ")", ":", "if", "initial_params", "is", "None", ":", "params", "=", "np", ".", "zeros", "(", "n_items", ")", "else", ":", "par...
Iteratively refine MM estimates until convergence. Raises ------ RuntimeError If the algorithm does not converge after `max_iter` iterations.
[ "Iteratively", "refine", "MM", "estimates", "until", "convergence", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L10-L29
lucasmaystre/choix
choix/mm.py
_mm_pairwise
def _mm_pairwise(n_items, data, params): """Inner loop of MM algorithm for pairwise data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for winner, loser in data: wins[winner] += 1.0 val = 1.0 / (weights[winner] + wei...
python
def _mm_pairwise(n_items, data, params): """Inner loop of MM algorithm for pairwise data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for winner, loser in data: wins[winner] += 1.0 val = 1.0 / (weights[winner] + wei...
[ "def", "_mm_pairwise", "(", "n_items", ",", "data", ",", "params", ")", ":", "weights", "=", "exp_transform", "(", "params", ")", "wins", "=", "np", ".", "zeros", "(", "n_items", ",", "dtype", "=", "float", ")", "denoms", "=", "np", ".", "zeros", "("...
Inner loop of MM algorithm for pairwise data.
[ "Inner", "loop", "of", "MM", "algorithm", "for", "pairwise", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L32-L42
lucasmaystre/choix
choix/mm.py
mm_pairwise
def mm_pairwise( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pa...
python
def mm_pairwise( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pa...
[ "def", "mm_pairwise", "(", "n_items", ",", "data", ",", "initial_params", "=", "None", ",", "alpha", "=", "0.0", ",", "max_iter", "=", "10000", ",", "tol", "=", "1e-8", ")", ":", "return", "_mm", "(", "n_items", ",", "data", ",", "initial_params", ",",...
Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given pairwise-comparison data (see :ref:`data-pairwise`), using the minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the fun...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "the", "MM", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L45-L80
lucasmaystre/choix
choix/mm.py
_mm_rankings
def _mm_rankings(n_items, data, params): """Inner loop of MM algorithm for ranking data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for ranking in data: sum_ = weights.take(ranking).sum() for i, winner in enumerate...
python
def _mm_rankings(n_items, data, params): """Inner loop of MM algorithm for ranking data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for ranking in data: sum_ = weights.take(ranking).sum() for i, winner in enumerate...
[ "def", "_mm_rankings", "(", "n_items", ",", "data", ",", "params", ")", ":", "weights", "=", "exp_transform", "(", "params", ")", "wins", "=", "np", ".", "zeros", "(", "n_items", ",", "dtype", "=", "float", ")", "denoms", "=", "np", ".", "zeros", "("...
Inner loop of MM algorithm for ranking data.
[ "Inner", "loop", "of", "MM", "algorithm", "for", "ranking", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L83-L96
lucasmaystre/choix
choix/mm.py
mm_rankings
def mm_rankings(n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the ...
python
def mm_rankings(n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the ...
[ "def", "mm_rankings", "(", "n_items", ",", "data", ",", "initial_params", "=", "None", ",", "alpha", "=", "0.0", ",", "max_iter", "=", "10000", ",", "tol", "=", "1e-8", ")", ":", "return", "_mm", "(", "n_items", ",", "data", ",", "initial_params", ",",...
Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the function return...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "the", "MM", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L99-L133
lucasmaystre/choix
choix/mm.py
_mm_top1
def _mm_top1(n_items, data, params): """Inner loop of MM algorithm for top1 data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for winner, losers in data: wins[winner] += 1 val = 1 / (weights.take(losers).sum() + wei...
python
def _mm_top1(n_items, data, params): """Inner loop of MM algorithm for top1 data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for winner, losers in data: wins[winner] += 1 val = 1 / (weights.take(losers).sum() + wei...
[ "def", "_mm_top1", "(", "n_items", ",", "data", ",", "params", ")", ":", "weights", "=", "exp_transform", "(", "params", ")", "wins", "=", "np", ".", "zeros", "(", "n_items", ",", "dtype", "=", "float", ")", "denoms", "=", "np", ".", "zeros", "(", ...
Inner loop of MM algorithm for top1 data.
[ "Inner", "loop", "of", "MM", "algorithm", "for", "top1", "data", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L136-L146
lucasmaystre/choix
choix/mm.py
mm_top1
def mm_top1( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the ...
python
def mm_top1( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the ...
[ "def", "mm_top1", "(", "n_items", ",", "data", ",", "initial_params", "=", "None", ",", "alpha", "=", "0.0", ",", "max_iter", "=", "10000", ",", "tol", "=", "1e-8", ")", ":", "return", "_mm", "(", "n_items", ",", "data", ",", "initial_params", ",", "...
Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the function returns the ...
[ "Compute", "the", "ML", "estimate", "of", "model", "parameters", "using", "the", "MM", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L149-L183
lucasmaystre/choix
choix/mm.py
_choicerank
def _choicerank(n_items, data, params): """Inner loop of ChoiceRank algorithm.""" weights = exp_transform(params) adj, adj_t, traffic_in, traffic_out = data # First phase of message passing. zs = adj.dot(weights) # Second phase of message passing. with np.errstate(invalid="ignore"): ...
python
def _choicerank(n_items, data, params): """Inner loop of ChoiceRank algorithm.""" weights = exp_transform(params) adj, adj_t, traffic_in, traffic_out = data # First phase of message passing. zs = adj.dot(weights) # Second phase of message passing. with np.errstate(invalid="ignore"): ...
[ "def", "_choicerank", "(", "n_items", ",", "data", ",", "params", ")", ":", "weights", "=", "exp_transform", "(", "params", ")", "adj", ",", "adj_t", ",", "traffic_in", ",", "traffic_out", "=", "data", "# First phase of message passing.", "zs", "=", "adj", "...
Inner loop of ChoiceRank algorithm.
[ "Inner", "loop", "of", "ChoiceRank", "algorithm", "." ]
train
https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/mm.py#L186-L195