Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def data(self, root):
'''Convert etree.Element into a dictionary'''
value = self.dict()
children = [node for node in root if isinstance(node.tag, basestring)]
for attr, attrval in root.attrib.items():
attr = attr if self.attr_prefi... | [] |
Please provide a description of the function:def data(self, root, preserve_root=False):
'''Convert etree.Element into a dictionary'''
# If preserve_root is False, return the root element. This is easiest
# done by wrapping the XML in a dummy root element that will be ignored.
if preserve... | [] |
Please provide a description of the function:def data(self, root):
'''Convert etree.Element into a dictionary'''
value = self.dict()
# Add attributes specific 'attributes' key
if root.attrib:
value['attributes'] = self.dict()
for attr, attrval in root.attrib.ite... | [] |
Please provide a description of the function:def etree(self, data, root=None):
'''Convert data structure into a list of etree.Element'''
result = self.list() if root is None else root
if isinstance(data, (self.dict, dict)):
for key, value in data.items():
if isinstanc... | [] |
Please provide a description of the function:def who_likes(obj):
return Like.objects.filter(
receiver_content_type=ContentType.objects.get_for_model(obj),
receiver_object_id=obj.pk
) | [
"\n Usage:\n {% who_likes obj as var %}\n "
] |
Please provide a description of the function:def likes(user, *models):
content_types = []
model_list = models or settings.PINAX_LIKES_LIKABLE_MODELS.keys()
for model in model_list:
if not _allowed(model):
continue
app, model = model.split(".")
content_types.append(
... | [
"\n Usage:\n {% likes user as var %}\n Or\n {% likes user [model1, model2] as var %}\n "
] |
Please provide a description of the function:def likes_count(obj):
return Like.objects.filter(
receiver_content_type=ContentType.objects.get_for_model(obj),
receiver_object_id=obj.pk
).count() | [
"\n Usage:\n\n {% likes_count obj %}\n or\n {% likes_count obj as var %}\n or\n {{ obj|likes_count }}\n "
] |
Please provide a description of the function:def likes_widget(context, user, obj, template_name="pinax/likes/_widget.html"):
request = context["request"]
return loader.get_template(template_name).render(
widget_context(user, obj, request)) | [
"\n Usage:\n\n {% likes_widget request.user post %}\n or\n {% likes_widget request.user post \"pinax/likes/_widget_brief.html\" %}\n "
] |
Please provide a description of the function:def render_like(parser, token):
tokens = token.split_contents()
var = tokens[1]
return LikeRenderer(var) | [
"\n {% likes user as like_list %}\n <ul>\n {% for like in like_list %}\n <li>{% render_like like %}</li>\n {% endfor %}\n </ul>\n "
] |
Please provide a description of the function:def liked(parser, token):
tag, objects, _, user, _, varname = token.split_contents()
return LikedObjectsNode(objects, user, varname) | [
"\n {% liked objects by user as varname %}\n "
] |
Please provide a description of the function:def by_col(cls, df, cols, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
if outvals is None:
outvals = []
outvals.extend(['bb', 'p_sim_bw', 'p_sim_bb'])
pvalue = ''
return _univariate_handler(df, c... | [
"\n Function to compute a Join_Count statistic on a dataframe\n\n Arguments\n ---------\n df : pandas.DataFrame\n a pandas dataframe with a geometry column\n cols : string or list of string\n name or list of names o... |
Please provide a description of the function:def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
try:
# check if pandas is installed
import pandas
if isinstance(variables, pandas.DataFrame):
# if yes use variables as df and convert to numpy_array
va... | [
"\n Bivariate Moran Matrix\n\n Calculates bivariate Moran between all pairs of a set of variables.\n\n Parameters\n ----------\n variables : array or pandas.DataFrame\n sequence of variables to be assessed\n w : W\n a spatial weights object\n pe... |
Please provide a description of the function:def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in range(i + 1... | [
"\n Base calculation for MORAN_BV_Matrix\n "
] |
Please provide a description of the function:def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
return _bivariate_handler(df, x, y=y, w=w, inplace=inplace,
pvalue = pvalue, outvals = outvals,
... | [
"\n Function to compute a Moran_BV statistic on a dataframe\n\n Arguments\n ---------\n df : pandas.DataFrame\n a pandas dataframe with a geometry column\n X : list of strings\n column name or list of column name... |
Please provide a description of the function:def by_col(cls, df, events, populations, w=None, inplace=False,
pvalue='sim', outvals=None, swapname='', **stat_kws):
if not inplace:
new = df.copy()
cls.by_col(new, events, populations, w=w, inplace=True,
... | [
"\n Function to compute a Moran_Rate statistic on a dataframe\n\n Arguments\n ---------\n df : pandas.DataFrame\n a pandas dataframe with a geometry column\n events : string or list of strings\n one or more names whe... |
Please provide a description of the function:def __crand(self):
lisas = np.zeros((self.n, self.permutations))
n_1 = self.n - 1
prange = list(range(self.permutations))
k = self.w.max_neighbors + 1
nn = self.n - 1
rids = np.array([np.random.permutation(nn)[0:k] for... | [
"\n conditional randomization\n\n for observation i with ni neighbors, the candidate set cannot include\n i (we don't want i being a neighbor of i). we have to sample without\n replacement from a set of ids that doesn't include i. numpy doesn't\n directly support sampling wo repl... |
Please provide a description of the function:def flatten(l, unique=True):
l = reduce(lambda x, y: x + y, l)
if not unique:
return list(l)
return list(set(l)) | [
"flatten a list of lists\n\n Parameters\n ----------\n l : list\n of lists\n unique : boolean\n whether or not only unique items are wanted (default=True)\n\n Returns\n -------\n list\n of single items\n\n Examples\n --------\n\n Crea... |
Please provide a description of the function:def weighted_median(d, w):
dtype = [('w', '%s' % w.dtype), ('v', '%s' % d.dtype)]
d_w = np.array(list(zip(w, d)), dtype=dtype)
d_w.sort(order='v')
reordered_w = d_w['w'].cumsum()
cumsum_threshold = reordered_w[-1] * 1.0 / 2
median_inx = (reordere... | [
"A utility function to find a median of d based on w\n\n Parameters\n ----------\n d : array\n (n, 1), variable for which median will be found\n w : array\n (n, 1), variable on which d's median will be decided\n\n Notes\n -----\n d and w are arr... |
Please provide a description of the function:def sum_by_n(d, w, n):
t = len(d)
h = t // n #must be floor!
d = d * w
return np.array([sum(d[i: i + h]) for i in range(0, t, h)]) | [
"A utility function to summarize a data array into n values\n after weighting the array with another weight array w\n\n Parameters\n ----------\n d : array\n (t, 1), numerical values\n w : array\n (t, 1), numerical values for weighting\n n ... |
Please provide a description of the function:def crude_age_standardization(e, b, n):
r = e * 1.0 / b
b_by_n = sum_by_n(b, 1.0, n)
age_weight = b * 1.0 / b_by_n.repeat(len(e) // n)
return sum_by_n(r, age_weight, n) | [
"A utility function to compute rate through crude age standardization\n\n Parameters\n ----------\n e : array\n (n*h, 1), event variable measured for each age group across n spatial units\n b : array\n (n*h, 1), population at risk variable measured for e... |
Please provide a description of the function:def direct_age_standardization(e, b, s, n, alpha=0.05):
age_weight = (1.0 / b) * (s * 1.0 / sum_by_n(s, 1.0, n).repeat(len(s) // n))
adjusted_r = sum_by_n(e, age_weight, n)
var_estimate = sum_by_n(e, np.square(age_weight), n)
g_a = np.square(adjusted_r) ... | [
"A utility function to compute rate through direct age standardization\n\n Parameters\n ----------\n e : array\n (n*h, 1), event variable measured for each age group across n spatial units\n b : array\n (n*h, 1), population at risk variable measured for ... |
Please provide a description of the function:def indirect_age_standardization(e, b, s_e, s_b, n, alpha=0.05):
smr = standardized_mortality_ratio(e, b, s_e, s_b, n)
s_r_all = sum(s_e * 1.0) / sum(s_b * 1.0)
adjusted_r = s_r_all * smr
e_by_n = sum_by_n(e, 1.0, n)
log_smr = np.log(smr)
log_sm... | [
"A utility function to compute rate through indirect age standardization\n\n Parameters\n ----------\n e : array\n (n*h, 1), event variable measured for each age group across n spatial units\n b : array\n (n*h, 1), population at risk variable measured fo... |
Please provide a description of the function:def standardized_mortality_ratio(e, b, s_e, s_b, n):
s_r = s_e * 1.0 / s_b
e_by_n = sum_by_n(e, 1.0, n)
expected = sum_by_n(b, s_r, n)
smr = e_by_n * 1.0 / expected
return smr | [
"A utility function to compute standardized mortality ratio (SMR).\n\n Parameters\n ----------\n e : array\n (n*h, 1), event variable measured for each age group across n spatial units\n b : array\n (n*h, 1), population at risk variable measured for each... |
Please provide a description of the function:def choynowski(e, b, n, threshold=None):
e_by_n = sum_by_n(e, 1.0, n)
b_by_n = sum_by_n(b, 1.0, n)
r_by_n = sum(e_by_n) * 1.0 / sum(b_by_n)
expected = r_by_n * b_by_n
p = []
for index, i in enumerate(e_by_n):
if i <= expected[index]:
... | [
"Choynowski map probabilities [Choynowski1959]_ .\n\n Parameters\n ----------\n e : array(n*h, 1)\n event variable measured for each age group across n spatial units\n b : array(n*h, 1)\n population at risk variable measured for each age group across n s... |
Please provide a description of the function:def assuncao_rate(e, b):
y = e * 1.0 / b
e_sum, b_sum = sum(e), sum(b)
ebi_b = e_sum * 1.0 / b_sum
s2 = sum(b * ((y - ebi_b) ** 2)) / b_sum
ebi_a = s2 - ebi_b / (float(b_sum) / len(e))
ebi_v = ebi_a + ebi_b / b
return (y - ebi_b) / np.sqrt(e... | [
"The standardized rates where the mean and stadard deviation used for\n the standardization are those of Empirical Bayes rate estimates\n The standardized rates resulting from this function are used to compute\n Moran's I corrected for rate variables [Choynowski1959]_ .\n\n Parameters\n ----------\n ... |
Please provide a description of the function:def by_col(cls, df, e,b, inplace=False, **kwargs):
if not inplace:
new = df.copy()
cls.by_col(new, e, b, inplace=True, **kwargs)
return new
if isinstance(e, str):
e = [e]
if isinstance(b, str):
... | [
"\n Compute smoothing by columns in a dataframe.\n\n Parameters\n -----------\n df : pandas.DataFrame\n a dataframe containing the data to be smoothed\n e : string or list of strings\n the name or names of columns containing event v... |
Please provide a description of the function:def by_col(cls, df, e,b, w=None, inplace=False, **kwargs):
if not inplace:
new = df.copy()
cls.by_col(new, e, b, w=w, inplace=True, **kwargs)
return new
if isinstance(e, str):
e = [e]
if isinsta... | [
"\n Compute smoothing by columns in a dataframe.\n\n Parameters\n -----------\n df : pandas.DataFrame\n a dataframe containing the data to be smoothed\n e : string or list of strings\n the name or names of columns containing event v... |
Please provide a description of the function:def by_col(cls, df, e,b, w=None, s=None, **kwargs):
if s is None:
raise Exception('Standard population variable "s" must be supplied.')
import pandas as pd
if isinstance(e, str):
e = [e]
if isinstance(b, str):
... | [
"\n Compute smoothing by columns in a dataframe.\n\n Parameters\n -----------\n df : pandas.DataFrame\n a dataframe containing the data to be smoothed\n e : string or list of strings\n the name or names of columns containing event v... |
Please provide a description of the function:def by_col(cls, df, e, b, x_grid, y_grid, geom_col='geometry', **kwargs):
import pandas as pd
# prep for application over multiple event/population pairs
if isinstance(e, str):
e = [e]
if isinstance(b, str):
b ... | [
"\n Compute smoothing by columns in a dataframe. The bounding box and point\n information is computed from the geometry column.\n\n Parameters\n -----------\n df : pandas.DataFrame\n a dataframe containing the data to be smoothed\n e : string ... |
Please provide a description of the function:def by_col(cls, df, e, b, t=None, geom_col='geometry', inplace=False, **kwargs):
import pandas as pd
if not inplace:
new = df.copy()
cls.by_col(new, e, b, t=t, geom_col=geom_col, inplace=True, **kwargs)
return new
... | [
"\n Compute smoothing by columns in a dataframe. The bounding box and point\n information is computed from the geometry column.\n\n Parameters\n -----------\n df : pandas.DataFrame\n a dataframe containing the data to be smoothed\n e : string ... |
Please provide a description of the function:def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
### Preprocess
if not inplace:
new_df = df.copy()
_univariate_handler(new_df, cols, stat=stat, w=w,... | [
"\n Compute a univariate descriptive statistic `stat` over columns `cols` in\n `df`.\n\n Parameters\n ----------\n df : pandas.DataFrame\n the dataframe containing columns to compute the descriptive\n statistics\n cols : string or list of strings\n... |
Please provide a description of the function:def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
real_swapname = kwargs.pop('swapname', '')
if isinstance(y, str):
y = [y]
if isinstance(x, str):
x = [x]
if not inpl... | [
"\n Compute a descriptive bivariate statistic over two sets of columns, `x` and\n `y`, contained in `df`.\n\n Parameters\n ----------\n df : pandas.DataFrame\n dataframe in which columns `x` and `y` are contained\n x : string or list of strings\n ... |
Please provide a description of the function:def _swap_ending(s, ending, delim='_'):
parts = [x for x in s.split(delim)[:-1] if x != '']
parts.append(ending)
return delim.join(parts) | [
"\n Replace the ending of a string, delimited into an arbitrary\n number of chunks by `delim`, with the ending provided\n\n Parameters\n ----------\n s : string\n string to replace endings\n ending : string\n string used to replace ending of `s`\n delim ... |
Please provide a description of the function:def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
... | [
"\n Create a base class with a metaclass.\n\n For example, if you have the metaclass\n\n >>> class Meta(type):\n ... pass\n\n Use this as the metaclass by doing\n\n >>> from symengine.compatibility import with_metaclass\n >>> class MyClass(with_metaclass(Meta, object)):\n ... pass\n\... |
Please provide a description of the function:def iterable(i, exclude=(string_types, dict, NotIterable)):
try:
iter(i)
except TypeError:
return False
if exclude:
return not isinstance(i, exclude)
return True | [
"\n Return a boolean indicating whether ``i`` is SymPy iterable.\n True also indicates that the iterator is finite, i.e. you e.g.\n call list(...) on the instance.\n\n When SymPy is working with iterables, it is almost always assuming\n that the iterable is not a string or a mapping, so those are exc... |
Please provide a description of the function:def is_sequence(i, include=None):
return (hasattr(i, '__getitem__') and
iterable(i) or
bool(include) and
isinstance(i, include)) | [
"\n Return a boolean indicating whether ``i`` is a sequence in the SymPy\n sense. If anything that fails the test below should be included as\n being a sequence for your application, set 'include' to that object's\n type; multiple types should be passed as a tuple of types.\n\n Note: although generat... |
Please provide a description of the function:def as_int(n):
try:
result = int(n)
if result != n:
raise TypeError
except TypeError:
raise ValueError('%s is not an integer' % n)
return result | [
"\n Convert the argument to a builtin integer.\n\n The return value is guaranteed to be equal to the input. ValueError is\n raised if the input has a non-integral value.\n\n Examples\n ========\n\n >>> from sympy.core.compatibility import as_int\n >>> from sympy import sqrt\n >>> 3.0\n 3.... |
Please provide a description of the function:def default_sort_key(item, order=None):
from sympy.core import S, Basic
from sympy.core.sympify import sympify, SympifyError
from sympy.core.compatibility import iterable
if isinstance(item, Basic):
return item.sort_key(order=order)
if ite... | [
"Return a key that can be used for sorting.\n\n The key has the structure:\n\n (class_key, (len(args), args), exponent.sort_key(), coefficient)\n\n This key is supplied by the sort_key routine of Basic objects when\n ``item`` is a Basic object or an object (other than a string) that\n sympifies to a ... |
Please provide a description of the function:def _nodes(e):
from .basic import Basic
if isinstance(e, Basic):
return e.count(Basic)
elif iterable(e):
return 1 + sum(_nodes(ei) for ei in e)
elif isinstance(e, dict):
return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items())... | [
"\n A helper for ordered() which returns the node count of ``e`` which\n for Basic objects is the number of Basic nodes in the expression tree\n but for other objects is 1 (unless the object is an iterable or dict\n for which the sum of nodes is returned).\n "
] |
Please provide a description of the function:def ordered(seq, keys=None, default=True, warn=False):
d = defaultdict(list)
if keys:
if not isinstance(keys, (list, tuple)):
keys = [keys]
keys = list(keys)
f = keys.pop(0)
for a in seq:
d[f(a)].append(a)
... | [
"Return an iterator of the seq where keys are used to break ties in\n a conservative fashion: if, after applying a key, there are no ties\n then no other keys will be computed.\n\n Two default keys will be applied if 1) keys are not provided or 2) the\n given keys don't resolve all ties (but only if `de... |
Please provide a description of the function:def symbols(names, **args):
result = []
if isinstance(names, string_types):
marker = 0
literals = ['\,', '\:', '\ ']
for i in range(len(literals)):
lit = literals.pop(0)
if lit in names:
while chr(... | [
"\n Transform strings into instances of :class:`Symbol` class.\n :func:`symbols` function returns a sequence of symbols with names taken\n from ``names`` argument, which can be a comma or whitespace delimited\n string, or a sequence of strings::\n >>> from symengine import symbols\n >>> x,... |
Please provide a description of the function:def var(names, **args):
def traverse(symbols, frame):
for symbol in symbols:
if isinstance(symbol, Basic):
frame.f_globals[symbol.__str__()] = symbol
# Once we hace an undefined function class
# im... | [
"\n Create symbols and inject them into the global namespace.\n\n INPUT:\n- s -- a string, either a single variable name, or\n- a space separated list of variable names, or\n- a list of variable names.\n\n This calls :func:`symbols` with the same arguments and put... |
Please provide a description of the function:def _combine_attribute_arguments(self, attr_dict, attr):
# Note: Code & comments unchanged from DirectedHypergraph
# If no attribute dict was passed, treat the keyword
# arguments as the dict
if attr_dict is None:
attr_dic... | [
"Combines attr_dict and attr dictionaries, by updating attr_dict\n with attr.\n\n :param attr_dict: dictionary of attributes of the node.\n :param attr: keyword arguments of attributes of the node;\n attr's values will override attr_dict's values\n if b... |
Please provide a description of the function:def add_hyperedge(self, nodes, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow empty node set (invalid hyperedge)
if not nodes:
raise ValueError("nodes argument cannot be empt... | [
"Adds a hyperedge to the hypergraph, along with any related\n attributes of the hyperedge.\n This method will automatically add any node from the node set\n that was not in the hypergraph.\n A hyperedge without a \"weight\" attribute specified will be\n assigne... |
Please provide a description of the function:def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for nodes in hyperedges:
hyperedge_id = self.add_hyperedge(nodes, attr_dict.copy())
... | [
"Adds multiple hyperedges to the graph, along with any related\n attributes of the hyperedges.\n If any node of a hyperedge has not previously been added to the\n hypergraph, it will automatically be added here.\n Hyperedges without a \"weight\" attribute specified will b... |
Please provide a description of the function:def remove_hyperedge(self, hyperedge_id):
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
frozen_nodes = \
self._hyperedge_attributes[hyperedge_id]["__frozen_nodes"]
# Remove... | [
"Removes a hyperedge and its attributes from the hypergraph.\n\n :param hyperedge_id: ID of the hyperedge to be removed.\n :raises: ValueError -- No such hyperedge exists.\n\n Examples:\n ::\n\n >>> H = UndirectedHypergraph()\n >>> hyperedge_list = ([\"A\", \"B\", \... |
Please provide a description of the function:def get_hyperedge_id(self, nodes):
frozen_nodes = frozenset(nodes)
if not self.has_hyperedge(frozen_nodes):
raise ValueError("No such hyperedge exists.")
return self._node_set_to_hyperedge[frozen_nodes] | [
"From a set of nodes, returns the ID of the hyperedge that this\n set comprises.\n\n :param nodes: iterable container of references to nodes in the\n the hyperedge to be added\n :returns: str -- ID of the hyperedge that has that the specified\n node set compris... |
Please provide a description of the function:def get_hyperedge_attribute(self, hyperedge_id, attribute_name):
# Note: Code unchanged from DirectedHypergraph
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
elif attribute_name not in s... | [
"Given a hyperedge ID and the name of an attribute, get a copy\n of that hyperedge's attribute.\n\n :param hyperedge_id: ID of the hyperedge to retrieve the attribute of.\n :param attribute_name: name of the attribute to retrieve.\n :returns: attribute value of the attribute_name key for... |
Please provide a description of the function:def get_hyperedge_attributes(self, hyperedge_id):
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
dict_to_copy = self._hyperedge_attributes[hyperedge_id].items()
attributes = {}
fo... | [
"Given a hyperedge ID, get a dictionary of copies of that hyperedge's\n attributes.\n\n :param hyperedge_id: ID of the hyperedge to retrieve the attributes of.\n :returns: dict -- copy of each attribute of the specified hyperedge_id\n (except the private __frozen_nodes entry).\n ... |
Please provide a description of the function:def get_star(self, node):
if node not in self._node_attributes:
raise ValueError("No such node exists.")
return self._star[node].copy() | [
"Given a node, get a copy of that node's star, that is, the set of\n hyperedges that the node belongs to.\n\n :param node: node to retrieve the star of.\n :returns: set -- set of hyperedge_ids for the hyperedges\n in the node's star.\n :raises: ValueError -- No suc... |
Please provide a description of the function:def write(self, file_name, delim=',', sep='\t'):
out_file = open(file_name, 'w')
# write first header line
out_file.write("nodes" + sep + "weight\n")
for hyperedge_id in self.get_hyperedge_id_set():
line = ""
... | [
"Writes an undirected hypergraph from a file, where nodes are\n represented as strings.\n Each column is separated by \"sep\", and the individual nodes are\n delimited by \"delim\".\n The header line is currently ignored, but columns should be of\n the format:\n node1[delim... |
Please provide a description of the function:def _F_outdegree(H, F):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_forward_star(node))
for node in H.get_node_set()]) | [
"Returns the result of a function F applied to the set of outdegrees in\n in the hypergraph.\n\n :param H: the hypergraph whose outdegrees will be operated on.\n :param F: function to execute on the list of outdegrees in the hypergraph.\n :returns: result of the given function F.\n :raises: TypeError... |
Please provide a description of the function:def _F_indegree(H, F):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_backward_star(node))
for node in H.get_node_set()]) | [
"Returns the result of a function F applied to the list of indegrees in\n in the hypergraph.\n\n :param H: the hypergraph whose indegrees will be operated on.\n :param F: function to execute on the list of indegrees in the hypergraph.\n :returns: result of the given function F.\n :raises: TypeError -... |
Please provide a description of the function:def _F_hyperedge_tail_cardinality(H, F):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_tail(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id... | [
"Returns the result of a function F applied to the set of cardinalities\n of hyperedge tails in the hypergraph.\n\n :param H: the hypergraph whose tail cardinalities will be\n operated on.\n :param F: function to execute on the set of cardinalities in the\n hypergraph.\n :r... |
Please provide a description of the function:def _F_hyperedge_head_cardinality(H, F):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return F([len(H.get_hyperedge_head(hyperedge_id))
for hyperedge_id in H.get_hyperedge_id... | [
"Returns the result of a function F applied to the set of cardinalities\n of hyperedge heads in the hypergraph.\n\n :param H: the hypergraph whose head cardinalities will be\n operated on.\n :param F: function to execute on the set of cardinalities in the\n hypergraph.\n :r... |
Please provide a description of the function:def hyperedge_cardinality_pairs_list(H):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
return [(len(H.get_hyperedge_tail(hyperedge_id)),
len(H.get_hyperedge_head(hyperedge_id))... | [
"Returns a list of 2-tuples of (\\|tail\\|, \\|head\\|) for each hyperedge\n in the hypergraph.\n\n :param H: the hypergraph whose cardinality ratios will be\n operated on.\n :returns: list -- list of 2-tuples for each hyperedge's cardinality.\n :raises: TypeError -- Algorithm only applicable... |
Please provide a description of the function:def _F_hyperedge_cardinality_ratio(H, F):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
# Since |head| can potentially be 0 (causing a division by 0 exception),
# we use numpy's float6... | [
"Returns the result of a function F applied to the set of cardinality\n ratios between the tail and the head sets (specifically, |tail|/|head|) of\n hyperedges in the hypergraph.\n\n :param H: the hypergraph whose cardinality ratios will be\n operated on.\n :param F: function to execu... |
Please provide a description of the function:def get_node_mapping(H):
node_set = H.get_node_set()
nodes_to_indices, indices_to_nodes = {}, {}
node_index = 0
for node in node_set:
nodes_to_indices.update({node: node_index})
indices_to_nodes.update({node_index: node})
node_in... | [
"Generates mappings between the set of nodes and integer indices (where\n every node corresponds to exactly 1 integer index).\n\n :param H: the hypergraph to find the node mapping on.\n :returns: dict -- for each integer index, maps the index to the node.\n dict -- for each node, maps the node... |
Please provide a description of the function:def get_hyperedge_id_mapping(H):
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Algorithm only applicable to undirected hypergraphs")
indices_to_hyperedge_ids, hyperedge_ids_to_indices = {}, {}
hyperedge_index = 0
for hyperedge_id ... | [
"Generates mappings between the set of hyperedge IDs and integer indices\n (where every hyperedge ID corresponds to exactly 1 integer index).\n\n :param H: the hypergraph to find the hyperedge ID mapping on.\n :returns: dict -- for each integer index, maps the index to the hyperedge\n ID.\n ... |
Please provide a description of the function:def get_hyperedge_weight_matrix(H, hyperedge_ids_to_indices):
# Combined 2 methods into 1; this could be written better
hyperedge_weights = {}
for hyperedge_id in H.hyperedge_id_iterator():
hyperedge_weights.update({hyperedge_ids_to_indices[hyperedge... | [
"Creates the diagonal matrix W of hyperedge weights as a sparse matrix.\n\n :param H: the hypergraph to find the weights.\n :param hyperedge_weights: the mapping from the indices of hyperedge IDs to\n the corresponding hyperedge weights.\n :returns: sparse.csc_matrix -- the diago... |
Please provide a description of the function:def get_hyperedge_degree_matrix(M):
degrees = M.sum(0).transpose()
new_degree = []
for degree in degrees:
new_degree.append(int(degree[0:]))
return sparse.diags([new_degree], [0]) | [
"Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix,\n where a hyperedge degree is the cardinality of the hyperedge.\n\n :param M: the incidence matrix of the hypergraph to find the D_e matrix on.\n :returns: sparse.csc_matrix -- the diagonal hyperedge degree matrix as a\n s... |
Please provide a description of the function:def fast_inverse(M):
diags = M.diagonal()
new_diag = []
for value in diags:
new_diag.append(1.0/value)
return sparse.diags([new_diag], [0]) | [
"Computes the inverse of a diagonal matrix.\n\n :param H: the diagonal matrix to find the inverse of.\n :returns: sparse.csc_matrix -- the inverse of the input matrix as a\n sparse matrix.\n\n "
] |
Please provide a description of the function:def node_iterator(self):
return iter(self._node_attributes)
def has_hypernode(self, hypernode):
return hypernode in self._hypernode_attributes | [
"Provides an iterator over the nodes.\n\n ",
"Determines if a specific hypernode is present in the hypergraph.\n\n :param node: reference to hypernode whose presence is being checked.\n :returns: bool -- true iff the node exists in the hypergraph.\n\n "
] |
Please provide a description of the function:def add_hypernode(self, hypernode, composing_nodes=set(), attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the hypernode hasn't previously been added, add it along
# with its attributes
if ... | [
"Adds a hypernode to the graph, along with any related attributes\n of the hypernode.\n\n :param hypernode: reference to the hypernode being added.\n :param nodes: reference to the set of nodes that compose\n \t\t\tthe hypernode.\n :param in_hypernodes: set of references to the... |
Please provide a description of the function:def normalized_hypergraph_cut(H, threshold=0):
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Algorithm only applicable to undirected hypergraphs")
# TODO: make sure that the hypergraph is connected
# Get index<->node mappings and ind... | [
"Executes the min-cut algorithm described in the paper:\n Zhou, Dengyong, Jiayuan Huang, and Bernhard Scholkopf.\n \"Learning with hypergraphs: Clustering, classification, and embedding.\"\n Advances in neural information processing systems. 2006.\n (http://machinelearning.wustl.edu/mlpapers/paper_files... |
Please provide a description of the function:def _compute_normalized_laplacian(H,
nodes_to_indices,
hyperedge_ids_to_indices):
M = umat.get_incidence_matrix(H,
nodes_to_indices, hyperedge_ids_to_indices)
W... | [
"Computes the normalized Laplacian as described in the paper:\n Zhou, Dengyong, Jiayuan Huang, and Bernhard Scholkopf.\n \"Learning with hypergraphs: Clustering, classification, and embedding.\"\n Advances in neural information processing systems. 2006.\n (http://machinelearning.wustl.edu/mlpapers/paper... |
Please provide a description of the function:def stationary_distribution(H, pi=None, P=None):
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Algorithm only applicable to undirected hypergraphs")
indices_to_nodes, nodes_to_indices = \
umat.get_node_mapping(H)
indices_to_hy... | [
"Computes the stationary distribution of a random walk on the given\n hypergraph using the iterative approach explained in the paper:\n (http://pages.cs.wisc.edu/~shuchi/courses/787-F09/scribe-notes/lec15.pdf)\n\n :param H: the hypergraph to find the stationary distribution on.\n :param pi: the initial ... |
Please provide a description of the function:def _compute_transition_matrix(H,
nodes_to_indices,
hyperedge_ids_to_indices):
M = umat.get_incidence_matrix(H,
nodes_to_indices, hyperedge_ids_to_indices)
W = umat.g... | [
"Computes the transition matrix for a random walk on the given\n hypergraph as described in the paper:\n Zhou, Dengyong, Jiayuan Huang, and Bernhard Scholkopf.\n \"Learning with hypergraphs: Clustering, classification, and embedding.\"\n Advances in neural information processing systems. 2006.\n (htt... |
Please provide a description of the function:def _create_random_starter(node_count):
pi = np.zeros(node_count, dtype=float)
for i in range(node_count):
pi[i] = random.random()
summation = np.sum(pi)
for i in range(node_count):
pi[i] = pi[i] / summation
return pi | [
"Creates the random starter for the random walk.\n\n :param node_count: number of nodes to create the random vector.\n :returns: list -- list of starting probabilities for each node.\n\n "
] |
Please provide a description of the function:def _has_converged(pi_star, pi):
node_count = pi.shape[0]
EPS = 10e-6
for i in range(node_count):
if pi[i] - pi_star[i] > EPS:
return False
return True | [
"Checks if the random walk has converged.\n\n :param pi_star: the new vector\n :param pi: the old vector\n :returns: bool-- True iff pi has converged.\n\n "
] |
Please provide a description of the function:def add_element(self, priority, element, count=None):
if count is None:
count = next(self.counter)
entry = [priority, count, element]
self.element_finder[element] = entry
heapq.heappush(self.pq, entry) | [
"Adds an element with a specific priority.\n\n :param priority: priority of the element.\n :param element: element to add.\n\n "
] |
Please provide a description of the function:def get_top_priority(self):
if self.is_empty():
raise IndexError("Priority queue is empty.")
_, _, element = heapq.heappop(self.pq)
if element in self.element_finder:
del self.element_finder[element]
return ele... | [
"Pops the element that has the top (smallest) priority.\n\n :returns: element with the top (smallest) priority.\n :raises: IndexError -- Priority queue is empty.\n\n "
] |
Please provide a description of the function:def delete_element(self, element):
if element not in self.element_finder:
raise ValueError("No such element in the priority queue.")
entry = self.element_finder[element]
entry[1] = self.INVALID | [
"Deletes an element (lazily).\n\n :raises: ValueError -- No such element in the priority queue.\n\n "
] |
Please provide a description of the function:def reprioritize(self, priority, element):
if element not in self.element_finder:
raise ValueError("No such element in the priority queue.")
entry = self.element_finder[element]
self.add_element(priority, element, entry[1])
... | [
"Updates the priority of an element.\n\n :raises: ValueError -- No such element in the priority queue.\n\n "
] |
Please provide a description of the function:def contains_element(self, element):
return (element in self.element_finder) and \
(self.element_finder[element][1] != self.INVALID) | [
"Determines if an element is contained in the priority queue.\"\n\n :returns: bool -- true iff element is in the priority queue.\n\n "
] |
Please provide a description of the function:def is_empty(self):
while self.pq:
if self.pq[0][1] != self.INVALID:
return False
else:
_, _, element = heapq.heappop(self.pq)
if element in self.element_finder:
del ... | [
"Determines if the priority queue has any elements.\n Performs removal of any elements that were \"marked-as-invalid\".\n\n :returns: true iff the priority queue has no elements.\n\n "
] |
Please provide a description of the function:def visit(H, source_node):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
node_set = H.get_node_set()
# Pv keeps track of the ID of the hyperedge that directely
# preceeded each nod... | [
"Executes the 'Visit' algorithm described in the paper:\n Giorgio Gallo, Giustino Longo, Stefano Pallottino, Sang Nguyen,\n Directed hypergraphs and applications, Discrete Applied Mathematics,\n Volume 42, Issues 2-3, 27 April 1993, Pages 177-201, ISSN 0166-218X,\n http://dx.doi.org/10.1016/0166-218X(93... |
Please provide a description of the function:def is_connected(H, source_node, target_node):
visited_nodes, Pv, Pe = visit(H, source_node)
return target_node in visited_nodes | [
"Checks if a target node is connected to a source node. That is,\n this method determines if a target node can be visited from the source\n node in the sense of the 'Visit' algorithm.\n\n Refer to 'visit's documentation for more details.\n\n :param H: the hypergraph to check connectedness on.\n :para... |
Please provide a description of the function:def is_b_connected(H, source_node, target_node):
b_visited_nodes, Pv, Pe, v = b_visit(H, source_node)
return target_node in b_visited_nodes | [
"Checks if a target node is B-connected to a source node.\n\n A node t is B-connected to a node s iff:\n - t is s, or\n - there exists an edge in the backward star of t such that all nodes in\n the tail of that edge are B-connected to s\n\n In other words, this method determines if a ... |
Please provide a description of the function:def is_f_connected(H, source_node, target_node):
f_visited_nodes, Pv, Pe, v = f_visit(H, source_node)
return target_node in f_visited_nodes | [
"Checks if a target node is F-connected to a source node.\n\n A node t is F-connected to a node s iff s if B-connected to t.\n Refer to 'f_visit's or 'is_b_connected's documentation for more details.\n\n :param H: the hypergraph to check F-connectedness on.\n :param source_node: the node to check F-conn... |
Please provide a description of the function:def get_hypertree_from_predecessors(H, Pv, source_node,
node_weights=None, attr_name="weight"):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
sub_H = Di... | [
"Gives the hypertree (i.e., the subhypergraph formed from the union of\n the set of paths from an execution of, e.g., the SBT algorithm) defined by\n Pv beginning at a source node. Returns a dictionary mapping each node to\n the ID of the hyperedge that preceeded it in the path (i.e., a Pv vector).\n As... |
Please provide a description of the function:def get_hyperpath_from_predecessors(H, Pv, source_node, destination_node,
node_weights=None, attr_name="weight"):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs... | [
"Gives the hyperpath (DirectedHypergraph) representing the shortest\n B-hyperpath from the source to the destination, given a predecessor\n function and source and destination nodes.\n\n :note: The IDs of the hyperedges in the subhypergraph returned may be\n different than those in the original hype... |
Please provide a description of the function:def to_graph_decomposition(H):
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Transformation only applicable to \
undirected Hs")
G = UndirectedHypergraph()
nodes = [(node, H.get_node_attributes(node_attributes... | [
"Returns an UndirectedHypergraph object that has the same nodes (and\n corresponding attributes) as the given H, except that for all\n hyperedges in the given H, each node in the hyperedge is pairwise\n connected to every other node also in that hyperedge in the new H.\n Said another way, each of the or... |
Please provide a description of the function:def to_networkx_graph(H):
import networkx as nx
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Transformation only applicable to \
undirected Hs")
G = to_graph_decomposition(H)
nx_graph = nx.Graph()
f... | [
"Returns a NetworkX Graph object that is the graph decomposition of\n the given H.\n See \"to_graph_decomposition()\" for more details.\n\n :param H: the H to decompose into a graph.\n :returns: nx.Graph -- NetworkX Graph object representing the\n decomposed H.\n :raises: TypeError -- Tran... |
Please provide a description of the function:def from_networkx_graph(nx_graph):
import networkx as nx
if not isinstance(nx_graph, nx.Graph):
raise TypeError("Transformation only applicable to undirected \
NetworkX graphs")
G = UndirectedHypergraph()
for node in nx... | [
"Returns an UndirectedHypergraph object that is the graph equivalent of\n the given NetworkX Graph object.\n\n :param nx_graph: the NetworkX undirected graph object to transform.\n :returns: UndirectedHypergraph -- H object equivalent to the\n NetworkX undirected graph.\n :raises: TypeError -... |
Please provide a description of the function:def stationary_distribution(H, pi=None, P=None):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to undirected hypergraphs")
for node in H.node_iterator():
if len(H.get_forward_star(node)) == 0:
r... | [
"Computes the stationary distribution of a random walk on the given\n hypergraph using the iterative approach explained in the paper:\n Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and\n application to semi-supervised image segmentation,\n Computer Vision and Image Understandin... |
Please provide a description of the function:def _compute_transition_matrix(H,
nodes_to_indices,
hyperedge_ids_to_indices):
M_out = dmat.get_tail_incidence_matrix(H,
nodes_to_indices,
... | [
"Computes the transition matrix for a random walk on the given\n hypergraph as described in the paper:\n Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and\n application to semi-supervised image segmentation,\n Computer Vision and Image Understanding, Volume 120, March 2014,\n ... |
Please provide a description of the function:def to_graph_decomposition(H):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Transformation only applicable to \
directed hypergraphs")
G = DirectedHypergraph()
nodes = [(node, H.get_node_attributes(node_attribu... | [
"Returns a DirectedHypergraph object that has the same nodes (and\n corresponding attributes) as the given hypergraph, except that for all\n hyperedges in the given hypergraph, each node in the tail of the hyperedge\n is pairwise connected to each node in the head of the hyperedge in the\n new hypergrap... |
Please provide a description of the function:def to_networkx_digraph(H):
import networkx as nx
if not isinstance(H, DirectedHypergraph):
raise TypeError("Transformation only applicable to \
directed hypergraphs")
G = to_graph_decomposition(H)
nx_graph = nx.DiGraph... | [
"Returns a NetworkX DiGraph object that is the graph decomposition of\n the given hypergraph.\n See \"to_graph_decomposition()\" for more details.\n\n :param H: the hypergraph to decompose into a graph.\n :returns: nx.DiGraph -- NetworkX DiGraph object representing the\n decomposed hypergraph... |
Please provide a description of the function:def from_networkx_digraph(nx_digraph):
import networkx as nx
if not isinstance(nx_digraph, nx.DiGraph):
raise TypeError("Transformation only applicable to directed \
NetworkX graphs")
G = DirectedHypergraph()
for node i... | [
"Returns a DirectedHypergraph object that is the graph equivalent of the\n given NetworkX DiGraph object.\n\n :param nx_digraph: the NetworkX directed graph object to transform.\n :returns: DirectedHypergraph -- hypergraph object equivalent to the\n NetworkX directed graph.\n :raises: TypeErr... |
Please provide a description of the function:def get_tail_incidence_matrix(H, nodes_to_indices, hyperedge_ids_to_indices):
if not isinstance(H, DirectedHypergraph):
raise TypeError("Algorithm only applicable to directed hypergraphs")
rows, cols = [], []
for hyperedge_id, hyperedge_index in hyp... | [
"Creates the incidence matrix of the tail nodes of the given\n hypergraph as a sparse matrix.\n\n :param H: the hypergraph for which to create the incidence matrix of.\n :param nodes_to_indices: for each node, maps the node to its\n corresponding integer index.\n :param hypere... |
Please provide a description of the function:def add_node(self, node, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# If the node hasn't previously been added, add it along
# with its attributes
if not self.has_node(node):
s... | [
"Adds a node to the graph, along with any related attributes\n of the node.\n\n :param node: reference to the node being added.\n :param attr_dict: dictionary of attributes of the node.\n :param attr: keyword arguments of attributes of the node;\n attr's values will... |
Please provide a description of the function:def add_nodes(self, nodes, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
for node in nodes:
# Note: This won't behave properly if the node is actually a tuple
if type(node) is tuple:
... | [
"Adds multiple nodes to the graph, along with any related attributes\n of the nodes.\n\n :param nodes: iterable container to either references of the nodes\n OR tuples of (node reference, attribute dictionary);\n if an attribute dictionary is provided in the t... |
Please provide a description of the function:def trim_node(self, node):
fs = self.get_forward_star(node)
bs = self.get_backward_star(node)
remove_set = set()
def get_attrs(H, hyperedge):
#copies the attribute dictionary of a hyperedge except for the head an... | [
"Removes a node from the hypergraph. Modifies hypredges with the \n trimmed node in their head or tail so that they no longer include \n the trimmed node. If a hyperedge has solely the trimmed node in its\n head or tail, that hyperedge is removed.\n \n Note: hyperedges modified th... |
Please provide a description of the function:def get_node_attribute(self, node, attribute_name):
if not self.has_node(node):
raise ValueError("No such node exists.")
elif attribute_name not in self._node_attributes[node]:
raise ValueError("No such attribute exists.")
... | [
"Given a node and the name of an attribute, get a copy\n of that node's attribute.\n\n :param node: reference to the node to retrieve the attribute of.\n :param attribute_name: name of the attribute to retrieve.\n :returns: attribute value of the attribute_name key for the\n ... |
Please provide a description of the function:def get_node_attributes(self, node):
if not self.has_node(node):
raise ValueError("No such node exists.")
attributes = {}
for attr_name, attr_value in self._node_attributes[node].items():
attributes[attr_name] = copy.c... | [
"Given a node, get a dictionary with copies of that node's\n attributes.\n\n :param node: reference to the node to retrieve the attributes of.\n :returns: dict -- copy of each attribute of the specified node.\n :raises: ValueError -- No such node exists.\n\n "
] |
Please provide a description of the function:def add_hyperedge(self, tail, head, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
# Don't allow both empty tail and head containers (invalid hyperedge)
if not tail and not head:
raise Val... | [
"Adds a hyperedge to the hypergraph, along with any related\n attributes of the hyperedge.\n This method will automatically add any node from the tail and\n head that was not in the hypergraph.\n A hyperedge without a \"weight\" attribute specified will be\n assigned the default v... |
Please provide a description of the function:def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
attr_dict = self._combine_attribute_arguments(attr_dict, attr)
hyperedge_ids = []
for hyperedge in hyperedges:
if len(hyperedge) == 3:
# See ("A", "C"... | [
"Adds multiple hyperedges to the graph, along with any related\n attributes of the hyperedges.\n If any node in the tail or head of any hyperedge has not\n previously been added to the hypergraph, it will automatically\n be added here. Hyperedges without a \"weight\" attr... |
Please provide a description of the function:def remove_hyperedge(self, hyperedge_id):
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
frozen_tail = \
self._hyperedge_attributes[hyperedge_id]["__frozen_tail"]
frozen_head... | [
"Removes a hyperedge and its attributes from the hypergraph.\n\n :param hyperedge_id: ID of the hyperedge to be removed.\n :raises: ValueError -- No such hyperedge exists.\n\n Examples:\n ::\n\n >>> H = DirectedHypergraph()\n >>> xyz = hyperedge_list = (([\"A\"], [\... |
Please provide a description of the function:def get_hyperedge_id(self, tail, head):
frozen_tail = frozenset(tail)
frozen_head = frozenset(head)
if not self.has_hyperedge(frozen_tail, frozen_head):
raise ValueError("No such hyperedge exists.")
return self._successo... | [
"From a tail and head set of nodes, returns the ID of the hyperedge\n that these sets comprise.\n\n :param tail: iterable container of references to nodes in the\n tail of the hyperedge to be added\n :param head: iterable container of references to nodes in the\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.