text stringlengths 81 112k |
|---|
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)
def get_style_bits(matc... |
Get the bit mask that, when anded with data, will turn off the
selected bits
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
... |
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.
def byte_bounds_offset(self):
"""Return start and end offsets of this segment's data into the... |
Get index into base array's raw data, given the index into this
segment
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:
... |
Get array of indexes from the base array, as if this raw data were
indexed.
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... |
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
def reverse_index_mapping(self):
"""Get mapping from this segment's indexes to the... |
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
def get_reverse_index(self, base_index):
"""Get index into this segment's data given the index into the base data
Raises IndexError ... |
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
... |
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.
def restore_renamed_serializable_attributes(self):
"""Hook for the future if attr... |
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.
def reconstruct_raw(self, rawdata):
"""Reconstruct the pointers to the parent data arrays
Each segment is ... |
Get the raw data that is similar to the specified other segment
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:
... |
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... |
Get index into this array's data given the index into the base array
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 Inde... |
Return a list of start, end pairs that match the specified style
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... |
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.
def fixup_comments(self):
... |
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 ... |
Get a list of comments at specified 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 =... |
Get a chunk of data (designed to be opaque) containing comments,
styles & locations that can be used to recreate the comments on an undo
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 recreat... |
Restore comment styles and data
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):... |
Get a list of comments at specified indexes
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 ... |
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.
def copy_user_data(self, source, index_offset=0):
"""Copy comments and other user data from the source segment to this
segment.
The... |
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.
def xpath_book(request, uuid, version, return_json=True):
"""
Given a request, book UUID... |
Given a page UUID (and optional version), returns a JSON object of
results, as in xpath_book()
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(xpa... |
Executes either xpath or xpath-module SQL function with given input
params.
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:
... |
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.
def xpath(request):
"""View for the route. Determines UUID and version from input request
and determines the type of UUID (collection or modul... |
Return html list version of book tree.
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)) |
Return a content as a dict from its ident-hash (uuid@version).
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_... |
Retrieve content as JSON using the ident-hash (uuid@version).
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.d... |
Retrieve content as HTML using the ident-hash (uuid@version).
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['tr... |
Recursively construct HTML nested list version of book tree.
The original caller should not call this function with the
`parent_id` defined.
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 ... |
Return export 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 t... |
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.
def get_book_info(cursor, real_dict_cursor, book_id,
book_version, page_id, page_version):
"""Return information about a given book.
... |
Return the module's 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(... |
Return a list of book names and UUIDs
that contain a given module UUID.
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_conn... |
Builds canonical in book url from a pages metadata.
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-hostna... |
Retrieve content using the ident-hash (uuid@version).
Depending on extension or HTTP_ACCEPT header return HTML or JSON.
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.... |
Return information about a module / collection that cannot be cached.
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 arg... |
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
def map_indices_c... |
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 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
def map_indices_par... |
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... |
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
... |
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 ... |
Overridden `apply_filter` to perform tasks for hierarchy child
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_m... |
Hashes of a hierarchy child changes if the parent changes
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)
retu... |
Tries to find a video file that belongs to an RTDC dataset
Returns None if no video file is found.
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.... |
Same as __getitem__ but seek through the video beforehand
This is a workaround for an all-zero image returned by `imageio`.
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`.... |
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:
... |
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`
"=... |
Create a new disk image in the specified 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)
imag... |
Selects and saves 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) |
Finds and returns the location of the database migrations directory.
This function is used from a setuptools entry-point for db-migrator.
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-migra... |
Declare routes, with a custom pregenerator.
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:
#... |
Lookup type info from app configuration.
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
... |
Main WSGI application factory.
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
conf... |
Initialize the LSR Markov chain and the weights.
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_... |
Iteratively refine LSR estimates until convergence.
Raises
------
RuntimeError
If the algorithm does not converge after ``max_iter`` iterations.
def _ilsr(fun, params, max_iter, tol):
"""Iteratively refine LSR estimates until convergence.
Raises
------
RuntimeError
If the ... |
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 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 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 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 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 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 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 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 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 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.
Raises
------
RuntimeError
If the algorithm does not converge after ``max_iter`` iterations.
def _ep_pairwise(
n_items, comparisons, alpha, match_moments, max_iter, initial_state):
"""Compute a distribution of model par... |
Stable computation of the log of the Normal CDF and its derivative.
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 = fun... |
Initialize parameters in the weight space.
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] * MA... |
Transform parameters into exp-scale weights.
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 |
Stable implementation of the softmax function.
def softmax(xs):
"""Stable implementation of the softmax function."""
ys = xs - np.max(xs)
exps = np.exp(ys)
return exps / exps.sum(axis=0) |
Stable inverse of a positive definite matrix.
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[... |
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 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 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.
def rmse(params1, param... |
Compute the log-likelihood of model parameters.
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 |
Compute the log-likelihood of model parameters.
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(rank... |
Compute the log-likelihood of model parameters.
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[w... |
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).
def log_likelihood_network(
digraph, traffic_in, traffic_out, params, weight=None):
"""
Compute the log-likelihood of model parame... |
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
------
... |
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... |
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 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 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 ... |
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 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``.
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``.
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 negative penalized log-likelihood.
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 |
Alternative constructor for ranking data.
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,... |
Compute the negative penalized log-likelihood.
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) - ... |
Iteratively refine MM estimates until convergence.
Raises
------
RuntimeError
If the algorithm does not converge after `max_iter` iterations.
def _mm(n_items, data, initial_params, alpha, max_iter, tol, mm_fun):
"""
Iteratively refine MM estimates until convergence.
Raises
------
... |
Inner loop of MM algorithm for pairwise data.
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] +=... |
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... |
Inner loop of MM algorithm for ranking data.
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(ran... |
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... |
Inner loop of MM algorithm for top1 data.
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
... |
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 ... |
Inner loop of ChoiceRank algorithm.
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.