repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.drop_edges
def drop_edges(self) -> None: """Drop all edges in the database.""" t = time.time() self.session.query(Edge).delete() self.session.commit() log.info('dropped all edges in %.2f seconds', time.time() - t)
python
def drop_edges(self) -> None: """Drop all edges in the database.""" t = time.time() self.session.query(Edge).delete() self.session.commit() log.info('dropped all edges in %.2f seconds', time.time() - t)
[ "def", "drop_edges", "(", "self", ")", "->", "None", ":", "t", "=", "time", ".", "time", "(", ")", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "delete", "(", ")", "self", ".", "session", ".", "commit", "(", ")", "log", ".", "in...
Drop all edges in the database.
[ "Drop", "all", "edges", "in", "the", "database", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L892-L899
train
29,600
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.get_or_create_edge
def get_or_create_edge(self, source: Node, target: Node, relation: str, bel: str, sha512: str, data: EdgeData, evidence: Optional[Evidence] = None, annotations: Optional[List[NamespaceEntry]] = None, properties: Optional[List[Property]] = None, ) -> Edge: """Create an edge if it does not exist, or return it if it does. :param source: Source node of the relation :param target: Target node of the relation :param relation: Type of the relation between source and target node :param bel: BEL statement that describes the relation :param sha512: The SHA512 hash of the edge as a string :param data: The PyBEL data dictionary :param Evidence evidence: Evidence object that proves the given relation :param properties: List of all properties that belong to the edge :param annotations: List of all annotations that belong to the edge """ if sha512 in self.object_cache_edge: edge = self.object_cache_edge[sha512] self.session.add(edge) return edge edge = self.get_edge_by_hash(sha512) if edge is not None: self.object_cache_edge[sha512] = edge return edge edge = Edge( source=source, target=target, relation=relation, bel=bel, sha512=sha512, data=json.dumps(data), ) if evidence is not None: edge.evidence = evidence if properties is not None: edge.properties = properties if annotations is not None: edge.annotations = annotations self.session.add(edge) self.object_cache_edge[sha512] = edge return edge
python
def get_or_create_edge(self, source: Node, target: Node, relation: str, bel: str, sha512: str, data: EdgeData, evidence: Optional[Evidence] = None, annotations: Optional[List[NamespaceEntry]] = None, properties: Optional[List[Property]] = None, ) -> Edge: """Create an edge if it does not exist, or return it if it does. :param source: Source node of the relation :param target: Target node of the relation :param relation: Type of the relation between source and target node :param bel: BEL statement that describes the relation :param sha512: The SHA512 hash of the edge as a string :param data: The PyBEL data dictionary :param Evidence evidence: Evidence object that proves the given relation :param properties: List of all properties that belong to the edge :param annotations: List of all annotations that belong to the edge """ if sha512 in self.object_cache_edge: edge = self.object_cache_edge[sha512] self.session.add(edge) return edge edge = self.get_edge_by_hash(sha512) if edge is not None: self.object_cache_edge[sha512] = edge return edge edge = Edge( source=source, target=target, relation=relation, bel=bel, sha512=sha512, data=json.dumps(data), ) if evidence is not None: edge.evidence = evidence if properties is not None: edge.properties = properties if annotations is not None: edge.annotations = annotations self.session.add(edge) self.object_cache_edge[sha512] = edge return edge
[ "def", "get_or_create_edge", "(", "self", ",", "source", ":", "Node", ",", "target", ":", "Node", ",", "relation", ":", "str", ",", "bel", ":", "str", ",", "sha512", ":", "str", ",", "data", ":", "EdgeData", ",", "evidence", ":", "Optional", "[", "Ev...
Create an edge if it does not exist, or return it if it does. :param source: Source node of the relation :param target: Target node of the relation :param relation: Type of the relation between source and target node :param bel: BEL statement that describes the relation :param sha512: The SHA512 hash of the edge as a string :param data: The PyBEL data dictionary :param Evidence evidence: Evidence object that proves the given relation :param properties: List of all properties that belong to the edge :param annotations: List of all annotations that belong to the edge
[ "Create", "an", "edge", "if", "it", "does", "not", "exist", "or", "return", "it", "if", "it", "does", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L901-L953
train
29,601
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.get_or_create_citation
def get_or_create_citation(self, reference: str, type: Optional[str] = None, name: Optional[str] = None, title: Optional[str] = None, volume: Optional[str] = None, issue: Optional[str] = None, pages: Optional[str] = None, date: Optional[str] = None, first: Optional[str] = None, last: Optional[str] = None, authors: Union[None, List[str]] = None, ) -> Citation: """Create a citation if it does not exist, or return it if it does. :param type: Citation type (e.g. PubMed) :param reference: Identifier of the given citation (e.g. PubMed id) :param name: Name of the publication :param title: Title of article :param volume: Volume of publication :param issue: Issue of publication :param pages: Pages of issue :param date: Date of publication in ISO 8601 (YYYY-MM-DD) format :param first: Name of first author :param last: Name of last author :param authors: Either a list of authors separated by |, or an actual list of authors """ if type is None: type = CITATION_TYPE_PUBMED sha512 = hash_citation(type=type, reference=reference) if sha512 in self.object_cache_citation: citation = self.object_cache_citation[sha512] self.session.add(citation) return citation citation = self.get_citation_by_hash(sha512) if citation is not None: self.object_cache_citation[sha512] = citation return citation citation = Citation( type=type, reference=reference, sha512=sha512, name=name, title=title, volume=volume, issue=issue, pages=pages ) if date is not None: citation.date = parse_datetime(date) if first is not None: citation.first = self.get_or_create_author(first) if last is not None: citation.last = self.get_or_create_author(last) if authors is not None: for author in authors: author_model = self.get_or_create_author(author) if author_model not in citation.authors: citation.authors.append(author_model) self.session.add(citation) self.object_cache_citation[sha512] = citation return citation
python
def get_or_create_citation(self, reference: str, type: Optional[str] = None, name: Optional[str] = None, title: Optional[str] = None, volume: Optional[str] = None, issue: Optional[str] = None, pages: Optional[str] = None, date: Optional[str] = None, first: Optional[str] = None, last: Optional[str] = None, authors: Union[None, List[str]] = None, ) -> Citation: """Create a citation if it does not exist, or return it if it does. :param type: Citation type (e.g. PubMed) :param reference: Identifier of the given citation (e.g. PubMed id) :param name: Name of the publication :param title: Title of article :param volume: Volume of publication :param issue: Issue of publication :param pages: Pages of issue :param date: Date of publication in ISO 8601 (YYYY-MM-DD) format :param first: Name of first author :param last: Name of last author :param authors: Either a list of authors separated by |, or an actual list of authors """ if type is None: type = CITATION_TYPE_PUBMED sha512 = hash_citation(type=type, reference=reference) if sha512 in self.object_cache_citation: citation = self.object_cache_citation[sha512] self.session.add(citation) return citation citation = self.get_citation_by_hash(sha512) if citation is not None: self.object_cache_citation[sha512] = citation return citation citation = Citation( type=type, reference=reference, sha512=sha512, name=name, title=title, volume=volume, issue=issue, pages=pages ) if date is not None: citation.date = parse_datetime(date) if first is not None: citation.first = self.get_or_create_author(first) if last is not None: citation.last = self.get_or_create_author(last) if authors is not None: for author in authors: author_model = self.get_or_create_author(author) if author_model not in citation.authors: citation.authors.append(author_model) self.session.add(citation) self.object_cache_citation[sha512] = citation return citation
[ "def", "get_or_create_citation", "(", "self", ",", "reference", ":", "str", ",", "type", ":", "Optional", "[", "str", "]", "=", "None", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "title", ":", "Optional", "[", "str", "]", "=", ...
Create a citation if it does not exist, or return it if it does. :param type: Citation type (e.g. PubMed) :param reference: Identifier of the given citation (e.g. PubMed id) :param name: Name of the publication :param title: Title of article :param volume: Volume of publication :param issue: Issue of publication :param pages: Pages of issue :param date: Date of publication in ISO 8601 (YYYY-MM-DD) format :param first: Name of first author :param last: Name of last author :param authors: Either a list of authors separated by |, or an actual list of authors
[ "Create", "a", "citation", "if", "it", "does", "not", "exist", "or", "return", "it", "if", "it", "does", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L955-L1025
train
29,602
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.get_or_create_author
def get_or_create_author(self, name: str) -> Author: """Get an author by name, or creates one if it does not exist.""" author = self.object_cache_author.get(name) if author is not None: self.session.add(author) return author author = self.get_author_by_name(name) if author is not None: self.object_cache_author[name] = author return author author = self.object_cache_author[name] = Author.from_name(name=name) self.session.add(author) return author
python
def get_or_create_author(self, name: str) -> Author: """Get an author by name, or creates one if it does not exist.""" author = self.object_cache_author.get(name) if author is not None: self.session.add(author) return author author = self.get_author_by_name(name) if author is not None: self.object_cache_author[name] = author return author author = self.object_cache_author[name] = Author.from_name(name=name) self.session.add(author) return author
[ "def", "get_or_create_author", "(", "self", ",", "name", ":", "str", ")", "->", "Author", ":", "author", "=", "self", ".", "object_cache_author", ".", "get", "(", "name", ")", "if", "author", "is", "not", "None", ":", "self", ".", "session", ".", "add"...
Get an author by name, or creates one if it does not exist.
[ "Get", "an", "author", "by", "name", "or", "creates", "one", "if", "it", "does", "not", "exist", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1027-L1043
train
29,603
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.get_modification_by_hash
def get_modification_by_hash(self, sha512: str) -> Optional[Modification]: """Get a modification by a SHA512 hash.""" return self.session.query(Modification).filter(Modification.sha512 == sha512).one_or_none()
python
def get_modification_by_hash(self, sha512: str) -> Optional[Modification]: """Get a modification by a SHA512 hash.""" return self.session.query(Modification).filter(Modification.sha512 == sha512).one_or_none()
[ "def", "get_modification_by_hash", "(", "self", ",", "sha512", ":", "str", ")", "->", "Optional", "[", "Modification", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Modification", ")", ".", "filter", "(", "Modification", ".", "sha512", "=...
Get a modification by a SHA512 hash.
[ "Get", "a", "modification", "by", "a", "SHA512", "hash", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1045-L1047
train
29,604
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager.get_property_by_hash
def get_property_by_hash(self, property_hash: str) -> Optional[Property]: """Get a property by its hash if it exists.""" return self.session.query(Property).filter(Property.sha512 == property_hash).one_or_none()
python
def get_property_by_hash(self, property_hash: str) -> Optional[Property]: """Get a property by its hash if it exists.""" return self.session.query(Property).filter(Property.sha512 == property_hash).one_or_none()
[ "def", "get_property_by_hash", "(", "self", ",", "property_hash", ":", "str", ")", "->", "Optional", "[", "Property", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Property", ")", ".", "filter", "(", "Property", ".", "sha512", "==", "pr...
Get a property by its hash if it exists.
[ "Get", "a", "property", "by", "its", "hash", "if", "it", "exists", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1171-L1173
train
29,605
pybel/pybel
src/pybel/manager/cache_manager.py
InsertManager._make_property_from_dict
def _make_property_from_dict(self, property_def: Dict) -> Property: """Build an edge property from a dictionary.""" property_hash = hash_dump(property_def) edge_property_model = self.object_cache_property.get(property_hash) if edge_property_model is None: edge_property_model = self.get_property_by_hash(property_hash) if not edge_property_model: property_def['sha512'] = property_hash edge_property_model = Property(**property_def) self.object_cache_property[property_hash] = edge_property_model return edge_property_model
python
def _make_property_from_dict(self, property_def: Dict) -> Property: """Build an edge property from a dictionary.""" property_hash = hash_dump(property_def) edge_property_model = self.object_cache_property.get(property_hash) if edge_property_model is None: edge_property_model = self.get_property_by_hash(property_hash) if not edge_property_model: property_def['sha512'] = property_hash edge_property_model = Property(**property_def) self.object_cache_property[property_hash] = edge_property_model return edge_property_model
[ "def", "_make_property_from_dict", "(", "self", ",", "property_def", ":", "Dict", ")", "->", "Property", ":", "property_hash", "=", "hash_dump", "(", "property_def", ")", "edge_property_model", "=", "self", ".", "object_cache_property", ".", "get", "(", "property_...
Build an edge property from a dictionary.
[ "Build", "an", "edge", "property", "from", "a", "dictionary", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1175-L1189
train
29,606
pybel/pybel
src/pybel/struct/graph.py
_clean_annotations
def _clean_annotations(annotations_dict: AnnotationsHint) -> AnnotationsDict: """Fix the formatting of annotation dict.""" return { key: ( values if isinstance(values, dict) else {v: True for v in values} if isinstance(values, set) else {values: True} ) for key, values in annotations_dict.items() }
python
def _clean_annotations(annotations_dict: AnnotationsHint) -> AnnotationsDict: """Fix the formatting of annotation dict.""" return { key: ( values if isinstance(values, dict) else {v: True for v in values} if isinstance(values, set) else {values: True} ) for key, values in annotations_dict.items() }
[ "def", "_clean_annotations", "(", "annotations_dict", ":", "AnnotationsHint", ")", "->", "AnnotationsDict", ":", "return", "{", "key", ":", "(", "values", "if", "isinstance", "(", "values", ",", "dict", ")", "else", "{", "v", ":", "True", "for", "v", "in",...
Fix the formatting of annotation dict.
[ "Fix", "the", "formatting", "of", "annotation", "dict", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L817-L826
train
29,607
pybel/pybel
src/pybel/struct/graph.py
BELGraph.defined_namespace_keywords
def defined_namespace_keywords(self) -> Set[str]: # noqa: D401 """The set of all keywords defined as namespaces in this graph.""" return set(self.namespace_pattern) | set(self.namespace_url)
python
def defined_namespace_keywords(self) -> Set[str]: # noqa: D401 """The set of all keywords defined as namespaces in this graph.""" return set(self.namespace_pattern) | set(self.namespace_url)
[ "def", "defined_namespace_keywords", "(", "self", ")", "->", "Set", "[", "str", "]", ":", "# noqa: D401", "return", "set", "(", "self", ".", "namespace_pattern", ")", "|", "set", "(", "self", ".", "namespace_url", ")" ]
The set of all keywords defined as namespaces in this graph.
[ "The", "set", "of", "all", "keywords", "defined", "as", "namespaces", "in", "this", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L251-L253
train
29,608
pybel/pybel
src/pybel/struct/graph.py
BELGraph.defined_annotation_keywords
def defined_annotation_keywords(self) -> Set[str]: """Get the set of all keywords defined as annotations in this graph.""" return ( set(self.annotation_pattern) | set(self.annotation_url) | set(self.annotation_list) )
python
def defined_annotation_keywords(self) -> Set[str]: """Get the set of all keywords defined as annotations in this graph.""" return ( set(self.annotation_pattern) | set(self.annotation_url) | set(self.annotation_list) )
[ "def", "defined_annotation_keywords", "(", "self", ")", "->", "Set", "[", "str", "]", ":", "return", "(", "set", "(", "self", ".", "annotation_pattern", ")", "|", "set", "(", "self", ".", "annotation_url", ")", "|", "set", "(", "self", ".", "annotation_l...
Get the set of all keywords defined as annotations in this graph.
[ "Get", "the", "set", "of", "all", "keywords", "defined", "as", "annotations", "in", "this", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L300-L306
train
29,609
pybel/pybel
src/pybel/struct/graph.py
BELGraph.skip_storing_namespace
def skip_storing_namespace(self, namespace: Optional[str]) -> bool: """Check if the namespace should be skipped. :param namespace: The keyword of the namespace to check. """ return ( namespace is not None and namespace in self.namespace_url and self.namespace_url[namespace] in self.uncached_namespaces )
python
def skip_storing_namespace(self, namespace: Optional[str]) -> bool: """Check if the namespace should be skipped. :param namespace: The keyword of the namespace to check. """ return ( namespace is not None and namespace in self.namespace_url and self.namespace_url[namespace] in self.uncached_namespaces )
[ "def", "skip_storing_namespace", "(", "self", ",", "namespace", ":", "Optional", "[", "str", "]", ")", "->", "bool", ":", "return", "(", "namespace", "is", "not", "None", "and", "namespace", "in", "self", ".", "namespace_url", "and", "self", ".", "namespac...
Check if the namespace should be skipped. :param namespace: The keyword of the namespace to check.
[ "Check", "if", "the", "namespace", "should", "be", "skipped", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L345-L354
train
29,610
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_warning
def add_warning(self, exception: BELParserWarning, context: Optional[Mapping[str, Any]] = None, ) -> None: """Add a warning to the internal warning log in the graph, with optional context information. :param exception: The exception that occurred :param context: The context from the parser when the exception occurred """ self.warnings.append(( self.path, exception, {} if context is None else context, ))
python
def add_warning(self, exception: BELParserWarning, context: Optional[Mapping[str, Any]] = None, ) -> None: """Add a warning to the internal warning log in the graph, with optional context information. :param exception: The exception that occurred :param context: The context from the parser when the exception occurred """ self.warnings.append(( self.path, exception, {} if context is None else context, ))
[ "def", "add_warning", "(", "self", ",", "exception", ":", "BELParserWarning", ",", "context", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ",", ")", "->", "None", ":", "self", ".", "warnings", ".", "append", "(", "(...
Add a warning to the internal warning log in the graph, with optional context information. :param exception: The exception that occurred :param context: The context from the parser when the exception occurred
[ "Add", "a", "warning", "to", "the", "internal", "warning", "log", "in", "the", "graph", "with", "optional", "context", "information", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L356-L369
train
29,611
pybel/pybel
src/pybel/struct/graph.py
BELGraph._help_add_edge
def _help_add_edge(self, u: BaseEntity, v: BaseEntity, attr: Mapping) -> str: """Help add a pre-built edge.""" self.add_node_from_data(u) self.add_node_from_data(v) return self._help_add_edge_helper(u, v, attr)
python
def _help_add_edge(self, u: BaseEntity, v: BaseEntity, attr: Mapping) -> str: """Help add a pre-built edge.""" self.add_node_from_data(u) self.add_node_from_data(v) return self._help_add_edge_helper(u, v, attr)
[ "def", "_help_add_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "attr", ":", "Mapping", ")", "->", "str", ":", "self", ".", "add_node_from_data", "(", "u", ")", "self", ".", "add_node_from_data", "(", "v", ")", "ret...
Help add a pre-built edge.
[ "Help", "add", "a", "pre", "-", "built", "edge", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L371-L376
train
29,612
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_unqualified_edge
def add_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add a unique edge that has no annotations. :param u: The source node :param v: The target node :param relation: A relationship label from :mod:`pybel.constants` :return: The key for this edge (a unique hash) """ attr = {RELATION: relation} return self._help_add_edge(u, v, attr)
python
def add_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add a unique edge that has no annotations. :param u: The source node :param v: The target node :param relation: A relationship label from :mod:`pybel.constants` :return: The key for this edge (a unique hash) """ attr = {RELATION: relation} return self._help_add_edge(u, v, attr)
[ "def", "add_unqualified_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "relation", ":", "str", ")", "->", "str", ":", "attr", "=", "{", "RELATION", ":", "relation", "}", "return", "self", ".", "_help_add_edge", "(", ...
Add a unique edge that has no annotations. :param u: The source node :param v: The target node :param relation: A relationship label from :mod:`pybel.constants` :return: The key for this edge (a unique hash)
[ "Add", "a", "unique", "edge", "that", "has", "no", "annotations", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L386-L395
train
29,613
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_transcription
def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str: """Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node """ return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO)
python
def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str: """Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node """ return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO)
[ "def", "add_transcription", "(", "self", ",", "gene", ":", "Gene", ",", "rna", ":", "Union", "[", "Rna", ",", "MicroRna", "]", ")", "->", "str", ":", "return", "self", ".", "add_unqualified_edge", "(", "gene", ",", "rna", ",", "TRANSCRIBED_TO", ")" ]
Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node
[ "Add", "a", "transcription", "relation", "from", "a", "gene", "to", "an", "RNA", "or", "miRNA", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L397-L403
train
29,614
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_translation
def add_translation(self, rna: Rna, protein: Protein) -> str: """Add a translation relation from a RNA to a protein. :param rna: An RNA node :param protein: A protein node """ return self.add_unqualified_edge(rna, protein, TRANSLATED_TO)
python
def add_translation(self, rna: Rna, protein: Protein) -> str: """Add a translation relation from a RNA to a protein. :param rna: An RNA node :param protein: A protein node """ return self.add_unqualified_edge(rna, protein, TRANSLATED_TO)
[ "def", "add_translation", "(", "self", ",", "rna", ":", "Rna", ",", "protein", ":", "Protein", ")", "->", "str", ":", "return", "self", ".", "add_unqualified_edge", "(", "rna", ",", "protein", ",", "TRANSLATED_TO", ")" ]
Add a translation relation from a RNA to a protein. :param rna: An RNA node :param protein: A protein node
[ "Add", "a", "translation", "relation", "from", "a", "RNA", "to", "a", "protein", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L405-L411
train
29,615
pybel/pybel
src/pybel/struct/graph.py
BELGraph._add_two_way_unqualified_edge
def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add an unqualified edge both ways.""" self.add_unqualified_edge(v, u, relation) return self.add_unqualified_edge(u, v, relation)
python
def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add an unqualified edge both ways.""" self.add_unqualified_edge(v, u, relation) return self.add_unqualified_edge(u, v, relation)
[ "def", "_add_two_way_unqualified_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "relation", ":", "str", ")", "->", "str", ":", "self", ".", "add_unqualified_edge", "(", "v", ",", "u", ",", "relation", ")", "return", "s...
Add an unqualified edge both ways.
[ "Add", "an", "unqualified", "edge", "both", "ways", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L413-L416
train
29,616
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_qualified_edge
def add_qualified_edge( self, u, v, *, relation: str, evidence: str, citation: Union[str, Mapping[str, str]], annotations: Optional[AnnotationsHint] = None, subject_modifier: Optional[Mapping] = None, object_modifier: Optional[Mapping] = None, **attr ) -> str: """Add a qualified edge. Qualified edges have a relation, evidence, citation, and optional annotations, subject modifications, and object modifications. :param u: The source node :param v: The target node :param relation: The type of relation this edge represents :param evidence: The evidence string from an article :param citation: The citation data dictionary for this evidence. If a string is given, assumes it's a PubMed identifier and auto-fills the citation type. :param annotations: The annotations data dictionary :param subject_modifier: The modifiers (like activity) on the subject node. See data model documentation. :param object_modifier: The modifiers (like activity) on the object node. See data model documentation. :return: The hash of the edge """ attr.update({ RELATION: relation, EVIDENCE: evidence, }) if isinstance(citation, str): attr[CITATION] = { CITATION_TYPE: CITATION_TYPE_PUBMED, CITATION_REFERENCE: citation, } elif isinstance(citation, dict): attr[CITATION] = citation else: raise TypeError if annotations: # clean up annotations attr[ANNOTATIONS] = _clean_annotations(annotations) if subject_modifier: attr[SUBJECT] = subject_modifier if object_modifier: attr[OBJECT] = object_modifier return self._help_add_edge(u, v, attr)
python
def add_qualified_edge( self, u, v, *, relation: str, evidence: str, citation: Union[str, Mapping[str, str]], annotations: Optional[AnnotationsHint] = None, subject_modifier: Optional[Mapping] = None, object_modifier: Optional[Mapping] = None, **attr ) -> str: """Add a qualified edge. Qualified edges have a relation, evidence, citation, and optional annotations, subject modifications, and object modifications. :param u: The source node :param v: The target node :param relation: The type of relation this edge represents :param evidence: The evidence string from an article :param citation: The citation data dictionary for this evidence. If a string is given, assumes it's a PubMed identifier and auto-fills the citation type. :param annotations: The annotations data dictionary :param subject_modifier: The modifiers (like activity) on the subject node. See data model documentation. :param object_modifier: The modifiers (like activity) on the object node. See data model documentation. :return: The hash of the edge """ attr.update({ RELATION: relation, EVIDENCE: evidence, }) if isinstance(citation, str): attr[CITATION] = { CITATION_TYPE: CITATION_TYPE_PUBMED, CITATION_REFERENCE: citation, } elif isinstance(citation, dict): attr[CITATION] = citation else: raise TypeError if annotations: # clean up annotations attr[ANNOTATIONS] = _clean_annotations(annotations) if subject_modifier: attr[SUBJECT] = subject_modifier if object_modifier: attr[OBJECT] = object_modifier return self._help_add_edge(u, v, attr)
[ "def", "add_qualified_edge", "(", "self", ",", "u", ",", "v", ",", "*", ",", "relation", ":", "str", ",", "evidence", ":", "str", ",", "citation", ":", "Union", "[", "str", ",", "Mapping", "[", "str", ",", "str", "]", "]", ",", "annotations", ":", ...
Add a qualified edge. Qualified edges have a relation, evidence, citation, and optional annotations, subject modifications, and object modifications. :param u: The source node :param v: The target node :param relation: The type of relation this edge represents :param evidence: The evidence string from an article :param citation: The citation data dictionary for this evidence. If a string is given, assumes it's a PubMed identifier and auto-fills the citation type. :param annotations: The annotations data dictionary :param subject_modifier: The modifiers (like activity) on the subject node. See data model documentation. :param object_modifier: The modifiers (like activity) on the object node. See data model documentation. :return: The hash of the edge
[ "Add", "a", "qualified", "edge", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L445-L499
train
29,617
pybel/pybel
src/pybel/struct/graph.py
BELGraph.add_node_from_data
def add_node_from_data(self, node: BaseEntity) -> BaseEntity: """Add an entity to the graph.""" assert isinstance(node, BaseEntity) if node in self: return node self.add_node(node) if VARIANTS in node: self.add_has_variant(node.get_parent(), node) elif MEMBERS in node: for member in node[MEMBERS]: self.add_has_component(node, member) elif PRODUCTS in node and REACTANTS in node: for reactant_tokens in node[REACTANTS]: self.add_has_reactant(node, reactant_tokens) for product_tokens in node[PRODUCTS]: self.add_has_product(node, product_tokens) return node
python
def add_node_from_data(self, node: BaseEntity) -> BaseEntity: """Add an entity to the graph.""" assert isinstance(node, BaseEntity) if node in self: return node self.add_node(node) if VARIANTS in node: self.add_has_variant(node.get_parent(), node) elif MEMBERS in node: for member in node[MEMBERS]: self.add_has_component(node, member) elif PRODUCTS in node and REACTANTS in node: for reactant_tokens in node[REACTANTS]: self.add_has_reactant(node, reactant_tokens) for product_tokens in node[PRODUCTS]: self.add_has_product(node, product_tokens) return node
[ "def", "add_node_from_data", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "BaseEntity", ":", "assert", "isinstance", "(", "node", ",", "BaseEntity", ")", "if", "node", "in", "self", ":", "return", "node", "self", ".", "add_node", "(", "node", ...
Add an entity to the graph.
[ "Add", "an", "entity", "to", "the", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L525-L547
train
29,618
pybel/pybel
src/pybel/struct/graph.py
BELGraph.has_edge_citation
def has_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has a citation.""" return self._has_edge_attr(u, v, key, CITATION)
python
def has_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has a citation.""" return self._has_edge_attr(u, v, key, CITATION)
[ "def", "has_edge_citation", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "_has_edge_attr", "(", "u", ",", "v", ",", "key", ",", "CITATION", ")" ]
Check if the given edge has a citation.
[ "Check", "if", "the", "given", "edge", "has", "a", "citation", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L554-L556
train
29,619
pybel/pybel
src/pybel/struct/graph.py
BELGraph.has_edge_evidence
def has_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has an evidence.""" return self._has_edge_attr(u, v, key, EVIDENCE)
python
def has_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has an evidence.""" return self._has_edge_attr(u, v, key, EVIDENCE)
[ "def", "has_edge_evidence", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "_has_edge_attr", "(", "u", ",", "v", ",", "key", ",", "EVIDENCE", ")" ]
Check if the given edge has an evidence.
[ "Check", "if", "the", "given", "edge", "has", "an", "evidence", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L558-L560
train
29,620
pybel/pybel
src/pybel/struct/graph.py
BELGraph.get_edge_citation
def get_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[CitationDict]: """Get the citation for a given edge.""" return self._get_edge_attr(u, v, key, CITATION)
python
def get_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[CitationDict]: """Get the citation for a given edge.""" return self._get_edge_attr(u, v, key, CITATION)
[ "def", "get_edge_citation", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "Optional", "[", "CitationDict", "]", ":", "return", "self", ".", "_get_edge_attr", "(", "u", ",", "v", ",", "key", ...
Get the citation for a given edge.
[ "Get", "the", "citation", "for", "a", "given", "edge", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L565-L567
train
29,621
pybel/pybel
src/pybel/struct/graph.py
BELGraph.get_edge_evidence
def get_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[str]: """Get the evidence for a given edge.""" return self._get_edge_attr(u, v, key, EVIDENCE)
python
def get_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[str]: """Get the evidence for a given edge.""" return self._get_edge_attr(u, v, key, EVIDENCE)
[ "def", "get_edge_evidence", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_get_edge_attr", "(", "u", ",", "v", ",", "key", ",", "E...
Get the evidence for a given edge.
[ "Get", "the", "evidence", "for", "a", "given", "edge", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L569-L571
train
29,622
pybel/pybel
src/pybel/struct/graph.py
BELGraph.get_edge_annotations
def get_edge_annotations(self, u, v, key: str) -> Optional[AnnotationsDict]: """Get the annotations for a given edge.""" return self._get_edge_attr(u, v, key, ANNOTATIONS)
python
def get_edge_annotations(self, u, v, key: str) -> Optional[AnnotationsDict]: """Get the annotations for a given edge.""" return self._get_edge_attr(u, v, key, ANNOTATIONS)
[ "def", "get_edge_annotations", "(", "self", ",", "u", ",", "v", ",", "key", ":", "str", ")", "->", "Optional", "[", "AnnotationsDict", "]", ":", "return", "self", ".", "_get_edge_attr", "(", "u", ",", "v", ",", "key", ",", "ANNOTATIONS", ")" ]
Get the annotations for a given edge.
[ "Get", "the", "annotations", "for", "a", "given", "edge", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L573-L575
train
29,623
pybel/pybel
src/pybel/struct/graph.py
BELGraph.get_node_description
def get_node_description(self, node: BaseEntity) -> Optional[str]: """Get the description for a given node.""" return self._get_node_attr(node, DESCRIPTION)
python
def get_node_description(self, node: BaseEntity) -> Optional[str]: """Get the description for a given node.""" return self._get_node_attr(node, DESCRIPTION)
[ "def", "get_node_description", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_get_node_attr", "(", "node", ",", "DESCRIPTION", ")" ]
Get the description for a given node.
[ "Get", "the", "description", "for", "a", "given", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L589-L591
train
29,624
pybel/pybel
src/pybel/struct/graph.py
BELGraph.set_node_description
def set_node_description(self, node: BaseEntity, description: str) -> None: """Set the description for a given node.""" self._set_node_attr(node, DESCRIPTION, description)
python
def set_node_description(self, node: BaseEntity, description: str) -> None: """Set the description for a given node.""" self._set_node_attr(node, DESCRIPTION, description)
[ "def", "set_node_description", "(", "self", ",", "node", ":", "BaseEntity", ",", "description", ":", "str", ")", "->", "None", ":", "self", ".", "_set_node_attr", "(", "node", ",", "DESCRIPTION", ",", "description", ")" ]
Set the description for a given node.
[ "Set", "the", "description", "for", "a", "given", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L597-L599
train
29,625
pybel/pybel
src/pybel/struct/graph.py
BELGraph.edge_to_bel
def edge_to_bel(u: BaseEntity, v: BaseEntity, edge_data: EdgeData, sep: Optional[str] = None) -> str: """Serialize a pair of nodes and related edge data as a BEL relation.""" return edge_to_bel(u, v, data=edge_data, sep=sep)
python
def edge_to_bel(u: BaseEntity, v: BaseEntity, edge_data: EdgeData, sep: Optional[str] = None) -> str: """Serialize a pair of nodes and related edge data as a BEL relation.""" return edge_to_bel(u, v, data=edge_data, sep=sep)
[ "def", "edge_to_bel", "(", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "edge_data", ":", "EdgeData", ",", "sep", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "str", ":", "return", "edge_to_bel", "(", "u", ",", "v", ",", "...
Serialize a pair of nodes and related edge data as a BEL relation.
[ "Serialize", "a", "pair", "of", "nodes", "and", "related", "edge", "data", "as", "a", "BEL", "relation", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L705-L707
train
29,626
pybel/pybel
src/pybel/struct/graph.py
BELGraph._equivalent_node_iterator_helper
def _equivalent_node_iterator_helper(self, node: BaseEntity, visited: Set[BaseEntity]) -> BaseEntity: """Iterate over nodes and their data that are equal to the given node, starting with the original.""" for v in self[node]: if v in visited: continue if self._has_no_equivalent_edge(node, v): continue visited.add(v) yield v yield from self._equivalent_node_iterator_helper(v, visited)
python
def _equivalent_node_iterator_helper(self, node: BaseEntity, visited: Set[BaseEntity]) -> BaseEntity: """Iterate over nodes and their data that are equal to the given node, starting with the original.""" for v in self[node]: if v in visited: continue if self._has_no_equivalent_edge(node, v): continue visited.add(v) yield v yield from self._equivalent_node_iterator_helper(v, visited)
[ "def", "_equivalent_node_iterator_helper", "(", "self", ",", "node", ":", "BaseEntity", ",", "visited", ":", "Set", "[", "BaseEntity", "]", ")", "->", "BaseEntity", ":", "for", "v", "in", "self", "[", "node", "]", ":", "if", "v", "in", "visited", ":", ...
Iterate over nodes and their data that are equal to the given node, starting with the original.
[ "Iterate", "over", "nodes", "and", "their", "data", "that", "are", "equal", "to", "the", "given", "node", "starting", "with", "the", "original", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L715-L726
train
29,627
pybel/pybel
src/pybel/struct/graph.py
BELGraph.iter_equivalent_nodes
def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]: """Iterate over nodes that are equivalent to the given node, including the original.""" yield node yield from self._equivalent_node_iterator_helper(node, {node})
python
def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]: """Iterate over nodes that are equivalent to the given node, including the original.""" yield node yield from self._equivalent_node_iterator_helper(node, {node})
[ "def", "iter_equivalent_nodes", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "yield", "node", "yield", "from", "self", ".", "_equivalent_node_iterator_helper", "(", "node", ",", "{", "node", "}", ")" ]
Iterate over nodes that are equivalent to the given node, including the original.
[ "Iterate", "over", "nodes", "that", "are", "equivalent", "to", "the", "given", "node", "including", "the", "original", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L728-L731
train
29,628
pybel/pybel
src/pybel/struct/graph.py
BELGraph.get_equivalent_nodes
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]: """Get a set of equivalent nodes to this node, excluding the given node.""" if isinstance(node, BaseEntity): return set(self.iter_equivalent_nodes(node)) return set(self.iter_equivalent_nodes(node))
python
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]: """Get a set of equivalent nodes to this node, excluding the given node.""" if isinstance(node, BaseEntity): return set(self.iter_equivalent_nodes(node)) return set(self.iter_equivalent_nodes(node))
[ "def", "get_equivalent_nodes", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Set", "[", "BaseEntity", "]", ":", "if", "isinstance", "(", "node", ",", "BaseEntity", ")", ":", "return", "set", "(", "self", ".", "iter_equivalent_nodes", "(", "node"...
Get a set of equivalent nodes to this node, excluding the given node.
[ "Get", "a", "set", "of", "equivalent", "nodes", "to", "this", "node", "excluding", "the", "given", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L733-L738
train
29,629
pybel/pybel
src/pybel/struct/graph.py
BELGraph._node_has_namespace_helper
def _node_has_namespace_helper(node: BaseEntity, namespace: str) -> bool: """Check that the node has namespace information. Might have cross references in future. """ return namespace == node.get(NAMESPACE)
python
def _node_has_namespace_helper(node: BaseEntity, namespace: str) -> bool: """Check that the node has namespace information. Might have cross references in future. """ return namespace == node.get(NAMESPACE)
[ "def", "_node_has_namespace_helper", "(", "node", ":", "BaseEntity", ",", "namespace", ":", "str", ")", "->", "bool", ":", "return", "namespace", "==", "node", ".", "get", "(", "NAMESPACE", ")" ]
Check that the node has namespace information. Might have cross references in future.
[ "Check", "that", "the", "node", "has", "namespace", "information", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L741-L746
train
29,630
pybel/pybel
src/pybel/struct/graph.py
BELGraph.node_has_namespace
def node_has_namespace(self, node: BaseEntity, namespace: str) -> bool: """Check if the node have the given namespace. This also should look in the equivalent nodes. """ return any( self._node_has_namespace_helper(n, namespace) for n in self.iter_equivalent_nodes(node) )
python
def node_has_namespace(self, node: BaseEntity, namespace: str) -> bool: """Check if the node have the given namespace. This also should look in the equivalent nodes. """ return any( self._node_has_namespace_helper(n, namespace) for n in self.iter_equivalent_nodes(node) )
[ "def", "node_has_namespace", "(", "self", ",", "node", ":", "BaseEntity", ",", "namespace", ":", "str", ")", "->", "bool", ":", "return", "any", "(", "self", ".", "_node_has_namespace_helper", "(", "n", ",", "namespace", ")", "for", "n", "in", "self", "....
Check if the node have the given namespace. This also should look in the equivalent nodes.
[ "Check", "if", "the", "node", "have", "the", "given", "namespace", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L748-L756
train
29,631
pybel/pybel
src/pybel/struct/graph.py
BELGraph._describe_list
def _describe_list(self) -> List[Tuple[str, float]]: """Return useful information about the graph as a list of tuples.""" number_nodes = self.number_of_nodes() return [ ('Number of Nodes', number_nodes), ('Number of Edges', self.number_of_edges()), ('Number of Citations', self.number_of_citations()), ('Number of Authors', self.number_of_authors()), ('Network Density', '{:.2E}'.format(nx.density(self))), ('Number of Components', nx.number_weakly_connected_components(self)), ('Number of Warnings', self.number_of_warnings()), ]
python
def _describe_list(self) -> List[Tuple[str, float]]: """Return useful information about the graph as a list of tuples.""" number_nodes = self.number_of_nodes() return [ ('Number of Nodes', number_nodes), ('Number of Edges', self.number_of_edges()), ('Number of Citations', self.number_of_citations()), ('Number of Authors', self.number_of_authors()), ('Network Density', '{:.2E}'.format(nx.density(self))), ('Number of Components', nx.number_weakly_connected_components(self)), ('Number of Warnings', self.number_of_warnings()), ]
[ "def", "_describe_list", "(", "self", ")", "->", "List", "[", "Tuple", "[", "str", ",", "float", "]", "]", ":", "number_nodes", "=", "self", ".", "number_of_nodes", "(", ")", "return", "[", "(", "'Number of Nodes'", ",", "number_nodes", ")", ",", "(", ...
Return useful information about the graph as a list of tuples.
[ "Return", "useful", "information", "about", "the", "graph", "as", "a", "list", "of", "tuples", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L758-L769
train
29,632
pybel/pybel
src/pybel/struct/graph.py
BELGraph.summary_str
def summary_str(self) -> str: """Return a string that summarizes the graph.""" return '{}\n'.format(self) + '\n'.join( '{}: {}'.format(label, value) for label, value in self._describe_list() )
python
def summary_str(self) -> str: """Return a string that summarizes the graph.""" return '{}\n'.format(self) + '\n'.join( '{}: {}'.format(label, value) for label, value in self._describe_list() )
[ "def", "summary_str", "(", "self", ")", "->", "str", ":", "return", "'{}\\n'", ".", "format", "(", "self", ")", "+", "'\\n'", ".", "join", "(", "'{}: {}'", ".", "format", "(", "label", ",", "value", ")", "for", "label", ",", "value", "in", "self", ...
Return a string that summarizes the graph.
[ "Return", "a", "string", "that", "summarizes", "the", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L775-L780
train
29,633
pybel/pybel
src/pybel/struct/graph.py
BELGraph.summarize
def summarize(self, file: Optional[TextIO] = None) -> None: """Print a summary of the graph.""" print(self.summary_str(), file=file)
python
def summarize(self, file: Optional[TextIO] = None) -> None: """Print a summary of the graph.""" print(self.summary_str(), file=file)
[ "def", "summarize", "(", "self", ",", "file", ":", "Optional", "[", "TextIO", "]", "=", "None", ")", "->", "None", ":", "print", "(", "self", ".", "summary_str", "(", ")", ",", "file", "=", "file", ")" ]
Print a summary of the graph.
[ "Print", "a", "summary", "of", "the", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L782-L784
train
29,634
pybel/pybel
src/pybel/struct/graph.py
BELGraph.serialize
def serialize(self, *, fmt: str = 'nodelink', file: Union[None, str, TextIO] = None, **kwargs): """Serialize the graph to an object or file if given. For additional I/O, see the :mod:`pybel.io` module. """ if file is None: return self._serialize_object(fmt=fmt, **kwargs) elif isinstance(file, str): with open(file, 'w') as file_obj: self._serialize_file(fmt=fmt, file=file_obj, **kwargs) else: self._serialize_file(fmt=fmt, file=file, **kwargs)
python
def serialize(self, *, fmt: str = 'nodelink', file: Union[None, str, TextIO] = None, **kwargs): """Serialize the graph to an object or file if given. For additional I/O, see the :mod:`pybel.io` module. """ if file is None: return self._serialize_object(fmt=fmt, **kwargs) elif isinstance(file, str): with open(file, 'w') as file_obj: self._serialize_file(fmt=fmt, file=file_obj, **kwargs) else: self._serialize_file(fmt=fmt, file=file, **kwargs)
[ "def", "serialize", "(", "self", ",", "*", ",", "fmt", ":", "str", "=", "'nodelink'", ",", "file", ":", "Union", "[", "None", ",", "str", ",", "TextIO", "]", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "file", "is", "None", ":", "retu...
Serialize the graph to an object or file if given. For additional I/O, see the :mod:`pybel.io` module.
[ "Serialize", "the", "graph", "to", "an", "object", "or", "file", "if", "given", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L786-L797
train
29,635
pybel/pybel
src/pybel/struct/mutation/utils.py
remove_isolated_nodes
def remove_isolated_nodes(graph): """Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph """ nodes = list(nx.isolates(graph)) graph.remove_nodes_from(nodes)
python
def remove_isolated_nodes(graph): """Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph """ nodes = list(nx.isolates(graph)) graph.remove_nodes_from(nodes)
[ "def", "remove_isolated_nodes", "(", "graph", ")", ":", "nodes", "=", "list", "(", "nx", ".", "isolates", "(", "graph", ")", ")", "graph", ".", "remove_nodes_from", "(", "nodes", ")" ]
Remove isolated nodes from the network, in place. :param pybel.BELGraph graph: A BEL graph
[ "Remove", "isolated", "nodes", "from", "the", "network", "in", "place", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/utils.py#L20-L26
train
29,636
pybel/pybel
src/pybel/struct/mutation/utils.py
remove_isolated_nodes_op
def remove_isolated_nodes_op(graph): """Build a new graph excluding the isolated nodes. :param pybel.BELGraph graph: A BEL graph :rtype: pybel.BELGraph """ rv = graph.copy() nodes = list(nx.isolates(rv)) rv.remove_nodes_from(nodes) return rv
python
def remove_isolated_nodes_op(graph): """Build a new graph excluding the isolated nodes. :param pybel.BELGraph graph: A BEL graph :rtype: pybel.BELGraph """ rv = graph.copy() nodes = list(nx.isolates(rv)) rv.remove_nodes_from(nodes) return rv
[ "def", "remove_isolated_nodes_op", "(", "graph", ")", ":", "rv", "=", "graph", ".", "copy", "(", ")", "nodes", "=", "list", "(", "nx", ".", "isolates", "(", "rv", ")", ")", "rv", ".", "remove_nodes_from", "(", "nodes", ")", "return", "rv" ]
Build a new graph excluding the isolated nodes. :param pybel.BELGraph graph: A BEL graph :rtype: pybel.BELGraph
[ "Build", "a", "new", "graph", "excluding", "the", "isolated", "nodes", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/utils.py#L30-L39
train
29,637
pybel/pybel
src/pybel/struct/mutation/utils.py
expand_by_edge_filter
def expand_by_edge_filter(source, target, edge_predicates: EdgePredicates): """Expand a target graph by edges in the source matching the given predicates. :param pybel.BELGraph source: A BEL graph :param pybel.BELGraph target: A BEL graph :param edge_predicates: An edge predicate or list of edge predicates :return: A BEL sub-graph induced over the edges passing the given filters :rtype: pybel.BELGraph """ target.add_edges_from( (u, v, k, source[u][v][k]) for u, v, k in filter_edges(source, edge_predicates=edge_predicates) ) update_node_helper(source, target) update_metadata(source, target)
python
def expand_by_edge_filter(source, target, edge_predicates: EdgePredicates): """Expand a target graph by edges in the source matching the given predicates. :param pybel.BELGraph source: A BEL graph :param pybel.BELGraph target: A BEL graph :param edge_predicates: An edge predicate or list of edge predicates :return: A BEL sub-graph induced over the edges passing the given filters :rtype: pybel.BELGraph """ target.add_edges_from( (u, v, k, source[u][v][k]) for u, v, k in filter_edges(source, edge_predicates=edge_predicates) ) update_node_helper(source, target) update_metadata(source, target)
[ "def", "expand_by_edge_filter", "(", "source", ",", "target", ",", "edge_predicates", ":", "EdgePredicates", ")", ":", "target", ".", "add_edges_from", "(", "(", "u", ",", "v", ",", "k", ",", "source", "[", "u", "]", "[", "v", "]", "[", "k", "]", ")"...
Expand a target graph by edges in the source matching the given predicates. :param pybel.BELGraph source: A BEL graph :param pybel.BELGraph target: A BEL graph :param edge_predicates: An edge predicate or list of edge predicates :return: A BEL sub-graph induced over the edges passing the given filters :rtype: pybel.BELGraph
[ "Expand", "a", "target", "graph", "by", "edges", "in", "the", "source", "matching", "the", "given", "predicates", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/utils.py#L43-L58
train
29,638
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.handle_document
def handle_document(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``SET DOCUMENT X = "Y"``. :raises: InvalidMetadataException :raises: VersionFormatWarning """ key = tokens['key'] value = tokens['value'] if key not in DOCUMENT_KEYS: raise InvalidMetadataException(self.get_line_number(), line, position, key, value) norm_key = DOCUMENT_KEYS[key] if norm_key in self.document_metadata: log.warning('Tried to overwrite metadata: %s', key) return tokens self.document_metadata[norm_key] = value if norm_key == METADATA_VERSION: self.raise_for_version(line, position, value) return tokens
python
def handle_document(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``SET DOCUMENT X = "Y"``. :raises: InvalidMetadataException :raises: VersionFormatWarning """ key = tokens['key'] value = tokens['value'] if key not in DOCUMENT_KEYS: raise InvalidMetadataException(self.get_line_number(), line, position, key, value) norm_key = DOCUMENT_KEYS[key] if norm_key in self.document_metadata: log.warning('Tried to overwrite metadata: %s', key) return tokens self.document_metadata[norm_key] = value if norm_key == METADATA_VERSION: self.raise_for_version(line, position, value) return tokens
[ "def", "handle_document", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "key", "=", "tokens", "[", "'key'", "]", "value", "=", "tokens", "[", "'value'", "]", "if",...
Handle statements like ``SET DOCUMENT X = "Y"``. :raises: InvalidMetadataException :raises: VersionFormatWarning
[ "Handle", "statements", "like", "SET", "DOCUMENT", "X", "=", "Y", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L132-L155
train
29,639
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.raise_for_redefined_namespace
def raise_for_redefined_namespace(self, line: str, position: int, namespace: str) -> None: """Raise an exception if a namespace is already defined. :raises: RedefinedNamespaceError """ if self.disallow_redefinition and self.has_namespace(namespace): raise RedefinedNamespaceError(self.get_line_number(), line, position, namespace)
python
def raise_for_redefined_namespace(self, line: str, position: int, namespace: str) -> None: """Raise an exception if a namespace is already defined. :raises: RedefinedNamespaceError """ if self.disallow_redefinition and self.has_namespace(namespace): raise RedefinedNamespaceError(self.get_line_number(), line, position, namespace)
[ "def", "raise_for_redefined_namespace", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "namespace", ":", "str", ")", "->", "None", ":", "if", "self", ".", "disallow_redefinition", "and", "self", ".", "has_namespace", "(", "namespace"...
Raise an exception if a namespace is already defined. :raises: RedefinedNamespaceError
[ "Raise", "an", "exception", "if", "a", "namespace", "is", "already", "defined", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L157-L163
train
29,640
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.handle_namespace_url
def handle_namespace_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``. :raises: RedefinedNamespaceError :raises: pybel.resources.exc.ResourceError """ namespace = tokens['name'] self.raise_for_redefined_namespace(line, position, namespace) url = tokens['url'] self.namespace_url_dict[namespace] = url if self.skip_validation: return tokens namespace_result = self.manager.get_or_create_namespace(url) if isinstance(namespace_result, dict): self.namespace_to_term[namespace] = namespace_result self.uncachable_namespaces.add(url) else: self.namespace_to_term[namespace] = self.manager.get_namespace_encoding(url) return tokens
python
def handle_namespace_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``. :raises: RedefinedNamespaceError :raises: pybel.resources.exc.ResourceError """ namespace = tokens['name'] self.raise_for_redefined_namespace(line, position, namespace) url = tokens['url'] self.namespace_url_dict[namespace] = url if self.skip_validation: return tokens namespace_result = self.manager.get_or_create_namespace(url) if isinstance(namespace_result, dict): self.namespace_to_term[namespace] = namespace_result self.uncachable_namespaces.add(url) else: self.namespace_to_term[namespace] = self.manager.get_namespace_encoding(url) return tokens
[ "def", "handle_namespace_url", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "namespace", "=", "tokens", "[", "'name'", "]", "self", ".", "raise_for_redefined_namespace", ...
Handle statements like ``DEFINE NAMESPACE X AS URL "Y"``. :raises: RedefinedNamespaceError :raises: pybel.resources.exc.ResourceError
[ "Handle", "statements", "like", "DEFINE", "NAMESPACE", "X", "AS", "URL", "Y", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L165-L188
train
29,641
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.handle_namespace_pattern
def handle_namespace_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE NAMESPACE X AS PATTERN "Y"``. :raises: RedefinedNamespaceError """ namespace = tokens['name'] self.raise_for_redefined_namespace(line, position, namespace) self.namespace_to_pattern[namespace] = re.compile(tokens['value']) return tokens
python
def handle_namespace_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE NAMESPACE X AS PATTERN "Y"``. :raises: RedefinedNamespaceError """ namespace = tokens['name'] self.raise_for_redefined_namespace(line, position, namespace) self.namespace_to_pattern[namespace] = re.compile(tokens['value']) return tokens
[ "def", "handle_namespace_pattern", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "namespace", "=", "tokens", "[", "'name'", "]", "self", ".", "raise_for_redefined_namespac...
Handle statements like ``DEFINE NAMESPACE X AS PATTERN "Y"``. :raises: RedefinedNamespaceError
[ "Handle", "statements", "like", "DEFINE", "NAMESPACE", "X", "AS", "PATTERN", "Y", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L190-L198
train
29,642
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.raise_for_redefined_annotation
def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None: """Raise an exception if the given annotation is already defined. :raises: RedefinedAnnotationError """ if self.disallow_redefinition and self.has_annotation(annotation): raise RedefinedAnnotationError(self.get_line_number(), line, position, annotation)
python
def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None: """Raise an exception if the given annotation is already defined. :raises: RedefinedAnnotationError """ if self.disallow_redefinition and self.has_annotation(annotation): raise RedefinedAnnotationError(self.get_line_number(), line, position, annotation)
[ "def", "raise_for_redefined_annotation", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "annotation", ":", "str", ")", "->", "None", ":", "if", "self", ".", "disallow_redefinition", "and", "self", ".", "has_annotation", "(", "annotat...
Raise an exception if the given annotation is already defined. :raises: RedefinedAnnotationError
[ "Raise", "an", "exception", "if", "the", "given", "annotation", "is", "already", "defined", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L200-L206
train
29,643
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.handle_annotations_url
def handle_annotations_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS URL "Y"``. :raises: RedefinedAnnotationError """ keyword = tokens['name'] self.raise_for_redefined_annotation(line, position, keyword) url = tokens['url'] self.annotation_url_dict[keyword] = url if self.skip_validation: return tokens self.annotation_to_term[keyword] = self.manager.get_annotation_entry_names(url) return tokens
python
def handle_annotations_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS URL "Y"``. :raises: RedefinedAnnotationError """ keyword = tokens['name'] self.raise_for_redefined_annotation(line, position, keyword) url = tokens['url'] self.annotation_url_dict[keyword] = url if self.skip_validation: return tokens self.annotation_to_term[keyword] = self.manager.get_annotation_entry_names(url) return tokens
[ "def", "handle_annotations_url", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "keyword", "=", "tokens", "[", "'name'", "]", "self", ".", "raise_for_redefined_annotation",...
Handle statements like ``DEFINE ANNOTATION X AS URL "Y"``. :raises: RedefinedAnnotationError
[ "Handle", "statements", "like", "DEFINE", "ANNOTATION", "X", "AS", "URL", "Y", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L208-L224
train
29,644
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.handle_annotation_pattern
def handle_annotation_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS PATTERN "Y"``. :raises: RedefinedAnnotationError """ annotation = tokens['name'] self.raise_for_redefined_annotation(line, position, annotation) self.annotation_to_pattern[annotation] = re.compile(tokens['value']) return tokens
python
def handle_annotation_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS PATTERN "Y"``. :raises: RedefinedAnnotationError """ annotation = tokens['name'] self.raise_for_redefined_annotation(line, position, annotation) self.annotation_to_pattern[annotation] = re.compile(tokens['value']) return tokens
[ "def", "handle_annotation_pattern", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "annotation", "=", "tokens", "[", "'name'", "]", "self", ".", "raise_for_redefined_annota...
Handle statements like ``DEFINE ANNOTATION X AS PATTERN "Y"``. :raises: RedefinedAnnotationError
[ "Handle", "statements", "like", "DEFINE", "ANNOTATION", "X", "AS", "PATTERN", "Y", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L236-L244
train
29,645
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.has_annotation
def has_annotation(self, annotation: str) -> bool: """Check if this annotation is defined.""" return ( self.has_enumerated_annotation(annotation) or self.has_regex_annotation(annotation) or self.has_local_annotation(annotation) )
python
def has_annotation(self, annotation: str) -> bool: """Check if this annotation is defined.""" return ( self.has_enumerated_annotation(annotation) or self.has_regex_annotation(annotation) or self.has_local_annotation(annotation) )
[ "def", "has_annotation", "(", "self", ",", "annotation", ":", "str", ")", "->", "bool", ":", "return", "(", "self", ".", "has_enumerated_annotation", "(", "annotation", ")", "or", "self", ".", "has_regex_annotation", "(", "annotation", ")", "or", "self", "."...
Check if this annotation is defined.
[ "Check", "if", "this", "annotation", "is", "defined", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L258-L264
train
29,646
pybel/pybel
src/pybel/parser/parse_metadata.py
MetadataParser.raise_for_version
def raise_for_version(self, line: str, position: int, version: str) -> None: """Check that a version string is valid for BEL documents. This means it's either in the YYYYMMDD or semantic version format. :param line: The line being parsed :param position: The position in the line being parsed :param str version: A version string :raises: VersionFormatWarning """ if valid_date_version(version): return if not SEMANTIC_VERSION_STRING_RE.match(version): raise VersionFormatWarning(self.get_line_number(), line, position, version)
python
def raise_for_version(self, line: str, position: int, version: str) -> None: """Check that a version string is valid for BEL documents. This means it's either in the YYYYMMDD or semantic version format. :param line: The line being parsed :param position: The position in the line being parsed :param str version: A version string :raises: VersionFormatWarning """ if valid_date_version(version): return if not SEMANTIC_VERSION_STRING_RE.match(version): raise VersionFormatWarning(self.get_line_number(), line, position, version)
[ "def", "raise_for_version", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "version", ":", "str", ")", "->", "None", ":", "if", "valid_date_version", "(", "version", ")", ":", "return", "if", "not", "SEMANTIC_VERSION_STRING_RE", "....
Check that a version string is valid for BEL documents. This means it's either in the YYYYMMDD or semantic version format. :param line: The line being parsed :param position: The position in the line being parsed :param str version: A version string :raises: VersionFormatWarning
[ "Check", "that", "a", "version", "string", "is", "valid", "for", "BEL", "documents", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_metadata.py#L278-L292
train
29,647
pybel/pybel
src/pybel/dsl/namespaces.py
chebi
def chebi(name=None, identifier=None) -> Abundance: """Build a ChEBI abundance node.""" return Abundance(namespace='CHEBI', name=name, identifier=identifier)
python
def chebi(name=None, identifier=None) -> Abundance: """Build a ChEBI abundance node.""" return Abundance(namespace='CHEBI', name=name, identifier=identifier)
[ "def", "chebi", "(", "name", "=", "None", ",", "identifier", "=", "None", ")", "->", "Abundance", ":", "return", "Abundance", "(", "namespace", "=", "'CHEBI'", ",", "name", "=", "name", ",", "identifier", "=", "identifier", ")" ]
Build a ChEBI abundance node.
[ "Build", "a", "ChEBI", "abundance", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/namespaces.py#L13-L15
train
29,648
pybel/pybel
src/pybel/dsl/namespaces.py
hgnc
def hgnc(name=None, identifier=None) -> Protein: """Build an HGNC protein node.""" return Protein(namespace='HGNC', name=name, identifier=identifier)
python
def hgnc(name=None, identifier=None) -> Protein: """Build an HGNC protein node.""" return Protein(namespace='HGNC', name=name, identifier=identifier)
[ "def", "hgnc", "(", "name", "=", "None", ",", "identifier", "=", "None", ")", "->", "Protein", ":", "return", "Protein", "(", "namespace", "=", "'HGNC'", ",", "name", "=", "name", ",", "identifier", "=", "identifier", ")" ]
Build an HGNC protein node.
[ "Build", "an", "HGNC", "protein", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/namespaces.py#L18-L20
train
29,649
pybel/pybel
src/pybel/manager/base_manager.py
build_engine_session
def build_engine_session(connection: str, echo: bool = False, autoflush: Optional[bool] = None, autocommit: Optional[bool] = None, expire_on_commit: Optional[bool] = None, scopefunc=None) -> Tuple: """Build an engine and a session. :param connection: An RFC-1738 database connection string :param echo: Turn on echoing SQL :param autoflush: Defaults to True if not specified in kwargs or configuration. :param autocommit: Defaults to False if not specified in kwargs or configuration. :param expire_on_commit: Defaults to False if not specified in kwargs or configuration. :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session` :rtype: tuple[Engine,Session] From the Flask-SQLAlchemy documentation: An extra key ``'scopefunc'`` can be set on the ``options`` dict to specify a custom scope function. If it's not provided, Flask's app context stack identity is used. This will ensure that sessions are created and removed with the request/response cycle, and should be fine in most cases. """ if connection is None: raise ValueError('can not build engine when connection is None') engine = create_engine(connection, echo=echo) if autoflush is None: autoflush = config.get('PYBEL_MANAGER_AUTOFLUSH', False) if autocommit is None: autocommit = config.get('PYBEL_MANAGER_AUTOCOMMIT', False) if expire_on_commit is None: expire_on_commit = config.get('PYBEL_MANAGER_AUTOEXPIRE', True) log.debug('auto flush: %s, auto commit: %s, expire on commmit: %s', autoflush, autocommit, expire_on_commit) #: A SQLAlchemy session maker session_maker = sessionmaker( bind=engine, autoflush=autoflush, autocommit=autocommit, expire_on_commit=expire_on_commit, ) #: A SQLAlchemy session object session = scoped_session( session_maker, scopefunc=scopefunc, ) return engine, session
python
def build_engine_session(connection: str, echo: bool = False, autoflush: Optional[bool] = None, autocommit: Optional[bool] = None, expire_on_commit: Optional[bool] = None, scopefunc=None) -> Tuple: """Build an engine and a session. :param connection: An RFC-1738 database connection string :param echo: Turn on echoing SQL :param autoflush: Defaults to True if not specified in kwargs or configuration. :param autocommit: Defaults to False if not specified in kwargs or configuration. :param expire_on_commit: Defaults to False if not specified in kwargs or configuration. :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session` :rtype: tuple[Engine,Session] From the Flask-SQLAlchemy documentation: An extra key ``'scopefunc'`` can be set on the ``options`` dict to specify a custom scope function. If it's not provided, Flask's app context stack identity is used. This will ensure that sessions are created and removed with the request/response cycle, and should be fine in most cases. """ if connection is None: raise ValueError('can not build engine when connection is None') engine = create_engine(connection, echo=echo) if autoflush is None: autoflush = config.get('PYBEL_MANAGER_AUTOFLUSH', False) if autocommit is None: autocommit = config.get('PYBEL_MANAGER_AUTOCOMMIT', False) if expire_on_commit is None: expire_on_commit = config.get('PYBEL_MANAGER_AUTOEXPIRE', True) log.debug('auto flush: %s, auto commit: %s, expire on commmit: %s', autoflush, autocommit, expire_on_commit) #: A SQLAlchemy session maker session_maker = sessionmaker( bind=engine, autoflush=autoflush, autocommit=autocommit, expire_on_commit=expire_on_commit, ) #: A SQLAlchemy session object session = scoped_session( session_maker, scopefunc=scopefunc, ) return engine, session
[ "def", "build_engine_session", "(", "connection", ":", "str", ",", "echo", ":", "bool", "=", "False", ",", "autoflush", ":", "Optional", "[", "bool", "]", "=", "None", ",", "autocommit", ":", "Optional", "[", "bool", "]", "=", "None", ",", "expire_on_com...
Build an engine and a session. :param connection: An RFC-1738 database connection string :param echo: Turn on echoing SQL :param autoflush: Defaults to True if not specified in kwargs or configuration. :param autocommit: Defaults to False if not specified in kwargs or configuration. :param expire_on_commit: Defaults to False if not specified in kwargs or configuration. :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session` :rtype: tuple[Engine,Session] From the Flask-SQLAlchemy documentation: An extra key ``'scopefunc'`` can be set on the ``options`` dict to specify a custom scope function. If it's not provided, Flask's app context stack identity is used. This will ensure that sessions are created and removed with the request/response cycle, and should be fine in most cases.
[ "Build", "an", "engine", "and", "a", "session", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/base_manager.py#L24-L78
train
29,650
pybel/pybel
src/pybel/manager/base_manager.py
BaseManager.create_all
def create_all(self, checkfirst: bool = True) -> None: """Create the PyBEL cache's database and tables. :param checkfirst: Check if the database exists before trying to re-make it """ self.base.metadata.create_all(bind=self.engine, checkfirst=checkfirst)
python
def create_all(self, checkfirst: bool = True) -> None: """Create the PyBEL cache's database and tables. :param checkfirst: Check if the database exists before trying to re-make it """ self.base.metadata.create_all(bind=self.engine, checkfirst=checkfirst)
[ "def", "create_all", "(", "self", ",", "checkfirst", ":", "bool", "=", "True", ")", "->", "None", ":", "self", ".", "base", ".", "metadata", ".", "create_all", "(", "bind", "=", "self", ".", "engine", ",", "checkfirst", "=", "checkfirst", ")" ]
Create the PyBEL cache's database and tables. :param checkfirst: Check if the database exists before trying to re-make it
[ "Create", "the", "PyBEL", "cache", "s", "database", "and", "tables", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/base_manager.py#L92-L97
train
29,651
pybel/pybel
src/pybel/manager/base_manager.py
BaseManager.drop_all
def drop_all(self, checkfirst: bool = True) -> None: """Drop all data, tables, and databases for the PyBEL cache. :param checkfirst: Check if the database exists before trying to drop it """ self.session.close() self.base.metadata.drop_all(bind=self.engine, checkfirst=checkfirst)
python
def drop_all(self, checkfirst: bool = True) -> None: """Drop all data, tables, and databases for the PyBEL cache. :param checkfirst: Check if the database exists before trying to drop it """ self.session.close() self.base.metadata.drop_all(bind=self.engine, checkfirst=checkfirst)
[ "def", "drop_all", "(", "self", ",", "checkfirst", ":", "bool", "=", "True", ")", "->", "None", ":", "self", ".", "session", ".", "close", "(", ")", "self", ".", "base", ".", "metadata", ".", "drop_all", "(", "bind", "=", "self", ".", "engine", ","...
Drop all data, tables, and databases for the PyBEL cache. :param checkfirst: Check if the database exists before trying to drop it
[ "Drop", "all", "data", "tables", "and", "databases", "for", "the", "PyBEL", "cache", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/base_manager.py#L99-L105
train
29,652
pybel/pybel
src/pybel/manager/base_manager.py
BaseManager.bind
def bind(self) -> None: """Bind the metadata to the engine and session.""" self.base.metadata.bind = self.engine self.base.query = self.session.query_property()
python
def bind(self) -> None: """Bind the metadata to the engine and session.""" self.base.metadata.bind = self.engine self.base.query = self.session.query_property()
[ "def", "bind", "(", "self", ")", "->", "None", ":", "self", ".", "base", ".", "metadata", ".", "bind", "=", "self", ".", "engine", "self", ".", "base", ".", "query", "=", "self", ".", "session", ".", "query_property", "(", ")" ]
Bind the metadata to the engine and session.
[ "Bind", "the", "metadata", "to", "the", "engine", "and", "session", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/base_manager.py#L107-L110
train
29,653
pybel/pybel
src/pybel/manager/base_manager.py
BaseManager._list_model
def _list_model(self, model_cls: Type[X]) -> List[X]: """List the models in this class.""" return self.session.query(model_cls).all()
python
def _list_model(self, model_cls: Type[X]) -> List[X]: """List the models in this class.""" return self.session.query(model_cls).all()
[ "def", "_list_model", "(", "self", ",", "model_cls", ":", "Type", "[", "X", "]", ")", "->", "List", "[", "X", "]", ":", "return", "self", ".", "session", ".", "query", "(", "model_cls", ")", ".", "all", "(", ")" ]
List the models in this class.
[ "List", "the", "models", "in", "this", "class", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/base_manager.py#L112-L114
train
29,654
pybel/pybel
src/pybel/manager/citation_utils.py
sanitize_date
def sanitize_date(publication_date: str) -> str: """Sanitize lots of different date strings into ISO-8601.""" if re1.search(publication_date): return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d') if re2.search(publication_date): return datetime.strptime(publication_date, '%Y %b').strftime('%Y-%m-01') if re3.search(publication_date): return publication_date + "-01-01" if re4.search(publication_date): return datetime.strptime(publication_date[:-4], '%Y %b').strftime('%Y-%m-01') s = re5.search(publication_date) if s: year, season = s.groups() return '{}-{}-01'.format(year, season_map[season]) s = re6.search(publication_date) if s: return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d') s = re7.search(publication_date) if s: return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')
python
def sanitize_date(publication_date: str) -> str: """Sanitize lots of different date strings into ISO-8601.""" if re1.search(publication_date): return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d') if re2.search(publication_date): return datetime.strptime(publication_date, '%Y %b').strftime('%Y-%m-01') if re3.search(publication_date): return publication_date + "-01-01" if re4.search(publication_date): return datetime.strptime(publication_date[:-4], '%Y %b').strftime('%Y-%m-01') s = re5.search(publication_date) if s: year, season = s.groups() return '{}-{}-01'.format(year, season_map[season]) s = re6.search(publication_date) if s: return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d') s = re7.search(publication_date) if s: return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')
[ "def", "sanitize_date", "(", "publication_date", ":", "str", ")", "->", "str", ":", "if", "re1", ".", "search", "(", "publication_date", ")", ":", "return", "datetime", ".", "strptime", "(", "publication_date", ",", "'%Y %b %d'", ")", ".", "strftime", "(", ...
Sanitize lots of different date strings into ISO-8601.
[ "Sanitize", "lots", "of", "different", "date", "strings", "into", "ISO", "-", "8601", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L39-L67
train
29,655
pybel/pybel
src/pybel/manager/citation_utils.py
clean_pubmed_identifiers
def clean_pubmed_identifiers(pmids: Iterable[str]) -> List[str]: """Clean a list of PubMed identifiers with string strips, deduplicates, and sorting.""" return sorted({str(pmid).strip() for pmid in pmids})
python
def clean_pubmed_identifiers(pmids: Iterable[str]) -> List[str]: """Clean a list of PubMed identifiers with string strips, deduplicates, and sorting.""" return sorted({str(pmid).strip() for pmid in pmids})
[ "def", "clean_pubmed_identifiers", "(", "pmids", ":", "Iterable", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "sorted", "(", "{", "str", "(", "pmid", ")", ".", "strip", "(", ")", "for", "pmid", "in", "pmids", "}", ")" ]
Clean a list of PubMed identifiers with string strips, deduplicates, and sorting.
[ "Clean", "a", "list", "of", "PubMed", "identifiers", "with", "string", "strips", "deduplicates", "and", "sorting", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L79-L81
train
29,656
pybel/pybel
src/pybel/manager/citation_utils.py
get_pubmed_citation_response
def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict """ pubmed_identifiers = list(pubmed_identifiers) url = EUTILS_URL_FMT.format(','.join( pubmed_identifier for pubmed_identifier in pubmed_identifiers if pubmed_identifier )) response = requests.get(url) return response.json()
python
def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict """ pubmed_identifiers = list(pubmed_identifiers) url = EUTILS_URL_FMT.format(','.join( pubmed_identifier for pubmed_identifier in pubmed_identifiers if pubmed_identifier )) response = requests.get(url) return response.json()
[ "def", "get_pubmed_citation_response", "(", "pubmed_identifiers", ":", "Iterable", "[", "str", "]", ")", ":", "pubmed_identifiers", "=", "list", "(", "pubmed_identifiers", ")", "url", "=", "EUTILS_URL_FMT", ".", "format", "(", "','", ".", "join", "(", "pubmed_id...
Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict
[ "Get", "the", "response", "from", "PubMed", "E", "-", "Utils", "for", "a", "given", "list", "of", "PubMed", "identifiers", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L84-L97
train
29,657
pybel/pybel
src/pybel/manager/citation_utils.py
enrich_citation_model
def enrich_citation_model(manager, citation, p) -> bool: """Enrich a citation model with the information from PubMed. :param pybel.manager.Manager manager: :param Citation citation: A citation model :param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid] """ if 'error' in p: log.warning('Error downloading PubMed') return False citation.name = p['fulljournalname'] citation.title = p['title'] citation.volume = p['volume'] citation.issue = p['issue'] citation.pages = p['pages'] citation.first = manager.get_or_create_author(p['sortfirstauthor']) citation.last = manager.get_or_create_author(p['lastauthor']) if 'authors' in p: for author in p['authors']: author_model = manager.get_or_create_author(author['name']) if author_model not in citation.authors: citation.authors.append(author_model) publication_date = p['pubdate'] sanitized_publication_date = sanitize_date(publication_date) if sanitized_publication_date: citation.date = datetime.strptime(sanitized_publication_date, '%Y-%m-%d') else: log.info('result had date with strange format: %s', publication_date) return True
python
def enrich_citation_model(manager, citation, p) -> bool: """Enrich a citation model with the information from PubMed. :param pybel.manager.Manager manager: :param Citation citation: A citation model :param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid] """ if 'error' in p: log.warning('Error downloading PubMed') return False citation.name = p['fulljournalname'] citation.title = p['title'] citation.volume = p['volume'] citation.issue = p['issue'] citation.pages = p['pages'] citation.first = manager.get_or_create_author(p['sortfirstauthor']) citation.last = manager.get_or_create_author(p['lastauthor']) if 'authors' in p: for author in p['authors']: author_model = manager.get_or_create_author(author['name']) if author_model not in citation.authors: citation.authors.append(author_model) publication_date = p['pubdate'] sanitized_publication_date = sanitize_date(publication_date) if sanitized_publication_date: citation.date = datetime.strptime(sanitized_publication_date, '%Y-%m-%d') else: log.info('result had date with strange format: %s', publication_date) return True
[ "def", "enrich_citation_model", "(", "manager", ",", "citation", ",", "p", ")", "->", "bool", ":", "if", "'error'", "in", "p", ":", "log", ".", "warning", "(", "'Error downloading PubMed'", ")", "return", "False", "citation", ".", "name", "=", "p", "[", ...
Enrich a citation model with the information from PubMed. :param pybel.manager.Manager manager: :param Citation citation: A citation model :param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid]
[ "Enrich", "a", "citation", "model", "with", "the", "information", "from", "PubMed", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L100-L133
train
29,658
pybel/pybel
src/pybel/manager/citation_utils.py
get_citations_by_pmids
def get_citations_by_pmids(manager, pmids: Iterable[Union[str, int]], group_size: Optional[int] = None, sleep_time: Optional[int] = None, ) -> Tuple[Dict[str, Dict], Set[str]]: """Get citation information for the given list of PubMed identifiers using the NCBI's eUtils service. :type manager: pybel.Manager :param pmids: an iterable of PubMed identifiers :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A dictionary of {pmid: pmid data dictionary} or a pair of this dictionary and a set ot erroneous pmids if return_errors is :data:`True` """ group_size = group_size if group_size is not None else 200 sleep_time = sleep_time if sleep_time is not None else 1 pmids = clean_pubmed_identifiers(pmids) log.info('Ensuring %d PubMed identifiers', len(pmids)) result = {} unenriched_pmids = {} for pmid in pmids: citation = manager.get_or_create_citation(type=CITATION_TYPE_PUBMED, reference=pmid) if not citation.date or not citation.name or not citation.authors: unenriched_pmids[pmid] = citation continue result[pmid] = citation.to_json() manager.session.commit() log.debug('Found %d PubMed identifiers in database', len(pmids) - len(unenriched_pmids)) if not unenriched_pmids: return result, set() number_unenriched = len(unenriched_pmids) log.info('Querying PubMed for %d identifiers', number_unenriched) errors = set() t = time.time() for pmid_group_index, pmid_list in enumerate(grouper(group_size, unenriched_pmids), start=1): pmid_list = list(pmid_list) log.info('Getting group %d having %d PubMed identifiers', pmid_group_index, len(pmid_list)) response = get_pubmed_citation_response(pmid_list) response_pmids = response['result']['uids'] for pmid in response_pmids: p = response['result'][pmid] citation = unenriched_pmids[pmid] successful_enrichment = enrich_citation_model(manager, citation, p) if not successful_enrichment: log.warning("Error downloading PubMed identifier: %s", pmid) errors.add(pmid) continue result[pmid] = citation.to_json() manager.session.add(citation) manager.session.commit() # commit in groups # Don't want to hit that rate limit time.sleep(sleep_time) log.info('retrieved %d PubMed identifiers in %.02f seconds', len(unenriched_pmids), time.time() - t) return result, errors
python
def get_citations_by_pmids(manager, pmids: Iterable[Union[str, int]], group_size: Optional[int] = None, sleep_time: Optional[int] = None, ) -> Tuple[Dict[str, Dict], Set[str]]: """Get citation information for the given list of PubMed identifiers using the NCBI's eUtils service. :type manager: pybel.Manager :param pmids: an iterable of PubMed identifiers :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A dictionary of {pmid: pmid data dictionary} or a pair of this dictionary and a set ot erroneous pmids if return_errors is :data:`True` """ group_size = group_size if group_size is not None else 200 sleep_time = sleep_time if sleep_time is not None else 1 pmids = clean_pubmed_identifiers(pmids) log.info('Ensuring %d PubMed identifiers', len(pmids)) result = {} unenriched_pmids = {} for pmid in pmids: citation = manager.get_or_create_citation(type=CITATION_TYPE_PUBMED, reference=pmid) if not citation.date or not citation.name or not citation.authors: unenriched_pmids[pmid] = citation continue result[pmid] = citation.to_json() manager.session.commit() log.debug('Found %d PubMed identifiers in database', len(pmids) - len(unenriched_pmids)) if not unenriched_pmids: return result, set() number_unenriched = len(unenriched_pmids) log.info('Querying PubMed for %d identifiers', number_unenriched) errors = set() t = time.time() for pmid_group_index, pmid_list in enumerate(grouper(group_size, unenriched_pmids), start=1): pmid_list = list(pmid_list) log.info('Getting group %d having %d PubMed identifiers', pmid_group_index, len(pmid_list)) response = get_pubmed_citation_response(pmid_list) response_pmids = response['result']['uids'] for pmid in response_pmids: p = response['result'][pmid] citation = unenriched_pmids[pmid] successful_enrichment = enrich_citation_model(manager, citation, p) if not successful_enrichment: log.warning("Error downloading PubMed identifier: %s", pmid) errors.add(pmid) continue result[pmid] = citation.to_json() manager.session.add(citation) manager.session.commit() # commit in groups # Don't want to hit that rate limit time.sleep(sleep_time) log.info('retrieved %d PubMed identifiers in %.02f seconds', len(unenriched_pmids), time.time() - t) return result, errors
[ "def", "get_citations_by_pmids", "(", "manager", ",", "pmids", ":", "Iterable", "[", "Union", "[", "str", ",", "int", "]", "]", ",", "group_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "sleep_time", ":", "Optional", "[", "int", "]", "=", ...
Get citation information for the given list of PubMed identifiers using the NCBI's eUtils service. :type manager: pybel.Manager :param pmids: an iterable of PubMed identifiers :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A dictionary of {pmid: pmid data dictionary} or a pair of this dictionary and a set ot erroneous pmids if return_errors is :data:`True`
[ "Get", "citation", "information", "for", "the", "given", "list", "of", "PubMed", "identifiers", "using", "the", "NCBI", "s", "eUtils", "service", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L136-L209
train
29,659
pybel/pybel
src/pybel/manager/citation_utils.py
enrich_pubmed_citations
def enrich_pubmed_citations(manager, graph, group_size: Optional[int] = None, sleep_time: Optional[int] = None, ) -> Set[str]: """Overwrite all PubMed citations with values from NCBI's eUtils lookup service. Sets authors as list, so probably a good idea to run :func:`pybel_tools.mutation.serialize_authors` before exporting. :type manager: pybel.manager.Manager :type graph: pybel.BELGraph :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A set of PMIDs for which the eUtils service crashed """ pmids = get_pubmed_identifiers(graph) pmid_data, errors = get_citations_by_pmids(manager, pmids=pmids, group_size=group_size, sleep_time=sleep_time) for u, v, k in filter_edges(graph, has_pubmed): pmid = graph[u][v][k][CITATION][CITATION_REFERENCE].strip() if pmid not in pmid_data: log.warning('Missing data for PubMed identifier: %s', pmid) errors.add(pmid) continue graph[u][v][k][CITATION].update(pmid_data[pmid]) return errors
python
def enrich_pubmed_citations(manager, graph, group_size: Optional[int] = None, sleep_time: Optional[int] = None, ) -> Set[str]: """Overwrite all PubMed citations with values from NCBI's eUtils lookup service. Sets authors as list, so probably a good idea to run :func:`pybel_tools.mutation.serialize_authors` before exporting. :type manager: pybel.manager.Manager :type graph: pybel.BELGraph :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A set of PMIDs for which the eUtils service crashed """ pmids = get_pubmed_identifiers(graph) pmid_data, errors = get_citations_by_pmids(manager, pmids=pmids, group_size=group_size, sleep_time=sleep_time) for u, v, k in filter_edges(graph, has_pubmed): pmid = graph[u][v][k][CITATION][CITATION_REFERENCE].strip() if pmid not in pmid_data: log.warning('Missing data for PubMed identifier: %s', pmid) errors.add(pmid) continue graph[u][v][k][CITATION].update(pmid_data[pmid]) return errors
[ "def", "enrich_pubmed_citations", "(", "manager", ",", "graph", ",", "group_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "sleep_time", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "Set", "[", "str", "]", ":", "pmids", ...
Overwrite all PubMed citations with values from NCBI's eUtils lookup service. Sets authors as list, so probably a good idea to run :func:`pybel_tools.mutation.serialize_authors` before exporting. :type manager: pybel.manager.Manager :type graph: pybel.BELGraph :param group_size: The number of PubMed identifiers to query at a time. Defaults to 200 identifiers. :param sleep_time: Number of seconds to sleep between queries. Defaults to 1 second. :return: A set of PMIDs for which the eUtils service crashed
[ "Overwrite", "all", "PubMed", "citations", "with", "values", "from", "NCBI", "s", "eUtils", "lookup", "service", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/citation_utils.py#L212-L241
train
29,660
pybel/pybel
src/pybel/struct/mutation/collapse/protein_rna_origins.py
_build_collapse_to_gene_dict
def _build_collapse_to_gene_dict(graph) -> Dict[BaseEntity, Set[BaseEntity]]: """Build a collapse dictionary. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {node: set of PyBEL node tuples} """ collapse_dict = defaultdict(set) r2g = {} for gene_node, rna_node, d in graph.edges(data=True): if d[RELATION] != TRANSCRIBED_TO: continue collapse_dict[gene_node].add(rna_node) r2g[rna_node] = gene_node for rna_node, protein_node, d in graph.edges(data=True): if d[RELATION] != TRANSLATED_TO: continue if rna_node not in r2g: raise ValueError('Should complete origin before running this function') collapse_dict[r2g[rna_node]].add(protein_node) return collapse_dict
python
def _build_collapse_to_gene_dict(graph) -> Dict[BaseEntity, Set[BaseEntity]]: """Build a collapse dictionary. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {node: set of PyBEL node tuples} """ collapse_dict = defaultdict(set) r2g = {} for gene_node, rna_node, d in graph.edges(data=True): if d[RELATION] != TRANSCRIBED_TO: continue collapse_dict[gene_node].add(rna_node) r2g[rna_node] = gene_node for rna_node, protein_node, d in graph.edges(data=True): if d[RELATION] != TRANSLATED_TO: continue if rna_node not in r2g: raise ValueError('Should complete origin before running this function') collapse_dict[r2g[rna_node]].add(protein_node) return collapse_dict
[ "def", "_build_collapse_to_gene_dict", "(", "graph", ")", "->", "Dict", "[", "BaseEntity", ",", "Set", "[", "BaseEntity", "]", "]", ":", "collapse_dict", "=", "defaultdict", "(", "set", ")", "r2g", "=", "{", "}", "for", "gene_node", ",", "rna_node", ",", ...
Build a collapse dictionary. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {node: set of PyBEL node tuples}
[ "Build", "a", "collapse", "dictionary", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/collapse/protein_rna_origins.py#L19-L44
train
29,661
pybel/pybel
src/pybel/struct/mutation/collapse/protein_rna_origins.py
collapse_to_genes
def collapse_to_genes(graph): """Collapse all protein, RNA, and miRNA nodes to their corresponding gene nodes. :param pybel.BELGraph graph: A BEL graph """ enrich_protein_and_rna_origins(graph) collapse_dict = _build_collapse_to_gene_dict(graph) collapse_nodes(graph, collapse_dict)
python
def collapse_to_genes(graph): """Collapse all protein, RNA, and miRNA nodes to their corresponding gene nodes. :param pybel.BELGraph graph: A BEL graph """ enrich_protein_and_rna_origins(graph) collapse_dict = _build_collapse_to_gene_dict(graph) collapse_nodes(graph, collapse_dict)
[ "def", "collapse_to_genes", "(", "graph", ")", ":", "enrich_protein_and_rna_origins", "(", "graph", ")", "collapse_dict", "=", "_build_collapse_to_gene_dict", "(", "graph", ")", "collapse_nodes", "(", "graph", ",", "collapse_dict", ")" ]
Collapse all protein, RNA, and miRNA nodes to their corresponding gene nodes. :param pybel.BELGraph graph: A BEL graph
[ "Collapse", "all", "protein", "RNA", "and", "miRNA", "nodes", "to", "their", "corresponding", "gene", "nodes", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/collapse/protein_rna_origins.py#L49-L56
train
29,662
pybel/pybel
src/pybel/cli.py
main
def main(ctx, connection): """Command line interface for PyBEL.""" ctx.obj = Manager(connection=connection) ctx.obj.bind()
python
def main(ctx, connection): """Command line interface for PyBEL.""" ctx.obj = Manager(connection=connection) ctx.obj.bind()
[ "def", "main", "(", "ctx", ",", "connection", ")", ":", "ctx", ".", "obj", "=", "Manager", "(", "connection", "=", "connection", ")", "ctx", ".", "obj", ".", "bind", "(", ")" ]
Command line interface for PyBEL.
[ "Command", "line", "interface", "for", "PyBEL", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L87-L90
train
29,663
pybel/pybel
src/pybel/cli.py
compile
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations, no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose): """Compile a BEL script to a graph.""" if verbose: logging.basicConfig(level=logging.DEBUG) log.setLevel(logging.DEBUG) log.debug('using connection: %s', manager.engine.url) click.secho('Compilation', fg='red', bold=True) if skip_tqdm: click.echo('```') graph = from_path( path, manager=manager, use_tqdm=(not (skip_tqdm or verbose)), allow_nested=allow_nested, allow_naked_names=allow_naked_names, disallow_unqualified_translocations=disallow_unqualified_translocations, citation_clearing=(not no_citation_clearing), required_annotations=required_annotations, no_identifier_validation=no_identifier_validation, allow_definition_failures=True, ) if skip_tqdm: click.echo('```') to_pickle(graph, get_corresponding_pickle_path(path)) click.echo('') _print_summary(graph, ticks=skip_tqdm) sys.exit(0 if 0 == graph.number_of_warnings() else 1)
python
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations, no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose): """Compile a BEL script to a graph.""" if verbose: logging.basicConfig(level=logging.DEBUG) log.setLevel(logging.DEBUG) log.debug('using connection: %s', manager.engine.url) click.secho('Compilation', fg='red', bold=True) if skip_tqdm: click.echo('```') graph = from_path( path, manager=manager, use_tqdm=(not (skip_tqdm or verbose)), allow_nested=allow_nested, allow_naked_names=allow_naked_names, disallow_unqualified_translocations=disallow_unqualified_translocations, citation_clearing=(not no_citation_clearing), required_annotations=required_annotations, no_identifier_validation=no_identifier_validation, allow_definition_failures=True, ) if skip_tqdm: click.echo('```') to_pickle(graph, get_corresponding_pickle_path(path)) click.echo('') _print_summary(graph, ticks=skip_tqdm) sys.exit(0 if 0 == graph.number_of_warnings() else 1)
[ "def", "compile", "(", "manager", ",", "path", ",", "allow_naked_names", ",", "allow_nested", ",", "disallow_unqualified_translocations", ",", "no_identifier_validation", ",", "no_citation_clearing", ",", "required_annotations", ",", "skip_tqdm", ",", "verbose", ")", ":...
Compile a BEL script to a graph.
[ "Compile", "a", "BEL", "script", "to", "a", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L104-L134
train
29,664
pybel/pybel
src/pybel/cli.py
insert
def insert(manager, graph: BELGraph): """Insert a graph to the database.""" to_database(graph, manager=manager, use_tqdm=True)
python
def insert(manager, graph: BELGraph): """Insert a graph to the database.""" to_database(graph, manager=manager, use_tqdm=True)
[ "def", "insert", "(", "manager", ",", "graph", ":", "BELGraph", ")", ":", "to_database", "(", "graph", ",", "manager", "=", "manager", ",", "use_tqdm", "=", "True", ")" ]
Insert a graph to the database.
[ "Insert", "a", "graph", "to", "the", "database", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L200-L202
train
29,665
pybel/pybel
src/pybel/cli.py
post
def post(graph: BELGraph, host: str): """Upload a graph to BEL Commons.""" resp = to_web(graph, host=host) resp.raise_for_status()
python
def post(graph: BELGraph, host: str): """Upload a graph to BEL Commons.""" resp = to_web(graph, host=host) resp.raise_for_status()
[ "def", "post", "(", "graph", ":", "BELGraph", ",", "host", ":", "str", ")", ":", "resp", "=", "to_web", "(", "graph", ",", "host", "=", "host", ")", "resp", ".", "raise_for_status", "(", ")" ]
Upload a graph to BEL Commons.
[ "Upload", "a", "graph", "to", "BEL", "Commons", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L208-L211
train
29,666
pybel/pybel
src/pybel/cli.py
serialize
def serialize(graph: BELGraph, csv, sif, gsea, graphml, json, bel): """Serialize a graph to various formats.""" if csv: log.info('Outputting CSV to %s', csv) to_csv(graph, csv) if sif: log.info('Outputting SIF to %s', sif) to_sif(graph, sif) if graphml: log.info('Outputting GraphML to %s', graphml) to_graphml(graph, graphml) if gsea: log.info('Outputting GRP to %s', gsea) to_gsea(graph, gsea) if json: log.info('Outputting JSON to %s', json) to_json_file(graph, json) if bel: log.info('Outputting BEL to %s', bel) to_bel(graph, bel)
python
def serialize(graph: BELGraph, csv, sif, gsea, graphml, json, bel): """Serialize a graph to various formats.""" if csv: log.info('Outputting CSV to %s', csv) to_csv(graph, csv) if sif: log.info('Outputting SIF to %s', sif) to_sif(graph, sif) if graphml: log.info('Outputting GraphML to %s', graphml) to_graphml(graph, graphml) if gsea: log.info('Outputting GRP to %s', gsea) to_gsea(graph, gsea) if json: log.info('Outputting JSON to %s', json) to_json_file(graph, json) if bel: log.info('Outputting BEL to %s', bel) to_bel(graph, bel)
[ "def", "serialize", "(", "graph", ":", "BELGraph", ",", "csv", ",", "sif", ",", "gsea", ",", "graphml", ",", "json", ",", "bel", ")", ":", "if", "csv", ":", "log", ".", "info", "(", "'Outputting CSV to %s'", ",", "csv", ")", "to_csv", "(", "graph", ...
Serialize a graph to various formats.
[ "Serialize", "a", "graph", "to", "various", "formats", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L222-L246
train
29,667
pybel/pybel
src/pybel/cli.py
neo
def neo(graph: BELGraph, connection: str, password: str): """Upload to neo4j.""" import py2neo neo_graph = py2neo.Graph(connection, password=password) to_neo4j(graph, neo_graph)
python
def neo(graph: BELGraph, connection: str, password: str): """Upload to neo4j.""" import py2neo neo_graph = py2neo.Graph(connection, password=password) to_neo4j(graph, neo_graph)
[ "def", "neo", "(", "graph", ":", "BELGraph", ",", "connection", ":", "str", ",", "password", ":", "str", ")", ":", "import", "py2neo", "neo_graph", "=", "py2neo", ".", "Graph", "(", "connection", ",", "password", "=", "password", ")", "to_neo4j", "(", ...
Upload to neo4j.
[ "Upload", "to", "neo4j", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L253-L257
train
29,668
pybel/pybel
src/pybel/cli.py
machine
def machine(manager: Manager, agents: List[str], local: bool, host: str): """Get content from the INDRA machine and upload to BEL Commons.""" from indra.sources import indra_db_rest from pybel import from_indra_statements statements = indra_db_rest.get_statements(agents=agents) click.echo('got {} statements from INDRA'.format(len(statements))) graph = from_indra_statements( statements, name='INDRA Machine for {}'.format(', '.join(sorted(agents))), version=time.strftime('%Y%m%d'), ) click.echo('built BEL graph with {} nodes and {} edges'.format(graph.number_of_nodes(), graph.number_of_edges())) if 0 == len(graph): click.echo('not uploading empty graph') sys.exit(-1) if local: to_database(graph, manager=manager) else: resp = to_web(graph, host=host) resp.raise_for_status()
python
def machine(manager: Manager, agents: List[str], local: bool, host: str): """Get content from the INDRA machine and upload to BEL Commons.""" from indra.sources import indra_db_rest from pybel import from_indra_statements statements = indra_db_rest.get_statements(agents=agents) click.echo('got {} statements from INDRA'.format(len(statements))) graph = from_indra_statements( statements, name='INDRA Machine for {}'.format(', '.join(sorted(agents))), version=time.strftime('%Y%m%d'), ) click.echo('built BEL graph with {} nodes and {} edges'.format(graph.number_of_nodes(), graph.number_of_edges())) if 0 == len(graph): click.echo('not uploading empty graph') sys.exit(-1) if local: to_database(graph, manager=manager) else: resp = to_web(graph, host=host) resp.raise_for_status()
[ "def", "machine", "(", "manager", ":", "Manager", ",", "agents", ":", "List", "[", "str", "]", ",", "local", ":", "bool", ",", "host", ":", "str", ")", ":", "from", "indra", ".", "sources", "import", "indra_db_rest", "from", "pybel", "import", "from_in...
Get content from the INDRA machine and upload to BEL Commons.
[ "Get", "content", "from", "the", "INDRA", "machine", "and", "upload", "to", "BEL", "Commons", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L265-L288
train
29,669
pybel/pybel
src/pybel/cli.py
examples
def examples(manager: Manager): """Load examples to the database.""" for graph in (sialic_acid_graph, statin_graph, homology_graph, braf_graph, egf_graph): if manager.has_name_version(graph.name, graph.version): click.echo('already inserted {}'.format(graph)) continue click.echo('inserting {}'.format(graph)) manager.insert_graph(graph, use_tqdm=True)
python
def examples(manager: Manager): """Load examples to the database.""" for graph in (sialic_acid_graph, statin_graph, homology_graph, braf_graph, egf_graph): if manager.has_name_version(graph.name, graph.version): click.echo('already inserted {}'.format(graph)) continue click.echo('inserting {}'.format(graph)) manager.insert_graph(graph, use_tqdm=True)
[ "def", "examples", "(", "manager", ":", "Manager", ")", ":", "for", "graph", "in", "(", "sialic_acid_graph", ",", "statin_graph", ",", "homology_graph", ",", "braf_graph", ",", "egf_graph", ")", ":", "if", "manager", ".", "has_name_version", "(", "graph", "....
Load examples to the database.
[ "Load", "examples", "to", "the", "database", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L306-L313
train
29,670
pybel/pybel
src/pybel/cli.py
ls
def ls(manager: Manager, url: Optional[str], namespace_id: Optional[int]): """List cached namespaces.""" if url: n = manager.get_or_create_namespace(url) if isinstance(n, Namespace): _page(n.entries) else: click.echo('uncachable namespace') elif namespace_id is not None: _ls(manager, Namespace, namespace_id) else: click.echo('Missing argument -i or -u')
python
def ls(manager: Manager, url: Optional[str], namespace_id: Optional[int]): """List cached namespaces.""" if url: n = manager.get_or_create_namespace(url) if isinstance(n, Namespace): _page(n.entries) else: click.echo('uncachable namespace') elif namespace_id is not None: _ls(manager, Namespace, namespace_id) else: click.echo('Missing argument -i or -u')
[ "def", "ls", "(", "manager", ":", "Manager", ",", "url", ":", "Optional", "[", "str", "]", ",", "namespace_id", ":", "Optional", "[", "int", "]", ")", ":", "if", "url", ":", "n", "=", "manager", ".", "get_or_create_namespace", "(", "url", ")", "if", ...
List cached namespaces.
[ "List", "cached", "namespaces", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L343-L354
train
29,671
pybel/pybel
src/pybel/cli.py
ls
def ls(manager: Manager): """List network names, versions, and optionally, descriptions.""" for n in manager.list_networks(): click.echo('{}\t{}\t{}'.format(n.id, n.name, n.version))
python
def ls(manager: Manager): """List network names, versions, and optionally, descriptions.""" for n in manager.list_networks(): click.echo('{}\t{}\t{}'.format(n.id, n.name, n.version))
[ "def", "ls", "(", "manager", ":", "Manager", ")", ":", "for", "n", "in", "manager", ".", "list_networks", "(", ")", ":", "click", ".", "echo", "(", "'{}\\t{}\\t{}'", ".", "format", "(", "n", ".", "id", ",", "n", ".", "name", ",", "n", ".", "versi...
List network names, versions, and optionally, descriptions.
[ "List", "network", "names", "versions", "and", "optionally", "descriptions", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L372-L375
train
29,672
pybel/pybel
src/pybel/cli.py
drop
def drop(manager: Manager, network_id: Optional[int], yes): """Drop a network by its identifier or drop all networks.""" if network_id: manager.drop_network_by_id(network_id) elif yes or click.confirm('Drop all networks?'): manager.drop_networks()
python
def drop(manager: Manager, network_id: Optional[int], yes): """Drop a network by its identifier or drop all networks.""" if network_id: manager.drop_network_by_id(network_id) elif yes or click.confirm('Drop all networks?'): manager.drop_networks()
[ "def", "drop", "(", "manager", ":", "Manager", ",", "network_id", ":", "Optional", "[", "int", "]", ",", "yes", ")", ":", "if", "network_id", ":", "manager", ".", "drop_network_by_id", "(", "network_id", ")", "elif", "yes", "or", "click", ".", "confirm",...
Drop a network by its identifier or drop all networks.
[ "Drop", "a", "network", "by", "its", "identifier", "or", "drop", "all", "networks", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L382-L388
train
29,673
pybel/pybel
src/pybel/cli.py
ls
def ls(manager: Manager, offset: Optional[int], limit: Optional[int]): """List edges.""" q = manager.session.query(Edge) if offset: q = q.offset(offset) if limit > 0: q = q.limit(limit) for e in q: click.echo(e.bel)
python
def ls(manager: Manager, offset: Optional[int], limit: Optional[int]): """List edges.""" q = manager.session.query(Edge) if offset: q = q.offset(offset) if limit > 0: q = q.limit(limit) for e in q: click.echo(e.bel)
[ "def", "ls", "(", "manager", ":", "Manager", ",", "offset", ":", "Optional", "[", "int", "]", ",", "limit", ":", "Optional", "[", "int", "]", ")", ":", "q", "=", "manager", ".", "session", ".", "query", "(", "Edge", ")", "if", "offset", ":", "q",...
List edges.
[ "List", "edges", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L400-L411
train
29,674
pybel/pybel
src/pybel/cli.py
prune
def prune(manager: Manager): """Prune nodes not belonging to any edges.""" nodes_to_delete = [ node for node in tqdm(manager.session.query(Node), total=manager.count_nodes()) if not node.networks ] manager.session.delete(nodes_to_delete) manager.session.commit()
python
def prune(manager: Manager): """Prune nodes not belonging to any edges.""" nodes_to_delete = [ node for node in tqdm(manager.session.query(Node), total=manager.count_nodes()) if not node.networks ] manager.session.delete(nodes_to_delete) manager.session.commit()
[ "def", "prune", "(", "manager", ":", "Manager", ")", ":", "nodes_to_delete", "=", "[", "node", "for", "node", "in", "tqdm", "(", "manager", ".", "session", ".", "query", "(", "Node", ")", ",", "total", "=", "manager", ".", "count_nodes", "(", ")", ")...
Prune nodes not belonging to any edges.
[ "Prune", "nodes", "not", "belonging", "to", "any", "edges", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L421-L429
train
29,675
pybel/pybel
src/pybel/cli.py
summarize
def summarize(manager: Manager): """Summarize the contents of the database.""" click.echo('Networks: {}'.format(manager.count_networks())) click.echo('Edges: {}'.format(manager.count_edges())) click.echo('Nodes: {}'.format(manager.count_nodes())) click.echo('Namespaces: {}'.format(manager.count_namespaces())) click.echo('Namespaces entries: {}'.format(manager.count_namespace_entries())) click.echo('Annotations: {}'.format(manager.count_annotations())) click.echo('Annotation entries: {}'.format(manager.count_annotation_entries()))
python
def summarize(manager: Manager): """Summarize the contents of the database.""" click.echo('Networks: {}'.format(manager.count_networks())) click.echo('Edges: {}'.format(manager.count_edges())) click.echo('Nodes: {}'.format(manager.count_nodes())) click.echo('Namespaces: {}'.format(manager.count_namespaces())) click.echo('Namespaces entries: {}'.format(manager.count_namespace_entries())) click.echo('Annotations: {}'.format(manager.count_annotations())) click.echo('Annotation entries: {}'.format(manager.count_annotation_entries()))
[ "def", "summarize", "(", "manager", ":", "Manager", ")", ":", "click", ".", "echo", "(", "'Networks: {}'", ".", "format", "(", "manager", ".", "count_networks", "(", ")", ")", ")", "click", ".", "echo", "(", "'Edges: {}'", ".", "format", "(", "manager", ...
Summarize the contents of the database.
[ "Summarize", "the", "contents", "of", "the", "database", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L434-L442
train
29,676
pybel/pybel
src/pybel/cli.py
echo_warnings_via_pager
def echo_warnings_via_pager(warnings: List[WarningTuple], sep: str = '\t') -> None: """Output the warnings from a BEL graph with Click and the system's pager.""" # Exit if no warnings if not warnings: click.echo('Congratulations! No warnings.') sys.exit(0) max_line_width = max( len(str(exc.line_number)) for _, exc, _ in warnings ) max_warning_width = max( len(exc.__class__.__name__) for _, exc, _ in warnings ) s1 = '{:>' + str(max_line_width) + '}' + sep s2 = '{:>' + str(max_warning_width) + '}' + sep def _make_line(path: str, exc: BELParserWarning): s = click.style(path, fg='cyan') + sep s += click.style(s1.format(exc.line_number), fg='blue', bold=True) s += click.style(s2.format(exc.__class__.__name__), fg=('red' if exc.__class__.__name__.endswith('Error') else 'yellow')) s += click.style(exc.line, bold=True) + sep s += click.style(str(exc)) return s click.echo_via_pager('\n'.join( _make_line(path, exc) for path, exc, _ in warnings ))
python
def echo_warnings_via_pager(warnings: List[WarningTuple], sep: str = '\t') -> None: """Output the warnings from a BEL graph with Click and the system's pager.""" # Exit if no warnings if not warnings: click.echo('Congratulations! No warnings.') sys.exit(0) max_line_width = max( len(str(exc.line_number)) for _, exc, _ in warnings ) max_warning_width = max( len(exc.__class__.__name__) for _, exc, _ in warnings ) s1 = '{:>' + str(max_line_width) + '}' + sep s2 = '{:>' + str(max_warning_width) + '}' + sep def _make_line(path: str, exc: BELParserWarning): s = click.style(path, fg='cyan') + sep s += click.style(s1.format(exc.line_number), fg='blue', bold=True) s += click.style(s2.format(exc.__class__.__name__), fg=('red' if exc.__class__.__name__.endswith('Error') else 'yellow')) s += click.style(exc.line, bold=True) + sep s += click.style(str(exc)) return s click.echo_via_pager('\n'.join( _make_line(path, exc) for path, exc, _ in warnings ))
[ "def", "echo_warnings_via_pager", "(", "warnings", ":", "List", "[", "WarningTuple", "]", ",", "sep", ":", "str", "=", "'\\t'", ")", "->", "None", ":", "# Exit if no warnings", "if", "not", "warnings", ":", "click", ".", "echo", "(", "'Congratulations! No warn...
Output the warnings from a BEL graph with Click and the system's pager.
[ "Output", "the", "warnings", "from", "a", "BEL", "graph", "with", "Click", "and", "the", "system", "s", "pager", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/cli.py#L445-L477
train
29,677
pybel/pybel
src/pybel/tokens.py
parse_result_to_dsl
def parse_result_to_dsl(tokens): """Convert a ParseResult to a PyBEL DSL object. :type tokens: dict or pyparsing.ParseResults :rtype: BaseEntity """ if MODIFIER in tokens: return parse_result_to_dsl(tokens[TARGET]) elif REACTION == tokens[FUNCTION]: return _reaction_po_to_dict(tokens) elif VARIANTS in tokens: return _variant_po_to_dict(tokens) elif MEMBERS in tokens: return _list_po_to_dict(tokens) elif FUSION in tokens: return _fusion_to_dsl(tokens) return _simple_po_to_dict(tokens)
python
def parse_result_to_dsl(tokens): """Convert a ParseResult to a PyBEL DSL object. :type tokens: dict or pyparsing.ParseResults :rtype: BaseEntity """ if MODIFIER in tokens: return parse_result_to_dsl(tokens[TARGET]) elif REACTION == tokens[FUNCTION]: return _reaction_po_to_dict(tokens) elif VARIANTS in tokens: return _variant_po_to_dict(tokens) elif MEMBERS in tokens: return _list_po_to_dict(tokens) elif FUSION in tokens: return _fusion_to_dsl(tokens) return _simple_po_to_dict(tokens)
[ "def", "parse_result_to_dsl", "(", "tokens", ")", ":", "if", "MODIFIER", "in", "tokens", ":", "return", "parse_result_to_dsl", "(", "tokens", "[", "TARGET", "]", ")", "elif", "REACTION", "==", "tokens", "[", "FUNCTION", "]", ":", "return", "_reaction_po_to_dic...
Convert a ParseResult to a PyBEL DSL object. :type tokens: dict or pyparsing.ParseResults :rtype: BaseEntity
[ "Convert", "a", "ParseResult", "to", "a", "PyBEL", "DSL", "object", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L24-L45
train
29,678
pybel/pybel
src/pybel/tokens.py
_fusion_to_dsl
def _fusion_to_dsl(tokens) -> FusionBase: """Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult """ func = tokens[FUNCTION] fusion_dsl = FUNC_TO_FUSION_DSL[func] member_dsl = FUNC_TO_DSL[func] partner_5p = member_dsl( namespace=tokens[FUSION][PARTNER_5P][NAMESPACE], name=tokens[FUSION][PARTNER_5P][NAME] ) partner_3p = member_dsl( namespace=tokens[FUSION][PARTNER_3P][NAMESPACE], name=tokens[FUSION][PARTNER_3P][NAME] ) range_5p = _fusion_range_to_dsl(tokens[FUSION][RANGE_5P]) range_3p = _fusion_range_to_dsl(tokens[FUSION][RANGE_3P]) return fusion_dsl( partner_5p=partner_5p, partner_3p=partner_3p, range_5p=range_5p, range_3p=range_3p, )
python
def _fusion_to_dsl(tokens) -> FusionBase: """Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult """ func = tokens[FUNCTION] fusion_dsl = FUNC_TO_FUSION_DSL[func] member_dsl = FUNC_TO_DSL[func] partner_5p = member_dsl( namespace=tokens[FUSION][PARTNER_5P][NAMESPACE], name=tokens[FUSION][PARTNER_5P][NAME] ) partner_3p = member_dsl( namespace=tokens[FUSION][PARTNER_3P][NAMESPACE], name=tokens[FUSION][PARTNER_3P][NAME] ) range_5p = _fusion_range_to_dsl(tokens[FUSION][RANGE_5P]) range_3p = _fusion_range_to_dsl(tokens[FUSION][RANGE_3P]) return fusion_dsl( partner_5p=partner_5p, partner_3p=partner_3p, range_5p=range_5p, range_3p=range_3p, )
[ "def", "_fusion_to_dsl", "(", "tokens", ")", "->", "FusionBase", ":", "func", "=", "tokens", "[", "FUNCTION", "]", "fusion_dsl", "=", "FUNC_TO_FUSION_DSL", "[", "func", "]", "member_dsl", "=", "FUNC_TO_DSL", "[", "func", "]", "partner_5p", "=", "member_dsl", ...
Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult
[ "Convert", "a", "PyParsing", "data", "dictionary", "to", "a", "PyBEL", "fusion", "data", "dictionary", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L48-L76
train
29,679
pybel/pybel
src/pybel/tokens.py
_fusion_range_to_dsl
def _fusion_range_to_dsl(tokens) -> FusionRangeBase: """Convert a PyParsing data dictionary into a PyBEL. :type tokens: ParseResult """ if FUSION_MISSING in tokens: return missing_fusion_range() return fusion_range( reference=tokens[FUSION_REFERENCE], start=tokens[FUSION_START], stop=tokens[FUSION_STOP] )
python
def _fusion_range_to_dsl(tokens) -> FusionRangeBase: """Convert a PyParsing data dictionary into a PyBEL. :type tokens: ParseResult """ if FUSION_MISSING in tokens: return missing_fusion_range() return fusion_range( reference=tokens[FUSION_REFERENCE], start=tokens[FUSION_START], stop=tokens[FUSION_STOP] )
[ "def", "_fusion_range_to_dsl", "(", "tokens", ")", "->", "FusionRangeBase", ":", "if", "FUSION_MISSING", "in", "tokens", ":", "return", "missing_fusion_range", "(", ")", "return", "fusion_range", "(", "reference", "=", "tokens", "[", "FUSION_REFERENCE", "]", ",", ...
Convert a PyParsing data dictionary into a PyBEL. :type tokens: ParseResult
[ "Convert", "a", "PyParsing", "data", "dictionary", "into", "a", "PyBEL", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L79-L91
train
29,680
pybel/pybel
src/pybel/tokens.py
_simple_po_to_dict
def _simple_po_to_dict(tokens) -> BaseAbundance: """Convert a simple named entity to a DSL object. :type tokens: ParseResult """ dsl = FUNC_TO_DSL.get(tokens[FUNCTION]) if dsl is None: raise ValueError('invalid tokens: {}'.format(tokens)) return dsl( namespace=tokens[NAMESPACE], name=tokens.get(NAME), identifier=tokens.get(IDENTIFIER), )
python
def _simple_po_to_dict(tokens) -> BaseAbundance: """Convert a simple named entity to a DSL object. :type tokens: ParseResult """ dsl = FUNC_TO_DSL.get(tokens[FUNCTION]) if dsl is None: raise ValueError('invalid tokens: {}'.format(tokens)) return dsl( namespace=tokens[NAMESPACE], name=tokens.get(NAME), identifier=tokens.get(IDENTIFIER), )
[ "def", "_simple_po_to_dict", "(", "tokens", ")", "->", "BaseAbundance", ":", "dsl", "=", "FUNC_TO_DSL", ".", "get", "(", "tokens", "[", "FUNCTION", "]", ")", "if", "dsl", "is", "None", ":", "raise", "ValueError", "(", "'invalid tokens: {}'", ".", "format", ...
Convert a simple named entity to a DSL object. :type tokens: ParseResult
[ "Convert", "a", "simple", "named", "entity", "to", "a", "DSL", "object", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L94-L107
train
29,681
pybel/pybel
src/pybel/tokens.py
_variant_to_dsl_helper
def _variant_to_dsl_helper(tokens) -> Variant: """Convert variant tokens to DSL objects. :type tokens: ParseResult """ kind = tokens[KIND] if kind == HGVS: return hgvs(tokens[IDENTIFIER]) if kind == GMOD: return gmod( name=tokens[IDENTIFIER][NAME], namespace=tokens[IDENTIFIER][NAMESPACE], ) if kind == PMOD: return pmod( name=tokens[IDENTIFIER][NAME], namespace=tokens[IDENTIFIER][NAMESPACE], code=tokens.get(PMOD_CODE), position=tokens.get(PMOD_POSITION), ) if kind == FRAGMENT: start, stop = tokens.get(FRAGMENT_START), tokens.get(FRAGMENT_STOP) return fragment( start=start, stop=stop, description=tokens.get(FRAGMENT_DESCRIPTION) ) raise ValueError('invalid fragment kind: {}'.format(kind))
python
def _variant_to_dsl_helper(tokens) -> Variant: """Convert variant tokens to DSL objects. :type tokens: ParseResult """ kind = tokens[KIND] if kind == HGVS: return hgvs(tokens[IDENTIFIER]) if kind == GMOD: return gmod( name=tokens[IDENTIFIER][NAME], namespace=tokens[IDENTIFIER][NAMESPACE], ) if kind == PMOD: return pmod( name=tokens[IDENTIFIER][NAME], namespace=tokens[IDENTIFIER][NAMESPACE], code=tokens.get(PMOD_CODE), position=tokens.get(PMOD_POSITION), ) if kind == FRAGMENT: start, stop = tokens.get(FRAGMENT_START), tokens.get(FRAGMENT_STOP) return fragment( start=start, stop=stop, description=tokens.get(FRAGMENT_DESCRIPTION) ) raise ValueError('invalid fragment kind: {}'.format(kind))
[ "def", "_variant_to_dsl_helper", "(", "tokens", ")", "->", "Variant", ":", "kind", "=", "tokens", "[", "KIND", "]", "if", "kind", "==", "HGVS", ":", "return", "hgvs", "(", "tokens", "[", "IDENTIFIER", "]", ")", "if", "kind", "==", "GMOD", ":", "return"...
Convert variant tokens to DSL objects. :type tokens: ParseResult
[ "Convert", "variant", "tokens", "to", "DSL", "objects", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L129-L161
train
29,682
pybel/pybel
src/pybel/tokens.py
_reaction_po_to_dict
def _reaction_po_to_dict(tokens) -> Reaction: """Convert a reaction parse object to a DSL. :type tokens: ParseResult """ return Reaction( reactants=_reaction_part_po_to_dict(tokens[REACTANTS]), products=_reaction_part_po_to_dict(tokens[PRODUCTS]), )
python
def _reaction_po_to_dict(tokens) -> Reaction: """Convert a reaction parse object to a DSL. :type tokens: ParseResult """ return Reaction( reactants=_reaction_part_po_to_dict(tokens[REACTANTS]), products=_reaction_part_po_to_dict(tokens[PRODUCTS]), )
[ "def", "_reaction_po_to_dict", "(", "tokens", ")", "->", "Reaction", ":", "return", "Reaction", "(", "reactants", "=", "_reaction_part_po_to_dict", "(", "tokens", "[", "REACTANTS", "]", ")", ",", "products", "=", "_reaction_part_po_to_dict", "(", "tokens", "[", ...
Convert a reaction parse object to a DSL. :type tokens: ParseResult
[ "Convert", "a", "reaction", "parse", "object", "to", "a", "DSL", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L164-L172
train
29,683
pybel/pybel
src/pybel/tokens.py
_list_po_to_dict
def _list_po_to_dict(tokens) -> ListAbundance: """Convert a list parse object to a node. :type tokens: ParseResult """ func = tokens[FUNCTION] dsl = FUNC_TO_LIST_DSL[func] members = [parse_result_to_dsl(token) for token in tokens[MEMBERS]] return dsl(members)
python
def _list_po_to_dict(tokens) -> ListAbundance: """Convert a list parse object to a node. :type tokens: ParseResult """ func = tokens[FUNCTION] dsl = FUNC_TO_LIST_DSL[func] members = [parse_result_to_dsl(token) for token in tokens[MEMBERS]] return dsl(members)
[ "def", "_list_po_to_dict", "(", "tokens", ")", "->", "ListAbundance", ":", "func", "=", "tokens", "[", "FUNCTION", "]", "dsl", "=", "FUNC_TO_LIST_DSL", "[", "func", "]", "members", "=", "[", "parse_result_to_dsl", "(", "token", ")", "for", "token", "in", "...
Convert a list parse object to a node. :type tokens: ParseResult
[ "Convert", "a", "list", "parse", "object", "to", "a", "node", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L183-L193
train
29,684
pybel/pybel
src/pybel/struct/mutation/induction/annotations.py
get_subgraph_by_annotations
def get_subgraph_by_annotations(graph, annotations, or_=None): """Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True any annotation should be present, if False all annotations should be present in the edge. Defaults to True. :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph """ edge_filter_builder = ( build_annotation_dict_any_filter if (or_ is None or or_) else build_annotation_dict_all_filter ) return get_subgraph_by_edge_filter(graph, edge_filter_builder(annotations))
python
def get_subgraph_by_annotations(graph, annotations, or_=None): """Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True any annotation should be present, if False all annotations should be present in the edge. Defaults to True. :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph """ edge_filter_builder = ( build_annotation_dict_any_filter if (or_ is None or or_) else build_annotation_dict_all_filter ) return get_subgraph_by_edge_filter(graph, edge_filter_builder(annotations))
[ "def", "get_subgraph_by_annotations", "(", "graph", ",", "annotations", ",", "or_", "=", "None", ")", ":", "edge_filter_builder", "=", "(", "build_annotation_dict_any_filter", "if", "(", "or_", "is", "None", "or", "or_", ")", "else", "build_annotation_dict_all_filte...
Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True any annotation should be present, if False all annotations should be present in the edge. Defaults to True. :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph
[ "Induce", "a", "sub", "-", "graph", "given", "an", "annotations", "filter", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/annotations.py#L20-L36
train
29,685
pybel/pybel
src/pybel/struct/mutation/induction/annotations.py
get_subgraph_by_annotation_value
def get_subgraph_by_annotation_value(graph, annotation, values): """Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph """ if isinstance(values, str): values = {values} return get_subgraph_by_annotations(graph, {annotation: values})
python
def get_subgraph_by_annotation_value(graph, annotation, values): """Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph """ if isinstance(values, str): values = {values} return get_subgraph_by_annotations(graph, {annotation: values})
[ "def", "get_subgraph_by_annotation_value", "(", "graph", ",", "annotation", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "str", ")", ":", "values", "=", "{", "values", "}", "return", "get_subgraph_by_annotations", "(", "graph", ",", "{", ...
Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph :rtype: pybel.BELGraph
[ "Induce", "a", "sub", "-", "graph", "over", "all", "edges", "whose", "annotations", "match", "the", "given", "key", "and", "value", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/annotations.py#L40-L53
train
29,686
pybel/pybel
src/pybel/struct/filters/edge_filters.py
invert_edge_predicate
def invert_edge_predicate(edge_predicate: EdgePredicate) -> EdgePredicate: # noqa: D202 """Build an edge predicate that is the inverse of the given edge predicate.""" def _inverse_filter(graph, u, v, k): return not edge_predicate(graph, u, v, k) return _inverse_filter
python
def invert_edge_predicate(edge_predicate: EdgePredicate) -> EdgePredicate: # noqa: D202 """Build an edge predicate that is the inverse of the given edge predicate.""" def _inverse_filter(graph, u, v, k): return not edge_predicate(graph, u, v, k) return _inverse_filter
[ "def", "invert_edge_predicate", "(", "edge_predicate", ":", "EdgePredicate", ")", "->", "EdgePredicate", ":", "# noqa: D202", "def", "_inverse_filter", "(", "graph", ",", "u", ",", "v", ",", "k", ")", ":", "return", "not", "edge_predicate", "(", "graph", ",", ...
Build an edge predicate that is the inverse of the given edge predicate.
[ "Build", "an", "edge", "predicate", "that", "is", "the", "inverse", "of", "the", "given", "edge", "predicate", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_filters.py#L28-L34
train
29,687
pybel/pybel
src/pybel/struct/filters/edge_filters.py
and_edge_predicates
def and_edge_predicates(edge_predicates: EdgePredicates) -> EdgePredicate: """Concatenate multiple edge predicates to a new predicate that requires all predicates to be met.""" # If something that isn't a list or tuple is given, assume it's a function and return it if not isinstance(edge_predicates, Iterable): return edge_predicates edge_predicates = tuple(edge_predicates) # If only one predicate is given, don't bother wrapping it if 1 == len(edge_predicates): return edge_predicates[0] def concatenated_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: """Pass only for an edge that pass all enclosed predicates. :return: If the edge passes all enclosed predicates """ return all( edge_predicate(graph, u, v, k) for edge_predicate in edge_predicates ) return concatenated_edge_predicate
python
def and_edge_predicates(edge_predicates: EdgePredicates) -> EdgePredicate: """Concatenate multiple edge predicates to a new predicate that requires all predicates to be met.""" # If something that isn't a list or tuple is given, assume it's a function and return it if not isinstance(edge_predicates, Iterable): return edge_predicates edge_predicates = tuple(edge_predicates) # If only one predicate is given, don't bother wrapping it if 1 == len(edge_predicates): return edge_predicates[0] def concatenated_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: """Pass only for an edge that pass all enclosed predicates. :return: If the edge passes all enclosed predicates """ return all( edge_predicate(graph, u, v, k) for edge_predicate in edge_predicates ) return concatenated_edge_predicate
[ "def", "and_edge_predicates", "(", "edge_predicates", ":", "EdgePredicates", ")", "->", "EdgePredicate", ":", "# If something that isn't a list or tuple is given, assume it's a function and return it", "if", "not", "isinstance", "(", "edge_predicates", ",", "Iterable", ")", ":"...
Concatenate multiple edge predicates to a new predicate that requires all predicates to be met.
[ "Concatenate", "multiple", "edge", "predicates", "to", "a", "new", "predicate", "that", "requires", "all", "predicates", "to", "be", "met", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_filters.py#L37-L59
train
29,688
pybel/pybel
src/pybel/struct/filters/edge_filters.py
filter_edges
def filter_edges(graph: BELGraph, edge_predicates: EdgePredicates) -> EdgeIterator: """Apply a set of filters to the edges iterator of a BEL graph. :return: An iterable of edges that pass all predicates """ compound_edge_predicate = and_edge_predicates(edge_predicates=edge_predicates) for u, v, k in graph.edges(keys=True): if compound_edge_predicate(graph, u, v, k): yield u, v, k
python
def filter_edges(graph: BELGraph, edge_predicates: EdgePredicates) -> EdgeIterator: """Apply a set of filters to the edges iterator of a BEL graph. :return: An iterable of edges that pass all predicates """ compound_edge_predicate = and_edge_predicates(edge_predicates=edge_predicates) for u, v, k in graph.edges(keys=True): if compound_edge_predicate(graph, u, v, k): yield u, v, k
[ "def", "filter_edges", "(", "graph", ":", "BELGraph", ",", "edge_predicates", ":", "EdgePredicates", ")", "->", "EdgeIterator", ":", "compound_edge_predicate", "=", "and_edge_predicates", "(", "edge_predicates", "=", "edge_predicates", ")", "for", "u", ",", "v", "...
Apply a set of filters to the edges iterator of a BEL graph. :return: An iterable of edges that pass all predicates
[ "Apply", "a", "set", "of", "filters", "to", "the", "edges", "iterator", "of", "a", "BEL", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_filters.py#L62-L70
train
29,689
pybel/pybel
src/pybel/struct/filters/edge_filters.py
count_passed_edge_filter
def count_passed_edge_filter(graph: BELGraph, edge_predicates: EdgePredicates) -> int: """Return the number of edges passing a given set of predicates.""" return sum( 1 for _ in filter_edges(graph, edge_predicates=edge_predicates) )
python
def count_passed_edge_filter(graph: BELGraph, edge_predicates: EdgePredicates) -> int: """Return the number of edges passing a given set of predicates.""" return sum( 1 for _ in filter_edges(graph, edge_predicates=edge_predicates) )
[ "def", "count_passed_edge_filter", "(", "graph", ":", "BELGraph", ",", "edge_predicates", ":", "EdgePredicates", ")", "->", "int", ":", "return", "sum", "(", "1", "for", "_", "in", "filter_edges", "(", "graph", ",", "edge_predicates", "=", "edge_predicates", "...
Return the number of edges passing a given set of predicates.
[ "Return", "the", "number", "of", "edges", "passing", "a", "given", "set", "of", "predicates", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_filters.py#L73-L78
train
29,690
pybel/pybel
src/pybel/struct/operations.py
subgraph
def subgraph(graph, nodes: Iterable[BaseEntity]): """Induce a sub-graph over the given nodes. :rtype: BELGraph """ sg = graph.subgraph(nodes) # see implementation for .copy() result = graph.fresh_copy() result.graph.update(sg.graph) for node, data in sg.nodes(data=True): result.add_node(node, **data) result.add_edges_from( (u, v, key, datadict.copy()) for u, v, key, datadict in sg.edges(keys=True, data=True) ) return result
python
def subgraph(graph, nodes: Iterable[BaseEntity]): """Induce a sub-graph over the given nodes. :rtype: BELGraph """ sg = graph.subgraph(nodes) # see implementation for .copy() result = graph.fresh_copy() result.graph.update(sg.graph) for node, data in sg.nodes(data=True): result.add_node(node, **data) result.add_edges_from( (u, v, key, datadict.copy()) for u, v, key, datadict in sg.edges(keys=True, data=True) ) return result
[ "def", "subgraph", "(", "graph", ",", "nodes", ":", "Iterable", "[", "BaseEntity", "]", ")", ":", "sg", "=", "graph", ".", "subgraph", "(", "nodes", ")", "# see implementation for .copy()", "result", "=", "graph", ".", "fresh_copy", "(", ")", "result", "."...
Induce a sub-graph over the given nodes. :rtype: BELGraph
[ "Induce", "a", "sub", "-", "graph", "over", "the", "given", "nodes", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L23-L42
train
29,691
pybel/pybel
src/pybel/struct/operations.py
left_full_join
def left_full_join(g, h) -> None: """Add all nodes and edges from ``h`` to ``g``, in-place for ``g``. :param pybel.BELGraph g: A BEL graph :param pybel.BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_full_join(g, h) """ g.add_nodes_from( (node, data) for node, data in h.nodes(data=True) if node not in g ) g.add_edges_from( (u, v, key, data) for u, v, key, data in h.edges(keys=True, data=True) if u not in g or v not in g[u] or key not in g[u][v] ) update_metadata(h, g) update_node_helper(h, g) g.warnings.extend(h.warnings)
python
def left_full_join(g, h) -> None: """Add all nodes and edges from ``h`` to ``g``, in-place for ``g``. :param pybel.BELGraph g: A BEL graph :param pybel.BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_full_join(g, h) """ g.add_nodes_from( (node, data) for node, data in h.nodes(data=True) if node not in g ) g.add_edges_from( (u, v, key, data) for u, v, key, data in h.edges(keys=True, data=True) if u not in g or v not in g[u] or key not in g[u][v] ) update_metadata(h, g) update_node_helper(h, g) g.warnings.extend(h.warnings)
[ "def", "left_full_join", "(", "g", ",", "h", ")", "->", "None", ":", "g", ".", "add_nodes_from", "(", "(", "node", ",", "data", ")", "for", "node", ",", "data", "in", "h", ".", "nodes", "(", "data", "=", "True", ")", "if", "node", "not", "in", ...
Add all nodes and edges from ``h`` to ``g``, in-place for ``g``. :param pybel.BELGraph g: A BEL graph :param pybel.BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_full_join(g, h)
[ "Add", "all", "nodes", "and", "edges", "from", "h", "to", "g", "in", "-", "place", "for", "g", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L45-L71
train
29,692
pybel/pybel
src/pybel/struct/operations.py
left_outer_join
def left_outer_join(g, h) -> None: """Only add components from the ``h`` that are touching ``g``. Algorithm: 1. Identify all weakly connected components in ``h`` 2. Add those that have an intersection with the ``g`` :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_outer_join(g, h) """ g_nodes = set(g) for comp in nx.weakly_connected_components(h): if g_nodes.intersection(comp): h_subgraph = subgraph(h, comp) left_full_join(g, h_subgraph)
python
def left_outer_join(g, h) -> None: """Only add components from the ``h`` that are touching ``g``. Algorithm: 1. Identify all weakly connected components in ``h`` 2. Add those that have an intersection with the ``g`` :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_outer_join(g, h) """ g_nodes = set(g) for comp in nx.weakly_connected_components(h): if g_nodes.intersection(comp): h_subgraph = subgraph(h, comp) left_full_join(g, h_subgraph)
[ "def", "left_outer_join", "(", "g", ",", "h", ")", "->", "None", ":", "g_nodes", "=", "set", "(", "g", ")", "for", "comp", "in", "nx", ".", "weakly_connected_components", "(", "h", ")", ":", "if", "g_nodes", ".", "intersection", "(", "comp", ")", ":"...
Only add components from the ``h`` that are touching ``g``. Algorithm: 1. Identify all weakly connected components in ``h`` 2. Add those that have an intersection with the ``g`` :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> left_outer_join(g, h)
[ "Only", "add", "components", "from", "the", "h", "that", "are", "touching", "g", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L74-L96
train
29,693
pybel/pybel
src/pybel/struct/operations.py
union
def union(graphs, use_tqdm: bool = False): """Take the union over a collection of graphs into a new graph. Assumes iterator is longer than 2, but not infinite. :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite. :param use_tqdm: Should a progress bar be displayed? :return: A merged graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = union([g, h, k]) """ it = iter(graphs) if use_tqdm: it = tqdm(it, desc='taking union') try: target = next(it) except StopIteration as e: raise ValueError('no graphs given') from e try: graph = next(it) except StopIteration: return target else: target = target.copy() left_full_join(target, graph) for graph in it: left_full_join(target, graph) return target
python
def union(graphs, use_tqdm: bool = False): """Take the union over a collection of graphs into a new graph. Assumes iterator is longer than 2, but not infinite. :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite. :param use_tqdm: Should a progress bar be displayed? :return: A merged graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = union([g, h, k]) """ it = iter(graphs) if use_tqdm: it = tqdm(it, desc='taking union') try: target = next(it) except StopIteration as e: raise ValueError('no graphs given') from e try: graph = next(it) except StopIteration: return target else: target = target.copy() left_full_join(target, graph) for graph in it: left_full_join(target, graph) return target
[ "def", "union", "(", "graphs", ",", "use_tqdm", ":", "bool", "=", "False", ")", ":", "it", "=", "iter", "(", "graphs", ")", "if", "use_tqdm", ":", "it", "=", "tqdm", "(", "it", ",", "desc", "=", "'taking union'", ")", "try", ":", "target", "=", "...
Take the union over a collection of graphs into a new graph. Assumes iterator is longer than 2, but not infinite. :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite. :param use_tqdm: Should a progress bar be displayed? :return: A merged graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = union([g, h, k])
[ "Take", "the", "union", "over", "a", "collection", "of", "graphs", "into", "a", "new", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L113-L152
train
29,694
pybel/pybel
src/pybel/struct/operations.py
left_node_intersection_join
def left_node_intersection_join(g, h): """Take the intersection over two graphs. This intersection of two graphs is defined by the union of the sub-graphs induced over the intersection of their nodes :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> merged = left_node_intersection_join(g, h) """ intersecting = set(g).intersection(set(h)) g_inter = subgraph(g, intersecting) h_inter = subgraph(h, intersecting) left_full_join(g_inter, h_inter) return g_inter
python
def left_node_intersection_join(g, h): """Take the intersection over two graphs. This intersection of two graphs is defined by the union of the sub-graphs induced over the intersection of their nodes :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> merged = left_node_intersection_join(g, h) """ intersecting = set(g).intersection(set(h)) g_inter = subgraph(g, intersecting) h_inter = subgraph(h, intersecting) left_full_join(g_inter, h_inter) return g_inter
[ "def", "left_node_intersection_join", "(", "g", ",", "h", ")", ":", "intersecting", "=", "set", "(", "g", ")", ".", "intersection", "(", "set", "(", "h", ")", ")", "g_inter", "=", "subgraph", "(", "g", ",", "intersecting", ")", "h_inter", "=", "subgrap...
Take the intersection over two graphs. This intersection of two graphs is defined by the union of the sub-graphs induced over the intersection of their nodes :param BELGraph g: A BEL graph :param BELGraph h: A BEL graph :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> merged = left_node_intersection_join(g, h)
[ "Take", "the", "intersection", "over", "two", "graphs", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L155-L178
train
29,695
pybel/pybel
src/pybel/struct/operations.py
node_intersection
def node_intersection(graphs): """Take the node intersection over a collection of graphs into a new graph. This intersection is defined the same way as by :func:`left_node_intersection_join` :param iter[BELGraph] graphs: An iterable of graphs. Since it's iterated over twice, it gets converted to a tuple first, so this isn't a safe operation for infinite lists. :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = node_intersection([g, h, k]) """ graphs = tuple(graphs) n_graphs = len(graphs) if n_graphs == 0: raise ValueError('no graphs given') if n_graphs == 1: return graphs[0] nodes = set(graphs[0].nodes()) for graph in graphs[1:]: nodes.intersection_update(graph) return union( subgraph(graph, nodes) for graph in graphs )
python
def node_intersection(graphs): """Take the node intersection over a collection of graphs into a new graph. This intersection is defined the same way as by :func:`left_node_intersection_join` :param iter[BELGraph] graphs: An iterable of graphs. Since it's iterated over twice, it gets converted to a tuple first, so this isn't a safe operation for infinite lists. :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = node_intersection([g, h, k]) """ graphs = tuple(graphs) n_graphs = len(graphs) if n_graphs == 0: raise ValueError('no graphs given') if n_graphs == 1: return graphs[0] nodes = set(graphs[0].nodes()) for graph in graphs[1:]: nodes.intersection_update(graph) return union( subgraph(graph, nodes) for graph in graphs )
[ "def", "node_intersection", "(", "graphs", ")", ":", "graphs", "=", "tuple", "(", "graphs", ")", "n_graphs", "=", "len", "(", "graphs", ")", "if", "n_graphs", "==", "0", ":", "raise", "ValueError", "(", "'no graphs given'", ")", "if", "n_graphs", "==", "...
Take the node intersection over a collection of graphs into a new graph. This intersection is defined the same way as by :func:`left_node_intersection_join` :param iter[BELGraph] graphs: An iterable of graphs. Since it's iterated over twice, it gets converted to a tuple first, so this isn't a safe operation for infinite lists. :rtype: BELGraph Example usage: >>> import pybel >>> g = pybel.from_path('...') >>> h = pybel.from_path('...') >>> k = pybel.from_path('...') >>> merged = node_intersection([g, h, k])
[ "Take", "the", "node", "intersection", "over", "a", "collection", "of", "graphs", "into", "a", "new", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/operations.py#L181-L216
train
29,696
pybel/pybel
src/pybel/struct/mutation/metadata.py
strip_annotations
def strip_annotations(graph): """Strip all the annotations from a BEL graph. :param pybel.BELGraph graph: A BEL graph """ for u, v, k in graph.edges(keys=True): if ANNOTATIONS in graph[u][v][k]: del graph[u][v][k][ANNOTATIONS]
python
def strip_annotations(graph): """Strip all the annotations from a BEL graph. :param pybel.BELGraph graph: A BEL graph """ for u, v, k in graph.edges(keys=True): if ANNOTATIONS in graph[u][v][k]: del graph[u][v][k][ANNOTATIONS]
[ "def", "strip_annotations", "(", "graph", ")", ":", "for", "u", ",", "v", ",", "k", "in", "graph", ".", "edges", "(", "keys", "=", "True", ")", ":", "if", "ANNOTATIONS", "in", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ":", "del", ...
Strip all the annotations from a BEL graph. :param pybel.BELGraph graph: A BEL graph
[ "Strip", "all", "the", "annotations", "from", "a", "BEL", "graph", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/metadata.py#L21-L28
train
29,697
pybel/pybel
src/pybel/struct/mutation/metadata.py
remove_citation_metadata
def remove_citation_metadata(graph): """Remove the metadata associated with a citation. Best practice is to add this information programmatically. """ for u, v, k in graph.edges(keys=True): if CITATION not in graph[u][v][k]: continue for key in list(graph[u][v][k][CITATION]): if key not in _CITATION_KEEP_KEYS: del graph[u][v][k][CITATION][key]
python
def remove_citation_metadata(graph): """Remove the metadata associated with a citation. Best practice is to add this information programmatically. """ for u, v, k in graph.edges(keys=True): if CITATION not in graph[u][v][k]: continue for key in list(graph[u][v][k][CITATION]): if key not in _CITATION_KEEP_KEYS: del graph[u][v][k][CITATION][key]
[ "def", "remove_citation_metadata", "(", "graph", ")", ":", "for", "u", ",", "v", ",", "k", "in", "graph", ".", "edges", "(", "keys", "=", "True", ")", ":", "if", "CITATION", "not", "in", "graph", "[", "u", "]", "[", "v", "]", "[", "k", "]", ":"...
Remove the metadata associated with a citation. Best practice is to add this information programmatically.
[ "Remove", "the", "metadata", "associated", "with", "a", "citation", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/metadata.py#L81-L91
train
29,698
pybel/pybel
src/pybel/io/nodelink.py
to_json
def to_json(graph: BELGraph) -> Mapping[str, Any]: """Convert this graph to a Node-Link JSON object.""" graph_json_dict = node_link_data(graph) # Convert annotation list definitions (which are sets) to canonicalized/sorted lists graph_json_dict['graph'][GRAPH_ANNOTATION_LIST] = { keyword: list(sorted(values)) for keyword, values in graph_json_dict['graph'].get(GRAPH_ANNOTATION_LIST, {}).items() } # Convert set to list graph_json_dict['graph'][GRAPH_UNCACHED_NAMESPACES] = list( graph_json_dict['graph'].get(GRAPH_UNCACHED_NAMESPACES, []) ) return graph_json_dict
python
def to_json(graph: BELGraph) -> Mapping[str, Any]: """Convert this graph to a Node-Link JSON object.""" graph_json_dict = node_link_data(graph) # Convert annotation list definitions (which are sets) to canonicalized/sorted lists graph_json_dict['graph'][GRAPH_ANNOTATION_LIST] = { keyword: list(sorted(values)) for keyword, values in graph_json_dict['graph'].get(GRAPH_ANNOTATION_LIST, {}).items() } # Convert set to list graph_json_dict['graph'][GRAPH_UNCACHED_NAMESPACES] = list( graph_json_dict['graph'].get(GRAPH_UNCACHED_NAMESPACES, []) ) return graph_json_dict
[ "def", "to_json", "(", "graph", ":", "BELGraph", ")", "->", "Mapping", "[", "str", ",", "Any", "]", ":", "graph_json_dict", "=", "node_link_data", "(", "graph", ")", "# Convert annotation list definitions (which are sets) to canonicalized/sorted lists", "graph_json_dict",...
Convert this graph to a Node-Link JSON object.
[ "Convert", "this", "graph", "to", "a", "Node", "-", "Link", "JSON", "object", "." ]
c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L29-L44
train
29,699