code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
mdict["comment ranges"] = [list(a) for a in self.get_style_ranges(comment=True)] mdict["data ranges"] = [list(a) for a in self.get_style_ranges(data=True)] for i in range(1, user_bit_mask): r = [list(a) for a in self.get_style_ranges(user=i)] if r: ...
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 main json so that it can be more easil...
4.810031
4.943283
0.973044
r = self.rawdata try: index = r.get_reverse_index(base_index) except IndexError: raise IndexError("index %d not in this segment" % base_index) if index < 0: raise IndexError("index %d not in this segment" % base_index) return int(index...
def get_index_from_base_index(self, base_index)
Get index into this array's data given the index into the base array
3.508885
3.405642
1.030315
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)
Return a list of start, end pairs that match the specified style
5.462262
5.05041
1.081548
style_base = self.rawdata.style_base comment_text_indexes = np.asarray(list(self.rawdata.extra.comments.keys()), dtype=np.uint32) comment_mask = self.get_style_mask(comment=True) has_comments = np.where(style_base & comment_bit_mask > 0)[0] both = np.intersect1d(comment_...
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 data.
4.239803
3.888356
1.090385
style_bits = self.get_style_bits(**kwargs) matches = self.get_comment_locations(**kwargs) groups = np.split(matches, np.where(np.diff(matches) != 0)[0] + 1) if split_comments is None: split_comments = [] # print groups # split into groups with the sam...
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 ignored when splitting. The returned list covers the entire length of ...
2.522499
2.482054
1.016295
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]) try: comment = self.rawdata.extra.comments[raw] except K...
def get_comments_at_indexes(self, indexes)
Get a list of comments at specified indexes
4.935488
4.936781
0.999738
restore_data = [] for start, end in ranges: log.debug("range: %d-%d" % (start, end)) styles = self.style[start:end].copy() items = {} for i in range(start, end): rawindex = self.get_raw_index(i) try: ...
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
3.026549
2.99574
1.010284
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, comment = items[i] if comment: log.debug(" restoring comm...
def restore_comments(self, restore_data)
Restore comment styles and data
3.760078
3.590726
1.047164
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(): try: index = self.get_index_from_base_index(rawindex) except I...
def get_comments_in_range(self, start, end)
Get a list of comments at specified indexes
6.571332
6.532405
1.005959
for index, comment in source.iter_comments_in_segment(): self.set_comment_at(index + index_offset, comment)
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.
7.438558
4.340489
1.71376
xpath_string = request.params.get('q') results = execute_xpath(xpath_string, 'xpath', uuid, version) if return_json: return results else: return xpath_book_html(request, results)
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.
4.626383
4.585963
1.008814
xpath_string = request.params.get('q') return execute_xpath(xpath_string, 'xpath-module', uuid, version)
def xpath_page(request, uuid, version)
Given a page UUID (and optional version), returns a JSON object of results, as in xpath_book()
9.031519
8.945289
1.00964
settings = get_current_registry().settings with db_connect() as db_connection: with db_connection.cursor() as cursor: try: cursor.execute(SQL[sql_function], {'document_uuid': uuid, 'document_version': versio...
def execute_xpath(xpath_string, sql_function, uuid, version)
Executes either xpath or xpath-module SQL function with given input params.
3.208842
3.431844
0.93502
ident_hash = request.params.get('id') xpath_string = request.params.get('q') if not ident_hash or not xpath_string: exc = httpexceptions.HTTPBadRequest exc.explanation = 'You must supply both a UUID and an xpath' raise exc try: uuid, version = split_ident_hash(iden...
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.
3.473736
3.418719
1.016093
ul = etree.Element('ul') html_listify([tree], ul) return HTML_WRAPPER.format(etree.tostring(ul))
def tree_to_html(tree)
Return html list version of book tree.
7.847122
7.168724
1.094633
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_collated', True)) page_ident_hash = routing_args.get('page_ident_hash', '') p_id, p_version = (None...
def _get_content_json(ident_hash=None)
Return a content as a dict from its ident-hash (uuid@version).
3.612251
3.571229
1.011487
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)
Retrieve content as JSON using the ident-hash (uuid@version).
3.259004
3.356162
0.971051
result = _get_content_json() media_type = result['mediaType'] if media_type == COLLECTION_MIMETYPE: content = tree_to_html(result['tree']) else: content = result['content'] resp = request.response resp.body = content resp.status = "200 OK" resp.content_type = 'appl...
def get_content_html(request)
Retrieve content as HTML using the ident-hash (uuid@version).
4.194966
4.133386
1.014898
request = get_current_request() is_first_node = parent_id is None if is_first_node: parent_id = tree[0]['id'] for node in tree: li_elm = etree.SubElement(root_ul_element, 'li') a_elm = etree.SubElement(li_elm, 'a') a_elm.text = node['title'] if node['id'] != ...
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.
2.485051
2.479893
1.00208
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 directly from the setting this function uses to # check for valid types, so it should never ...
def get_export_allowable_types(cursor, exports_dirs, id, version)
Return export types.
4.816312
4.820528
0.999125
book_ident_hash = join_ident_hash(book_id, book_version) page_ident_hash = join_ident_hash(page_id, page_version) tree = get_tree(book_ident_hash, cursor) # Check if the page appears in the book tree if not tree or page_ident_hash not in flatten_tree_to_ident_hashes(tree): # Return a 4...
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.
3.809808
3.848127
0.990042
args = join_ident_hash(id, version) sql_statement = cursor.execute(sql_statement, vars=(args,)) res = cursor.fetchone() if res is None: return None else: return res[0]
def get_portal_type(cursor, id, version)
Return the module's portal_type.
6.009754
5.509502
1.090798
with db_connect() as db_connection: # Uses a RealDictCursor instead of the regular cursor with db_connection.cursor( cursor_factory=psycopg2.extras.RealDictCursor ) as real_dict_cursor: # In the future the books-containing-page SQL might handle ...
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.
4.885577
4.890806
0.998931
slug_title = u'/{}'.format('-'.join(metadata['title'].split())) settings = get_current_registry().settings canon_host = settings.get('canonical-hostname', re.sub('archive.', '', request.host)) if metadata['canonical'] is None: canon_url = request.route_url( ...
def get_canonical_url(metadata, request)
Builds canonical in book url from a pages metadata.
4.701107
4.728541
0.994198
ext = request.matchdict.get('ext') accept = request.headers.get('ACCEPT', '') if not ext: if ('application/xhtml+xml' in accept): result, resp = get_content_html(request) else: # default to json result, resp = get_content_json(request) elif ext == '.html': ...
def get_content(request)
Retrieve content using the ident-hash (uuid@version). Depending on extension or HTTP_ACCEPT header return HTML or JSON.
3.75393
3.566065
1.052681
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_hash(args['ident_hash']) try: id, version = split_ident_hash(args['page_ident_...
def get_extra(request)
Return information about a module / collection that cannot be cached.
4.365382
4.33836
1.006229
parent = child.hparent # filters pf = parent.filter.all # indices corresponding to all child events idx = np.where(pf)[0] # True means present in the child # indices corresponding to selected child events parent_indices = idx[child_indices] return parent_indices
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 ndarray hierarchy parent indices
11.765179
11.150138
1.05516
while True: indices = map_indices_child2parent(child=child, child_indices=child_indices) if isinstance(child.hparent, RTDC_Hierarchy): child = child.hparent child_indices = indices else: break return indi...
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 hierarchy root indices (not necessarily the indices...
5.156825
3.521393
1.464428
parent = child.hparent # filters pf = parent.filter.all # indices in child child_indices = [] count = 0 for ii in range(len(pf)): if pf[ii]: # only append indices if they exist in child if ii in parent_indices: # current child event count ...
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_indices: 1d ndarray child indices
6.375457
6.06732
1.050786
# construct hierarchy tree containing only RTDC_Hierarchy instances hierarchy = [child] while True: if isinstance(child.hparent, RTDC_Hierarchy): # the parent is a hierarchy tree hierarchy.append(child.hparent) child = child.hparent else: ...
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`) Returns ------- child_indices: 1d ndarray c...
6.017029
5.628837
1.068965
if self.parent_changed: msg = "Cannot apply filter, because parent changed: " \ + "dataset {}. ".format(self.rtdc_ds) \ + "Run `RTDC_Hierarchy.apply_filter()` first!" raise HierarchyFilterError(msg) else: self._man_root_ids...
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 filter and the child did not yet hear about this, then ...
9.096559
5.248453
1.733188
if self.parent_changed: # ignore pass else: # indices from boolean array pbool = map_indices_child2root( child=self.rtdc_ds, child_indices=np.where(~self.manual)[0]).tolist() # retrieve all indices that ...
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 ----- This method also retrieves ...
5.736817
4.978315
1.152361
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 self.hparent.apply_filter() # update event index event_count = np.sum(self.hparent._...
def apply_filter(self, *args, **kwargs)
Overridden `apply_filter` to perform tasks for hierarchy child
4.886022
4.696815
1.040284
# Do not apply filters here (speed) hph = self.hparent.hash hpfilt = hashobj(self.hparent._filter) dhash = hashobj(hph + hpfilt) return dhash
def hash(self)
Hashes of a hierarchy child changes if the parent changes
13.937859
13.116218
1.062643
video = None if rtdc_dataset._fdir.exists(): # Cell images (video) videos = [v.name for v in rtdc_dataset._fdir.rglob("*.avi")] # Filter videos according to measurement number meas_id = rtdc_dataset._mid videos = [v for v in videos if ...
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.
6.768879
6.955818
0.973125
warnings.warn("imageio workaround used!") cap = self.video_handle mult = 50 for ii in range(idx//mult): cap.get_data(ii*mult) final = cap.get_data(idx) return final
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`.
11.377693
8.275683
1.374834
return List([_select(item, attr, default) for item in self])
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 contain desired attribute Returns: ...
10.997606
23.930258
0.459569
return List([item for item in self if _filter(_select(item, attr), value, compare)])
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): comparison type "=": `attr == value` "=...
9.455622
14.139524
0.668737
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")
Create a new disk image in the specified format
9.862446
8.058892
1.223797
def set_source(self, source): route = Navigator(source=self.source).navigate_to_source(source) # Save new source self.source = source return self._send_keystroke(route, wait=True)
Selects and saves source.
null
null
null
here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, 'sql/migrations')
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.
3.126514
3.220626
0.970778
# 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='') # it's possible to do this: # request.route_path('resour...
def declare_api_routes(config)
Declare routes, with a custom pregenerator.
3.433067
3.357169
1.022608
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(':', 1) type_info = type_info.split(',', 3) settings['_type_i...
def declare_type_info(config)
Lookup type info from app configuration.
2.943623
2.834282
1.038578
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') config.add_jinja2_renderer('.rss') config.add_jinja2_renderer('.xml'...
def main(global_config, **settings)
Main WSGI application factory.
5.858617
5.747921
1.019258
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)
Initialize the LSR Markov chain and the weights.
3.776735
3.013813
1.253142
converged = NormOfDifferenceTest(tol, order=1) for _ in range(max_iter): params = fun(initial_params=params) if converged(params): return params raise RuntimeError("Did not converge after {} iterations".format(max_iter))
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.
5.028646
6.252302
0.804287
weights, chain = _init_lsr(n_items, alpha, initial_params) for winner, loser in data: chain[loser, winner] += 1 / (weights[winner] + weights[loser]) chain -= np.diag(chain.sum(axis=1)) return log_transform(statdist(chain))
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 iteratively refine an existing parameter estimate (see the implementation...
5.87837
6.683987
0.879471
fun = functools.partial( lsr_pairwise, n_items=n_items, data=data, alpha=alpha) return _ilsr(fun, initial_params, max_iter, tol)
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 the iterative Luce Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain ...
3.148
4.987872
0.631131
n_items = comp_mat.shape[0] ws, chain = _init_lsr(n_items, alpha, initial_params) denom = np.tile(ws, (n_items, 1)) chain += comp_mat.T / (denom + denom.T) chain -= np.diag(chain.sum(axis=1)) return log_transform(statdist(chain))
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 ``comp_mat`` such that ``comp_mat[i,j]`` contains the number of times ...
5.832385
7.035879
0.828949
fun = functools.partial( lsr_pairwise_dense, comp_mat=comp_mat, alpha=alpha) return _ilsr(fun, initial_params, max_iter, tol)
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 described by a pairwise-comparison matrix ``comp_mat`` such that ``comp_mat[i,j]`` contains the number of time...
3.156483
5.14014
0.614085
_, chain = _init_lsr(n_items, alpha, None) for winner, loser in data: chain[loser, winner] += 1.0 # Transform the counts into ratios. idx = chain > 0 # Indices (i,j) of non-zero entries. chain[idx] = chain[idx] / (chain + chain.T)[idx] # Finalize the Markov chain by adding the self...
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 of the total count). The transition rates of the R...
7.444923
6.168554
1.206915
weights, chain = _init_lsr(n_items, alpha, initial_params) for ranking in data: sum_ = weights.take(ranking).sum() for i, winner in enumerate(ranking[:-1]): val = 1.0 / sum_ for loser in ranking[i+1:]: chain[loser, winner] += val sum_ -= w...
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 refine an existing parameter estimate (see the implementation of :fun...
5.391638
6.159237
0.875374
fun = functools.partial( lsr_rankings, n_items=n_items, data=data, alpha=alpha) return _ilsr(fun, initial_params, max_iter, tol)
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 iterative Luce Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain are initiali...
3.231629
4.949021
0.652983
weights, chain = _init_lsr(n_items, alpha, initial_params) for winner, losers in data: val = 1 / (weights.take(losers).sum() + weights[winner]) for loser in losers: chain[loser, winner] += val chain -= np.diag(chain.sum(axis=1)) return log_transform(statdist(chain))
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 existing parameter estimate (see the implementation of :func:`~ch...
6.740822
7.939664
0.849006
fun = functools.partial(lsr_top1, n_items=n_items, data=data, alpha=alpha) return _ilsr(fun, initial_params, max_iter, tol)
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 Spectral Ranking algorithm [MG15]_. The transition rates of the LSR Markov chain are initialized wi...
2.580321
4.597047
0.5613
if model == "logit": match_moments = _match_moments_logit elif model == "probit": match_moments = _match_moments_probit else: raise ValueError("unknown model '{}'".format(model)) return _ep_pairwise( n_items, data, alpha, match_moments, max_iter, initial_state)
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 :ref:`data-pairwise`). It uses the expectation propagation algorithm, as presented, e.g., in [C...
2.273118
2.978457
0.763186
# Static variable that allows to check the # of iterations after the call. _ep_pairwise.iterations = 0 m = len(comparisons) prior_inv = alpha * np.eye(n_items) if initial_state is None: # Initially, mean and covariance come from the prior. mean = np.zeros(n_items) cov = ...
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.
3.381613
3.415193
0.990167
# 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 = -2 * val - log(2) dres = exp(-(z * z) / 2 - res) / SQRT2PI elif z < -11.3137: ...
def _log_phi(z)
Stable computation of the log of the Normal CDF and its derivative.
4.711327
4.498902
1.047217
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] xs[b] -= nu[i] cov = inv_posdef(prior_inv + prec) mean = cov.dot(xs) return mean, cov, xs , p...
def _init_ws(n_items, comparisons, prior_inv, tau, nu)
Initialize parameters in the weight space.
4.187202
4.143614
1.010519
weights = np.exp(np.asarray(params) - np.mean(params)) return (len(weights) / weights.sum()) * weights
def exp_transform(params)
Transform parameters into exp-scale weights.
4.944187
4.407779
1.121696
ys = xs - np.max(xs) exps = np.exp(ys) return exps / exps.sum(axis=0)
def softmax(xs)
Stable implementation of the softmax function.
2.548292
2.690453
0.947161
# 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, lower=True, overwrite_b=True) return np.transpose(res).dot(res)
def inv_posdef(mat)
Stable inverse of a positive definite matrix.
3.87325
3.865861
1.001911
r assert params2 is None or len(params1) == len(params2) ranks1 = rankdata(params1, method="average") if params2 is None: ranks2 = np.arange(1, len(params1) + 1, dtype=float) else: ranks2 = rankdata(params2, method="average") return np.sum(np.abs(ranks1 - ranks2))
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 :math:`\tau_i` be its rank in the model descr...
2.422298
2.461289
0.984158
r assert params2 is None or len(params1) == len(params2) ranks1 = rankdata(params1, method="ordinal") if params2 is None: ranks2 = np.arange(1, len(params1) + 1, dtype=float) else: ranks2 = rankdata(params2, method="ordinal") tau, _ = kendalltau(ranks1, ranks2) n_items = len(...
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:`\tau_i` be its rank in the model described by ...
2.394897
2.465517
0.971357
r assert len(params1) == len(params2) params1 = np.asarray(params1) - np.mean(params1) params2 = np.asarray(params2) - np.mean(params2) sqrt_n = math.sqrt(len(params1)) return np.linalg.norm(params1 - params2, ord=2) / sqrt_n
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 error.
2.474668
2.693695
0.918689
loglik = 0 for winner, loser in data: loglik -= np.logaddexp(0, -(params[winner] - params[loser])) return loglik
def log_likelihood_pairwise(data, params)
Compute the log-likelihood of model parameters.
3.850246
3.828626
1.005647
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)
Compute the log-likelihood of model parameters.
4.448766
4.57356
0.972714
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)
Compute the log-likelihood of model parameters.
5.306609
5.315629
0.998303
loglik = 0 for i in range(len(traffic_in)): loglik += traffic_in[i] * params[i] if digraph.out_degree(i) > 0: neighbors = list(digraph.successors(i)) if weight is None: loglik -= traffic_out[i] * logsumexp(params.take(neighbors)) else: ...
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).
2.580851
2.777459
0.929213
generator = np.asarray(generator) n = generator.shape[0] with warnings.catch_warnings(): # The LU decomposition raises a warning when the generator matrix is # singular (which it, by construction, is!). warnings.filterwarnings("ignore") lu, piv = spl.lu_factor(generator....
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 chain. Raises ------ ...
5.730217
5.949858
0.963085
r params = np.random.uniform(low=0, high=interval, size=n_items) if ordered: params.sort() return params - params.mean()
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 distinct items. interval : float Sampling interval. o...
3.80395
5.528703
0.688036
n = len(params) items = tuple(range(n)) params = np.asarray(params) data = list() for _ in range(n_comparisons): # Pick the pair uniformly at random. a, b = random.sample(items, 2) if compare((a, b), params) == a: data.append((a, b)) else: ...
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--Terry model parametrized by ``params``. Parame...
3.300848
3.273169
1.008456
n = len(params) items = tuple(range(n)) params = np.asarray(params) data = list() for _ in range(n_rankings): # Pick the alternatives uniformly at random. alts = random.sample(items, size) ranking = compare(alts, params, rank=True) data.append(ranking) return...
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``. Parameters ---------- params : array_like...
4.160394
4.276563
0.972836
probs = probabilities(items, params) if rank: return np.random.choice(items, size=len(items), replace=False, p=probs) else: return np.random.choice(items, p=probs)
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 item. Parameters ---------- items ...
2.617513
3.630884
0.720902
params = np.asarray(params) return softmax(params.take(items))
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 ---------- items : list Subset of items ...
9.680099
27.482206
0.352232
fcts = PairwiseFcts(data, alpha) return _opt(n_items, fcts, method, initial_params, max_iter, tol)
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:`data-pairwise`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns...
3.8677
10.635952
0.363644
fcts = Top1Fcts.from_rankings(data, alpha) return _opt(n_items, fcts, method, initial_params, max_iter, tol)
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-rankings`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns the maximum...
4.997758
11.44789
0.436566
fcts = Top1Fcts(data, alpha) return _opt(n_items, fcts, method, initial_params, max_iter, tol)
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`), using optimizers provided by the ``scipy.optimize`` module. If ``alpha > 0``, the function returns the maximum a-pos...
3.730314
9.768022
0.38189
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)
Compute the negative penalized log-likelihood.
7.245712
7.277751
0.995598
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)
Alternative constructor for ranking data.
4.144734
4.082052
1.015356
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)
Compute the negative penalized log-likelihood.
7.486351
6.637052
1.127963
if initial_params is None: params = np.zeros(n_items) else: params = initial_params converged = NormOfDifferenceTest(tol=tol, order=1) for _ in range(max_iter): nums, denoms = mm_fun(n_items, data, params) params = log_transform((nums + alpha) / (denoms + alpha)) ...
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.
3.540947
3.69512
0.958277
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] + weights[loser]) denoms[winner] += val denoms[loser] += val return wins, den...
def _mm_pairwise(n_items, data, params)
Inner loop of MM algorithm for pairwise data.
2.906044
3.027926
0.959747
return _mm( n_items, data, initial_params, alpha, max_iter, tol, _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-pairwise`), using the minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the fun...
3.4389
7.314248
0.470165
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(ranking[:-1]): wins[winner] += 1 val = 1.0 / sum_ for ...
def _mm_rankings(n_items, data, params)
Inner loop of MM algorithm for ranking data.
3.925167
3.994602
0.982618
return _mm(n_items, data, initial_params, alpha, max_iter, tol, _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 minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the function return...
2.943238
6.733179
0.437124
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() + weights[winner]) for item in itertools.chain([winner], losers): den...
def _mm_top1(n_items, data, params)
Inner loop of MM algorithm for top1 data.
4.251419
4.415878
0.962757
return _mm(n_items, data, initial_params, alpha, max_iter, tol, _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 minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the function returns the ...
2.741949
6.100308
0.449477
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"): denoms = adj_t.dot(traffic_out / zs) return traffic_in, denoms
def _choicerank(n_items, data, params)
Inner loop of ChoiceRank algorithm.
8.401456
8.012531
1.04854
import networkx as nx # Compute the (sparse) adjacency matrix. n_items = len(digraph) nodes = np.arange(n_items) adj = nx.to_scipy_sparse_matrix(digraph, nodelist=nodes, weight=weight) adj_t = adj.T.tocsr() # Process the data into a standard form. traffic_in = np.asarray(traffic_in)...
def choicerank( digraph, traffic_in, traffic_out, weight=None, initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8)
Compute the MAP estimate of a network choice model's parameters. This function computes the maximum-a-posteriori (MAP) estimate of model parameters given a network structure and node-level traffic data (see :ref:`data-network`), using the ChoiceRank algorithm [MG17]_, [KTVV15]_. The nodes are assumed ...
2.926661
3.44744
0.848938
''' Decorate a function so the function call is checked whenever a call is made. The calls that do not need any checks are skipped. The `function` argument is the function to be decorated. The return value will be either * the function itself, if there is nothing to va...
def decorate(cls, function)
Decorate a function so the function call is checked whenever a call is made. The calls that do not need any checks are skipped. The `function` argument is the function to be decorated. The return value will be either * the function itself, if there is nothing to validate, or *...
5.420727
2.356065
2.300755
''' Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator. ''' if cls.is_function_validated(function): return cls.get_function_validator(function).function return function
def undecorate(cls, function)
Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator.
9.278609
4.131864
2.245623
''' Validate the arguments passed to a function. If an error occurred, the function will throw a TypesafetyError. The `locals_dict` argument should be the local value dictionary of the function. An example call would be like: ''' for key, value, validator in sel...
def validate_arguments(self, locals_dict)
Validate the arguments passed to a function. If an error occurred, the function will throw a TypesafetyError. The `locals_dict` argument should be the local value dictionary of the function. An example call would be like:
5.812803
3.172079
1.83249
''' Validate the return value of a function call. If an error occurred, the function will throw a TypesafetyError. The `retval` should contain the return value of the function call. ''' if self.__return_annotation is None: return if not self.__is_va...
def validate_return_value(self, retval)
Validate the return value of a function call. If an error occurred, the function will throw a TypesafetyError. The `retval` should contain the return value of the function call.
4.439218
2.800007
1.585431
''' Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal). ''' if self.installed: sys.meta_path.remove(self) # Reload...
def uninstall(self)
Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal).
6.652557
2.884374
2.306413
''' Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the system to locate a module. ''' loader = None if self.__filter is None or self.__filter(fullname): loader = ModuleLoader(self, fullname, path) ...
def find_module(self, fullname, path=None)
Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the system to locate a module.
10.724668
3.347277
3.203998
''' Load the module. Required for the Python meta-loading mechanism. ''' modfile, pathname, description = loader.info module = imp.load_module( loader.fullname, modfile, pathname, description ) sys.modules[loader.fu...
def load_module(self, loader)
Load the module. Required for the Python meta-loading mechanism.
6.101636
4.34286
1.404981
event.listen(cls, 'after_insert', self._new_listener) event.listen(cls, 'after_update', self._update_listener) event.listen(cls, 'after_delete', self._delete_listener)
def _register_event_listeners(self, cls)
:param cls: DB class
2.154428
2.083152
1.034216
log.info('Commiting indexing orders for session %s' % session) try: if not any((session.index_new[self.cls_name], session.index_dirty[self.cls_name], session.index_deleted[self.cls_name])): return if session...
def after_commit_listener(self, session)
Processing the changes. All new or changed items are now indexed. All deleted items are now removed from the index.
2.857224
2.753573
1.037642
log.info('Queuing job...') with Connection(redis): q = Queue(queue_name) job = q.enqueue(delegate, *args) return job.id
def _queue_job(redis, queue_name, delegate, *args)
creates a new job on the queue :param redis: redis :param delegate: method to be executed by the queue. Use fully qualified method name as String. :param args: arguments of the method :return: job_id
4.050337
4.329111
0.935605