_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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 | 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)
| 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))
if eager:
aggregate_events.apply(
(aggregation_types,),
dict(start_date=start_date, end_date=end_date,
update_bookmark=update_bookmark),
throw=True) | 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 | 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:
aggr_cfg = current_stats.aggregations[a]
aggregator = aggr_cfg.aggregator_class(
| 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_type'] not in self.enabled_events:
continue
elif cfg['event_type'] in result:
raise DuplicateEventError(
| 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:
continue
elif cfg['aggregation_name'] in result:
raise DuplicateAggregationError(
'Duplicate aggregation {0} in entry point '
| 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['query_name'] in result:
raise DuplicateQueryError(
'Duplicate query {0} in entry point '
| python | {
"resource": ""
} |
q262008 | _InvenioStatsState.publish | validation | def publish(self, event_type, events):
"""Publish events."""
assert event_type in self.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
| 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 :attr:`Actor.sender` attribute.
:type | 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())
| python | {
"resource": ""
} |
q262012 | get_geoip | validation | def get_geoip(ip):
"""Lookup country for IP address."""
reader = geolite2.reader()
ip_data = reader.get(ip) or | 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 | 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_config[a]
| 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:
aggr_cfg = current_stats.aggregations[a]
| 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(headers))
self._return_response(response)
except Exception as e:
| 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
further secure the method, a randomly generated 32-byte salt is used, that
expires after 24 hours and is discarded. The salt values are stored in
Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``
is calculated in the same way as the ``visitor_id``, with the only
difference that it also takes into account the hour of the event . All of
these rules effectively mean that a user can have a unique ``visitor_id``
for each day and unique ``unique_session_id`` for each hour of a day.
This session ID generation process was designed according to the `Project
COUNTER Code of Practice <https://www.projectcounter.org/code-of-
practice-sections/general-information/>`_.
In addition to that the country of the user is extracted from the IP
address as a ISO 3166-1 alpha-2 two-letter country code (e.g. "CH" for
Switzerland).
"""
ip = doc.pop('ip_address', None)
if ip:
doc.update({'country': get_geoip(ip)})
user_id = doc.pop('user_id', '')
session_id = doc.pop('session_id', '')
user_agent = doc.pop('user_agent', '')
# A 'User Session' is defined as activity by a user in a period of
# one hour. timeslice represents the hour of the day in which
# the event has been generated and together with user info it determines
# the 'User Session'
timestamp = arrow.get(doc.get('timestamp'))
timeslice = timestamp.strftime('%Y%m%d%H')
salt = get_anonymization_salt(timestamp) | 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(
| python | {
"resource": ""
} |
q262020 | EventsIndexer.run | validation | def run(self):
"""Process events queue."""
return elasticsearch.helpers.bulk(
self.client,
| 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_robots,
anonymize_user,
build_file_unique_id
])),
dict(
| 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_client,
event='file-download',
aggregation_field='unique_id',
aggregation_interval='day',
copy_fields=dict(
file_key='file_key',
bucket_id='bucket_id',
file_id='file_id',
),
metric_aggregation_fields={
'unique_count': ('cardinality', 'unique_session_id',
{'precision_threshold': 1000}),
'volume': ('sum', 'size', {}),
},
)), dict(
aggregation_name='record-view-agg',
templates='invenio_stats.contrib.aggregations.aggr_record_view',
aggregator_class=StatAggregator,
aggregator_config=dict(
client=current_search_client, | 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',
copy_fields=dict(
bucket_id='bucket_id',
file_key='file_key',
),
required_filters=dict(
bucket_id='bucket_id',
file_key='file_key',
)
)
),
dict(
query_name='bucket-file-download-total',
query_class=ESTermsQuery,
query_config=dict(
| 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
| 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(
'Invalid date format for statistic {}.'
| 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)
| 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),
| 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),
| 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 exit code 127
So we catch this error upfront and print a nicer error message
with a | 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: | 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 extension causes it to be loaded
automatically by the IPython notebook.
user: [bool=None]
Whether or not the nbextension should be installed in user mode.
If this is undefined, the script will install as user mode IF the
installer is not sudo.
Usage
-----
For automatic loading:
# Assuming `./extension` is the relative path to the JS files and
# `./extension/main.js` is the file that you want automatically loaded.
setup(
name='extension',
...
cmdclass=cmdclass('extension', 'extension/main'),
)
For manual loading:
# Assuming `./extension` is the relative path to the JS files.
setup(
name='extension',
...
cmdclass=cmdclass('extension'),
)
"""
import warnings
from setuptools.command.install import install
from setuptools.command.develop import develop
from os.path import dirname, join, exists, realpath
from traceback import extract_stack
try:
# IPython/Jupyter 4.0
from notebook.nbextensions import install_nbextension
from notebook.services.config import ConfigManager
except ImportError:
# Pre-schism
try:
from IPython.html.nbextensions import install_nbextension
from IPython.html.services.config import ConfigManager
except ImportError:
warnings.warn("No jupyter notebook found in your environment. "
"Hence jupyter nbextensions were not installed. "
"If you would like to have them,"
"please issue 'pip install jupyter'.")
return {}
# Check if the user flag was set.
if user is None:
user = not _is_root()
# Get the path of the extension
calling_file = extract_stack()[-2][0]
fullpath = realpath(calling_file)
if not exists(fullpath):
raise Exception('Could not find path of setup file.') | 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'
| 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 different sub-graphs.
Options:
1. Total number of edges overlap (intersection)
2. Percentage overlap (tanimoto similarity)
:param graph: A BEL graph
:param annotation: The annotation to group by and compare. Defaults to 'Subgraph'
:return: {subgraph: set of edges}, {(subgraph 1, subgraph2): set of intersecting edges},
{(subgraph 1, subgraph2): set of unioned edges}, {(subgraph 1, subgraph2): tanimoto similarity},
"""
sg2edge = defaultdict(set)
for u, v, d in graph.edges(data=True):
if not edge_has_annotation(d, annotation):
| 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 | 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, int]]:
"""Rank sub-graphs by which have the most nodes matching an given filter.
A use case for this function would be to identify which subgraphs contain the most differentially expressed
genes.
>>> from pybel import from_pickle
>>> from | 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:
| 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[Gene] = get_nodes_by_function(graph, GENE)
hgnc_symbols = {
gene.name
for gene in genes
if gene.namespace.lower() == 'hgnc'
}
result = {}
hgnc_manager = bio2bel_hgnc.Manager()
human_genes = (
hgnc_manager.session
.query(HumanGene.symbol, HumanGene.location)
.filter(HumanGene.symbol.in_(hgnc_symbols))
.all()
)
for human_gene in human_genes:
| 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 type
:param pybel.BELGraph graph: A BEL graph
:param lax: An axis object from matplotlib
:param rax: An axis object from matplotlib
Example usage:
>>> import matplotlib.pyplot as plt
>>> from pybel import from_pickle
>>> from pybel_tools.summary import plot_summary_axes
>>> graph = from_pickle('~/dev/bms/aetionomy/parkinsons.gpickle')
>>> fig, axes = plt.subplots(1, 2, figsize=(10, 4))
>>> plot_summary_axes(graph, axes[0], axes[1])
>>> plt.tight_layout()
>>> plt.show()
"""
ntc = count_functions(graph)
etc = count_relations(graph)
| 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 | 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 Excel sheet, independent for AD and PD
df = pd.read_excel(path, sheetname=0, header=0)
# Indexes and column name
# [log.info(str(x)+': '+str((df.columns.values[x]))) for x in range | python | {
"resource": ""
} |
q262041 | preprocessing_br_projection_excel | validation | def preprocessing_br_projection_excel(path: str) -> pd.DataFrame:
"""Preprocess the excel file.
Parameters
----------
| 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.
""" | 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()
for u, v, d in cg.edges(data=True):
| 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()
for u, v, d in cg.edges(data=True):
| 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):
| 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], | 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 | 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)
for a, b, c in get_correlation_triangles(cg):
| 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)
separately_unstable_triples = get_separate_unstable_correlation_triples(graph)
mutually_unstable_triples = get_mutually_unstable_correlation_triples(graph)
jens_unstable_triples = get_jens_unstable(graph)
increase_mismatch_triples = get_increase_mismatch_triplets(graph)
decrease_mismatch_triples = get_decrease_mismatch_triplets(graph)
chaotic_triples = get_chaotic_triplets(graph)
dampened_triples = get_dampened_triplets(graph)
return {
'Regulatory Pairs': _count_or_len(regulatory_pairs),
'Chaotic Pairs': _count_or_len(chaotic_pairs),
'Dampened Pairs': _count_or_len(dampened_pairs),
'Contradictory Pairs': _count_or_len(contraditory_pairs),
| 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(
| 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 | 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, ListAbundance):
for u_member, v_member in itt.product(u.members, v.members):
graph.add_qualified_edge(
u_member, v_member,
relation=d[RELATION],
citation=d.get(CITATION),
evidence=d.get(EVIDENCE),
annotations=d.get(ANNOTATIONS),
)
elif isinstance(u, ListAbundance):
for member in u.members:
graph.add_qualified_edge(
member, v,
relation=d[RELATION],
| 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_in_reaction(u) | _get_catalysts_in_reaction(v)
for reactant, product in chain(itt.product(u.reactants, u.products),
itt.product(v.reactants, v.products)):
if reactant in enzymes or product in enzymes:
continue
graph.add_unqualified_edge(
reactant, product, INCREASES
)
for product, reactant in itt.product(u.products, u.reactants):
if reactant in enzymes or product in enzymes:
continue
graph.add_unqualified_edge(
product, reactant, d[RELATION],
)
elif isinstance(u, Reaction):
enzymes = _get_catalysts_in_reaction(u)
for product in u.products:
# Skip create increases edges between enzymes
if product in enzymes:
continue
# Only add edge between v and reaction if the node is not part of the reaction
# In practice skips hasReactant, hasProduct edges
if v not in u.products and v not in u.reactants:
graph.add_unqualified_edge(
product, v, INCREASES
)
for reactant in u.reactants:
graph.add_unqualified_edge(
reactant, product, INCREASES
| 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 {
| 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:
_reaction_cartesion_expansion_unqualified_helper(graph, u, v, d)
continue
if isinstance(u, Reaction) and isinstance(v, Reaction):
catalysts = _get_catalysts_in_reaction(u) | _get_catalysts_in_reaction(v)
for reactant, product in chain(itt.product(u.reactants, u.products), itt.product(v.reactants, v.products)):
if reactant in catalysts or product in catalysts:
continue
graph.add_increases(
reactant, product,
citation=d.get(CITATION),
evidence=d.get(EVIDENCE),
annotations=d.get(ANNOTATIONS),
)
for product, reactant in itt.product(u.products, u.reactants):
if reactant in catalysts or product in catalysts:
continue
graph.add_qualified_edge(
product, reactant,
relation=d[RELATION],
citation=d.get(CITATION),
evidence=d.get(EVIDENCE),
annotations=d.get(ANNOTATIONS),
)
elif isinstance(u, Reaction):
| 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 [
| 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))
for u, v, data in graph.edges(data=True):
| 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 = defaultdict(set)
annotation_dict_filter = build_edge_data_filter(annotations)
for u, v, _, d in filter_edges(graph, annotation_dict_filter):
| 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 {subgraph name: Counter from {citation: frequency}}
"""
citations = defaultdict(lambda: defaultdict(set))
for u, v, data in graph.edges(data=True):
if | 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."""
| 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 | 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 and converted to a set.
:return: A dictionary of {pmid: set of all evidence strings}
:rtype: dict
| 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:
| python | {
"resource": ""
} |
q262064 | get_citation_years | validation | def get_citation_years(graph: BELGraph) -> List[Tuple[int, int]]:
"""Create | 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) | 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
| 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_pmids(manager=manager, pmids=pmids)
for u, v, k in filter_edges(graph, has_pubmed):
pmid = graph[u][v][k][CITATION][CITATION_REFERENCE].strip()
| 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 namespace in universe.namespace_pattern:
graph.namespace_pattern[namespace] = universe.namespace_pattern[namespace]
else:
log.warning('namespace: %s missing from universe', namespace)
for annotation in get_annotations(graph):
if annotation in universe.annotation_url:
graph.annotation_url[annotation] = universe.annotation_url[annotation]
elif annotation | 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: | 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.
| 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 (use something that works with CSS)
"""
| 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 | 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 | 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.
| 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 | python | {
"resource": ""
} |
q262078 | count_top_centrality | validation | def count_top_centrality(graph: BELGraph, number: Optional[int] = 30) -> Mapping[BaseEntity, int]:
"""Get top centrality dictionary."""
| 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)),
| 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 {
| 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):
| python | {
"resource": ""
} |
q262082 | _collapse_edge_passing_predicates | validation | def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:
"""Collapse all | 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.
:param graph: A BEL Graph
:param victim_namespaces: The namespace(s) of the node to collapse
:param survivor_namespaces: The namespace of the node to keep
:param relations: The relation(s) to search
"""
| 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 survivor_namespace: The namespace of the node to keep
To collapse all MGI nodes to their HGNC orthologs, use:
>>> collapse_orthologies_by_namespace('MGI', | 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_predicates = [
| 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:
| 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(graph, r=2), total=graph.number_of_nodes() * (graph.number_of_nodes() - 1) / 2)
for a, b in it:
if b in victims:
continue
a_name, b_name = a.get(NAME), b.get(NAME)
if not a_name or not b_name or a_name.lower() != b_name.lower():
continue
| python | {
"resource": ""
} |
q262088 | main | validation | def main(output):
"""Output the HBP knowledge graph to the desktop"""
from hbp_knowledge import get_graph
| 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 | 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: The key in the node data dictionary representing the experimental data. Defaults to
:data:`pybel_tools.constants.WEIGHT`.
| 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.
| 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
| 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 | 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 | 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 | 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[float] = None,
topology_weight: Optional[float] = None,
preprocess: bool = False
) -> Optional[Mapping[str, float]]:
"""Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each.
:param graph: A BEL graph
:param genes: A list of gene nodes
:param annotation: The annotation to use to stratify the graph to subgraphs
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_gene_ora`. Defaults to 1.0.
:param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.
Defaults to 1.0.
:param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).
:param topology_weight: The relative weight of the topolgical analysis core from
| 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,
top_percent: Optional[float] = None,
topology_weight: Optional[float] = None,
) -> Optional[Mapping[str, float]]:
"""Takes a graph stratification and runs neurommsig on each
:param subgraphs: A pre-stratified set of graphs
:param genes: A list of gene nodes
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_gene_ora`. Defaults to 1.0.
:param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.
Defaults to 1.0.
:param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).
:param topology_weight: The relative weight of the topolgical analysis core | 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[float] = None) -> float:
"""Calculate the composite NeuroMMSig Score for a given list of genes.
:param graph: A BEL graph
:param genes: A list of gene nodes
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_gene_ora`. Defaults to 1.0.
:param hub_weight: The relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.
Defaults to 1.0.
:param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).
:param topology_weight: The relative weight of the topolgical analysis core from
:py:func:`neurommsig_topology`. Defaults to 1.0.
:return: The NeuroMMSig composite score
| 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 number_nodes <= 1:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.