_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q262000 | Future.get | validation | def get(self, timeout=None):
"""
Return value on success, or raise exception on failure.
"""
result = None
try:
result = self._result.get(True, timeout=timeout)
except Empty:
raise Timeout()
if isinstance(result, Failure):
six.... | python | {
"resource": ""
} |
q262001 | _events_process | validation | def _events_process(event_types=None, eager=False):
"""Process stats events."""
event_types = event_types or list(current_stats.enabled_events)
if eager:
process_events.apply((event_types,), throw=True)
click.secho('Events processed successfully.', fg='green')
else:
process_event... | python | {
"resource": ""
} |
q262002 | _aggregations_process | validation | def _aggregations_process(aggregation_types=None,
start_date=None, end_date=None,
update_bookmark=False, eager=False):
"""Process stats aggregations."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations)... | python | {
"resource": ""
} |
q262003 | _aggregations_delete | validation | def _aggregations_delete(aggregation_types=None,
start_date=None, end_date=None):
"""Delete computed aggregations."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations))
for a in aggregation_types:
aggr_cfg = current_s... | python | {
"resource": ""
} |
q262004 | _aggregations_list_bookmarks | validation | def _aggregations_list_bookmarks(aggregation_types=None,
start_date=None, end_date=None, limit=None):
"""List aggregation bookmarks."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations))
for a in aggregation_types:
... | python | {
"resource": ""
} |
q262005 | _InvenioStatsState._events_config | validation | def _events_config(self):
"""Load events configuration."""
# import iter_entry_points here so that it can be mocked in tests
result = {}
for ep in iter_entry_points(
group=self.entry_point_group_events):
for cfg in ep.load()():
if cfg['event_ty... | python | {
"resource": ""
} |
q262006 | _InvenioStatsState._aggregations_config | validation | def _aggregations_config(self):
"""Load aggregation configurations."""
result = {}
for ep in iter_entry_points(
group=self.entry_point_group_aggs):
for cfg in ep.load()():
if cfg['aggregation_name'] not in self.enabled_aggregations:
... | python | {
"resource": ""
} |
q262007 | _InvenioStatsState._queries_config | validation | def _queries_config(self):
"""Load queries configuration."""
result = {}
for ep in iter_entry_points(group=self.entry_point_group_queries):
for cfg in ep.load()():
if cfg['query_name'] not in self.enabled_queries:
continue
elif cfg[... | python | {
"resource": ""
} |
q262008 | _InvenioStatsState.publish | validation | def publish(self, event_type, events):
"""Publish events."""
assert event_type in self.events
current_queues.queues['stats-{}'.format(event_type)].publish(events) | python | {
"resource": ""
} |
q262009 | _InvenioStatsState.consume | validation | def consume(self, event_type, no_ack=True, payload=True):
"""Comsume all pending events."""
assert event_type in self.events
return current_queues.queues['stats-{}'.format(event_type)].consume(
payload=payload) | python | {
"resource": ""
} |
q262010 | ActorRef.tell | validation | def tell(self, message, sender=no_sender):
""" Send a message to this actor. Asynchronous fire-and-forget.
:param message: The message to send.
:type message: Any
:param sender: The sender of the message. If provided it will be made
available to the receiving actor via the ... | python | {
"resource": ""
} |
q262011 | get_anonymization_salt | validation | def get_anonymization_salt(ts):
"""Get the anonymization salt based on the event timestamp's day."""
salt_key = 'stats:salt:{}'.format(ts.date().isoformat())
salt = current_cache.get(salt_key)
if not salt:
salt_bytes = os.urandom(32)
salt = b64encode(salt_bytes).decode('utf-8')
c... | python | {
"resource": ""
} |
q262012 | get_geoip | validation | def get_geoip(ip):
"""Lookup country for IP address."""
reader = geolite2.reader()
ip_data = reader.get(ip) or {}
return ip_data.get('country', {}).get('iso_code') | python | {
"resource": ""
} |
q262013 | get_user | validation | def get_user():
"""User information.
.. note::
**Privacy note** A users IP address, user agent string, and user id
(if logged in) is sent to a message queue, where it is stored for about
5 minutes. The information is used to:
- Detect robot visits from the user agent string.
... | python | {
"resource": ""
} |
q262014 | default_permission_factory | validation | def default_permission_factory(query_name, params):
"""Default permission factory.
It enables by default the statistics if they don't have a dedicated
permission factory.
"""
from invenio_stats import current_stats
if current_stats.queries[query_name].permission_factory is None:
return ... | python | {
"resource": ""
} |
q262015 | register_templates | validation | def register_templates():
"""Register elasticsearch templates for events."""
event_templates = [current_stats._events_config[e]
['templates']
for e in
current_stats._events_config]
aggregation_templates = [current_stats._aggregations_confi... | python | {
"resource": ""
} |
q262016 | aggregate_events | validation | def aggregate_events(aggregations, start_date=None, end_date=None,
update_bookmark=True):
"""Aggregate indexed events."""
start_date = dateutil_parse(start_date) if start_date else None
end_date = dateutil_parse(end_date) if end_date else None
results = []
for a in aggregations:... | python | {
"resource": ""
} |
q262017 | ProxyRequestHandler._handle_request | validation | def _handle_request(self, scheme, netloc, path, headers, body=None, method="GET"):
"""
Run the actual request
"""
backend_url = "{}://{}{}".format(scheme, netloc, path)
try:
response = self.http_request.request(backend_url, method=method, body=body, headers=dict(heade... | python | {
"resource": ""
} |
q262018 | anonymize_user | validation | def anonymize_user(doc):
"""Preprocess an event by anonymizing user information.
The anonymization is done by removing fields that can uniquely identify a
user, such as the user's ID, session ID, IP address and User Agent, and
hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
f... | python | {
"resource": ""
} |
q262019 | hash_id | validation | def hash_id(iso_timestamp, msg):
"""Generate event id, optimized for ES."""
return '{0}-{1}'.format(iso_timestamp,
hashlib.sha1(
msg.get('unique_id').encode('utf-8') +
str(msg.get('visitor_id')).
... | python | {
"resource": ""
} |
q262020 | EventsIndexer.run | validation | def run(self):
"""Process events queue."""
return elasticsearch.helpers.bulk(
self.client,
self.actionsiter(),
stats_only=True,
chunk_size=50
) | python | {
"resource": ""
} |
q262021 | register_events | validation | def register_events():
"""Register sample events."""
return [
dict(
event_type='file-download',
templates='invenio_stats.contrib.file_download',
processor_class=EventsIndexer,
processor_config=dict(
preprocessors=[
flag_... | python | {
"resource": ""
} |
q262022 | register_aggregations | validation | def register_aggregations():
"""Register sample aggregations."""
return [dict(
aggregation_name='file-download-agg',
templates='invenio_stats.contrib.aggregations.aggr_file_download',
aggregator_class=StatAggregator,
aggregator_config=dict(
client=current_search_clien... | python | {
"resource": ""
} |
q262023 | register_queries | validation | def register_queries():
"""Register queries."""
return [
dict(
query_name='bucket-file-download-histogram',
query_class=ESDateHistogramQuery,
query_config=dict(
index='stats-file-download',
doc_type='file-download-day-aggregation',
... | python | {
"resource": ""
} |
q262024 | QueryParser._parse_time | validation | def _parse_time(self, tokens):
"""
Parse the date range for the query
E.g. WHERE time > now() - 48h AND time < now() - 24h
would result in DateRange(datetime_start, datetime_end)
where
datetime_start would be parsed from now() - 48h
and
datetime_end would... | python | {
"resource": ""
} |
q262025 | ESQuery.extract_date | validation | def extract_date(self, date):
"""Extract date from string if necessary.
:returns: the extracted date.
"""
if isinstance(date, six.string_types):
try:
date = dateutil.parser.parse(date)
except ValueError:
raise ValueError(
... | python | {
"resource": ""
} |
q262026 | ESTermsQuery.run | validation | def run(self, start_date=None, end_date=None, **kwargs):
"""Run the query."""
start_date = self.extract_date(start_date) if start_date else None
end_date = self.extract_date(end_date) if end_date else None
self.validate_arguments(start_date, end_date, **kwargs)
agg_query = self.... | python | {
"resource": ""
} |
q262027 | file_download_event_builder | validation | def file_download_event_builder(event, sender_app, obj=None, **kwargs):
"""Build a file-download event."""
event.update(dict(
# When:
timestamp=datetime.datetime.utcnow().isoformat(),
# What:
bucket_id=str(obj.bucket_id),
file_id=str(obj.file_id),
file_key=obj.key... | python | {
"resource": ""
} |
q262028 | record_view_event_builder | validation | def record_view_event_builder(event, sender_app, pid=None, record=None,
**kwargs):
"""Build a record-view event."""
event.update(dict(
# When:
timestamp=datetime.datetime.utcnow().isoformat(),
# What:
record_id=str(record.id),
pid_type=pid.pi... | python | {
"resource": ""
} |
q262029 | check_write_permissions | validation | def check_write_permissions(file):
"""
Check if we can write to the given file
Otherwise since we might detach the process to run in the background
we might never find out that writing failed and get an ugly
exit message on startup. For example:
ERROR: Child exited immediately with non-zero exi... | python | {
"resource": ""
} |
q262030 | _is_root | validation | def _is_root():
"""Checks if the user is rooted."""
import os
import ctypes
try:
return os.geteuid() == 0
except AttributeError:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
return False | python | {
"resource": ""
} |
q262031 | cmdclass | validation | def cmdclass(path, enable=None, user=None):
"""Build nbextension cmdclass dict for the setuptools.setup method.
Parameters
----------
path: str
Directory relative to the setup file that the nbextension code
lives in.
enable: [str=None]
Extension to "enable". Enabling an ext... | python | {
"resource": ""
} |
q262032 | count_subgraph_sizes | validation | def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]:
"""Count the number of nodes in each subgraph induced by an annotation.
:param annotation: The annotation to group by and compare. Defaults to 'Subgraph'
:return: A dictionary from {annotation value: number of nodes}
... | python | {
"resource": ""
} |
q262033 | calculate_subgraph_edge_overlap | validation | def calculate_subgraph_edge_overlap(
graph: BELGraph,
annotation: str = 'Subgraph'
) -> Tuple[
Mapping[str, EdgeSet],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, float]],
]:
"""Build a DatafFame to show the overlap between diffe... | python | {
"resource": ""
} |
q262034 | summarize_subgraph_node_overlap | validation | def summarize_subgraph_node_overlap(graph: BELGraph, node_predicates=None, annotation: str = 'Subgraph'):
"""Calculate the subgraph similarity tanimoto similarity in nodes passing the given filter.
Provides an alternate view on subgraph similarity, from a more node-centric view
"""
r1 = group_nodes_by_... | python | {
"resource": ""
} |
q262035 | rank_subgraph_by_node_filter | validation | def rank_subgraph_by_node_filter(graph: BELGraph,
node_predicates: Union[NodePredicate, Iterable[NodePredicate]],
annotation: str = 'Subgraph',
reverse: bool = True,
) -> List[Tuple[str, i... | python | {
"resource": ""
} |
q262036 | to_jupyter | validation | def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript:
"""Render the graph as JavaScript in a Jupyter Notebook."""
with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f:
js_template = Template(f.read())
return Javascript(js_template.render(**_get_context(graph, ... | python | {
"resource": ""
} |
q262037 | prerender | validation | def prerender(graph: BELGraph) -> Mapping[str, Mapping[str, Any]]:
"""Generate the annotations JSON for Ideogram."""
import bio2bel_hgnc
from bio2bel_hgnc.models import HumanGene
graph: BELGraph = graph.copy()
enrich_protein_and_rna_origins(graph)
collapse_all_variants(graph)
genes: Set[Gen... | python | {
"resource": ""
} |
q262038 | plot_summary_axes | validation | def plot_summary_axes(graph: BELGraph, lax, rax, logx=True):
"""Plots your graph summary statistics on the given axes.
After, you should run :func:`plt.tight_layout` and you must run :func:`plt.show` to view.
Shows:
1. Count of nodes, grouped by function type
2. Count of edges, grouped by relation... | python | {
"resource": ""
} |
q262039 | remove_nodes_by_function_namespace | validation | def remove_nodes_by_function_namespace(graph: BELGraph, func: str, namespace: Strings) -> None:
"""Remove nodes with the given function and namespace.
This might be useful to exclude information learned about distant species, such as excluding all information
from MGI and RGD in diseases where mice and rat... | python | {
"resource": ""
} |
q262040 | preprocessing_excel | validation | def preprocessing_excel(path):
"""Preprocess the excel sheet
:param filepath: filepath of the excel data
:return: df: pandas dataframe with excel data
:rtype: pandas.DataFrame
"""
if not os.path.exists(path):
raise ValueError("Error: %s file not found" % path)
# Import Models from ... | python | {
"resource": ""
} |
q262041 | preprocessing_br_projection_excel | validation | def preprocessing_br_projection_excel(path: str) -> pd.DataFrame:
"""Preprocess the excel file.
Parameters
----------
path : Filepath of the excel sheet
"""
if not os.path.exists(path):
raise ValueError("Error: %s file not found" % path)
return pd.read_excel(path, sheetname=0, head... | python | {
"resource": ""
} |
q262042 | get_nift_values | validation | def get_nift_values() -> Mapping[str, str]:
"""Extract the list of NIFT names from the BEL resource and builds a dictionary mapping from the lowercased version
to the uppercase version.
"""
r = get_bel_resource(NIFT)
return {
name.lower(): name
for name in r['Values']
} | python | {
"resource": ""
} |
q262043 | get_regulatory_pairs | validation | def get_regulatory_pairs(graph: BELGraph) -> Set[NodePair]:
"""Find pairs of nodes that have mutual causal edges that are regulating each other such that ``A -> B`` and
``B -| A``.
:return: A set of pairs of nodes with mutual causal edges
"""
cg = get_causal_subgraph(graph)
results = set()
... | python | {
"resource": ""
} |
q262044 | get_chaotic_pairs | validation | def get_chaotic_pairs(graph: BELGraph) -> SetOfNodePairs:
"""Find pairs of nodes that have mutual causal edges that are increasing each other such that ``A -> B`` and
``B -> A``.
:return: A set of pairs of nodes with mutual causal edges
"""
cg = get_causal_subgraph(graph)
results = set()
... | python | {
"resource": ""
} |
q262045 | get_correlation_graph | validation | def get_correlation_graph(graph: BELGraph) -> Graph:
"""Extract an undirected graph of only correlative relationships."""
result = Graph()
for u, v, d in graph.edges(data=True):
if d[RELATION] not in CORRELATIVE_RELATIONS:
continue
if not result.has_edge(u, v):
resu... | python | {
"resource": ""
} |
q262046 | get_correlation_triangles | validation | def get_correlation_triangles(graph: BELGraph) -> SetOfNodeTriples:
"""Return a set of all triangles pointed by the given node."""
return {
tuple(sorted([n, u, v], key=str))
for n in graph
for u, v in itt.combinations(graph[n], 2)
if graph.has_edge(u, v)
} | python | {
"resource": ""
} |
q262047 | get_triangles | validation | def get_triangles(graph: DiGraph) -> SetOfNodeTriples:
"""Get a set of triples representing the 3-cycles from a directional graph.
Each 3-cycle is returned once, with nodes in sorted order.
"""
return {
tuple(sorted([a, b, c], key=str))
for a, b in graph.edges()
for c in graph.s... | python | {
"resource": ""
} |
q262048 | get_separate_unstable_correlation_triples | validation | def get_separate_unstable_correlation_triples(graph: BELGraph) -> Iterable[NodeTriple]:
"""Yield all triples of nodes A, B, C such that ``A pos B``, ``A pos C``, and ``B neg C``.
:return: An iterator over triples of unstable graphs, where the second two are negative
"""
cg = get_correlation_graph(graph... | python | {
"resource": ""
} |
q262049 | summarize_stability | validation | def summarize_stability(graph: BELGraph) -> Mapping[str, int]:
"""Summarize the stability of the graph."""
regulatory_pairs = get_regulatory_pairs(graph)
chaotic_pairs = get_chaotic_pairs(graph)
dampened_pairs = get_dampened_pairs(graph)
contraditory_pairs = get_contradiction_summary(graph)
sepa... | python | {
"resource": ""
} |
q262050 | flatten_list_abundance | validation | def flatten_list_abundance(node: ListAbundance) -> ListAbundance:
"""Flattens the complex or composite abundance."""
return node.__class__(list(chain.from_iterable(
(
flatten_list_abundance(member).members
if isinstance(member, ListAbundance) else
[member]
)
... | python | {
"resource": ""
} |
q262051 | list_abundance_expansion | validation | def list_abundance_expansion(graph: BELGraph) -> None:
"""Flatten list abundances."""
mapping = {
node: flatten_list_abundance(node)
for node in graph
if isinstance(node, ListAbundance)
}
relabel_nodes(graph, mapping, copy=False) | python | {
"resource": ""
} |
q262052 | list_abundance_cartesian_expansion | validation | def list_abundance_cartesian_expansion(graph: BELGraph) -> None:
"""Expand all list abundances to simple subject-predicate-object networks."""
for u, v, k, d in list(graph.edges(keys=True, data=True)):
if CITATION not in d:
continue
if isinstance(u, ListAbundance) and isinstance(v, ... | python | {
"resource": ""
} |
q262053 | _reaction_cartesion_expansion_unqualified_helper | validation | def _reaction_cartesion_expansion_unqualified_helper(
graph: BELGraph,
u: BaseEntity,
v: BaseEntity,
d: dict,
) -> None:
"""Helper to deal with cartension expansion in unqualified edges."""
if isinstance(u, Reaction) and isinstance(v, Reaction):
enzymes = _get_catalysts_i... | python | {
"resource": ""
} |
q262054 | _get_catalysts_in_reaction | validation | def _get_catalysts_in_reaction(reaction: Reaction) -> Set[BaseAbundance]:
"""Return nodes that are both in reactants and reactions in a reaction."""
return {
reactant
for reactant in reaction.reactants
if reactant in reaction.products
} | python | {
"resource": ""
} |
q262055 | reaction_cartesian_expansion | validation | def reaction_cartesian_expansion(graph: BELGraph, accept_unqualified_edges: bool = True) -> None:
"""Expand all reactions to simple subject-predicate-object networks."""
for u, v, d in list(graph.edges(data=True)):
# Deal with unqualified edges
if CITATION not in d and accept_unqualified_edges:
... | python | {
"resource": ""
} |
q262056 | DictManager.get_graphs_by_ids | validation | def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]:
"""Get several graphs by their identifiers."""
return [
self.networks[network_id]
for network_id in network_ids
] | python | {
"resource": ""
} |
q262057 | _generate_citation_dict | validation | def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, BaseEntity], str]]:
"""Prepare a citation data dictionary from a graph.
:return: A dictionary of dictionaries {citation type: {(source, target): citation reference}
"""
results = defaultdict(lambda: defaultdict(set))... | python | {
"resource": ""
} |
q262058 | count_citations | validation | def count_citations(graph: BELGraph, **annotations) -> Counter:
"""Counts the citations in a graph based on a given filter
:param graph: A BEL graph
:param dict annotations: The annotation filters to use
:return: A counter from {(citation type, citation reference): frequency}
"""
citations = de... | python | {
"resource": ""
} |
q262059 | count_citations_by_annotation | validation | def count_citations_by_annotation(graph: BELGraph, annotation: str) -> Mapping[str, typing.Counter[str]]:
"""Group the citation counters by subgraphs induced by the annotation.
:param graph: A BEL graph
:param annotation: The annotation to use to group the graph
:return: A dictionary of Counters {subgr... | python | {
"resource": ""
} |
q262060 | count_author_publications | validation | def count_author_publications(graph: BELGraph) -> typing.Counter[str]:
"""Count the number of publications of each author to the given graph."""
authors = group_as_dict(_iter_author_publiations(graph))
return Counter(count_dict_values(count_defaultdict(authors))) | python | {
"resource": ""
} |
q262061 | count_authors_by_annotation | validation | def count_authors_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, typing.Counter[str]]:
"""Group the author counters by sub-graphs induced by the annotation.
:param graph: A BEL graph
:param annotation: The annotation to use to group the graph
:return: A dictionary of Count... | python | {
"resource": ""
} |
q262062 | get_evidences_by_pmid | validation | def get_evidences_by_pmid(graph: BELGraph, pmids: Union[str, Iterable[str]]):
"""Get a dictionary from the given PubMed identifiers to the sets of all evidence strings associated with each
in the graph.
:param graph: A BEL graph
:param pmids: An iterable of PubMed identifiers, as strings. Is consumed a... | python | {
"resource": ""
} |
q262063 | count_citation_years | validation | def count_citation_years(graph: BELGraph) -> typing.Counter[int]:
"""Count the number of citations from each year."""
result = defaultdict(set)
for _, _, data in graph.edges(data=True):
if CITATION not in data or CITATION_DATE not in data[CITATION]:
continue
try:
dt... | python | {
"resource": ""
} |
q262064 | get_citation_years | validation | def get_citation_years(graph: BELGraph) -> List[Tuple[int, int]]:
"""Create a citation timeline counter from the graph."""
return create_timeline(count_citation_years(graph)) | python | {
"resource": ""
} |
q262065 | create_timeline | validation | def create_timeline(year_counter: typing.Counter[int]) -> List[Tuple[int, int]]:
"""Complete the Counter timeline.
:param Counter year_counter: counter dict for each year
:return: complete timeline
"""
if not year_counter:
return []
from_year = min(year_counter) - 1
until_year = da... | python | {
"resource": ""
} |
q262066 | count_confidences | validation | def count_confidences(graph: BELGraph) -> typing.Counter[str]:
"""Count the confidences in the graph."""
return Counter(
(
'None'
if ANNOTATIONS not in data or 'Confidence' not in data[ANNOTATIONS] else
list(data[ANNOTATIONS]['Confidence'])[0]
)
for _,... | python | {
"resource": ""
} |
q262067 | enrich_pubmed_citations | validation | def enrich_pubmed_citations(graph: BELGraph, manager: Manager) -> Set[str]:
"""Overwrite all PubMed citations with values from NCBI's eUtils lookup service.
:return: A set of PMIDs for which the eUtils service crashed
"""
pmids = get_pubmed_identifiers(graph)
pmid_data, errors = get_citations_by_pm... | python | {
"resource": ""
} |
q262068 | update_context | validation | def update_context(universe: BELGraph, graph: BELGraph):
"""Update the context of a subgraph from the universe of all knowledge."""
for namespace in get_namespaces(graph):
if namespace in universe.namespace_url:
graph.namespace_url[namespace] = universe.namespace_url[namespace]
elif ... | python | {
"resource": ""
} |
q262069 | highlight_nodes | validation | def highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]] = None, color: Optional[str]=None):
"""Adds a highlight tag to the given nodes.
:param graph: A BEL graph
:param nodes: The nodes to add a highlight tag on
:param color: The color to highlight (use something that works with CSS)... | python | {
"resource": ""
} |
q262070 | is_node_highlighted | validation | def is_node_highlighted(graph: BELGraph, node: BaseEntity) -> bool:
"""Returns if the given node is highlighted.
:param graph: A BEL graph
:param node: A BEL node
:type node: tuple
:return: Does the node contain highlight information?
:rtype: bool
"""
return NODE_HIGHLIGHT in graph.node... | python | {
"resource": ""
} |
q262071 | remove_highlight_nodes | validation | def remove_highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]]=None) -> None:
"""Removes the highlight from the given nodes, or all nodes if none given.
:param graph: A BEL graph
:param nodes: The list of nodes to un-highlight
"""
for node in graph if nodes is None else nodes:
... | python | {
"resource": ""
} |
q262072 | highlight_edges | validation | def highlight_edges(graph: BELGraph, edges=None, color: Optional[str]=None) -> None:
"""Adds a highlight tag to the given edges.
:param graph: A BEL graph
:param edges: The edges (4-tuples of u, v, k, d) to add a highlight tag on
:type edges: iter[tuple]
:param str color: The color to highlight (us... | python | {
"resource": ""
} |
q262073 | remove_highlight_edges | validation | def remove_highlight_edges(graph: BELGraph, edges=None):
"""Remove the highlight from the given edges, or all edges if none given.
:param graph: A BEL graph
:param edges: The edges (4-tuple of u,v,k,d) to remove the highlight from)
:type edges: iter[tuple]
"""
for u, v, k, _ in graph.edges(keys... | python | {
"resource": ""
} |
q262074 | get_causal_out_edges | validation | def get_causal_out_edges(
graph: BELGraph,
nbunch: Union[BaseEntity, Iterable[BaseEntity]],
) -> Set[Tuple[BaseEntity, BaseEntity]]:
"""Get the out-edges to the given node that are causal.
:return: A set of (source, target) pairs where the source is the given node
"""
return {
(... | python | {
"resource": ""
} |
q262075 | get_causal_source_nodes | validation | def get_causal_source_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:
"""Return a set of all nodes that have an in-degree of 0.
This likely means that it is an external perturbagen and is not known to have any causal origin from within the
biological system. These nodes are useful to identify because... | python | {
"resource": ""
} |
q262076 | get_causal_central_nodes | validation | def get_causal_central_nodes(graph: BELGraph, func: str) -> Set[BaseEntity]:
"""Return a set of all nodes that have both an in-degree > 0 and out-degree > 0.
This means that they are an integral part of a pathway, since they are both produced and consumed.
"""
return {
node
for node in ... | python | {
"resource": ""
} |
q262077 | get_causal_sink_nodes | validation | def get_causal_sink_nodes(graph: BELGraph, func) -> Set[BaseEntity]:
"""Returns a set of all ABUNDANCE nodes that have an causal out-degree of 0.
This likely means that the knowledge assembly is incomplete, or there is a curation error.
"""
return {
node
for node in graph
if nod... | python | {
"resource": ""
} |
q262078 | count_top_centrality | validation | def count_top_centrality(graph: BELGraph, number: Optional[int] = 30) -> Mapping[BaseEntity, int]:
"""Get top centrality dictionary."""
dd = nx.betweenness_centrality(graph)
dc = Counter(dd)
return dict(dc.most_common(number)) | python | {
"resource": ""
} |
q262079 | get_modifications_count | validation | def get_modifications_count(graph: BELGraph) -> Mapping[str, int]:
"""Get a modifications count dictionary."""
return remove_falsy_values({
'Translocations': len(get_translocated(graph)),
'Degradations': len(get_degradations(graph)),
'Molecular Activities': len(get_activities(graph)),
... | python | {
"resource": ""
} |
q262080 | remove_falsy_values | validation | def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:
"""Remove all values that are zero."""
return {
label: count
for label, count in counter.items()
if count
} | python | {
"resource": ""
} |
q262081 | _collapse_variants_by_function | validation | def _collapse_variants_by_function(graph: BELGraph, func: str) -> None:
"""Collapse all of the given functions' variants' edges to their parents, in-place."""
for parent_node, variant_node, data in graph.edges(data=True):
if data[RELATION] == HAS_VARIANT and parent_node.function == func:
col... | python | {
"resource": ""
} |
q262082 | _collapse_edge_passing_predicates | validation | def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:
"""Collapse all edges passing the given edge predicates."""
for u, v, _ in filter_edges(graph, edge_predicates=edge_predicates):
collapse_pair(graph, survivor=u, victim=v) | python | {
"resource": ""
} |
q262083 | _collapse_edge_by_namespace | validation | def _collapse_edge_by_namespace(graph: BELGraph,
victim_namespaces: Strings,
survivor_namespaces: str,
relations: Strings) -> None:
"""Collapse pairs of nodes with the given namespaces that have the given relationship.
... | python | {
"resource": ""
} |
q262084 | collapse_orthologies_by_namespace | validation | def collapse_orthologies_by_namespace(graph: BELGraph, victim_namespace: Strings, survivor_namespace: str) -> None:
"""Collapse pairs of nodes with the given namespaces that have orthology relationships.
:param graph: A BEL Graph
:param victim_namespace: The namespace(s) of the node to collapse
:param ... | python | {
"resource": ""
} |
q262085 | collapse_entrez_equivalencies | validation | def collapse_entrez_equivalencies(graph: BELGraph):
"""Collapse all equivalence edges away from Entrez. Assumes well formed, 2-way equivalencies."""
relation_filter = build_relation_predicate(EQUIVALENT_TO)
source_namespace_filter = build_source_namespace_filter(['EGID', 'EG', 'ENTREZ'])
edge_predicate... | python | {
"resource": ""
} |
q262086 | collapse_consistent_edges | validation | def collapse_consistent_edges(graph: BELGraph):
"""Collapse consistent edges together.
.. warning:: This operation doesn't preserve evidences or other annotations
"""
for u, v in graph.edges():
relation = pair_is_consistent(graph, u, v)
if not relation:
continue
ed... | python | {
"resource": ""
} |
q262087 | collapse_nodes_with_same_names | validation | def collapse_nodes_with_same_names(graph: BELGraph) -> None:
"""Collapse all nodes with the same name, merging namespaces by picking first alphabetical one."""
survivor_mapping = defaultdict(set) # Collapse mapping dict
victims = set() # Things already mapped while iterating
it = tqdm(itt.combinations(... | python | {
"resource": ""
} |
q262088 | main | validation | def main(output):
"""Output the HBP knowledge graph to the desktop"""
from hbp_knowledge import get_graph
graph = get_graph()
text = to_html(graph)
print(text, file=output) | python | {
"resource": ""
} |
q262089 | node_is_upstream_leaf | validation | def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:
"""Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.
"""
return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node)) | python | {
"resource": ""
} |
q262090 | get_unweighted_upstream_leaves | validation | def get_unweighted_upstream_leaves(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:
"""Get nodes with no incoming edges, one outgoing edge, and without the given key in its data dictionary.
.. seealso :: :func:`data_does_not_contain_key_builder`
:param graph: A BEL graph
:param key... | python | {
"resource": ""
} |
q262091 | is_unweighted_source | validation | def is_unweighted_source(graph: BELGraph, node: BaseEntity, key: str) -> bool:
"""Check if the node is both a source and also has an annotation.
:param graph: A BEL graph
:param node: A BEL node
:param key: The key in the node data dictionary representing the experimental data
"""
return graph.... | python | {
"resource": ""
} |
q262092 | get_unweighted_sources | validation | def get_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:
"""Get nodes on the periphery of the sub-graph that do not have a annotation for the given key.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data
:r... | python | {
"resource": ""
} |
q262093 | remove_unweighted_sources | validation | def remove_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> None:
"""Prune unannotated nodes on the periphery of the sub-graph.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data. Defaults to
:data:`pybel_tools.constants.WEIGHT... | python | {
"resource": ""
} |
q262094 | prune_mechanism_by_data | validation | def prune_mechanism_by_data(graph, key: Optional[str] = None) -> None:
"""Remove all leaves and source nodes that don't have weights.
Is a thin wrapper around :func:`remove_unweighted_leaves` and :func:`remove_unweighted_sources`
:param graph: A BEL graph
:param key: The key in the node data dictiona... | python | {
"resource": ""
} |
q262095 | generate_mechanism | validation | def generate_mechanism(graph: BELGraph, node: BaseEntity, key: Optional[str] = None) -> BELGraph:
"""Generate a mechanistic sub-graph upstream of the given node.
:param graph: A BEL graph
:param node: A BEL node
:param key: The key in the node data dictionary representing the experimental data.
:re... | python | {
"resource": ""
} |
q262096 | get_neurommsig_scores | validation | def get_neurommsig_scores(graph: BELGraph,
genes: List[Gene],
annotation: str = 'Subgraph',
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
top_percent: Optional[floa... | python | {
"resource": ""
} |
q262097 | get_neurommsig_scores_prestratified | validation | def get_neurommsig_scores_prestratified(subgraphs: Mapping[str, BELGraph],
genes: List[Gene],
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
... | python | {
"resource": ""
} |
q262098 | get_neurommsig_score | validation | def get_neurommsig_score(graph: BELGraph,
genes: List[Gene],
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
top_percent: Optional[float] = None,
topology_weight: Optional... | python | {
"resource": ""
} |
q262099 | neurommsig_topology | validation | def neurommsig_topology(graph: BELGraph, nodes: List[BaseEntity]) -> float:
"""Calculate the node neighbor score for a given list of nodes.
- Doesn't consider self loops
.. math::
\frac{\sum_i^n N_G[i]}{n*(n-1)}
"""
nodes = list(nodes)
number_nodes = len(nodes)
if n... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.