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/io/nodelink.py | to_json_path | def to_json_path(graph: BELGraph, path: str, **kwargs) -> None:
"""Write this graph to the given path as a Node-Link JSON."""
with open(os.path.expanduser(path), 'w') as f:
to_json_file(graph, file=f, **kwargs) | python | def to_json_path(graph: BELGraph, path: str, **kwargs) -> None:
"""Write this graph to the given path as a Node-Link JSON."""
with open(os.path.expanduser(path), 'w') as f:
to_json_file(graph, file=f, **kwargs) | [
"def",
"to_json_path",
"(",
"graph",
":",
"BELGraph",
",",
"path",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
",",
"'w'",
")",
"as",
"f",
":",
"to_json... | Write this graph to the given path as a Node-Link JSON. | [
"Write",
"this",
"graph",
"to",
"the",
"given",
"path",
"as",
"a",
"Node",
"-",
"Link",
"JSON",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L47-L50 | train | 29,700 |
pybel/pybel | src/pybel/io/nodelink.py | to_json_file | def to_json_file(graph: BELGraph, file: TextIO, **kwargs) -> None:
"""Write this graph as Node-Link JSON to a file."""
graph_json_dict = to_json(graph)
json.dump(graph_json_dict, file, ensure_ascii=False, **kwargs) | python | def to_json_file(graph: BELGraph, file: TextIO, **kwargs) -> None:
"""Write this graph as Node-Link JSON to a file."""
graph_json_dict = to_json(graph)
json.dump(graph_json_dict, file, ensure_ascii=False, **kwargs) | [
"def",
"to_json_file",
"(",
"graph",
":",
"BELGraph",
",",
"file",
":",
"TextIO",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"graph_json_dict",
"=",
"to_json",
"(",
"graph",
")",
"json",
".",
"dump",
"(",
"graph_json_dict",
",",
"file",
",",
"ens... | Write this graph as Node-Link JSON to a file. | [
"Write",
"this",
"graph",
"as",
"Node",
"-",
"Link",
"JSON",
"to",
"a",
"file",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L53-L56 | train | 29,701 |
pybel/pybel | src/pybel/io/nodelink.py | to_jsons | def to_jsons(graph: BELGraph, **kwargs) -> str:
"""Dump this graph as a Node-Link JSON object to a string."""
graph_json_str = to_json(graph)
return json.dumps(graph_json_str, ensure_ascii=False, **kwargs) | python | def to_jsons(graph: BELGraph, **kwargs) -> str:
"""Dump this graph as a Node-Link JSON object to a string."""
graph_json_str = to_json(graph)
return json.dumps(graph_json_str, ensure_ascii=False, **kwargs) | [
"def",
"to_jsons",
"(",
"graph",
":",
"BELGraph",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"graph_json_str",
"=",
"to_json",
"(",
"graph",
")",
"return",
"json",
".",
"dumps",
"(",
"graph_json_str",
",",
"ensure_ascii",
"=",
"False",
",",
"*",
"... | Dump this graph as a Node-Link JSON object to a string. | [
"Dump",
"this",
"graph",
"as",
"a",
"Node",
"-",
"Link",
"JSON",
"object",
"to",
"a",
"string",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L59-L62 | train | 29,702 |
pybel/pybel | src/pybel/io/nodelink.py | from_json | def from_json(graph_json_dict: Mapping[str, Any], check_version=True) -> BELGraph:
"""Build a graph from Node-Link JSON Object."""
graph = node_link_graph(graph_json_dict)
return ensure_version(graph, check_version=check_version) | python | def from_json(graph_json_dict: Mapping[str, Any], check_version=True) -> BELGraph:
"""Build a graph from Node-Link JSON Object."""
graph = node_link_graph(graph_json_dict)
return ensure_version(graph, check_version=check_version) | [
"def",
"from_json",
"(",
"graph_json_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"check_version",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph",
"=",
"node_link_graph",
"(",
"graph_json_dict",
")",
"return",
"ensure_version",
"(",
"graph",
",... | Build a graph from Node-Link JSON Object. | [
"Build",
"a",
"graph",
"from",
"Node",
"-",
"Link",
"JSON",
"Object",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L65-L68 | train | 29,703 |
pybel/pybel | src/pybel/io/nodelink.py | from_json_path | def from_json_path(path: str, check_version: bool = True) -> BELGraph:
"""Build a graph from a file containing Node-Link JSON."""
with open(os.path.expanduser(path)) as f:
return from_json_file(f, check_version=check_version) | python | def from_json_path(path: str, check_version: bool = True) -> BELGraph:
"""Build a graph from a file containing Node-Link JSON."""
with open(os.path.expanduser(path)) as f:
return from_json_file(f, check_version=check_version) | [
"def",
"from_json_path",
"(",
"path",
":",
"str",
",",
"check_version",
":",
"bool",
"=",
"True",
")",
"->",
"BELGraph",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
"as",
"f",
":",
"return",
"from_json_file",
... | Build a graph from a file containing Node-Link JSON. | [
"Build",
"a",
"graph",
"from",
"a",
"file",
"containing",
"Node",
"-",
"Link",
"JSON",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L71-L74 | train | 29,704 |
pybel/pybel | src/pybel/io/nodelink.py | from_json_file | def from_json_file(file: TextIO, check_version=True) -> BELGraph:
"""Build a graph from the Node-Link JSON contained in the given file."""
graph_json_dict = json.load(file)
return from_json(graph_json_dict, check_version=check_version) | python | def from_json_file(file: TextIO, check_version=True) -> BELGraph:
"""Build a graph from the Node-Link JSON contained in the given file."""
graph_json_dict = json.load(file)
return from_json(graph_json_dict, check_version=check_version) | [
"def",
"from_json_file",
"(",
"file",
":",
"TextIO",
",",
"check_version",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph_json_dict",
"=",
"json",
".",
"load",
"(",
"file",
")",
"return",
"from_json",
"(",
"graph_json_dict",
",",
"check_version",
"=",
"chec... | Build a graph from the Node-Link JSON contained in the given file. | [
"Build",
"a",
"graph",
"from",
"the",
"Node",
"-",
"Link",
"JSON",
"contained",
"in",
"the",
"given",
"file",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L77-L80 | train | 29,705 |
pybel/pybel | src/pybel/io/nodelink.py | from_jsons | def from_jsons(graph_json_str: str, check_version: bool = True) -> BELGraph:
"""Read a BEL graph from a Node-Link JSON string."""
graph_json_dict = json.loads(graph_json_str)
return from_json(graph_json_dict, check_version=check_version) | python | def from_jsons(graph_json_str: str, check_version: bool = True) -> BELGraph:
"""Read a BEL graph from a Node-Link JSON string."""
graph_json_dict = json.loads(graph_json_str)
return from_json(graph_json_dict, check_version=check_version) | [
"def",
"from_jsons",
"(",
"graph_json_str",
":",
"str",
",",
"check_version",
":",
"bool",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph_json_dict",
"=",
"json",
".",
"loads",
"(",
"graph_json_str",
")",
"return",
"from_json",
"(",
"graph_json_dict",
",",
... | Read a BEL graph from a Node-Link JSON string. | [
"Read",
"a",
"BEL",
"graph",
"from",
"a",
"Node",
"-",
"Link",
"JSON",
"string",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L83-L86 | train | 29,706 |
pybel/pybel | src/pybel/io/nodelink.py | node_link_data | def node_link_data(graph: BELGraph) -> Mapping[str, Any]:
"""Convert a BEL graph to a node-link format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_data`
"""
nodes = sorted(graph, key=methodcaller('as_bel'))
mapping = dict(zip(nodes, count()))
return {
'directed': True,
'multigraph': True,
'graph': graph.graph.copy(),
'nodes': [
_augment_node(node)
for node in nodes
],
'links': [
dict(chain(
data.copy().items(),
[('source', mapping[u]), ('target', mapping[v]), ('key', key)]
))
for u, v, key, data in graph.edges(keys=True, data=True)
]
} | python | def node_link_data(graph: BELGraph) -> Mapping[str, Any]:
"""Convert a BEL graph to a node-link format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_data`
"""
nodes = sorted(graph, key=methodcaller('as_bel'))
mapping = dict(zip(nodes, count()))
return {
'directed': True,
'multigraph': True,
'graph': graph.graph.copy(),
'nodes': [
_augment_node(node)
for node in nodes
],
'links': [
dict(chain(
data.copy().items(),
[('source', mapping[u]), ('target', mapping[v]), ('key', key)]
))
for u, v, key, data in graph.edges(keys=True, data=True)
]
} | [
"def",
"node_link_data",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"nodes",
"=",
"sorted",
"(",
"graph",
",",
"key",
"=",
"methodcaller",
"(",
"'as_bel'",
")",
")",
"mapping",
"=",
"dict",
"(",
"zip",
"(",... | Convert a BEL graph to a node-link format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_data` | [
"Convert",
"a",
"BEL",
"graph",
"to",
"a",
"node",
"-",
"link",
"format",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L89-L113 | train | 29,707 |
pybel/pybel | src/pybel/io/nodelink.py | _augment_node | def _augment_node(node: BaseEntity) -> BaseEntity:
"""Add the SHA-512 identifier to a node's dictionary."""
rv = node.copy()
rv['id'] = node.as_sha512()
rv['bel'] = node.as_bel()
for m in chain(node.get(MEMBERS, []), node.get(REACTANTS, []), node.get(PRODUCTS, [])):
m.update(_augment_node(m))
return rv | python | def _augment_node(node: BaseEntity) -> BaseEntity:
"""Add the SHA-512 identifier to a node's dictionary."""
rv = node.copy()
rv['id'] = node.as_sha512()
rv['bel'] = node.as_bel()
for m in chain(node.get(MEMBERS, []), node.get(REACTANTS, []), node.get(PRODUCTS, [])):
m.update(_augment_node(m))
return rv | [
"def",
"_augment_node",
"(",
"node",
":",
"BaseEntity",
")",
"->",
"BaseEntity",
":",
"rv",
"=",
"node",
".",
"copy",
"(",
")",
"rv",
"[",
"'id'",
"]",
"=",
"node",
".",
"as_sha512",
"(",
")",
"rv",
"[",
"'bel'",
"]",
"=",
"node",
".",
"as_bel",
... | Add the SHA-512 identifier to a node's dictionary. | [
"Add",
"the",
"SHA",
"-",
"512",
"identifier",
"to",
"a",
"node",
"s",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/nodelink.py#L116-L123 | train | 29,708 |
pybel/pybel | src/pybel/parser/baseparser.py | BaseParser.parse_lines | def parse_lines(self, lines: Iterable[str]) -> List[ParseResults]:
"""Parse multiple lines in succession."""
return [
self.parseString(line, line_number)
for line_number, line in enumerate(lines)
] | python | def parse_lines(self, lines: Iterable[str]) -> List[ParseResults]:
"""Parse multiple lines in succession."""
return [
self.parseString(line, line_number)
for line_number, line in enumerate(lines)
] | [
"def",
"parse_lines",
"(",
"self",
",",
"lines",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"ParseResults",
"]",
":",
"return",
"[",
"self",
".",
"parseString",
"(",
"line",
",",
"line_number",
")",
"for",
"line_number",
",",
"line",
"in... | Parse multiple lines in succession. | [
"Parse",
"multiple",
"lines",
"in",
"succession",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/baseparser.py#L36-L41 | train | 29,709 |
pybel/pybel | src/pybel/parser/baseparser.py | BaseParser.parseString | def parseString(self, line: str, line_number: int = 0) -> ParseResults: # noqa: N802
"""Parse a string with the language represented by this parser.
:param line: A string representing an instance of this parser's language
:param line_number: The current line number of the parser
"""
self._line_number = line_number
return self.language.parseString(line) | python | def parseString(self, line: str, line_number: int = 0) -> ParseResults: # noqa: N802
"""Parse a string with the language represented by this parser.
:param line: A string representing an instance of this parser's language
:param line_number: The current line number of the parser
"""
self._line_number = line_number
return self.language.parseString(line) | [
"def",
"parseString",
"(",
"self",
",",
"line",
":",
"str",
",",
"line_number",
":",
"int",
"=",
"0",
")",
"->",
"ParseResults",
":",
"# noqa: N802",
"self",
".",
"_line_number",
"=",
"line_number",
"return",
"self",
".",
"language",
".",
"parseString",
"(... | Parse a string with the language represented by this parser.
:param line: A string representing an instance of this parser's language
:param line_number: The current line number of the parser | [
"Parse",
"a",
"string",
"with",
"the",
"language",
"represented",
"by",
"this",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/baseparser.py#L43-L50 | train | 29,710 |
pybel/pybel | src/pybel/parser/baseparser.py | BaseParser.streamline | def streamline(self):
"""Streamline the language represented by this parser to make queries run faster."""
t = time.time()
self.language.streamline()
log.info('streamlined %s in %.02f seconds', self.__class__.__name__, time.time() - t) | python | def streamline(self):
"""Streamline the language represented by this parser to make queries run faster."""
t = time.time()
self.language.streamline()
log.info('streamlined %s in %.02f seconds', self.__class__.__name__, time.time() - t) | [
"def",
"streamline",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"language",
".",
"streamline",
"(",
")",
"log",
".",
"info",
"(",
"'streamlined %s in %.02f seconds'",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
... | Streamline the language represented by this parser to make queries run faster. | [
"Streamline",
"the",
"language",
"represented",
"by",
"this",
"parser",
"to",
"make",
"queries",
"run",
"faster",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/baseparser.py#L56-L60 | train | 29,711 |
pybel/pybel | src/pybel/struct/mutation/transfer.py | iter_children | def iter_children(graph, node: BaseEntity) -> Iterable[BaseEntity]:
"""Iterate over children of the node."""
return (
node
for node, _, d in graph.in_edges(node, data=True)
if d[RELATION] == IS_A
) | python | def iter_children(graph, node: BaseEntity) -> Iterable[BaseEntity]:
"""Iterate over children of the node."""
return (
node
for node, _, d in graph.in_edges(node, data=True)
if d[RELATION] == IS_A
) | [
"def",
"iter_children",
"(",
"graph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"Iterable",
"[",
"BaseEntity",
"]",
":",
"return",
"(",
"node",
"for",
"node",
",",
"_",
",",
"d",
"in",
"graph",
".",
"in_edges",
"(",
"node",
",",
"data",
"=",
"True",... | Iterate over children of the node. | [
"Iterate",
"over",
"children",
"of",
"the",
"node",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/transfer.py#L15-L21 | train | 29,712 |
pybel/pybel | src/pybel/struct/mutation/transfer.py | transfer_causal_edges | def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
"""Transfer causal edges that the source has to the target and yield the resulting hashes."""
for _, v, data in graph.out_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue
yield graph.add_qualified_edge(
target,
v,
relation=data[RELATION],
evidence=data[EVIDENCE],
citation=data[CITATION],
annotations=data.get(ANNOTATIONS),
subject_modifier=data.get(SUBJECT),
object_modifier=data.get(OBJECT),
)
for u, _, data in graph.in_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue
yield graph.add_qualified_edge(
u,
target,
relation=data[RELATION],
evidence=data[EVIDENCE],
citation=data[CITATION],
annotations=data.get(ANNOTATIONS),
subject_modifier=data.get(SUBJECT),
object_modifier=data.get(OBJECT),
) | python | def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
"""Transfer causal edges that the source has to the target and yield the resulting hashes."""
for _, v, data in graph.out_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue
yield graph.add_qualified_edge(
target,
v,
relation=data[RELATION],
evidence=data[EVIDENCE],
citation=data[CITATION],
annotations=data.get(ANNOTATIONS),
subject_modifier=data.get(SUBJECT),
object_modifier=data.get(OBJECT),
)
for u, _, data in graph.in_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue
yield graph.add_qualified_edge(
u,
target,
relation=data[RELATION],
evidence=data[EVIDENCE],
citation=data[CITATION],
annotations=data.get(ANNOTATIONS),
subject_modifier=data.get(SUBJECT),
object_modifier=data.get(OBJECT),
) | [
"def",
"transfer_causal_edges",
"(",
"graph",
",",
"source",
":",
"BaseEntity",
",",
"target",
":",
"BaseEntity",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"for",
"_",
",",
"v",
",",
"data",
"in",
"graph",
".",
"out_edges",
"(",
"source",
",",
"data... | Transfer causal edges that the source has to the target and yield the resulting hashes. | [
"Transfer",
"causal",
"edges",
"that",
"the",
"source",
"has",
"to",
"the",
"target",
"and",
"yield",
"the",
"resulting",
"hashes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/transfer.py#L24-L54 | train | 29,713 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | _get_protocol_tuple | def _get_protocol_tuple(data: Dict[str, Any]) -> Tuple[str, List, Dict]:
"""Convert a dictionary to a tuple."""
return data['function'], data.get('args', []), data.get('kwargs', {}) | python | def _get_protocol_tuple(data: Dict[str, Any]) -> Tuple[str, List, Dict]:
"""Convert a dictionary to a tuple."""
return data['function'], data.get('args', []), data.get('kwargs', {}) | [
"def",
"_get_protocol_tuple",
"(",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"str",
",",
"List",
",",
"Dict",
"]",
":",
"return",
"data",
"[",
"'function'",
"]",
",",
"data",
".",
"get",
"(",
"'args'",
",",
"[",
"... | Convert a dictionary to a tuple. | [
"Convert",
"a",
"dictionary",
"to",
"a",
"tuple",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L25-L27 | train | 29,714 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline.from_functions | def from_functions(functions) -> 'Pipeline':
"""Build a pipeline from a list of functions.
:param functions: A list of functions or names of functions
:type functions: iter[((pybel.BELGraph) -> pybel.BELGraph) or ((pybel.BELGraph) -> None) or str]
Example with function:
>>> from pybel.struct.pipeline import Pipeline
>>> from pybel.struct.mutation import remove_associations
>>> pipeline = Pipeline.from_functions([remove_associations])
Equivalent example with function names:
>>> from pybel.struct.pipeline import Pipeline
>>> pipeline = Pipeline.from_functions(['remove_associations'])
Lookup by name is possible for built in functions, and those that have been registered correctly using one of
the four decorators:
1. :func:`pybel.struct.pipeline.transformation`,
2. :func:`pybel.struct.pipeline.in_place_transformation`,
3. :func:`pybel.struct.pipeline.uni_transformation`,
4. :func:`pybel.struct.pipeline.uni_in_place_transformation`,
"""
result = Pipeline()
for func in functions:
result.append(func)
return result | python | def from_functions(functions) -> 'Pipeline':
"""Build a pipeline from a list of functions.
:param functions: A list of functions or names of functions
:type functions: iter[((pybel.BELGraph) -> pybel.BELGraph) or ((pybel.BELGraph) -> None) or str]
Example with function:
>>> from pybel.struct.pipeline import Pipeline
>>> from pybel.struct.mutation import remove_associations
>>> pipeline = Pipeline.from_functions([remove_associations])
Equivalent example with function names:
>>> from pybel.struct.pipeline import Pipeline
>>> pipeline = Pipeline.from_functions(['remove_associations'])
Lookup by name is possible for built in functions, and those that have been registered correctly using one of
the four decorators:
1. :func:`pybel.struct.pipeline.transformation`,
2. :func:`pybel.struct.pipeline.in_place_transformation`,
3. :func:`pybel.struct.pipeline.uni_transformation`,
4. :func:`pybel.struct.pipeline.uni_in_place_transformation`,
"""
result = Pipeline()
for func in functions:
result.append(func)
return result | [
"def",
"from_functions",
"(",
"functions",
")",
"->",
"'Pipeline'",
":",
"result",
"=",
"Pipeline",
"(",
")",
"for",
"func",
"in",
"functions",
":",
"result",
".",
"append",
"(",
"func",
")",
"return",
"result"
] | Build a pipeline from a list of functions.
:param functions: A list of functions or names of functions
:type functions: iter[((pybel.BELGraph) -> pybel.BELGraph) or ((pybel.BELGraph) -> None) or str]
Example with function:
>>> from pybel.struct.pipeline import Pipeline
>>> from pybel.struct.mutation import remove_associations
>>> pipeline = Pipeline.from_functions([remove_associations])
Equivalent example with function names:
>>> from pybel.struct.pipeline import Pipeline
>>> pipeline = Pipeline.from_functions(['remove_associations'])
Lookup by name is possible for built in functions, and those that have been registered correctly using one of
the four decorators:
1. :func:`pybel.struct.pipeline.transformation`,
2. :func:`pybel.struct.pipeline.in_place_transformation`,
3. :func:`pybel.struct.pipeline.uni_transformation`,
4. :func:`pybel.struct.pipeline.uni_in_place_transformation`, | [
"Build",
"a",
"pipeline",
"from",
"a",
"list",
"of",
"functions",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L60-L90 | train | 29,715 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline._get_function | def _get_function(self, name: str):
"""Wrap a function with the universe and in-place.
:param name: The name of the function
:rtype: types.FunctionType
:raises MissingPipelineFunctionError: If the functions is not registered
"""
f = mapped.get(name)
if f is None:
raise MissingPipelineFunctionError('{} is not registered as a pipeline function'.format(name))
if name in universe_map and name in in_place_map:
return self._wrap_in_place(self._wrap_universe(f))
if name in universe_map:
return self._wrap_universe(f)
if name in in_place_map:
return self._wrap_in_place(f)
return f | python | def _get_function(self, name: str):
"""Wrap a function with the universe and in-place.
:param name: The name of the function
:rtype: types.FunctionType
:raises MissingPipelineFunctionError: If the functions is not registered
"""
f = mapped.get(name)
if f is None:
raise MissingPipelineFunctionError('{} is not registered as a pipeline function'.format(name))
if name in universe_map and name in in_place_map:
return self._wrap_in_place(self._wrap_universe(f))
if name in universe_map:
return self._wrap_universe(f)
if name in in_place_map:
return self._wrap_in_place(f)
return f | [
"def",
"_get_function",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"f",
"=",
"mapped",
".",
"get",
"(",
"name",
")",
"if",
"f",
"is",
"None",
":",
"raise",
"MissingPipelineFunctionError",
"(",
"'{} is not registered as a pipeline function'",
".",
"format"... | Wrap a function with the universe and in-place.
:param name: The name of the function
:rtype: types.FunctionType
:raises MissingPipelineFunctionError: If the functions is not registered | [
"Wrap",
"a",
"function",
"with",
"the",
"universe",
"and",
"in",
"-",
"place",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L92-L113 | train | 29,716 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline.extend | def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.from_functions(['enrich_protein_and_rna_origins'])
>>> p2 = Pipeline.from_functions(['remove_pathologies'])
>>> p1.extend(p2)
"""
for data in protocol:
name, args, kwargs = _get_protocol_tuple(data)
self.append(name, *args, **kwargs)
return self | python | def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.from_functions(['enrich_protein_and_rna_origins'])
>>> p2 = Pipeline.from_functions(['remove_pathologies'])
>>> p1.extend(p2)
"""
for data in protocol:
name, args, kwargs = _get_protocol_tuple(data)
self.append(name, *args, **kwargs)
return self | [
"def",
"extend",
"(",
"self",
",",
"protocol",
":",
"Union",
"[",
"Iterable",
"[",
"Dict",
"]",
",",
"'Pipeline'",
"]",
")",
"->",
"'Pipeline'",
":",
"for",
"data",
"in",
"protocol",
":",
"name",
",",
"args",
",",
"kwargs",
"=",
"_get_protocol_tuple",
... | Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.from_functions(['enrich_protein_and_rna_origins'])
>>> p2 = Pipeline.from_functions(['remove_pathologies'])
>>> p1.extend(p2) | [
"Add",
"another",
"pipeline",
"to",
"the",
"end",
"of",
"the",
"current",
"pipeline",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L145-L161 | train | 29,717 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline._run_helper | def _run_helper(self, graph, protocol: Iterable[Dict]):
"""Help run the protocol.
:param pybel.BELGraph graph: A BEL graph
:param protocol: The protocol to run, as JSON
:rtype: pybel.BELGraph
"""
result = graph
for entry in protocol:
meta_entry = entry.get('meta')
if meta_entry is None:
name, args, kwargs = _get_protocol_tuple(entry)
func = self._get_function(name)
result = func(result, *args, **kwargs)
else:
networks = (
self._run_helper(graph, subprotocol)
for subprotocol in entry['pipelines']
)
if meta_entry == META_UNION:
result = union(networks)
elif meta_entry == META_INTERSECTION:
result = node_intersection(networks)
else:
raise MetaValueError('invalid meta-command: {}'.format(meta_entry))
return result | python | def _run_helper(self, graph, protocol: Iterable[Dict]):
"""Help run the protocol.
:param pybel.BELGraph graph: A BEL graph
:param protocol: The protocol to run, as JSON
:rtype: pybel.BELGraph
"""
result = graph
for entry in protocol:
meta_entry = entry.get('meta')
if meta_entry is None:
name, args, kwargs = _get_protocol_tuple(entry)
func = self._get_function(name)
result = func(result, *args, **kwargs)
else:
networks = (
self._run_helper(graph, subprotocol)
for subprotocol in entry['pipelines']
)
if meta_entry == META_UNION:
result = union(networks)
elif meta_entry == META_INTERSECTION:
result = node_intersection(networks)
else:
raise MetaValueError('invalid meta-command: {}'.format(meta_entry))
return result | [
"def",
"_run_helper",
"(",
"self",
",",
"graph",
",",
"protocol",
":",
"Iterable",
"[",
"Dict",
"]",
")",
":",
"result",
"=",
"graph",
"for",
"entry",
"in",
"protocol",
":",
"meta_entry",
"=",
"entry",
".",
"get",
"(",
"'meta'",
")",
"if",
"meta_entry"... | Help run the protocol.
:param pybel.BELGraph graph: A BEL graph
:param protocol: The protocol to run, as JSON
:rtype: pybel.BELGraph | [
"Help",
"run",
"the",
"protocol",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L163-L194 | train | 29,718 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline.run | def run(self, graph, universe=None):
"""Run the contained protocol on a seed graph.
:param pybel.BELGraph graph: The seed BEL graph
:param pybel.BELGraph universe: Allows just-in-time setting of the universe in case it wasn't set before.
Defaults to the given network.
:return: The new graph is returned if not applied in-place
:rtype: pybel.BELGraph
"""
self.universe = universe or graph.copy()
return self._run_helper(graph.copy(), self.protocol) | python | def run(self, graph, universe=None):
"""Run the contained protocol on a seed graph.
:param pybel.BELGraph graph: The seed BEL graph
:param pybel.BELGraph universe: Allows just-in-time setting of the universe in case it wasn't set before.
Defaults to the given network.
:return: The new graph is returned if not applied in-place
:rtype: pybel.BELGraph
"""
self.universe = universe or graph.copy()
return self._run_helper(graph.copy(), self.protocol) | [
"def",
"run",
"(",
"self",
",",
"graph",
",",
"universe",
"=",
"None",
")",
":",
"self",
".",
"universe",
"=",
"universe",
"or",
"graph",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_run_helper",
"(",
"graph",
".",
"copy",
"(",
")",
",",
"self",... | Run the contained protocol on a seed graph.
:param pybel.BELGraph graph: The seed BEL graph
:param pybel.BELGraph universe: Allows just-in-time setting of the universe in case it wasn't set before.
Defaults to the given network.
:return: The new graph is returned if not applied in-place
:rtype: pybel.BELGraph | [
"Run",
"the",
"contained",
"protocol",
"on",
"a",
"seed",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L196-L206 | train | 29,719 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline._wrap_universe | def _wrap_universe(self, func): # noqa: D202
"""Take a function that needs a universe graph as the first argument and returns a wrapped one."""
@wraps(func)
def wrapper(graph, *args, **kwargs):
"""Apply the enclosed function with the universe given as the first argument."""
if self.universe is None:
raise MissingUniverseError(
'Can not run universe function [{}] - No universe is set'.format(func.__name__))
return func(self.universe, graph, *args, **kwargs)
return wrapper | python | def _wrap_universe(self, func): # noqa: D202
"""Take a function that needs a universe graph as the first argument and returns a wrapped one."""
@wraps(func)
def wrapper(graph, *args, **kwargs):
"""Apply the enclosed function with the universe given as the first argument."""
if self.universe is None:
raise MissingUniverseError(
'Can not run universe function [{}] - No universe is set'.format(func.__name__))
return func(self.universe, graph, *args, **kwargs)
return wrapper | [
"def",
"_wrap_universe",
"(",
"self",
",",
"func",
")",
":",
"# noqa: D202",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"graph",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Apply the enclosed function with the universe given as the fi... | Take a function that needs a universe graph as the first argument and returns a wrapped one. | [
"Take",
"a",
"function",
"that",
"needs",
"a",
"universe",
"graph",
"as",
"the",
"first",
"argument",
"and",
"returns",
"a",
"wrapped",
"one",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L229-L241 | train | 29,720 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline._wrap_in_place | def _wrap_in_place(func): # noqa: D202
"""Take a function that doesn't return the graph and returns the graph."""
@wraps(func)
def wrapper(graph, *args, **kwargs):
"""Apply the enclosed function and returns the graph."""
func(graph, *args, **kwargs)
return graph
return wrapper | python | def _wrap_in_place(func): # noqa: D202
"""Take a function that doesn't return the graph and returns the graph."""
@wraps(func)
def wrapper(graph, *args, **kwargs):
"""Apply the enclosed function and returns the graph."""
func(graph, *args, **kwargs)
return graph
return wrapper | [
"def",
"_wrap_in_place",
"(",
"func",
")",
":",
"# noqa: D202",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"graph",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Apply the enclosed function and returns the graph.\"\"\"",
"func",
"(",
... | Take a function that doesn't return the graph and returns the graph. | [
"Take",
"a",
"function",
"that",
"doesn",
"t",
"return",
"the",
"graph",
"and",
"returns",
"the",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L244-L253 | train | 29,721 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline.dump | def dump(self, file: TextIO, **kwargs) -> None:
"""Dump this protocol to a file in JSON."""
return json.dump(self.to_json(), file, **kwargs) | python | def dump(self, file: TextIO, **kwargs) -> None:
"""Dump this protocol to a file in JSON."""
return json.dump(self.to_json(), file, **kwargs) | [
"def",
"dump",
"(",
"self",
",",
"file",
":",
"TextIO",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"return",
"json",
".",
"dump",
"(",
"self",
".",
"to_json",
"(",
")",
",",
"file",
",",
"*",
"*",
"kwargs",
")"
] | Dump this protocol to a file in JSON. | [
"Dump",
"this",
"protocol",
"to",
"a",
"file",
"in",
"JSON",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L263-L265 | train | 29,722 |
pybel/pybel | src/pybel/struct/pipeline/pipeline.py | Pipeline._build_meta | def _build_meta(meta: str, pipelines: Iterable['Pipeline']) -> 'Pipeline':
"""Build a pipeline with a given meta-argument.
:param meta: either union or intersection
:param pipelines:
"""
return Pipeline(protocol=[
{
'meta': meta,
'pipelines': [
pipeline.protocol
for pipeline in pipelines
]
},
]) | python | def _build_meta(meta: str, pipelines: Iterable['Pipeline']) -> 'Pipeline':
"""Build a pipeline with a given meta-argument.
:param meta: either union or intersection
:param pipelines:
"""
return Pipeline(protocol=[
{
'meta': meta,
'pipelines': [
pipeline.protocol
for pipeline in pipelines
]
},
]) | [
"def",
"_build_meta",
"(",
"meta",
":",
"str",
",",
"pipelines",
":",
"Iterable",
"[",
"'Pipeline'",
"]",
")",
"->",
"'Pipeline'",
":",
"return",
"Pipeline",
"(",
"protocol",
"=",
"[",
"{",
"'meta'",
":",
"meta",
",",
"'pipelines'",
":",
"[",
"pipeline",... | Build a pipeline with a given meta-argument.
:param meta: either union or intersection
:param pipelines: | [
"Build",
"a",
"pipeline",
"with",
"a",
"given",
"meta",
"-",
"argument",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/pipeline.py#L295-L309 | train | 29,723 |
pybel/pybel | src/pybel/struct/summary/node_summary.py | get_names | def get_names(graph):
"""Get all names for each namespace.
:type graph: pybel.BELGraph
:rtype: dict[str,set[str]]
"""
rv = defaultdict(set)
for namespace, name in _identifier_filtered_iterator(graph):
rv[namespace].add(name)
return dict(rv) | python | def get_names(graph):
"""Get all names for each namespace.
:type graph: pybel.BELGraph
:rtype: dict[str,set[str]]
"""
rv = defaultdict(set)
for namespace, name in _identifier_filtered_iterator(graph):
rv[namespace].add(name)
return dict(rv) | [
"def",
"get_names",
"(",
"graph",
")",
":",
"rv",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"namespace",
",",
"name",
"in",
"_identifier_filtered_iterator",
"(",
"graph",
")",
":",
"rv",
"[",
"namespace",
"]",
".",
"add",
"(",
"name",
")",
"return",
... | Get all names for each namespace.
:type graph: pybel.BELGraph
:rtype: dict[str,set[str]] | [
"Get",
"all",
"names",
"for",
"each",
"namespace",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/node_summary.py#L101-L110 | train | 29,724 |
pybel/pybel | src/pybel/struct/summary/node_summary.py | count_variants | def count_variants(graph):
"""Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter
"""
return Counter(
variant_data[KIND]
for data in graph
if has_variant(graph, data)
for variant_data in data[VARIANTS]
) | python | def count_variants(graph):
"""Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter
"""
return Counter(
variant_data[KIND]
for data in graph
if has_variant(graph, data)
for variant_data in data[VARIANTS]
) | [
"def",
"count_variants",
"(",
"graph",
")",
":",
"return",
"Counter",
"(",
"variant_data",
"[",
"KIND",
"]",
"for",
"data",
"in",
"graph",
"if",
"has_variant",
"(",
"graph",
",",
"data",
")",
"for",
"variant_data",
"in",
"data",
"[",
"VARIANTS",
"]",
")"... | Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter | [
"Count",
"how",
"many",
"of",
"each",
"type",
"of",
"variant",
"a",
"graph",
"has",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/node_summary.py#L202-L213 | train | 29,725 |
pybel/pybel | src/pybel/struct/summary/node_summary.py | get_top_hubs | def get_top_hubs(graph, *, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
"""Get the top hubs in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top hubs to return. If None, returns all nodes
"""
return Counter(dict(graph.degree())).most_common(n=n) | python | def get_top_hubs(graph, *, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
"""Get the top hubs in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top hubs to return. If None, returns all nodes
"""
return Counter(dict(graph.degree())).most_common(n=n) | [
"def",
"get_top_hubs",
"(",
"graph",
",",
"*",
",",
"n",
":",
"Optional",
"[",
"int",
"]",
"=",
"15",
")",
"->",
"List",
"[",
"Tuple",
"[",
"BaseEntity",
",",
"int",
"]",
"]",
":",
"return",
"Counter",
"(",
"dict",
"(",
"graph",
".",
"degree",
"(... | Get the top hubs in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top hubs to return. If None, returns all nodes | [
"Get",
"the",
"top",
"hubs",
"in",
"the",
"graph",
"by",
"BEL",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/node_summary.py#L216-L222 | train | 29,726 |
pybel/pybel | src/pybel/struct/summary/node_summary.py | _pathology_iterator | def _pathology_iterator(graph):
"""Iterate over edges in which either the source or target is a pathology node.
:param pybel.BELGraph graph: A BEL graph
:rtype: iter
"""
for node in itt.chain.from_iterable(graph.edges()):
if isinstance(node, Pathology):
yield node | python | def _pathology_iterator(graph):
"""Iterate over edges in which either the source or target is a pathology node.
:param pybel.BELGraph graph: A BEL graph
:rtype: iter
"""
for node in itt.chain.from_iterable(graph.edges()):
if isinstance(node, Pathology):
yield node | [
"def",
"_pathology_iterator",
"(",
"graph",
")",
":",
"for",
"node",
"in",
"itt",
".",
"chain",
".",
"from_iterable",
"(",
"graph",
".",
"edges",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"Pathology",
")",
":",
"yield",
"node"
] | Iterate over edges in which either the source or target is a pathology node.
:param pybel.BELGraph graph: A BEL graph
:rtype: iter | [
"Iterate",
"over",
"edges",
"in",
"which",
"either",
"the",
"source",
"or",
"target",
"is",
"a",
"pathology",
"node",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/node_summary.py#L225-L233 | train | 29,727 |
pybel/pybel | src/pybel/struct/summary/node_summary.py | get_top_pathologies | def get_top_pathologies(graph, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
"""Get the top highest relationship-having edges in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top connected pathologies to return. If None, returns all nodes
"""
return count_pathologies(graph).most_common(n) | python | def get_top_pathologies(graph, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
"""Get the top highest relationship-having edges in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top connected pathologies to return. If None, returns all nodes
"""
return count_pathologies(graph).most_common(n) | [
"def",
"get_top_pathologies",
"(",
"graph",
",",
"n",
":",
"Optional",
"[",
"int",
"]",
"=",
"15",
")",
"->",
"List",
"[",
"Tuple",
"[",
"BaseEntity",
",",
"int",
"]",
"]",
":",
"return",
"count_pathologies",
"(",
"graph",
")",
".",
"most_common",
"(",... | Get the top highest relationship-having edges in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top connected pathologies to return. If None, returns all nodes | [
"Get",
"the",
"top",
"highest",
"relationship",
"-",
"having",
"edges",
"in",
"the",
"graph",
"by",
"BEL",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/node_summary.py#L245-L251 | train | 29,728 |
pybel/pybel | src/pybel/struct/mutation/inference/protein_rna_origins.py | enrich_proteins_with_rnas | def enrich_proteins_with_rnas(graph):
"""Add the corresponding RNA node for each protein node and connect them with a translation edge.
:param pybel.BELGraph graph: A BEL graph
"""
for protein_node in list(graph):
if not isinstance(protein_node, Protein):
continue
if protein_node.variants:
continue
rna_node = protein_node.get_rna()
graph.add_translation(rna_node, protein_node) | python | def enrich_proteins_with_rnas(graph):
"""Add the corresponding RNA node for each protein node and connect them with a translation edge.
:param pybel.BELGraph graph: A BEL graph
"""
for protein_node in list(graph):
if not isinstance(protein_node, Protein):
continue
if protein_node.variants:
continue
rna_node = protein_node.get_rna()
graph.add_translation(rna_node, protein_node) | [
"def",
"enrich_proteins_with_rnas",
"(",
"graph",
")",
":",
"for",
"protein_node",
"in",
"list",
"(",
"graph",
")",
":",
"if",
"not",
"isinstance",
"(",
"protein_node",
",",
"Protein",
")",
":",
"continue",
"if",
"protein_node",
".",
"variants",
":",
"contin... | Add the corresponding RNA node for each protein node and connect them with a translation edge.
:param pybel.BELGraph graph: A BEL graph | [
"Add",
"the",
"corresponding",
"RNA",
"node",
"for",
"each",
"protein",
"node",
"and",
"connect",
"them",
"with",
"a",
"translation",
"edge",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/inference/protein_rna_origins.py#L19-L32 | train | 29,729 |
pybel/pybel | src/pybel/struct/mutation/induction/upstream.py | get_upstream_causal_subgraph | def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
"""Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph
"""
return get_subgraph_by_edge_filter(graph, build_upstream_edge_predicate(nbunch)) | python | def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
"""Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph
"""
return get_subgraph_by_edge_filter(graph, build_upstream_edge_predicate(nbunch)) | [
"def",
"get_upstream_causal_subgraph",
"(",
"graph",
",",
"nbunch",
":",
"Union",
"[",
"BaseEntity",
",",
"Iterable",
"[",
"BaseEntity",
"]",
"]",
")",
":",
"return",
"get_subgraph_by_edge_filter",
"(",
"graph",
",",
"build_upstream_edge_predicate",
"(",
"nbunch",
... | Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph | [
"Induce",
"a",
"sub",
"-",
"graph",
"from",
"all",
"of",
"the",
"upstream",
"causal",
"entities",
"of",
"the",
"nodes",
"in",
"the",
"nbunch",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/upstream.py#L22-L28 | train | 29,730 |
pybel/pybel | src/pybel/struct/mutation/induction/upstream.py | get_downstream_causal_subgraph | def get_downstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
"""Induce a sub-graph from all of the downstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph
"""
return get_subgraph_by_edge_filter(graph, build_downstream_edge_predicate(nbunch)) | python | def get_downstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
"""Induce a sub-graph from all of the downstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph
"""
return get_subgraph_by_edge_filter(graph, build_downstream_edge_predicate(nbunch)) | [
"def",
"get_downstream_causal_subgraph",
"(",
"graph",
",",
"nbunch",
":",
"Union",
"[",
"BaseEntity",
",",
"Iterable",
"[",
"BaseEntity",
"]",
"]",
")",
":",
"return",
"get_subgraph_by_edge_filter",
"(",
"graph",
",",
"build_downstream_edge_predicate",
"(",
"nbunch... | Induce a sub-graph from all of the downstream causal entities of the nodes in the nbunch.
:type graph: pybel.BELGraph
:rtype: pybel.BELGraph | [
"Induce",
"a",
"sub",
"-",
"graph",
"from",
"all",
"of",
"the",
"downstream",
"causal",
"entities",
"of",
"the",
"nodes",
"in",
"the",
"nbunch",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/upstream.py#L32-L38 | train | 29,731 |
pybel/pybel | src/pybel/struct/grouping/utils.py | cleanup | def cleanup(graph, subgraphs):
"""Clean up the metadata in the subgraphs.
:type graph: pybel.BELGraph
:type subgraphs: dict[Any,pybel.BELGraph]
"""
for subgraph in subgraphs.values():
update_node_helper(graph, subgraph)
update_metadata(graph, subgraph) | python | def cleanup(graph, subgraphs):
"""Clean up the metadata in the subgraphs.
:type graph: pybel.BELGraph
:type subgraphs: dict[Any,pybel.BELGraph]
"""
for subgraph in subgraphs.values():
update_node_helper(graph, subgraph)
update_metadata(graph, subgraph) | [
"def",
"cleanup",
"(",
"graph",
",",
"subgraphs",
")",
":",
"for",
"subgraph",
"in",
"subgraphs",
".",
"values",
"(",
")",
":",
"update_node_helper",
"(",
"graph",
",",
"subgraph",
")",
"update_metadata",
"(",
"graph",
",",
"subgraph",
")"
] | Clean up the metadata in the subgraphs.
:type graph: pybel.BELGraph
:type subgraphs: dict[Any,pybel.BELGraph] | [
"Clean",
"up",
"the",
"metadata",
"in",
"the",
"subgraphs",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/grouping/utils.py#L12-L20 | train | 29,732 |
pybel/pybel | src/pybel/parser/modifiers/fragment.py | get_fragment_language | def get_fragment_language() -> ParserElement:
"""Build a protein fragment parser."""
_fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
_fragment_value = _fragment_value_inner | And([Suppress('"'), _fragment_value_inner, Suppress('"')])
parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION)))
return parser_element | python | def get_fragment_language() -> ParserElement:
"""Build a protein fragment parser."""
_fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
_fragment_value = _fragment_value_inner | And([Suppress('"'), _fragment_value_inner, Suppress('"')])
parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION)))
return parser_element | [
"def",
"get_fragment_language",
"(",
")",
"->",
"ParserElement",
":",
"_fragment_value_inner",
"=",
"fragment_range",
"|",
"missing_fragment",
"(",
"FRAGMENT_MISSING",
")",
"_fragment_value",
"=",
"_fragment_value_inner",
"|",
"And",
"(",
"[",
"Suppress",
"(",
"'\"'",... | Build a protein fragment parser. | [
"Build",
"a",
"protein",
"fragment",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/fragment.py#L76-L81 | train | 29,733 |
pybel/pybel | src/pybel/parser/modifiers/protein_modification.py | get_protein_modification_language | def get_protein_modification_language(identifier_qualified: ParserElement) -> ParserElement:
"""Build a protein modification parser."""
pmod_identifier = MatchFirst([
identifier_qualified,
pmod_default_ns,
pmod_legacy_ns
])
return pmod_tag + nest(
Group(pmod_identifier)(IDENTIFIER) +
Optional(
WCW +
amino_acid(PMOD_CODE) +
Optional(
WCW +
ppc.integer(PMOD_POSITION)
)
)
) | python | def get_protein_modification_language(identifier_qualified: ParserElement) -> ParserElement:
"""Build a protein modification parser."""
pmod_identifier = MatchFirst([
identifier_qualified,
pmod_default_ns,
pmod_legacy_ns
])
return pmod_tag + nest(
Group(pmod_identifier)(IDENTIFIER) +
Optional(
WCW +
amino_acid(PMOD_CODE) +
Optional(
WCW +
ppc.integer(PMOD_POSITION)
)
)
) | [
"def",
"get_protein_modification_language",
"(",
"identifier_qualified",
":",
"ParserElement",
")",
"->",
"ParserElement",
":",
"pmod_identifier",
"=",
"MatchFirst",
"(",
"[",
"identifier_qualified",
",",
"pmod_default_ns",
",",
"pmod_legacy_ns",
"]",
")",
"return",
"pm... | Build a protein modification parser. | [
"Build",
"a",
"protein",
"modification",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/protein_modification.py#L112-L130 | train | 29,734 |
pybel/pybel | scripts/run_jgif.py | upload_cbn_dir | def upload_cbn_dir(dir_path, manager):
"""Uploads CBN data to edge store
:param str dir_path: Directory full of CBN JGIF files
:param pybel.Manager manager:
"""
t = time.time()
for jfg_path in os.listdir(dir_path):
if not jfg_path.endswith('.jgf'):
continue
path = os.path.join(dir_path, jfg_path)
log.info('opening %s', path)
with open(path) as f:
cbn_jgif_dict = json.load(f)
graph = pybel.from_cbn_jgif(cbn_jgif_dict)
out_path = os.path.join(dir_path, jfg_path.replace('.jgf', '.bel'))
with open(out_path, 'w') as o:
pybel.to_bel(graph, o)
strip_annotations(graph)
enrich_pubmed_citations(manager=manager, graph=graph)
pybel.to_database(graph, manager=manager)
log.info('')
log.info('done in %.2f', time.time() - t) | python | def upload_cbn_dir(dir_path, manager):
"""Uploads CBN data to edge store
:param str dir_path: Directory full of CBN JGIF files
:param pybel.Manager manager:
"""
t = time.time()
for jfg_path in os.listdir(dir_path):
if not jfg_path.endswith('.jgf'):
continue
path = os.path.join(dir_path, jfg_path)
log.info('opening %s', path)
with open(path) as f:
cbn_jgif_dict = json.load(f)
graph = pybel.from_cbn_jgif(cbn_jgif_dict)
out_path = os.path.join(dir_path, jfg_path.replace('.jgf', '.bel'))
with open(out_path, 'w') as o:
pybel.to_bel(graph, o)
strip_annotations(graph)
enrich_pubmed_citations(manager=manager, graph=graph)
pybel.to_database(graph, manager=manager)
log.info('')
log.info('done in %.2f', time.time() - t) | [
"def",
"upload_cbn_dir",
"(",
"dir_path",
",",
"manager",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"jfg_path",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"if",
"not",
"jfg_path",
".",
"endswith",
"(",
"'.jgf'",
")",
":",
... | Uploads CBN data to edge store
:param str dir_path: Directory full of CBN JGIF files
:param pybel.Manager manager: | [
"Uploads",
"CBN",
"data",
"to",
"edge",
"store"
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/scripts/run_jgif.py#L16-L47 | train | 29,735 |
pybel/pybel | src/pybel/dsl/edges.py | _activity_helper | def _activity_helper(modifier: str, location=None):
"""Make an activity dictionary.
:param str modifier:
:param Optional[dict] location: An entity from :func:`pybel.dsl.entity`
:rtype: dict
"""
rv = {MODIFIER: modifier}
if location:
rv[LOCATION] = location
return rv | python | def _activity_helper(modifier: str, location=None):
"""Make an activity dictionary.
:param str modifier:
:param Optional[dict] location: An entity from :func:`pybel.dsl.entity`
:rtype: dict
"""
rv = {MODIFIER: modifier}
if location:
rv[LOCATION] = location
return rv | [
"def",
"_activity_helper",
"(",
"modifier",
":",
"str",
",",
"location",
"=",
"None",
")",
":",
"rv",
"=",
"{",
"MODIFIER",
":",
"modifier",
"}",
"if",
"location",
":",
"rv",
"[",
"LOCATION",
"]",
"=",
"location",
"return",
"rv"
] | Make an activity dictionary.
:param str modifier:
:param Optional[dict] location: An entity from :func:`pybel.dsl.entity`
:rtype: dict | [
"Make",
"an",
"activity",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/edges.py#L21-L33 | train | 29,736 |
pybel/pybel | src/pybel/dsl/edges.py | translocation | def translocation(from_loc, to_loc):
"""Make a translocation dictionary.
:param dict from_loc: An entity dictionary from :func:`pybel.dsl.entity`
:param dict to_loc: An entity dictionary from :func:`pybel.dsl.entity`
:rtype: dict
"""
rv = _activity_helper(TRANSLOCATION)
rv[EFFECT] = {
FROM_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=from_loc) if isinstance(from_loc, str) else from_loc,
TO_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=to_loc) if isinstance(to_loc, str) else to_loc,
}
return rv | python | def translocation(from_loc, to_loc):
"""Make a translocation dictionary.
:param dict from_loc: An entity dictionary from :func:`pybel.dsl.entity`
:param dict to_loc: An entity dictionary from :func:`pybel.dsl.entity`
:rtype: dict
"""
rv = _activity_helper(TRANSLOCATION)
rv[EFFECT] = {
FROM_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=from_loc) if isinstance(from_loc, str) else from_loc,
TO_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=to_loc) if isinstance(to_loc, str) else to_loc,
}
return rv | [
"def",
"translocation",
"(",
"from_loc",
",",
"to_loc",
")",
":",
"rv",
"=",
"_activity_helper",
"(",
"TRANSLOCATION",
")",
"rv",
"[",
"EFFECT",
"]",
"=",
"{",
"FROM_LOC",
":",
"Entity",
"(",
"namespace",
"=",
"BEL_DEFAULT_NAMESPACE",
",",
"name",
"=",
"fr... | Make a translocation dictionary.
:param dict from_loc: An entity dictionary from :func:`pybel.dsl.entity`
:param dict to_loc: An entity dictionary from :func:`pybel.dsl.entity`
:rtype: dict | [
"Make",
"a",
"translocation",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/edges.py#L66-L78 | train | 29,737 |
pybel/pybel | src/pybel/struct/summary/provenance.py | iterate_pubmed_identifiers | def iterate_pubmed_identifiers(graph) -> Iterable[str]:
"""Iterate over all PubMed identifiers in a graph.
:param pybel.BELGraph graph: A BEL graph
:return: An iterator over the PubMed identifiers in the graph
"""
return (
data[CITATION][CITATION_REFERENCE].strip()
for _, _, data in graph.edges(data=True)
if has_pubmed(data)
) | python | def iterate_pubmed_identifiers(graph) -> Iterable[str]:
"""Iterate over all PubMed identifiers in a graph.
:param pybel.BELGraph graph: A BEL graph
:return: An iterator over the PubMed identifiers in the graph
"""
return (
data[CITATION][CITATION_REFERENCE].strip()
for _, _, data in graph.edges(data=True)
if has_pubmed(data)
) | [
"def",
"iterate_pubmed_identifiers",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"return",
"(",
"data",
"[",
"CITATION",
"]",
"[",
"CITATION_REFERENCE",
"]",
".",
"strip",
"(",
")",
"for",
"_",
",",
"_",
",",
"data",
"in",
"graph",
".",
... | Iterate over all PubMed identifiers in a graph.
:param pybel.BELGraph graph: A BEL graph
:return: An iterator over the PubMed identifiers in the graph | [
"Iterate",
"over",
"all",
"PubMed",
"identifiers",
"in",
"a",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/provenance.py#L18-L28 | train | 29,738 |
pybel/pybel | src/pybel/struct/mutation/deletion/deletion.py | remove_filtered_edges | def remove_filtered_edges(graph, edge_predicates=None):
"""Remove edges passing the given edge predicates.
:param pybel.BELGraph graph: A BEL graph
:param edge_predicates: A predicate or list of predicates
:type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGraph, tuple, tuple, int) -> bool]]
:return:
"""
edges = list(filter_edges(graph, edge_predicates=edge_predicates))
graph.remove_edges_from(edges) | python | def remove_filtered_edges(graph, edge_predicates=None):
"""Remove edges passing the given edge predicates.
:param pybel.BELGraph graph: A BEL graph
:param edge_predicates: A predicate or list of predicates
:type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGraph, tuple, tuple, int) -> bool]]
:return:
"""
edges = list(filter_edges(graph, edge_predicates=edge_predicates))
graph.remove_edges_from(edges) | [
"def",
"remove_filtered_edges",
"(",
"graph",
",",
"edge_predicates",
"=",
"None",
")",
":",
"edges",
"=",
"list",
"(",
"filter_edges",
"(",
"graph",
",",
"edge_predicates",
"=",
"edge_predicates",
")",
")",
"graph",
".",
"remove_edges_from",
"(",
"edges",
")"... | Remove edges passing the given edge predicates.
:param pybel.BELGraph graph: A BEL graph
:param edge_predicates: A predicate or list of predicates
:type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGraph, tuple, tuple, int) -> bool]]
:return: | [
"Remove",
"edges",
"passing",
"the",
"given",
"edge",
"predicates",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/deletion/deletion.py#L24-L33 | train | 29,739 |
pybel/pybel | src/pybel/struct/mutation/deletion/deletion.py | remove_filtered_nodes | def remove_filtered_nodes(graph, node_predicates=None):
"""Remove nodes passing the given node predicates.
:param pybel.BELGraph graph: A BEL graph
:type node_predicates: None or ((pybel.BELGraph, tuple) -> bool) or iter[(pybel.BELGraph, tuple) -> bool)]
"""
nodes = list(filter_nodes(graph, node_predicates=node_predicates))
graph.remove_nodes_from(nodes) | python | def remove_filtered_nodes(graph, node_predicates=None):
"""Remove nodes passing the given node predicates.
:param pybel.BELGraph graph: A BEL graph
:type node_predicates: None or ((pybel.BELGraph, tuple) -> bool) or iter[(pybel.BELGraph, tuple) -> bool)]
"""
nodes = list(filter_nodes(graph, node_predicates=node_predicates))
graph.remove_nodes_from(nodes) | [
"def",
"remove_filtered_nodes",
"(",
"graph",
",",
"node_predicates",
"=",
"None",
")",
":",
"nodes",
"=",
"list",
"(",
"filter_nodes",
"(",
"graph",
",",
"node_predicates",
"=",
"node_predicates",
")",
")",
"graph",
".",
"remove_nodes_from",
"(",
"nodes",
")"... | Remove nodes passing the given node predicates.
:param pybel.BELGraph graph: A BEL graph
:type node_predicates: None or ((pybel.BELGraph, tuple) -> bool) or iter[(pybel.BELGraph, tuple) -> bool)] | [
"Remove",
"nodes",
"passing",
"the",
"given",
"node",
"predicates",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/deletion/deletion.py#L37-L44 | train | 29,740 |
pybel/pybel | src/pybel/struct/mutation/induction/neighborhood.py | get_subgraph_by_neighborhood | def get_subgraph_by_neighborhood(graph, nodes: Iterable[BaseEntity]):
"""Get a BEL graph around the neighborhoods of the given nodes.
Returns none if no nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param nodes: An iterable of BEL nodes
:return: A BEL graph induced around the neighborhoods of the given nodes
:rtype: Optional[pybel.BELGraph]
"""
node_set = set(nodes)
if not any(node in graph for node in node_set):
return
rv = graph.fresh_copy()
rv.add_edges_from(itt.chain(
graph.in_edges(nodes, keys=True, data=True),
graph.out_edges(nodes, keys=True, data=True),
))
update_node_helper(graph, rv)
update_metadata(graph, rv)
return rv | python | def get_subgraph_by_neighborhood(graph, nodes: Iterable[BaseEntity]):
"""Get a BEL graph around the neighborhoods of the given nodes.
Returns none if no nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param nodes: An iterable of BEL nodes
:return: A BEL graph induced around the neighborhoods of the given nodes
:rtype: Optional[pybel.BELGraph]
"""
node_set = set(nodes)
if not any(node in graph for node in node_set):
return
rv = graph.fresh_copy()
rv.add_edges_from(itt.chain(
graph.in_edges(nodes, keys=True, data=True),
graph.out_edges(nodes, keys=True, data=True),
))
update_node_helper(graph, rv)
update_metadata(graph, rv)
return rv | [
"def",
"get_subgraph_by_neighborhood",
"(",
"graph",
",",
"nodes",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
":",
"node_set",
"=",
"set",
"(",
"nodes",
")",
"if",
"not",
"any",
"(",
"node",
"in",
"graph",
"for",
"node",
"in",
"node_set",
")",
":",
... | Get a BEL graph around the neighborhoods of the given nodes.
Returns none if no nodes are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param nodes: An iterable of BEL nodes
:return: A BEL graph induced around the neighborhoods of the given nodes
:rtype: Optional[pybel.BELGraph] | [
"Get",
"a",
"BEL",
"graph",
"around",
"the",
"neighborhoods",
"of",
"the",
"given",
"nodes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/neighborhood.py#L18-L42 | train | 29,741 |
pybel/pybel | src/pybel/parser/modifiers/gene_modification.py | get_gene_modification_language | def get_gene_modification_language(identifier_qualified: ParserElement) -> ParserElement:
"""Build a gene modification parser."""
gmod_identifier = MatchFirst([
identifier_qualified,
gmod_default_ns,
])
return gmod_tag + nest(
Group(gmod_identifier)(IDENTIFIER)
) | python | def get_gene_modification_language(identifier_qualified: ParserElement) -> ParserElement:
"""Build a gene modification parser."""
gmod_identifier = MatchFirst([
identifier_qualified,
gmod_default_ns,
])
return gmod_tag + nest(
Group(gmod_identifier)(IDENTIFIER)
) | [
"def",
"get_gene_modification_language",
"(",
"identifier_qualified",
":",
"ParserElement",
")",
"->",
"ParserElement",
":",
"gmod_identifier",
"=",
"MatchFirst",
"(",
"[",
"identifier_qualified",
",",
"gmod_default_ns",
",",
"]",
")",
"return",
"gmod_tag",
"+",
"nest... | Build a gene modification parser. | [
"Build",
"a",
"gene",
"modification",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/gene_modification.py#L66-L75 | train | 29,742 |
pybel/pybel | src/pybel/utils.py | expand_dict | def expand_dict(flat_dict, sep='_'):
"""Expand a flattened dictionary.
:param dict flat_dict: a nested dictionary that has been flattened so the keys are composite
:param str sep: the separator between concatenated keys
:rtype: dict
"""
res = {}
rdict = defaultdict(list)
for flat_key, value in flat_dict.items():
key = flat_key.split(sep, 1)
if 1 == len(key):
res[key[0]] = value
else:
rdict[key[0]].append((key[1:], value))
for k, v in rdict.items():
res[k] = expand_dict({ik: iv for (ik,), iv in v})
return res | python | def expand_dict(flat_dict, sep='_'):
"""Expand a flattened dictionary.
:param dict flat_dict: a nested dictionary that has been flattened so the keys are composite
:param str sep: the separator between concatenated keys
:rtype: dict
"""
res = {}
rdict = defaultdict(list)
for flat_key, value in flat_dict.items():
key = flat_key.split(sep, 1)
if 1 == len(key):
res[key[0]] = value
else:
rdict[key[0]].append((key[1:], value))
for k, v in rdict.items():
res[k] = expand_dict({ik: iv for (ik,), iv in v})
return res | [
"def",
"expand_dict",
"(",
"flat_dict",
",",
"sep",
"=",
"'_'",
")",
":",
"res",
"=",
"{",
"}",
"rdict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"flat_key",
",",
"value",
"in",
"flat_dict",
".",
"items",
"(",
")",
":",
"key",
"=",
"flat_key",
... | Expand a flattened dictionary.
:param dict flat_dict: a nested dictionary that has been flattened so the keys are composite
:param str sep: the separator between concatenated keys
:rtype: dict | [
"Expand",
"a",
"flattened",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L24-L44 | train | 29,743 |
pybel/pybel | src/pybel/utils.py | tokenize_version | def tokenize_version(version_string: str) -> Tuple[int, int, int]:
"""Tokenize a version string to a tuple.
Truncates qualifiers like ``-dev``.
:param version_string: A version string
:return: A tuple representing the version string
>>> tokenize_version('0.1.2-dev')
(0, 1, 2)
"""
before_dash = version_string.split('-')[0]
major, minor, patch = before_dash.split('.')[:3] # take only the first 3 in case there's an extension like -dev.0
return int(major), int(minor), int(patch) | python | def tokenize_version(version_string: str) -> Tuple[int, int, int]:
"""Tokenize a version string to a tuple.
Truncates qualifiers like ``-dev``.
:param version_string: A version string
:return: A tuple representing the version string
>>> tokenize_version('0.1.2-dev')
(0, 1, 2)
"""
before_dash = version_string.split('-')[0]
major, minor, patch = before_dash.split('.')[:3] # take only the first 3 in case there's an extension like -dev.0
return int(major), int(minor), int(patch) | [
"def",
"tokenize_version",
"(",
"version_string",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"before_dash",
"=",
"version_string",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
"major",
",",
"minor",
",",
"patch",
"... | Tokenize a version string to a tuple.
Truncates qualifiers like ``-dev``.
:param version_string: A version string
:return: A tuple representing the version string
>>> tokenize_version('0.1.2-dev')
(0, 1, 2) | [
"Tokenize",
"a",
"version",
"string",
"to",
"a",
"tuple",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L79-L92 | train | 29,744 |
pybel/pybel | src/pybel/utils.py | parse_datetime | def parse_datetime(s: str) -> datetime.date:
"""Try to parse a datetime object from a standard datetime format or date format."""
for fmt in (CREATION_DATE_FMT, PUBLISHED_DATE_FMT, PUBLISHED_DATE_FMT_2):
try:
dt = datetime.strptime(s, fmt)
except ValueError:
pass
else:
return dt
raise ValueError('Incorrect datetime format for {}'.format(s)) | python | def parse_datetime(s: str) -> datetime.date:
"""Try to parse a datetime object from a standard datetime format or date format."""
for fmt in (CREATION_DATE_FMT, PUBLISHED_DATE_FMT, PUBLISHED_DATE_FMT_2):
try:
dt = datetime.strptime(s, fmt)
except ValueError:
pass
else:
return dt
raise ValueError('Incorrect datetime format for {}'.format(s)) | [
"def",
"parse_datetime",
"(",
"s",
":",
"str",
")",
"->",
"datetime",
".",
"date",
":",
"for",
"fmt",
"in",
"(",
"CREATION_DATE_FMT",
",",
"PUBLISHED_DATE_FMT",
",",
"PUBLISHED_DATE_FMT_2",
")",
":",
"try",
":",
"dt",
"=",
"datetime",
".",
"strptime",
"(",... | Try to parse a datetime object from a standard datetime format or date format. | [
"Try",
"to",
"parse",
"a",
"datetime",
"object",
"from",
"a",
"standard",
"datetime",
"format",
"or",
"date",
"format",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L124-L134 | train | 29,745 |
pybel/pybel | src/pybel/utils.py | _get_edge_tuple | def _get_edge_tuple(source,
target,
edge_data: EdgeData,
) -> Tuple[str, str, str, Optional[str], Tuple[str, Optional[Tuple], Optional[Tuple]]]:
"""Convert an edge to a consistent tuple.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A tuple that can be hashed representing this edge. Makes no promises to its structure.
"""
return (
source.as_bel(),
target.as_bel(),
_get_citation_str(edge_data),
edge_data.get(EVIDENCE),
canonicalize_edge(edge_data),
) | python | def _get_edge_tuple(source,
target,
edge_data: EdgeData,
) -> Tuple[str, str, str, Optional[str], Tuple[str, Optional[Tuple], Optional[Tuple]]]:
"""Convert an edge to a consistent tuple.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A tuple that can be hashed representing this edge. Makes no promises to its structure.
"""
return (
source.as_bel(),
target.as_bel(),
_get_citation_str(edge_data),
edge_data.get(EVIDENCE),
canonicalize_edge(edge_data),
) | [
"def",
"_get_edge_tuple",
"(",
"source",
",",
"target",
",",
"edge_data",
":",
"EdgeData",
",",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
",",
"Optional",
"[",
"str",
"]",
",",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"Tuple",
"]",
... | Convert an edge to a consistent tuple.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A tuple that can be hashed representing this edge. Makes no promises to its structure. | [
"Convert",
"an",
"edge",
"to",
"a",
"consistent",
"tuple",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L150-L167 | train | 29,746 |
pybel/pybel | src/pybel/utils.py | hash_edge | def hash_edge(source, target, edge_data: EdgeData) -> str:
"""Convert an edge tuple to a SHA-512 hash.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A hashed version of the edge tuple using md5 hash of the binary pickle dump of u, v, and the json dump of d
"""
edge_tuple = _get_edge_tuple(source, target, edge_data)
return _hash_tuple(edge_tuple) | python | def hash_edge(source, target, edge_data: EdgeData) -> str:
"""Convert an edge tuple to a SHA-512 hash.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A hashed version of the edge tuple using md5 hash of the binary pickle dump of u, v, and the json dump of d
"""
edge_tuple = _get_edge_tuple(source, target, edge_data)
return _hash_tuple(edge_tuple) | [
"def",
"hash_edge",
"(",
"source",
",",
"target",
",",
"edge_data",
":",
"EdgeData",
")",
"->",
"str",
":",
"edge_tuple",
"=",
"_get_edge_tuple",
"(",
"source",
",",
"target",
",",
"edge_data",
")",
"return",
"_hash_tuple",
"(",
"edge_tuple",
")"
] | Convert an edge tuple to a SHA-512 hash.
:param BaseEntity source: The source BEL node
:param BaseEntity target: The target BEL node
:param edge_data: The edge's data dictionary
:return: A hashed version of the edge tuple using md5 hash of the binary pickle dump of u, v, and the json dump of d | [
"Convert",
"an",
"edge",
"tuple",
"to",
"a",
"SHA",
"-",
"512",
"hash",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L170-L179 | train | 29,747 |
pybel/pybel | src/pybel/utils.py | subdict_matches | def subdict_matches(target: Mapping, query: Mapping, partial_match: bool = True) -> bool:
"""Check if all the keys in the query dict are in the target dict, and that their values match.
1. Checks that all keys in the query dict are in the target dict
2. Matches the values of the keys in the query dict
a. If the value is a string, then must match exactly
b. If the value is a set/list/tuple, then will match any of them
c. If the value is a dict, then recursively check if that subdict matches
:param target: The dictionary to search
:param query: A query dict with keys to match
:param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.
:return: if all keys in b are in target_dict and their values match
"""
for k, v in query.items():
if k not in target:
return False
elif not isinstance(v, (int, str, dict, Iterable)):
raise ValueError('invalid value: {}'.format(v))
elif isinstance(v, (int, str)) and target[k] != v:
return False
elif isinstance(v, dict):
if partial_match:
if not isinstance(target[k], dict):
return False
elif not subdict_matches(target[k], v, partial_match):
return False
elif not partial_match and target[k] != v:
return False
elif isinstance(v, Iterable) and target[k] not in v:
return False
return True | python | def subdict_matches(target: Mapping, query: Mapping, partial_match: bool = True) -> bool:
"""Check if all the keys in the query dict are in the target dict, and that their values match.
1. Checks that all keys in the query dict are in the target dict
2. Matches the values of the keys in the query dict
a. If the value is a string, then must match exactly
b. If the value is a set/list/tuple, then will match any of them
c. If the value is a dict, then recursively check if that subdict matches
:param target: The dictionary to search
:param query: A query dict with keys to match
:param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.
:return: if all keys in b are in target_dict and their values match
"""
for k, v in query.items():
if k not in target:
return False
elif not isinstance(v, (int, str, dict, Iterable)):
raise ValueError('invalid value: {}'.format(v))
elif isinstance(v, (int, str)) and target[k] != v:
return False
elif isinstance(v, dict):
if partial_match:
if not isinstance(target[k], dict):
return False
elif not subdict_matches(target[k], v, partial_match):
return False
elif not partial_match and target[k] != v:
return False
elif isinstance(v, Iterable) and target[k] not in v:
return False
return True | [
"def",
"subdict_matches",
"(",
"target",
":",
"Mapping",
",",
"query",
":",
"Mapping",
",",
"partial_match",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"for",
"k",
",",
"v",
"in",
"query",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",... | Check if all the keys in the query dict are in the target dict, and that their values match.
1. Checks that all keys in the query dict are in the target dict
2. Matches the values of the keys in the query dict
a. If the value is a string, then must match exactly
b. If the value is a set/list/tuple, then will match any of them
c. If the value is a dict, then recursively check if that subdict matches
:param target: The dictionary to search
:param query: A query dict with keys to match
:param partial_match: Should the query values be used as partial or exact matches? Defaults to :code:`True`.
:return: if all keys in b are in target_dict and their values match | [
"Check",
"if",
"all",
"the",
"keys",
"in",
"the",
"query",
"dict",
"are",
"in",
"the",
"target",
"dict",
"and",
"that",
"their",
"values",
"match",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L182-L214 | train | 29,748 |
pybel/pybel | src/pybel/utils.py | hash_dump | def hash_dump(data) -> str:
"""Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple
"""
return hashlib.sha512(json.dumps(data, sort_keys=True).encode('utf-8')).hexdigest() | python | def hash_dump(data) -> str:
"""Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple
"""
return hashlib.sha512(json.dumps(data, sort_keys=True).encode('utf-8')).hexdigest() | [
"def",
"hash_dump",
"(",
"data",
")",
"->",
"str",
":",
"return",
"hashlib",
".",
"sha512",
"(",
"json",
".",
"dumps",
"(",
"data",
",",
"sort_keys",
"=",
"True",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")"
] | Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple | [
"Hash",
"an",
"arbitrary",
"JSON",
"dictionary",
"by",
"dumping",
"it",
"in",
"sorted",
"order",
"encoding",
"it",
"in",
"UTF",
"-",
"8",
"then",
"hashing",
"the",
"bytes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L217-L223 | train | 29,749 |
pybel/pybel | src/pybel/utils.py | hash_evidence | def hash_evidence(text: str, type: str, reference: str) -> str:
"""Create a hash for an evidence and its citation.
:param text: The evidence text
:param type: The corresponding citation type
:param reference: The citation reference
"""
s = u'{type}:{reference}:{text}'.format(type=type, reference=reference, text=text)
return hashlib.sha512(s.encode('utf8')).hexdigest() | python | def hash_evidence(text: str, type: str, reference: str) -> str:
"""Create a hash for an evidence and its citation.
:param text: The evidence text
:param type: The corresponding citation type
:param reference: The citation reference
"""
s = u'{type}:{reference}:{text}'.format(type=type, reference=reference, text=text)
return hashlib.sha512(s.encode('utf8')).hexdigest() | [
"def",
"hash_evidence",
"(",
"text",
":",
"str",
",",
"type",
":",
"str",
",",
"reference",
":",
"str",
")",
"->",
"str",
":",
"s",
"=",
"u'{type}:{reference}:{text}'",
".",
"format",
"(",
"type",
"=",
"type",
",",
"reference",
"=",
"reference",
",",
"... | Create a hash for an evidence and its citation.
:param text: The evidence text
:param type: The corresponding citation type
:param reference: The citation reference | [
"Create",
"a",
"hash",
"for",
"an",
"evidence",
"and",
"its",
"citation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L236-L244 | train | 29,750 |
pybel/pybel | src/pybel/utils.py | canonicalize_edge | def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
"""Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications."""
return (
edge_data[RELATION],
_canonicalize_edge_modifications(edge_data.get(SUBJECT)),
_canonicalize_edge_modifications(edge_data.get(OBJECT)),
) | python | def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
"""Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications."""
return (
edge_data[RELATION],
_canonicalize_edge_modifications(edge_data.get(SUBJECT)),
_canonicalize_edge_modifications(edge_data.get(OBJECT)),
) | [
"def",
"canonicalize_edge",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"Tuple",
"]",
",",
"Optional",
"[",
"Tuple",
"]",
"]",
":",
"return",
"(",
"edge_data",
"[",
"RELATION",
"]",
",",
"_canonicalize_edge_modi... | Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications. | [
"Canonicalize",
"the",
"edge",
"to",
"a",
"tuple",
"based",
"on",
"the",
"relation",
"subject",
"modifications",
"and",
"object",
"modifications",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L247-L253 | train | 29,751 |
pybel/pybel | src/pybel/utils.py | _canonicalize_edge_modifications | def _canonicalize_edge_modifications(edge_data: EdgeData) -> Optional[Tuple]:
"""Return the SUBJECT or OBJECT entry of a PyBEL edge data dictionary as a canonical tuple."""
if edge_data is None:
return
modifier = edge_data.get(MODIFIER)
location = edge_data.get(LOCATION)
effect = edge_data.get(EFFECT)
if modifier is None and location is None:
return
result = []
if modifier == ACTIVITY:
if effect:
effect_name = effect.get(NAME)
effect_identifier = effect.get(IDENTIFIER)
t = (
ACTIVITY,
effect[NAMESPACE],
effect_name or effect_identifier,
)
else:
t = (ACTIVITY,)
result.append(t)
elif modifier == DEGRADATION:
t = (DEGRADATION,)
result.append(t)
elif modifier == TRANSLOCATION:
if effect:
from_loc_name = effect[FROM_LOC].get(NAME)
from_loc_identifier = effect[FROM_LOC].get(IDENTIFIER)
to_loc_name = effect[TO_LOC].get(NAME)
to_loc_identifier = effect[TO_LOC].get(IDENTIFIER)
t = (
TRANSLOCATION,
edge_data[EFFECT][FROM_LOC][NAMESPACE],
from_loc_name or from_loc_identifier,
edge_data[EFFECT][TO_LOC][NAMESPACE],
to_loc_name or to_loc_identifier,
)
else:
t = (TRANSLOCATION,)
result.append(t)
if location:
location_name = location.get(NAME)
location_identifier = location.get(IDENTIFIER)
t = (
LOCATION,
location[NAMESPACE],
location_name or location_identifier,
)
result.append(t)
if not result:
raise ValueError('Invalid data: {}'.format(edge_data))
return tuple(result) | python | def _canonicalize_edge_modifications(edge_data: EdgeData) -> Optional[Tuple]:
"""Return the SUBJECT or OBJECT entry of a PyBEL edge data dictionary as a canonical tuple."""
if edge_data is None:
return
modifier = edge_data.get(MODIFIER)
location = edge_data.get(LOCATION)
effect = edge_data.get(EFFECT)
if modifier is None and location is None:
return
result = []
if modifier == ACTIVITY:
if effect:
effect_name = effect.get(NAME)
effect_identifier = effect.get(IDENTIFIER)
t = (
ACTIVITY,
effect[NAMESPACE],
effect_name or effect_identifier,
)
else:
t = (ACTIVITY,)
result.append(t)
elif modifier == DEGRADATION:
t = (DEGRADATION,)
result.append(t)
elif modifier == TRANSLOCATION:
if effect:
from_loc_name = effect[FROM_LOC].get(NAME)
from_loc_identifier = effect[FROM_LOC].get(IDENTIFIER)
to_loc_name = effect[TO_LOC].get(NAME)
to_loc_identifier = effect[TO_LOC].get(IDENTIFIER)
t = (
TRANSLOCATION,
edge_data[EFFECT][FROM_LOC][NAMESPACE],
from_loc_name or from_loc_identifier,
edge_data[EFFECT][TO_LOC][NAMESPACE],
to_loc_name or to_loc_identifier,
)
else:
t = (TRANSLOCATION,)
result.append(t)
if location:
location_name = location.get(NAME)
location_identifier = location.get(IDENTIFIER)
t = (
LOCATION,
location[NAMESPACE],
location_name or location_identifier,
)
result.append(t)
if not result:
raise ValueError('Invalid data: {}'.format(edge_data))
return tuple(result) | [
"def",
"_canonicalize_edge_modifications",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"Optional",
"[",
"Tuple",
"]",
":",
"if",
"edge_data",
"is",
"None",
":",
"return",
"modifier",
"=",
"edge_data",
".",
"get",
"(",
"MODIFIER",
")",
"location",
"=",
"edg... | Return the SUBJECT or OBJECT entry of a PyBEL edge data dictionary as a canonical tuple. | [
"Return",
"the",
"SUBJECT",
"or",
"OBJECT",
"entry",
"of",
"a",
"PyBEL",
"edge",
"data",
"dictionary",
"as",
"a",
"canonical",
"tuple",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/utils.py#L256-L322 | train | 29,752 |
pybel/pybel | src/pybel/struct/grouping/provenance.py | get_subgraphs_by_citation | def get_subgraphs_by_citation(graph):
"""Stratify the graph based on citations.
:type graph: pybel.BELGraph
:rtype: dict[tuple[str,str],pybel.BELGraph]
"""
rv = defaultdict(graph.fresh_copy)
for u, v, key, data in graph.edges(keys=True, data=True):
if CITATION not in data:
continue
dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]
rv[dk].add_edge(u, v, key=key, **data)
cleanup(graph, rv)
return dict(rv) | python | def get_subgraphs_by_citation(graph):
"""Stratify the graph based on citations.
:type graph: pybel.BELGraph
:rtype: dict[tuple[str,str],pybel.BELGraph]
"""
rv = defaultdict(graph.fresh_copy)
for u, v, key, data in graph.edges(keys=True, data=True):
if CITATION not in data:
continue
dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]
rv[dk].add_edge(u, v, key=key, **data)
cleanup(graph, rv)
return dict(rv) | [
"def",
"get_subgraphs_by_citation",
"(",
"graph",
")",
":",
"rv",
"=",
"defaultdict",
"(",
"graph",
".",
"fresh_copy",
")",
"for",
"u",
",",
"v",
",",
"key",
",",
"data",
"in",
"graph",
".",
"edges",
"(",
"keys",
"=",
"True",
",",
"data",
"=",
"True"... | Stratify the graph based on citations.
:type graph: pybel.BELGraph
:rtype: dict[tuple[str,str],pybel.BELGraph] | [
"Stratify",
"the",
"graph",
"based",
"on",
"citations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/grouping/provenance.py#L15-L32 | train | 29,753 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.raise_for_missing_citation | def raise_for_missing_citation(self, line: str, position: int) -> None:
"""Raise an exception if there is no citation present in the parser.
:raises: MissingCitationException
"""
if self.citation_clearing and not self.citation:
raise MissingCitationException(self.get_line_number(), line, position) | python | def raise_for_missing_citation(self, line: str, position: int) -> None:
"""Raise an exception if there is no citation present in the parser.
:raises: MissingCitationException
"""
if self.citation_clearing and not self.citation:
raise MissingCitationException(self.get_line_number(), line, position) | [
"def",
"raise_for_missing_citation",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"if",
"self",
".",
"citation_clearing",
"and",
"not",
"self",
".",
"citation",
":",
"raise",
"MissingCitationException",
"(",
"sel... | Raise an exception if there is no citation present in the parser.
:raises: MissingCitationException | [
"Raise",
"an",
"exception",
"if",
"there",
"is",
"no",
"citation",
"present",
"in",
"the",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L185-L191 | train | 29,754 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_annotation_key | def handle_annotation_key(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle an annotation key before parsing to validate that it's either enumerated or as a regex.
:raise: MissingCitationException or UndefinedAnnotationWarning
"""
key = tokens['key']
self.raise_for_missing_citation(line, position)
self.raise_for_undefined_annotation(line, position, key)
return tokens | python | def handle_annotation_key(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle an annotation key before parsing to validate that it's either enumerated or as a regex.
:raise: MissingCitationException or UndefinedAnnotationWarning
"""
key = tokens['key']
self.raise_for_missing_citation(line, position)
self.raise_for_undefined_annotation(line, position, key)
return tokens | [
"def",
"handle_annotation_key",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"key",
"=",
"tokens",
"[",
"'key'",
"]",
"self",
".",
"raise_for_missing_citation",
"(",
... | Handle an annotation key before parsing to validate that it's either enumerated or as a regex.
:raise: MissingCitationException or UndefinedAnnotationWarning | [
"Handle",
"an",
"annotation",
"key",
"before",
"parsing",
"to",
"validate",
"that",
"it",
"s",
"either",
"enumerated",
"or",
"as",
"a",
"regex",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L193-L201 | train | 29,755 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_set_statement_group | def handle_set_statement_group(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET STATEMENT_GROUP = "X"`` statement."""
self.statement_group = tokens['group']
return tokens | python | def handle_set_statement_group(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET STATEMENT_GROUP = "X"`` statement."""
self.statement_group = tokens['group']
return tokens | [
"def",
"handle_set_statement_group",
"(",
"self",
",",
"_",
",",
"__",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"self",
".",
"statement_group",
"=",
"tokens",
"[",
"'group'",
"]",
"return",
"tokens"
] | Handle a ``SET STATEMENT_GROUP = "X"`` statement. | [
"Handle",
"a",
"SET",
"STATEMENT_GROUP",
"=",
"X",
"statement",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L203-L206 | train | 29,756 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_set_evidence | def handle_set_evidence(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET Evidence = ""`` statement."""
self.evidence = tokens['value']
return tokens | python | def handle_set_evidence(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET Evidence = ""`` statement."""
self.evidence = tokens['value']
return tokens | [
"def",
"handle_set_evidence",
"(",
"self",
",",
"_",
",",
"__",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"self",
".",
"evidence",
"=",
"tokens",
"[",
"'value'",
"]",
"return",
"tokens"
] | Handle a ``SET Evidence = ""`` statement. | [
"Handle",
"a",
"SET",
"Evidence",
"=",
"statement",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L255-L258 | train | 29,757 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_set_command | def handle_set_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET X = "Y"`` statement."""
key, value = tokens['key'], tokens['value']
self.raise_for_invalid_annotation_value(line, position, key, value)
self.annotations[key] = value
return tokens | python | def handle_set_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle a ``SET X = "Y"`` statement."""
key, value = tokens['key'], tokens['value']
self.raise_for_invalid_annotation_value(line, position, key, value)
self.annotations[key] = value
return tokens | [
"def",
"handle_set_command",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"key",
",",
"value",
"=",
"tokens",
"[",
"'key'",
"]",
",",
"tokens",
"[",
"'value'",
"]... | Handle a ``SET X = "Y"`` statement. | [
"Handle",
"a",
"SET",
"X",
"=",
"Y",
"statement",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L260-L265 | train | 29,758 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_unset_statement_group | def handle_unset_statement_group(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the statement group, or raises an exception if it is not set.
:raises: MissingAnnotationKeyWarning
"""
if self.statement_group is None:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, BEL_KEYWORD_STATEMENT_GROUP)
self.statement_group = None
return tokens | python | def handle_unset_statement_group(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the statement group, or raises an exception if it is not set.
:raises: MissingAnnotationKeyWarning
"""
if self.statement_group is None:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, BEL_KEYWORD_STATEMENT_GROUP)
self.statement_group = None
return tokens | [
"def",
"handle_unset_statement_group",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"if",
"self",
".",
"statement_group",
"is",
"None",
":",
"raise",
"MissingAnnotationKe... | Unset the statement group, or raises an exception if it is not set.
:raises: MissingAnnotationKeyWarning | [
"Unset",
"the",
"statement",
"group",
"or",
"raises",
"an",
"exception",
"if",
"it",
"is",
"not",
"set",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L275-L283 | train | 29,759 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_unset_citation | def handle_unset_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the citation, or raise an exception if it is not set.
:raises: MissingAnnotationKeyWarning
"""
if not self.citation:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, BEL_KEYWORD_CITATION)
self.clear_citation()
return tokens | python | def handle_unset_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the citation, or raise an exception if it is not set.
:raises: MissingAnnotationKeyWarning
"""
if not self.citation:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, BEL_KEYWORD_CITATION)
self.clear_citation()
return tokens | [
"def",
"handle_unset_citation",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"if",
"not",
"self",
".",
"citation",
":",
"raise",
"MissingAnnotationKeyWarning",
"(",
"se... | Unset the citation, or raise an exception if it is not set.
:raises: MissingAnnotationKeyWarning | [
"Unset",
"the",
"citation",
"or",
"raise",
"an",
"exception",
"if",
"it",
"is",
"not",
"set",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L285-L294 | train | 29,760 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_unset_evidence | def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the evidence, or throws an exception if it is not already set.
The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in
the BEL script.
:raises: MissingAnnotationKeyWarning
"""
if self.evidence is None:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, tokens[EVIDENCE])
self.evidence = None
return tokens | python | def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Unset the evidence, or throws an exception if it is not already set.
The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in
the BEL script.
:raises: MissingAnnotationKeyWarning
"""
if self.evidence is None:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, tokens[EVIDENCE])
self.evidence = None
return tokens | [
"def",
"handle_unset_evidence",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"if",
"self",
".",
"evidence",
"is",
"None",
":",
"raise",
"MissingAnnotationKeyWarning",
"... | Unset the evidence, or throws an exception if it is not already set.
The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in
the BEL script.
:raises: MissingAnnotationKeyWarning | [
"Unset",
"the",
"evidence",
"or",
"throws",
"an",
"exception",
"if",
"it",
"is",
"not",
"already",
"set",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L296-L307 | train | 29,761 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.validate_unset_command | def validate_unset_command(self, line: str, position: int, annotation: str) -> None:
"""Raise an exception when trying to ``UNSET X`` if ``X`` is not already set.
:raises: MissingAnnotationKeyWarning
"""
if annotation not in self.annotations:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, annotation) | python | def validate_unset_command(self, line: str, position: int, annotation: str) -> None:
"""Raise an exception when trying to ``UNSET X`` if ``X`` is not already set.
:raises: MissingAnnotationKeyWarning
"""
if annotation not in self.annotations:
raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, annotation) | [
"def",
"validate_unset_command",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"annotation",
":",
"str",
")",
"->",
"None",
":",
"if",
"annotation",
"not",
"in",
"self",
".",
"annotations",
":",
"raise",
"MissingAnnotationKeyWarning... | Raise an exception when trying to ``UNSET X`` if ``X`` is not already set.
:raises: MissingAnnotationKeyWarning | [
"Raise",
"an",
"exception",
"when",
"trying",
"to",
"UNSET",
"X",
"if",
"X",
"is",
"not",
"already",
"set",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L309-L315 | train | 29,762 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.handle_unset_command | def handle_unset_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle an ``UNSET X`` statement or raises an exception if it is not already set.
:raises: MissingAnnotationKeyWarning
"""
key = tokens['key']
self.validate_unset_command(line, position, key)
del self.annotations[key]
return tokens | python | def handle_unset_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle an ``UNSET X`` statement or raises an exception if it is not already set.
:raises: MissingAnnotationKeyWarning
"""
key = tokens['key']
self.validate_unset_command(line, position, key)
del self.annotations[key]
return tokens | [
"def",
"handle_unset_command",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"key",
"=",
"tokens",
"[",
"'key'",
"]",
"self",
".",
"validate_unset_command",
"(",
"line... | Handle an ``UNSET X`` statement or raises an exception if it is not already set.
:raises: MissingAnnotationKeyWarning | [
"Handle",
"an",
"UNSET",
"X",
"statement",
"or",
"raises",
"an",
"exception",
"if",
"it",
"is",
"not",
"already",
"set",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L317-L325 | train | 29,763 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.get_annotations | def get_annotations(self) -> Dict:
"""Get the current annotations."""
return {
EVIDENCE: self.evidence,
CITATION: self.citation.copy(),
ANNOTATIONS: self.annotations.copy()
} | python | def get_annotations(self) -> Dict:
"""Get the current annotations."""
return {
EVIDENCE: self.evidence,
CITATION: self.citation.copy(),
ANNOTATIONS: self.annotations.copy()
} | [
"def",
"get_annotations",
"(",
"self",
")",
"->",
"Dict",
":",
"return",
"{",
"EVIDENCE",
":",
"self",
".",
"evidence",
",",
"CITATION",
":",
"self",
".",
"citation",
".",
"copy",
"(",
")",
",",
"ANNOTATIONS",
":",
"self",
".",
"annotations",
".",
"cop... | Get the current annotations. | [
"Get",
"the",
"current",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L348-L354 | train | 29,764 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.get_missing_required_annotations | def get_missing_required_annotations(self) -> List[str]:
"""Return missing required annotations."""
return [
required_annotation
for required_annotation in self.required_annotations
if required_annotation not in self.annotations
] | python | def get_missing_required_annotations(self) -> List[str]:
"""Return missing required annotations."""
return [
required_annotation
for required_annotation in self.required_annotations
if required_annotation not in self.annotations
] | [
"def",
"get_missing_required_annotations",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"required_annotation",
"for",
"required_annotation",
"in",
"self",
".",
"required_annotations",
"if",
"required_annotation",
"not",
"in",
"self",
".",
"... | Return missing required annotations. | [
"Return",
"missing",
"required",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L356-L362 | train | 29,765 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.clear_citation | def clear_citation(self):
"""Clear the citation and if citation clearing is enabled, clear the evidence and annotations."""
self.citation.clear()
if self.citation_clearing:
self.evidence = None
self.annotations.clear() | python | def clear_citation(self):
"""Clear the citation and if citation clearing is enabled, clear the evidence and annotations."""
self.citation.clear()
if self.citation_clearing:
self.evidence = None
self.annotations.clear() | [
"def",
"clear_citation",
"(",
"self",
")",
":",
"self",
".",
"citation",
".",
"clear",
"(",
")",
"if",
"self",
".",
"citation_clearing",
":",
"self",
".",
"evidence",
"=",
"None",
"self",
".",
"annotations",
".",
"clear",
"(",
")"
] | Clear the citation and if citation clearing is enabled, clear the evidence and annotations. | [
"Clear",
"the",
"citation",
"and",
"if",
"citation",
"clearing",
"is",
"enabled",
"clear",
"the",
"evidence",
"and",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L364-L370 | train | 29,766 |
pybel/pybel | src/pybel/parser/parse_control.py | ControlParser.clear | def clear(self):
"""Clear the statement_group, citation, evidence, and annotations."""
self.statement_group = None
self.citation.clear()
self.evidence = None
self.annotations.clear() | python | def clear(self):
"""Clear the statement_group, citation, evidence, and annotations."""
self.statement_group = None
self.citation.clear()
self.evidence = None
self.annotations.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"statement_group",
"=",
"None",
"self",
".",
"citation",
".",
"clear",
"(",
")",
"self",
".",
"evidence",
"=",
"None",
"self",
".",
"annotations",
".",
"clear",
"(",
")"
] | Clear the statement_group, citation, evidence, and annotations. | [
"Clear",
"the",
"statement_group",
"citation",
"evidence",
"and",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_control.py#L372-L377 | train | 29,767 |
pybel/pybel | src/pybel/io/jgif.py | map_cbn | def map_cbn(d):
"""Pre-processes the JSON from the CBN.
- removes statements without evidence, or with placeholder evidence
:param dict d: Raw JGIF from the CBN
:return: Preprocessed JGIF
:rtype: dict
"""
for i, edge in enumerate(d['graph']['edges']):
if 'metadata' not in d['graph']['edges'][i]:
continue
if 'evidences' not in d['graph']['edges'][i]['metadata']:
continue
for j, evidence in enumerate(d['graph']['edges'][i]['metadata']['evidences']):
if EXPERIMENT_CONTEXT not in evidence:
continue
# ctx = {k.strip().lower(): v.strip() for k, v in evidence[EXPERIMENT_CONTEXT].items() if v.strip()}
new_context = {}
for key, value in evidence[EXPERIMENT_CONTEXT].items():
if not value:
log.debug('key %s without value', key)
continue
value = value.strip()
if not value:
log.debug('key %s without value', key)
continue
key = key.strip().lower()
if key == 'species_common_name':
new_context['Species'] = species_map[value.lower()]
elif key in annotation_map:
new_context[annotation_map[key]] = value
else:
new_context[key] = value
'''
for k, v in annotation_map.items():
if k not in ctx:
continue
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][v] = ctx[k]
del d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][k]
if 'species_common_name' in ctx:
species_name = ctx['species_common_name'].strip().lower()
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT]['Species'] = species_map[
species_name]
del d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][
'species_common_name']
'''
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT] = new_context
return d | python | def map_cbn(d):
"""Pre-processes the JSON from the CBN.
- removes statements without evidence, or with placeholder evidence
:param dict d: Raw JGIF from the CBN
:return: Preprocessed JGIF
:rtype: dict
"""
for i, edge in enumerate(d['graph']['edges']):
if 'metadata' not in d['graph']['edges'][i]:
continue
if 'evidences' not in d['graph']['edges'][i]['metadata']:
continue
for j, evidence in enumerate(d['graph']['edges'][i]['metadata']['evidences']):
if EXPERIMENT_CONTEXT not in evidence:
continue
# ctx = {k.strip().lower(): v.strip() for k, v in evidence[EXPERIMENT_CONTEXT].items() if v.strip()}
new_context = {}
for key, value in evidence[EXPERIMENT_CONTEXT].items():
if not value:
log.debug('key %s without value', key)
continue
value = value.strip()
if not value:
log.debug('key %s without value', key)
continue
key = key.strip().lower()
if key == 'species_common_name':
new_context['Species'] = species_map[value.lower()]
elif key in annotation_map:
new_context[annotation_map[key]] = value
else:
new_context[key] = value
'''
for k, v in annotation_map.items():
if k not in ctx:
continue
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][v] = ctx[k]
del d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][k]
if 'species_common_name' in ctx:
species_name = ctx['species_common_name'].strip().lower()
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT]['Species'] = species_map[
species_name]
del d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT][
'species_common_name']
'''
d['graph']['edges'][i]['metadata']['evidences'][j][EXPERIMENT_CONTEXT] = new_context
return d | [
"def",
"map_cbn",
"(",
"d",
")",
":",
"for",
"i",
",",
"edge",
"in",
"enumerate",
"(",
"d",
"[",
"'graph'",
"]",
"[",
"'edges'",
"]",
")",
":",
"if",
"'metadata'",
"not",
"in",
"d",
"[",
"'graph'",
"]",
"[",
"'edges'",
"]",
"[",
"i",
"]",
":",
... | Pre-processes the JSON from the CBN.
- removes statements without evidence, or with placeholder evidence
:param dict d: Raw JGIF from the CBN
:return: Preprocessed JGIF
:rtype: dict | [
"Pre",
"-",
"processes",
"the",
"JSON",
"from",
"the",
"CBN",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/jgif.py#L62-L124 | train | 29,768 |
pybel/pybel | src/pybel/io/jgif.py | from_jgif | def from_jgif(graph_jgif_dict):
"""Build a BEL graph from a JGIF JSON object.
:param dict graph_jgif_dict: The JSON object representing the graph in JGIF format
:rtype: BELGraph
"""
graph = BELGraph()
root = graph_jgif_dict['graph']
if 'label' in root:
graph.name = root['label']
if 'metadata' in root:
metadata = root['metadata']
for key in METADATA_INSERT_KEYS:
if key in metadata:
graph.document[key] = metadata[key]
parser = BELParser(graph)
parser.bel_term.addParseAction(parser.handle_term)
for node in root['nodes']:
node_label = node.get('label')
if node_label is None:
log.warning('node missing label: %s', node)
continue
try:
parser.bel_term.parseString(node_label)
except NakedNameWarning as e:
log.info('Naked name: %s', e)
except ParseException:
log.info('Parse exception for %s', node_label)
for i, edge in enumerate(root['edges']):
relation = edge.get('relation')
if relation is None:
log.warning('no relation for edge: %s', edge)
if relation in {'actsIn', 'translocates'}:
continue # don't need legacy BEL format
edge_metadata = edge.get('metadata')
if edge_metadata is None:
log.warning('no metadata for edge: %s', edge)
continue
bel_statement = edge.get('label')
if bel_statement is None:
log.debug('No BEL statement for edge %s', edge)
evidences = edge_metadata.get('evidences')
if relation in UNQUALIFIED_EDGES:
pass # FIXME?
else:
if not evidences: # is none or is empty list
log.debug('No evidence for edge %s', edge)
continue
for evidence in evidences:
citation = evidence.get('citation')
if not citation:
continue
if 'type' not in citation or 'id' not in citation:
continue
summary_text = evidence['summary_text'].strip()
if not summary_text or summary_text == placeholder_evidence:
continue
parser.control_parser.clear()
parser.control_parser.citation = reformat_citation(citation)
parser.control_parser.evidence = summary_text
parser.control_parser.annotations.update(evidence[EXPERIMENT_CONTEXT])
try:
parser.parseString(bel_statement, line_number=i)
except Exception as e:
log.warning('JGIF relation parse error: %s for %s', e, bel_statement)
return graph | python | def from_jgif(graph_jgif_dict):
"""Build a BEL graph from a JGIF JSON object.
:param dict graph_jgif_dict: The JSON object representing the graph in JGIF format
:rtype: BELGraph
"""
graph = BELGraph()
root = graph_jgif_dict['graph']
if 'label' in root:
graph.name = root['label']
if 'metadata' in root:
metadata = root['metadata']
for key in METADATA_INSERT_KEYS:
if key in metadata:
graph.document[key] = metadata[key]
parser = BELParser(graph)
parser.bel_term.addParseAction(parser.handle_term)
for node in root['nodes']:
node_label = node.get('label')
if node_label is None:
log.warning('node missing label: %s', node)
continue
try:
parser.bel_term.parseString(node_label)
except NakedNameWarning as e:
log.info('Naked name: %s', e)
except ParseException:
log.info('Parse exception for %s', node_label)
for i, edge in enumerate(root['edges']):
relation = edge.get('relation')
if relation is None:
log.warning('no relation for edge: %s', edge)
if relation in {'actsIn', 'translocates'}:
continue # don't need legacy BEL format
edge_metadata = edge.get('metadata')
if edge_metadata is None:
log.warning('no metadata for edge: %s', edge)
continue
bel_statement = edge.get('label')
if bel_statement is None:
log.debug('No BEL statement for edge %s', edge)
evidences = edge_metadata.get('evidences')
if relation in UNQUALIFIED_EDGES:
pass # FIXME?
else:
if not evidences: # is none or is empty list
log.debug('No evidence for edge %s', edge)
continue
for evidence in evidences:
citation = evidence.get('citation')
if not citation:
continue
if 'type' not in citation or 'id' not in citation:
continue
summary_text = evidence['summary_text'].strip()
if not summary_text or summary_text == placeholder_evidence:
continue
parser.control_parser.clear()
parser.control_parser.citation = reformat_citation(citation)
parser.control_parser.evidence = summary_text
parser.control_parser.annotations.update(evidence[EXPERIMENT_CONTEXT])
try:
parser.parseString(bel_statement, line_number=i)
except Exception as e:
log.warning('JGIF relation parse error: %s for %s', e, bel_statement)
return graph | [
"def",
"from_jgif",
"(",
"graph_jgif_dict",
")",
":",
"graph",
"=",
"BELGraph",
"(",
")",
"root",
"=",
"graph_jgif_dict",
"[",
"'graph'",
"]",
"if",
"'label'",
"in",
"root",
":",
"graph",
".",
"name",
"=",
"root",
"[",
"'label'",
"]",
"if",
"'metadata'",... | Build a BEL graph from a JGIF JSON object.
:param dict graph_jgif_dict: The JSON object representing the graph in JGIF format
:rtype: BELGraph | [
"Build",
"a",
"BEL",
"graph",
"from",
"a",
"JGIF",
"JSON",
"object",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/jgif.py#L203-L291 | train | 29,769 |
pybel/pybel | src/pybel/io/jgif.py | to_jgif | def to_jgif(graph):
"""Build a JGIF dictionary from a BEL graph.
:param pybel.BELGraph graph: A BEL graph
:return: A JGIF dictionary
:rtype: dict
.. warning::
Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to
use Cytoscape.js, we suggest using :func:`pybel.to_cx` instead.
Example:
>>> import pybel, os, json
>>> graph_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/knowledge/selventa-small-corpus/selventa-small-corpus-20150611.bel'
>>> graph = pybel.from_url(graph_url)
>>> graph_jgif_json = pybel.to_jgif(graph)
>>> with open(os.path.expanduser('~/Desktop/small_corpus.json'), 'w') as f:
... json.dump(graph_jgif_json, f)
"""
node_bel = {}
u_v_r_bel = {}
nodes_entry = []
edges_entry = []
for i, node in enumerate(sorted(graph, key=methodcaller('as_bel'))):
node_bel[node] = bel = node.as_bel()
nodes_entry.append({
'id': bel,
'label': bel,
'nodeId': i,
'bel_function_type': node[FUNCTION],
'metadata': {}
})
for u, v in graph.edges():
relation_evidences = defaultdict(list)
for data in graph[u][v].values():
if (u, v, data[RELATION]) not in u_v_r_bel:
u_v_r_bel[u, v, data[RELATION]] = graph.edge_to_bel(u, v, edge_data=data)
bel = u_v_r_bel[u, v, data[RELATION]]
evidence_dict = {
'bel_statement': bel,
}
if ANNOTATIONS in data:
evidence_dict['experiment_context'] = data[ANNOTATIONS]
if EVIDENCE in data:
evidence_dict['summary_text'] = data[EVIDENCE]
if CITATION in data:
evidence_dict['citation'] = data[CITATION]
relation_evidences[data[RELATION]].append(evidence_dict)
for relation, evidences in relation_evidences.items():
edges_entry.append({
'source': node_bel[u],
'target': node_bel[v],
'relation': relation,
'label': u_v_r_bel[u, v, relation],
'metadata': {
'evidences': evidences
}
})
return {
'graph': {
'metadata': graph.document,
'nodes': nodes_entry,
'edges': edges_entry
}
} | python | def to_jgif(graph):
"""Build a JGIF dictionary from a BEL graph.
:param pybel.BELGraph graph: A BEL graph
:return: A JGIF dictionary
:rtype: dict
.. warning::
Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to
use Cytoscape.js, we suggest using :func:`pybel.to_cx` instead.
Example:
>>> import pybel, os, json
>>> graph_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/knowledge/selventa-small-corpus/selventa-small-corpus-20150611.bel'
>>> graph = pybel.from_url(graph_url)
>>> graph_jgif_json = pybel.to_jgif(graph)
>>> with open(os.path.expanduser('~/Desktop/small_corpus.json'), 'w') as f:
... json.dump(graph_jgif_json, f)
"""
node_bel = {}
u_v_r_bel = {}
nodes_entry = []
edges_entry = []
for i, node in enumerate(sorted(graph, key=methodcaller('as_bel'))):
node_bel[node] = bel = node.as_bel()
nodes_entry.append({
'id': bel,
'label': bel,
'nodeId': i,
'bel_function_type': node[FUNCTION],
'metadata': {}
})
for u, v in graph.edges():
relation_evidences = defaultdict(list)
for data in graph[u][v].values():
if (u, v, data[RELATION]) not in u_v_r_bel:
u_v_r_bel[u, v, data[RELATION]] = graph.edge_to_bel(u, v, edge_data=data)
bel = u_v_r_bel[u, v, data[RELATION]]
evidence_dict = {
'bel_statement': bel,
}
if ANNOTATIONS in data:
evidence_dict['experiment_context'] = data[ANNOTATIONS]
if EVIDENCE in data:
evidence_dict['summary_text'] = data[EVIDENCE]
if CITATION in data:
evidence_dict['citation'] = data[CITATION]
relation_evidences[data[RELATION]].append(evidence_dict)
for relation, evidences in relation_evidences.items():
edges_entry.append({
'source': node_bel[u],
'target': node_bel[v],
'relation': relation,
'label': u_v_r_bel[u, v, relation],
'metadata': {
'evidences': evidences
}
})
return {
'graph': {
'metadata': graph.document,
'nodes': nodes_entry,
'edges': edges_entry
}
} | [
"def",
"to_jgif",
"(",
"graph",
")",
":",
"node_bel",
"=",
"{",
"}",
"u_v_r_bel",
"=",
"{",
"}",
"nodes_entry",
"=",
"[",
"]",
"edges_entry",
"=",
"[",
"]",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"sorted",
"(",
"graph",
",",
"key",
"=",
... | Build a JGIF dictionary from a BEL graph.
:param pybel.BELGraph graph: A BEL graph
:return: A JGIF dictionary
:rtype: dict
.. warning::
Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to
use Cytoscape.js, we suggest using :func:`pybel.to_cx` instead.
Example:
>>> import pybel, os, json
>>> graph_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/knowledge/selventa-small-corpus/selventa-small-corpus-20150611.bel'
>>> graph = pybel.from_url(graph_url)
>>> graph_jgif_json = pybel.to_jgif(graph)
>>> with open(os.path.expanduser('~/Desktop/small_corpus.json'), 'w') as f:
... json.dump(graph_jgif_json, f) | [
"Build",
"a",
"JGIF",
"dictionary",
"from",
"a",
"BEL",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/jgif.py#L294-L374 | train | 29,770 |
pybel/pybel | src/pybel/struct/query/selection.py | get_subgraph | def get_subgraph(graph,
seed_method: Optional[str] = None,
seed_data: Optional[Any] = None,
expand_nodes: Optional[List[BaseEntity]] = None,
remove_nodes: Optional[List[BaseEntity]] = None,
):
"""Run a pipeline query on graph with multiple sub-graph filters and expanders.
Order of Operations:
1. Seeding by given function name and data
2. Add nodes
3. Remove nodes
:param pybel.BELGraph graph: A BEL graph
:param seed_method: The name of the get_subgraph_by_* function to use
:param seed_data: The argument to pass to the get_subgraph function
:param expand_nodes: Add the neighborhoods around all of these nodes
:param remove_nodes: Remove these nodes and all of their in/out edges
:rtype: Optional[pybel.BELGraph]
"""
# Seed by the given function
if seed_method == SEED_TYPE_INDUCTION:
result = get_subgraph_by_induction(graph, seed_data)
elif seed_method == SEED_TYPE_PATHS:
result = get_subgraph_by_all_shortest_paths(graph, seed_data)
elif seed_method == SEED_TYPE_NEIGHBORS:
result = get_subgraph_by_neighborhood(graph, seed_data)
elif seed_method == SEED_TYPE_DOUBLE_NEIGHBORS:
result = get_subgraph_by_second_neighbors(graph, seed_data)
elif seed_method == SEED_TYPE_UPSTREAM:
result = get_multi_causal_upstream(graph, seed_data)
elif seed_method == SEED_TYPE_DOWNSTREAM:
result = get_multi_causal_downstream(graph, seed_data)
elif seed_method == SEED_TYPE_PUBMED:
result = get_subgraph_by_pubmed(graph, seed_data)
elif seed_method == SEED_TYPE_AUTHOR:
result = get_subgraph_by_authors(graph, seed_data)
elif seed_method == SEED_TYPE_ANNOTATION:
result = get_subgraph_by_annotations(graph, seed_data['annotations'], or_=seed_data.get('or'))
elif seed_method == SEED_TYPE_SAMPLE:
result = get_random_subgraph(
graph,
number_edges=seed_data.get('number_edges'),
seed=seed_data.get('seed')
)
elif not seed_method: # Otherwise, don't seed a sub-graph
result = graph.copy()
log.debug('no seed function - using full network: %s', result.name)
else:
raise ValueError('Invalid seed method: {}'.format(seed_method))
if result is None:
log.debug('query returned no results')
return
log.debug('original graph has (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
# Expand around the given nodes
if expand_nodes:
expand_nodes_neighborhoods(graph, result, expand_nodes)
log.debug('graph expanded to (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
# Delete the given nodes
if remove_nodes:
for node in remove_nodes:
if node not in result:
log.debug('%s is not in graph %s', node, graph.name)
continue
result.remove_node(node)
log.debug('graph contracted to (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
log.debug(
'Subgraph coming from %s (seed type) %s (data) contains %d nodes and %d edges',
seed_method,
seed_data,
result.number_of_nodes(),
result.number_of_edges()
)
return result | python | def get_subgraph(graph,
seed_method: Optional[str] = None,
seed_data: Optional[Any] = None,
expand_nodes: Optional[List[BaseEntity]] = None,
remove_nodes: Optional[List[BaseEntity]] = None,
):
"""Run a pipeline query on graph with multiple sub-graph filters and expanders.
Order of Operations:
1. Seeding by given function name and data
2. Add nodes
3. Remove nodes
:param pybel.BELGraph graph: A BEL graph
:param seed_method: The name of the get_subgraph_by_* function to use
:param seed_data: The argument to pass to the get_subgraph function
:param expand_nodes: Add the neighborhoods around all of these nodes
:param remove_nodes: Remove these nodes and all of their in/out edges
:rtype: Optional[pybel.BELGraph]
"""
# Seed by the given function
if seed_method == SEED_TYPE_INDUCTION:
result = get_subgraph_by_induction(graph, seed_data)
elif seed_method == SEED_TYPE_PATHS:
result = get_subgraph_by_all_shortest_paths(graph, seed_data)
elif seed_method == SEED_TYPE_NEIGHBORS:
result = get_subgraph_by_neighborhood(graph, seed_data)
elif seed_method == SEED_TYPE_DOUBLE_NEIGHBORS:
result = get_subgraph_by_second_neighbors(graph, seed_data)
elif seed_method == SEED_TYPE_UPSTREAM:
result = get_multi_causal_upstream(graph, seed_data)
elif seed_method == SEED_TYPE_DOWNSTREAM:
result = get_multi_causal_downstream(graph, seed_data)
elif seed_method == SEED_TYPE_PUBMED:
result = get_subgraph_by_pubmed(graph, seed_data)
elif seed_method == SEED_TYPE_AUTHOR:
result = get_subgraph_by_authors(graph, seed_data)
elif seed_method == SEED_TYPE_ANNOTATION:
result = get_subgraph_by_annotations(graph, seed_data['annotations'], or_=seed_data.get('or'))
elif seed_method == SEED_TYPE_SAMPLE:
result = get_random_subgraph(
graph,
number_edges=seed_data.get('number_edges'),
seed=seed_data.get('seed')
)
elif not seed_method: # Otherwise, don't seed a sub-graph
result = graph.copy()
log.debug('no seed function - using full network: %s', result.name)
else:
raise ValueError('Invalid seed method: {}'.format(seed_method))
if result is None:
log.debug('query returned no results')
return
log.debug('original graph has (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
# Expand around the given nodes
if expand_nodes:
expand_nodes_neighborhoods(graph, result, expand_nodes)
log.debug('graph expanded to (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
# Delete the given nodes
if remove_nodes:
for node in remove_nodes:
if node not in result:
log.debug('%s is not in graph %s', node, graph.name)
continue
result.remove_node(node)
log.debug('graph contracted to (%s nodes / %s edges)', result.number_of_nodes(), result.number_of_edges())
log.debug(
'Subgraph coming from %s (seed type) %s (data) contains %d nodes and %d edges',
seed_method,
seed_data,
result.number_of_nodes(),
result.number_of_edges()
)
return result | [
"def",
"get_subgraph",
"(",
"graph",
",",
"seed_method",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"seed_data",
":",
"Optional",
"[",
"Any",
"]",
"=",
"None",
",",
"expand_nodes",
":",
"Optional",
"[",
"List",
"[",
"BaseEntity",
"]",
"]",
"="... | Run a pipeline query on graph with multiple sub-graph filters and expanders.
Order of Operations:
1. Seeding by given function name and data
2. Add nodes
3. Remove nodes
:param pybel.BELGraph graph: A BEL graph
:param seed_method: The name of the get_subgraph_by_* function to use
:param seed_data: The argument to pass to the get_subgraph function
:param expand_nodes: Add the neighborhoods around all of these nodes
:param remove_nodes: Remove these nodes and all of their in/out edges
:rtype: Optional[pybel.BELGraph] | [
"Run",
"a",
"pipeline",
"query",
"on",
"graph",
"with",
"multiple",
"sub",
"-",
"graph",
"filters",
"and",
"expanders",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/selection.py#L26-L117 | train | 29,771 |
pybel/pybel | src/pybel/struct/mutation/induction/paths.py | _remove_pathologies_oop | def _remove_pathologies_oop(graph):
"""Remove pathology nodes from the graph."""
rv = graph.copy()
victims = [
node
for node in rv
if node[FUNCTION] == PATHOLOGY
]
rv.remove_nodes_from(victims)
return rv | python | def _remove_pathologies_oop(graph):
"""Remove pathology nodes from the graph."""
rv = graph.copy()
victims = [
node
for node in rv
if node[FUNCTION] == PATHOLOGY
]
rv.remove_nodes_from(victims)
return rv | [
"def",
"_remove_pathologies_oop",
"(",
"graph",
")",
":",
"rv",
"=",
"graph",
".",
"copy",
"(",
")",
"victims",
"=",
"[",
"node",
"for",
"node",
"in",
"rv",
"if",
"node",
"[",
"FUNCTION",
"]",
"==",
"PATHOLOGY",
"]",
"rv",
".",
"remove_nodes_from",
"("... | Remove pathology nodes from the graph. | [
"Remove",
"pathology",
"nodes",
"from",
"the",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/paths.py#L26-L35 | train | 29,772 |
pybel/pybel | src/pybel/struct/mutation/induction/paths.py | get_random_path | def get_random_path(graph) -> List[BaseEntity]:
"""Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph
"""
wg = graph.to_undirected()
nodes = wg.nodes()
def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
"""Get a pair of random nodes."""
return random.sample(nodes, k=2)
source, target = pick_random_pair()
tries = 0
sentinel_tries = 5
while not nx.has_path(wg, source, target) and tries < sentinel_tries:
tries += 1
source, target = pick_random_pair()
if tries == sentinel_tries:
return [source]
return nx.shortest_path(wg, source=source, target=target) | python | def get_random_path(graph) -> List[BaseEntity]:
"""Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph
"""
wg = graph.to_undirected()
nodes = wg.nodes()
def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
"""Get a pair of random nodes."""
return random.sample(nodes, k=2)
source, target = pick_random_pair()
tries = 0
sentinel_tries = 5
while not nx.has_path(wg, source, target) and tries < sentinel_tries:
tries += 1
source, target = pick_random_pair()
if tries == sentinel_tries:
return [source]
return nx.shortest_path(wg, source=source, target=target) | [
"def",
"get_random_path",
"(",
"graph",
")",
"->",
"List",
"[",
"BaseEntity",
"]",
":",
"wg",
"=",
"graph",
".",
"to_undirected",
"(",
")",
"nodes",
"=",
"wg",
".",
"nodes",
"(",
")",
"def",
"pick_random_pair",
"(",
")",
"->",
"Tuple",
"[",
"BaseEntity... | Get a random path from the graph as a list of nodes.
:param pybel.BELGraph graph: A BEL graph | [
"Get",
"a",
"random",
"path",
"from",
"the",
"graph",
"as",
"a",
"list",
"of",
"nodes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/paths.py#L114-L139 | train | 29,773 |
pybel/pybel | src/pybel/io/gpickle.py | to_bytes | def to_bytes(graph: BELGraph, protocol: int = HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protocol: Pickling protocol to use. Defaults to ``HIGHEST_PROTOCOL``.
.. seealso:: https://docs.python.org/3.6/library/pickle.html#data-stream-format
"""
raise_for_not_bel(graph)
return dumps(graph, protocol=protocol) | python | def to_bytes(graph: BELGraph, protocol: int = HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protocol: Pickling protocol to use. Defaults to ``HIGHEST_PROTOCOL``.
.. seealso:: https://docs.python.org/3.6/library/pickle.html#data-stream-format
"""
raise_for_not_bel(graph)
return dumps(graph, protocol=protocol) | [
"def",
"to_bytes",
"(",
"graph",
":",
"BELGraph",
",",
"protocol",
":",
"int",
"=",
"HIGHEST_PROTOCOL",
")",
"->",
"bytes",
":",
"raise_for_not_bel",
"(",
"graph",
")",
"return",
"dumps",
"(",
"graph",
",",
"protocol",
"=",
"protocol",
")"
] | Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protocol: Pickling protocol to use. Defaults to ``HIGHEST_PROTOCOL``.
.. seealso:: https://docs.python.org/3.6/library/pickle.html#data-stream-format | [
"Convert",
"a",
"graph",
"to",
"bytes",
"with",
"pickle",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/gpickle.py#L21-L33 | train | 29,774 |
pybel/pybel | src/pybel/io/gpickle.py | from_pickle | def from_pickle(path: Union[str, BinaryIO], check_version: bool = True) -> BELGraph:
"""Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL
"""
graph = nx.read_gpickle(path)
raise_for_not_bel(graph)
if check_version:
raise_for_old_graph(graph)
return graph | python | def from_pickle(path: Union[str, BinaryIO], check_version: bool = True) -> BELGraph:
"""Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL
"""
graph = nx.read_gpickle(path)
raise_for_not_bel(graph)
if check_version:
raise_for_old_graph(graph)
return graph | [
"def",
"from_pickle",
"(",
"path",
":",
"Union",
"[",
"str",
",",
"BinaryIO",
"]",
",",
"check_version",
":",
"bool",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph",
"=",
"nx",
".",
"read_gpickle",
"(",
"path",
")",
"raise_for_not_bel",
"(",
"graph",
... | Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL | [
"Read",
"a",
"graph",
"from",
"a",
"pickle",
"file",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/gpickle.py#L67-L79 | train | 29,775 |
pybel/pybel | src/pybel/struct/filters/edge_predicate_builders.py | build_annotation_dict_all_filter | def build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:
"""Build an edge predicate for edges whose annotations are super-dictionaries of the given dictionary.
If no annotations are given, will always evaluate to true.
:param annotations: The annotation query dict to match
"""
if not annotations:
return keep_edge_permissive
@edge_predicate
def annotation_dict_all_filter(edge_data: EdgeData) -> bool:
"""Check if the all of the annotations in the enclosed query match."""
return _annotation_dict_all_filter(edge_data, query=annotations)
return annotation_dict_all_filter | python | def build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:
"""Build an edge predicate for edges whose annotations are super-dictionaries of the given dictionary.
If no annotations are given, will always evaluate to true.
:param annotations: The annotation query dict to match
"""
if not annotations:
return keep_edge_permissive
@edge_predicate
def annotation_dict_all_filter(edge_data: EdgeData) -> bool:
"""Check if the all of the annotations in the enclosed query match."""
return _annotation_dict_all_filter(edge_data, query=annotations)
return annotation_dict_all_filter | [
"def",
"build_annotation_dict_all_filter",
"(",
"annotations",
":",
"Mapping",
"[",
"str",
",",
"Iterable",
"[",
"str",
"]",
"]",
")",
"->",
"EdgePredicate",
":",
"if",
"not",
"annotations",
":",
"return",
"keep_edge_permissive",
"@",
"edge_predicate",
"def",
"a... | Build an edge predicate for edges whose annotations are super-dictionaries of the given dictionary.
If no annotations are given, will always evaluate to true.
:param annotations: The annotation query dict to match | [
"Build",
"an",
"edge",
"predicate",
"for",
"edges",
"whose",
"annotations",
"are",
"super",
"-",
"dictionaries",
"of",
"the",
"given",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicate_builders.py#L48-L63 | train | 29,776 |
pybel/pybel | src/pybel/struct/filters/edge_predicate_builders.py | build_annotation_dict_any_filter | def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:
"""Build an edge predicate that passes for edges whose data dictionaries match the given dictionary.
If the given dictionary is empty, will always evaluate to true.
:param annotations: The annotation query dict to match
"""
if not annotations:
return keep_edge_permissive
@edge_predicate
def annotation_dict_any_filter(edge_data: EdgeData) -> bool:
"""Check if the any of the annotations in the enclosed query match."""
return _annotation_dict_any_filter(edge_data, query=annotations)
return annotation_dict_any_filter | python | def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:
"""Build an edge predicate that passes for edges whose data dictionaries match the given dictionary.
If the given dictionary is empty, will always evaluate to true.
:param annotations: The annotation query dict to match
"""
if not annotations:
return keep_edge_permissive
@edge_predicate
def annotation_dict_any_filter(edge_data: EdgeData) -> bool:
"""Check if the any of the annotations in the enclosed query match."""
return _annotation_dict_any_filter(edge_data, query=annotations)
return annotation_dict_any_filter | [
"def",
"build_annotation_dict_any_filter",
"(",
"annotations",
":",
"Mapping",
"[",
"str",
",",
"Iterable",
"[",
"str",
"]",
"]",
")",
"->",
"EdgePredicate",
":",
"if",
"not",
"annotations",
":",
"return",
"keep_edge_permissive",
"@",
"edge_predicate",
"def",
"a... | Build an edge predicate that passes for edges whose data dictionaries match the given dictionary.
If the given dictionary is empty, will always evaluate to true.
:param annotations: The annotation query dict to match | [
"Build",
"an",
"edge",
"predicate",
"that",
"passes",
"for",
"edges",
"whose",
"data",
"dictionaries",
"match",
"the",
"given",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicate_builders.py#L83-L98 | train | 29,777 |
pybel/pybel | src/pybel/struct/filters/edge_predicate_builders.py | build_upstream_edge_predicate | def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
"""Build an edge predicate that pass for relations for which one of the given nodes is the object."""
nodes = set(nodes)
def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
"""Pass for relations for which one of the given nodes is the object."""
return v in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS
return upstream_filter | python | def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
"""Build an edge predicate that pass for relations for which one of the given nodes is the object."""
nodes = set(nodes)
def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
"""Pass for relations for which one of the given nodes is the object."""
return v in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS
return upstream_filter | [
"def",
"build_upstream_edge_predicate",
"(",
"nodes",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
"->",
"EdgePredicate",
":",
"nodes",
"=",
"set",
"(",
"nodes",
")",
"def",
"upstream_filter",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",... | Build an edge predicate that pass for relations for which one of the given nodes is the object. | [
"Build",
"an",
"edge",
"predicate",
"that",
"pass",
"for",
"relations",
"for",
"which",
"one",
"of",
"the",
"given",
"nodes",
"is",
"the",
"object",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicate_builders.py#L101-L109 | train | 29,778 |
pybel/pybel | src/pybel/struct/filters/edge_predicate_builders.py | build_downstream_edge_predicate | def build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
"""Build an edge predicate that passes for edges for which one of the given nodes is the subject."""
nodes = set(nodes)
def downstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
"""Pass for relations for which one of the given nodes is the subject."""
return u in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS
return downstream_filter | python | def build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
"""Build an edge predicate that passes for edges for which one of the given nodes is the subject."""
nodes = set(nodes)
def downstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
"""Pass for relations for which one of the given nodes is the subject."""
return u in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS
return downstream_filter | [
"def",
"build_downstream_edge_predicate",
"(",
"nodes",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
"->",
"EdgePredicate",
":",
"nodes",
"=",
"set",
"(",
"nodes",
")",
"def",
"downstream_filter",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
... | Build an edge predicate that passes for edges for which one of the given nodes is the subject. | [
"Build",
"an",
"edge",
"predicate",
"that",
"passes",
"for",
"edges",
"for",
"which",
"one",
"of",
"the",
"given",
"nodes",
"is",
"the",
"subject",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicate_builders.py#L112-L120 | train | 29,779 |
pybel/pybel | src/pybel/struct/filters/edge_predicate_builders.py | build_relation_predicate | def build_relation_predicate(relations: Strings) -> EdgePredicate:
"""Build an edge predicate that passes for edges with the given relation."""
if isinstance(relations, str):
@edge_predicate
def relation_predicate(edge_data: EdgeData) -> bool:
"""Pass for relations matching the enclosed value."""
return edge_data[RELATION] == relations
elif isinstance(relations, Iterable):
relation_set = set(relations)
@edge_predicate
def relation_predicate(edge_data: EdgeData) -> bool:
"""Pass for relations matching the enclosed values."""
return edge_data[RELATION] in relation_set
else:
raise TypeError
return relation_predicate | python | def build_relation_predicate(relations: Strings) -> EdgePredicate:
"""Build an edge predicate that passes for edges with the given relation."""
if isinstance(relations, str):
@edge_predicate
def relation_predicate(edge_data: EdgeData) -> bool:
"""Pass for relations matching the enclosed value."""
return edge_data[RELATION] == relations
elif isinstance(relations, Iterable):
relation_set = set(relations)
@edge_predicate
def relation_predicate(edge_data: EdgeData) -> bool:
"""Pass for relations matching the enclosed values."""
return edge_data[RELATION] in relation_set
else:
raise TypeError
return relation_predicate | [
"def",
"build_relation_predicate",
"(",
"relations",
":",
"Strings",
")",
"->",
"EdgePredicate",
":",
"if",
"isinstance",
"(",
"relations",
",",
"str",
")",
":",
"@",
"edge_predicate",
"def",
"relation_predicate",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
... | Build an edge predicate that passes for edges with the given relation. | [
"Build",
"an",
"edge",
"predicate",
"that",
"passes",
"for",
"edges",
"with",
"the",
"given",
"relation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicate_builders.py#L123-L142 | train | 29,780 |
pybel/pybel | src/pybel/struct/pipeline/decorators.py | _register_function | def _register_function(name: str, func, universe: bool, in_place: bool):
"""Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with additional properties added
"""
if name in mapped:
mapped_func = mapped[name]
raise PipelineNameError('{name} is already registered with {func_mod}.{func_name}'.format(
name=name,
func_mod=mapped_func.__module__,
func_name=mapped_func.__name__
))
mapped[name] = func
if universe:
universe_map[name] = func
if in_place:
in_place_map[name] = func
if _has_arguments(func, universe):
has_arguments_map[name] = func
else:
no_arguments_map[name] = func
return func | python | def _register_function(name: str, func, universe: bool, in_place: bool):
"""Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with additional properties added
"""
if name in mapped:
mapped_func = mapped[name]
raise PipelineNameError('{name} is already registered with {func_mod}.{func_name}'.format(
name=name,
func_mod=mapped_func.__module__,
func_name=mapped_func.__name__
))
mapped[name] = func
if universe:
universe_map[name] = func
if in_place:
in_place_map[name] = func
if _has_arguments(func, universe):
has_arguments_map[name] = func
else:
no_arguments_map[name] = func
return func | [
"def",
"_register_function",
"(",
"name",
":",
"str",
",",
"func",
",",
"universe",
":",
"bool",
",",
"in_place",
":",
"bool",
")",
":",
"if",
"name",
"in",
"mapped",
":",
"mapped_func",
"=",
"mapped",
"[",
"name",
"]",
"raise",
"PipelineNameError",
"(",... | Register a transformation function under the given name.
:param name: Name to register the function under
:param func: A function
:param universe:
:param in_place:
:return: The same function, with additional properties added | [
"Register",
"a",
"transformation",
"function",
"under",
"the",
"given",
"name",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/decorators.py#L44-L74 | train | 29,781 |
pybel/pybel | src/pybel/struct/pipeline/decorators.py | _build_register_function | def _build_register_function(universe: bool, in_place: bool): # noqa: D202
"""Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-place?
"""
def register(func):
"""Tag a transformation function.
:param func: A function
:return: The same function, with additional properties added
"""
return _register_function(func.__name__, func, universe, in_place)
return register | python | def _build_register_function(universe: bool, in_place: bool): # noqa: D202
"""Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-place?
"""
def register(func):
"""Tag a transformation function.
:param func: A function
:return: The same function, with additional properties added
"""
return _register_function(func.__name__, func, universe, in_place)
return register | [
"def",
"_build_register_function",
"(",
"universe",
":",
"bool",
",",
"in_place",
":",
"bool",
")",
":",
"# noqa: D202",
"def",
"register",
"(",
"func",
")",
":",
"\"\"\"Tag a transformation function.\n\n :param func: A function\n :return: The same function, with ... | Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-place? | [
"Build",
"a",
"decorator",
"function",
"to",
"tag",
"transformation",
"functions",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/decorators.py#L77-L92 | train | 29,782 |
pybel/pybel | src/pybel/struct/pipeline/decorators.py | register_deprecated | def register_deprecated(deprecated_name: str):
"""Register a function as deprecated.
:param deprecated_name: The old name of the function
:return: A decorator
Usage:
This function must be applied last, since it introspects on the definitions from before
>>> @register_deprecated('my_function')
>>> @transformation
>>> def my_old_function()
>>> ... pass
"""
if deprecated_name in mapped:
raise DeprecationMappingError('function name already mapped. can not register as deprecated name.')
def register_deprecated_f(func):
name = func.__name__
log.debug('%s is deprecated. please migrate to %s', deprecated_name, name)
if name not in mapped:
raise MissingPipelineFunctionError('function not mapped with transformation, uni_transformation, etc.')
universe = name in universe_map
in_place = name in in_place_map
# Add back-reference from deprecated function name to actual function name
deprecated[deprecated_name] = name
return _register_function(deprecated_name, func, universe, in_place)
return register_deprecated_f | python | def register_deprecated(deprecated_name: str):
"""Register a function as deprecated.
:param deprecated_name: The old name of the function
:return: A decorator
Usage:
This function must be applied last, since it introspects on the definitions from before
>>> @register_deprecated('my_function')
>>> @transformation
>>> def my_old_function()
>>> ... pass
"""
if deprecated_name in mapped:
raise DeprecationMappingError('function name already mapped. can not register as deprecated name.')
def register_deprecated_f(func):
name = func.__name__
log.debug('%s is deprecated. please migrate to %s', deprecated_name, name)
if name not in mapped:
raise MissingPipelineFunctionError('function not mapped with transformation, uni_transformation, etc.')
universe = name in universe_map
in_place = name in in_place_map
# Add back-reference from deprecated function name to actual function name
deprecated[deprecated_name] = name
return _register_function(deprecated_name, func, universe, in_place)
return register_deprecated_f | [
"def",
"register_deprecated",
"(",
"deprecated_name",
":",
"str",
")",
":",
"if",
"deprecated_name",
"in",
"mapped",
":",
"raise",
"DeprecationMappingError",
"(",
"'function name already mapped. can not register as deprecated name.'",
")",
"def",
"register_deprecated_f",
"(",... | Register a function as deprecated.
:param deprecated_name: The old name of the function
:return: A decorator
Usage:
This function must be applied last, since it introspects on the definitions from before
>>> @register_deprecated('my_function')
>>> @transformation
>>> def my_old_function()
>>> ... pass | [
"Register",
"a",
"function",
"as",
"deprecated",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/decorators.py#L105-L139 | train | 29,783 |
pybel/pybel | src/pybel/struct/pipeline/decorators.py | get_transformation | def get_transformation(name: str):
"""Get a transformation function and error if its name is not registered.
:param name: The name of a function to look up
:return: A transformation function
:raises MissingPipelineFunctionError: If the given function name is not registered
"""
func = mapped.get(name)
if func is None:
raise MissingPipelineFunctionError('{} is not registered as a pipeline function'.format(name))
return func | python | def get_transformation(name: str):
"""Get a transformation function and error if its name is not registered.
:param name: The name of a function to look up
:return: A transformation function
:raises MissingPipelineFunctionError: If the given function name is not registered
"""
func = mapped.get(name)
if func is None:
raise MissingPipelineFunctionError('{} is not registered as a pipeline function'.format(name))
return func | [
"def",
"get_transformation",
"(",
"name",
":",
"str",
")",
":",
"func",
"=",
"mapped",
".",
"get",
"(",
"name",
")",
"if",
"func",
"is",
"None",
":",
"raise",
"MissingPipelineFunctionError",
"(",
"'{} is not registered as a pipeline function'",
".",
"format",
"(... | Get a transformation function and error if its name is not registered.
:param name: The name of a function to look up
:return: A transformation function
:raises MissingPipelineFunctionError: If the given function name is not registered | [
"Get",
"a",
"transformation",
"function",
"and",
"error",
"if",
"its",
"name",
"is",
"not",
"registered",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/pipeline/decorators.py#L142-L154 | train | 29,784 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | _random_edge_iterator | def _random_edge_iterator(graph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]:
"""Get a random set of edges from the graph and randomly samples a key from each.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph
"""
edges = list(graph.edges())
edge_sample = random.sample(edges, n_edges)
for u, v in edge_sample:
keys = list(graph[u][v])
k = random.choice(keys)
yield u, v, k, graph[u][v][k] | python | def _random_edge_iterator(graph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]:
"""Get a random set of edges from the graph and randomly samples a key from each.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph
"""
edges = list(graph.edges())
edge_sample = random.sample(edges, n_edges)
for u, v in edge_sample:
keys = list(graph[u][v])
k = random.choice(keys)
yield u, v, k, graph[u][v][k] | [
"def",
"_random_edge_iterator",
"(",
"graph",
",",
"n_edges",
":",
"int",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"BaseEntity",
",",
"BaseEntity",
",",
"int",
",",
"Mapping",
"]",
"]",
":",
"edges",
"=",
"list",
"(",
"graph",
".",
"edges",
"(",
")",
... | Get a random set of edges from the graph and randomly samples a key from each.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph | [
"Get",
"a",
"random",
"set",
"of",
"edges",
"from",
"the",
"graph",
"and",
"randomly",
"samples",
"a",
"key",
"from",
"each",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L25-L36 | train | 29,785 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | get_graph_with_random_edges | def get_graph_with_random_edges(graph, n_edges: int):
"""Build a new graph from a seeding of edges.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph
:rtype: pybel.BELGraph
"""
result = graph.fresh_copy()
result.add_edges_from(_random_edge_iterator(graph, n_edges))
update_metadata(graph, result)
update_node_helper(graph, result)
return result | python | def get_graph_with_random_edges(graph, n_edges: int):
"""Build a new graph from a seeding of edges.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph
:rtype: pybel.BELGraph
"""
result = graph.fresh_copy()
result.add_edges_from(_random_edge_iterator(graph, n_edges))
update_metadata(graph, result)
update_node_helper(graph, result)
return result | [
"def",
"get_graph_with_random_edges",
"(",
"graph",
",",
"n_edges",
":",
"int",
")",
":",
"result",
"=",
"graph",
".",
"fresh_copy",
"(",
")",
"result",
".",
"add_edges_from",
"(",
"_random_edge_iterator",
"(",
"graph",
",",
"n_edges",
")",
")",
"update_metada... | Build a new graph from a seeding of edges.
:type graph: pybel.BELGraph
:param n_edges: Number of edges to randomly select from the given graph
:rtype: pybel.BELGraph | [
"Build",
"a",
"new",
"graph",
"from",
"a",
"seeding",
"of",
"edges",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L40-L52 | train | 29,786 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | get_random_node | def get_random_node(graph,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
) -> Optional[BaseEntity]:
"""Choose a node from the graph with probabilities based on their degrees.
:type graph: networkx.Graph
:param node_blacklist: Nodes to filter out
:param invert_degrees: Should the degrees be inverted? Defaults to true.
"""
try:
nodes, degrees = zip(*(
(node, degree)
for node, degree in sorted(graph.degree(), key=itemgetter(1))
if node not in node_blacklist
))
except ValueError: # something wrong with graph, probably no elements in graph.degree_iter
return
if invert_degrees is None or invert_degrees:
# More likely to choose low degree nodes to explore, so don't make hubs
degrees = [1 / degree for degree in degrees]
wrg = WeightedRandomGenerator(nodes, degrees)
return wrg.next() | python | def get_random_node(graph,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
) -> Optional[BaseEntity]:
"""Choose a node from the graph with probabilities based on their degrees.
:type graph: networkx.Graph
:param node_blacklist: Nodes to filter out
:param invert_degrees: Should the degrees be inverted? Defaults to true.
"""
try:
nodes, degrees = zip(*(
(node, degree)
for node, degree in sorted(graph.degree(), key=itemgetter(1))
if node not in node_blacklist
))
except ValueError: # something wrong with graph, probably no elements in graph.degree_iter
return
if invert_degrees is None or invert_degrees:
# More likely to choose low degree nodes to explore, so don't make hubs
degrees = [1 / degree for degree in degrees]
wrg = WeightedRandomGenerator(nodes, degrees)
return wrg.next() | [
"def",
"get_random_node",
"(",
"graph",
",",
"node_blacklist",
":",
"Set",
"[",
"BaseEntity",
"]",
",",
"invert_degrees",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
")",
"->",
"Optional",
"[",
"BaseEntity",
"]",
":",
"try",
":",
"nodes",
",",
... | Choose a node from the graph with probabilities based on their degrees.
:type graph: networkx.Graph
:param node_blacklist: Nodes to filter out
:param invert_degrees: Should the degrees be inverted? Defaults to true. | [
"Choose",
"a",
"node",
"from",
"the",
"graph",
"with",
"probabilities",
"based",
"on",
"their",
"degrees",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L95-L119 | train | 29,787 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | _helper | def _helper(result,
graph,
number_edges_remaining: int,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
):
"""Help build a random graph.
:type result: networkx.Graph
:type graph: networkx.Graph
"""
original_node_count = graph.number_of_nodes()
log.debug('adding remaining %d edges', number_edges_remaining)
for _ in range(number_edges_remaining):
source, possible_step_nodes, c = None, set(), 0
while not source or not possible_step_nodes:
source = get_random_node(result, node_blacklist, invert_degrees=invert_degrees)
c += 1
if c >= original_node_count:
log.warning('infinite loop happening')
log.warning('source: %s', source)
log.warning('no grow: %s', node_blacklist)
return # Happens when after exhausting the connected components. Try increasing the number seed edges
if source is None:
continue # maybe do something else?
# Only keep targets in the original graph that aren't in the result graph
possible_step_nodes = set(graph[source]) - set(result[source])
if not possible_step_nodes:
node_blacklist.add(
source) # there aren't any possible nodes to step to, so try growing from somewhere else
step_node = random.choice(list(possible_step_nodes))
# it's not really a big deal which, but it might be possible to weight this by the utility of edges later
key, attr_dict = random.choice(list(graph[source][step_node].items()))
result.add_edge(source, step_node, key=key, **attr_dict) | python | def _helper(result,
graph,
number_edges_remaining: int,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
):
"""Help build a random graph.
:type result: networkx.Graph
:type graph: networkx.Graph
"""
original_node_count = graph.number_of_nodes()
log.debug('adding remaining %d edges', number_edges_remaining)
for _ in range(number_edges_remaining):
source, possible_step_nodes, c = None, set(), 0
while not source or not possible_step_nodes:
source = get_random_node(result, node_blacklist, invert_degrees=invert_degrees)
c += 1
if c >= original_node_count:
log.warning('infinite loop happening')
log.warning('source: %s', source)
log.warning('no grow: %s', node_blacklist)
return # Happens when after exhausting the connected components. Try increasing the number seed edges
if source is None:
continue # maybe do something else?
# Only keep targets in the original graph that aren't in the result graph
possible_step_nodes = set(graph[source]) - set(result[source])
if not possible_step_nodes:
node_blacklist.add(
source) # there aren't any possible nodes to step to, so try growing from somewhere else
step_node = random.choice(list(possible_step_nodes))
# it's not really a big deal which, but it might be possible to weight this by the utility of edges later
key, attr_dict = random.choice(list(graph[source][step_node].items()))
result.add_edge(source, step_node, key=key, **attr_dict) | [
"def",
"_helper",
"(",
"result",
",",
"graph",
",",
"number_edges_remaining",
":",
"int",
",",
"node_blacklist",
":",
"Set",
"[",
"BaseEntity",
"]",
",",
"invert_degrees",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
")",
":",
"original_node_count",
... | Help build a random graph.
:type result: networkx.Graph
:type graph: networkx.Graph | [
"Help",
"build",
"a",
"random",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L122-L164 | train | 29,788 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | get_random_subgraph | def get_random_subgraph(graph, number_edges=None, number_seed_edges=None, seed=None, invert_degrees=None):
"""Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250).
:param Optional[int] number_seed_edges: Number of nodes to start with (which likely results in different components
in large graphs). Defaults to :data:`SAMPLE_RANDOM_EDGE_SEED_COUNT` (5).
:param Optional[int] seed: A seed for the random state
:param Optional[bool] invert_degrees: Should the degrees be inverted? Defaults to true.
:rtype: pybel.BELGraph
"""
if number_edges is None:
number_edges = SAMPLE_RANDOM_EDGE_COUNT
if number_seed_edges is None:
number_seed_edges = SAMPLE_RANDOM_EDGE_SEED_COUNT
if seed is not None:
random.seed(seed)
# Check if graph will sample full graph, and just return it if it would
if graph.number_of_edges() <= number_edges:
log.info('sampled full graph')
return graph.copy()
log.debug('getting random sub-graph with %d seed edges, %d final edges, and seed=%s', number_seed_edges,
number_edges, seed)
# Get initial graph with `number_seed_edges` edges
result = get_graph_with_random_edges(graph, number_seed_edges)
number_edges_remaining = number_edges - result.number_of_edges()
_helper(
result,
graph,
number_edges_remaining,
node_blacklist=set(), # This is the set of nodes that should no longer be chosen to grow from
invert_degrees=invert_degrees,
)
log.debug('removing isolated nodes')
remove_isolated_nodes(result)
# update metadata
update_node_helper(graph, result)
update_metadata(graph, result)
return result | python | def get_random_subgraph(graph, number_edges=None, number_seed_edges=None, seed=None, invert_degrees=None):
"""Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250).
:param Optional[int] number_seed_edges: Number of nodes to start with (which likely results in different components
in large graphs). Defaults to :data:`SAMPLE_RANDOM_EDGE_SEED_COUNT` (5).
:param Optional[int] seed: A seed for the random state
:param Optional[bool] invert_degrees: Should the degrees be inverted? Defaults to true.
:rtype: pybel.BELGraph
"""
if number_edges is None:
number_edges = SAMPLE_RANDOM_EDGE_COUNT
if number_seed_edges is None:
number_seed_edges = SAMPLE_RANDOM_EDGE_SEED_COUNT
if seed is not None:
random.seed(seed)
# Check if graph will sample full graph, and just return it if it would
if graph.number_of_edges() <= number_edges:
log.info('sampled full graph')
return graph.copy()
log.debug('getting random sub-graph with %d seed edges, %d final edges, and seed=%s', number_seed_edges,
number_edges, seed)
# Get initial graph with `number_seed_edges` edges
result = get_graph_with_random_edges(graph, number_seed_edges)
number_edges_remaining = number_edges - result.number_of_edges()
_helper(
result,
graph,
number_edges_remaining,
node_blacklist=set(), # This is the set of nodes that should no longer be chosen to grow from
invert_degrees=invert_degrees,
)
log.debug('removing isolated nodes')
remove_isolated_nodes(result)
# update metadata
update_node_helper(graph, result)
update_metadata(graph, result)
return result | [
"def",
"get_random_subgraph",
"(",
"graph",
",",
"number_edges",
"=",
"None",
",",
"number_seed_edges",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"invert_degrees",
"=",
"None",
")",
":",
"if",
"number_edges",
"is",
"None",
":",
"number_edges",
"=",
"SAMPLE... | Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250).
:param Optional[int] number_seed_edges: Number of nodes to start with (which likely results in different components
in large graphs). Defaults to :data:`SAMPLE_RANDOM_EDGE_SEED_COUNT` (5).
:param Optional[int] seed: A seed for the random state
:param Optional[bool] invert_degrees: Should the degrees be inverted? Defaults to true.
:rtype: pybel.BELGraph | [
"Generate",
"a",
"random",
"subgraph",
"based",
"on",
"weighted",
"random",
"walks",
"from",
"random",
"seed",
"edges",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L168-L216 | train | 29,789 |
pybel/pybel | src/pybel/struct/mutation/induction/random_subgraph.py | WeightedRandomGenerator.next_index | def next_index(self) -> int:
"""Get a random index."""
return bisect.bisect_right(self.totals, random.random() * self.total) | python | def next_index(self) -> int:
"""Get a random index."""
return bisect.bisect_right(self.totals, random.random() * self.total) | [
"def",
"next_index",
"(",
"self",
")",
"->",
"int",
":",
"return",
"bisect",
".",
"bisect_right",
"(",
"self",
".",
"totals",
",",
"random",
".",
"random",
"(",
")",
"*",
"self",
".",
"total",
")"
] | Get a random index. | [
"Get",
"a",
"random",
"index",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/random_subgraph.py#L86-L88 | train | 29,790 |
pybel/pybel | src/pybel/manager/models.py | Author.from_name | def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) | python | def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"return",
"Author",
"(",
"name",
"=",
"name",
",",
"sha512",
"=",
"cls",
".",
"hash_name",
"(",
"name",
")",
")"
] | Create an author by name, automatically populating the hash. | [
"Create",
"an",
"author",
"by",
"name",
"automatically",
"populating",
"the",
"hash",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/models.py#L503-L505 | train | 29,791 |
pybel/pybel | src/pybel/manager/models.py | Author.has_name_in | def has_name_in(cls, names):
"""Build a filter if the author has any of the given names."""
return cls.sha512.in_({
cls.hash_name(name)
for name in names
}) | python | def has_name_in(cls, names):
"""Build a filter if the author has any of the given names."""
return cls.sha512.in_({
cls.hash_name(name)
for name in names
}) | [
"def",
"has_name_in",
"(",
"cls",
",",
"names",
")",
":",
"return",
"cls",
".",
"sha512",
".",
"in_",
"(",
"{",
"cls",
".",
"hash_name",
"(",
"name",
")",
"for",
"name",
"in",
"names",
"}",
")"
] | Build a filter if the author has any of the given names. | [
"Build",
"a",
"filter",
"if",
"the",
"author",
"has",
"any",
"of",
"the",
"given",
"names",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/models.py#L533-L538 | train | 29,792 |
pybel/pybel | src/pybel/io/utils.py | raise_for_old_graph | def raise_for_old_graph(graph):
"""Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL.
:raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL
"""
graph_version = tokenize_version(graph.pybel_version)
if graph_version < PYBEL_MINIMUM_IMPORT_VERSION:
raise ImportVersionWarning(graph_version, PYBEL_MINIMUM_IMPORT_VERSION) | python | def raise_for_old_graph(graph):
"""Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL.
:raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL
"""
graph_version = tokenize_version(graph.pybel_version)
if graph_version < PYBEL_MINIMUM_IMPORT_VERSION:
raise ImportVersionWarning(graph_version, PYBEL_MINIMUM_IMPORT_VERSION) | [
"def",
"raise_for_old_graph",
"(",
"graph",
")",
":",
"graph_version",
"=",
"tokenize_version",
"(",
"graph",
".",
"pybel_version",
")",
"if",
"graph_version",
"<",
"PYBEL_MINIMUM_IMPORT_VERSION",
":",
"raise",
"ImportVersionWarning",
"(",
"graph_version",
",",
"PYBEL... | Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL.
:raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL | [
"Raise",
"an",
"ImportVersionWarning",
"if",
"the",
"BEL",
"graph",
"was",
"produced",
"by",
"a",
"legacy",
"version",
"of",
"PyBEL",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/utils.py#L11-L18 | train | 29,793 |
pybel/pybel | src/pybel/parser/utils.py | nest | def nest(*content):
"""Define a delimited list by enumerating each element of the list."""
if len(content) == 0:
raise ValueError('no arguments supplied')
return And([LPF, content[0]] + list(itt.chain.from_iterable(zip(itt.repeat(C), content[1:]))) + [RPF]) | python | def nest(*content):
"""Define a delimited list by enumerating each element of the list."""
if len(content) == 0:
raise ValueError('no arguments supplied')
return And([LPF, content[0]] + list(itt.chain.from_iterable(zip(itt.repeat(C), content[1:]))) + [RPF]) | [
"def",
"nest",
"(",
"*",
"content",
")",
":",
"if",
"len",
"(",
"content",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'no arguments supplied'",
")",
"return",
"And",
"(",
"[",
"LPF",
",",
"content",
"[",
"0",
"]",
"]",
"+",
"list",
"(",
"itt... | Define a delimited list by enumerating each element of the list. | [
"Define",
"a",
"delimited",
"list",
"by",
"enumerating",
"each",
"element",
"of",
"the",
"list",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/utils.py#L50-L54 | train | 29,794 |
pybel/pybel | src/pybel/parser/utils.py | triple | def triple(subject, relation, obj):
"""Build a simple triple in PyParsing that has a ``subject relation object`` format."""
return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)]) | python | def triple(subject, relation, obj):
"""Build a simple triple in PyParsing that has a ``subject relation object`` format."""
return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)]) | [
"def",
"triple",
"(",
"subject",
",",
"relation",
",",
"obj",
")",
":",
"return",
"And",
"(",
"[",
"Group",
"(",
"subject",
")",
"(",
"SUBJECT",
")",
",",
"relation",
"(",
"RELATION",
")",
",",
"Group",
"(",
"obj",
")",
"(",
"OBJECT",
")",
"]",
"... | Build a simple triple in PyParsing that has a ``subject relation object`` format. | [
"Build",
"a",
"simple",
"triple",
"in",
"PyParsing",
"that",
"has",
"a",
"subject",
"relation",
"object",
"format",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/utils.py#L78-L80 | train | 29,795 |
pybel/pybel | src/pybel/parser/modifiers/truncation.py | get_truncation_language | def get_truncation_language() -> ParserElement:
"""Build a parser for protein truncations."""
l1 = truncation_tag + nest(amino_acid(AMINO_ACID) + ppc.integer(TRUNCATION_POSITION))
l1.setParseAction(_handle_trunc)
l2 = truncation_tag + nest(ppc.integer(TRUNCATION_POSITION))
l2.setParseAction(_handle_trunc_legacy)
return l1 | l2 | python | def get_truncation_language() -> ParserElement:
"""Build a parser for protein truncations."""
l1 = truncation_tag + nest(amino_acid(AMINO_ACID) + ppc.integer(TRUNCATION_POSITION))
l1.setParseAction(_handle_trunc)
l2 = truncation_tag + nest(ppc.integer(TRUNCATION_POSITION))
l2.setParseAction(_handle_trunc_legacy)
return l1 | l2 | [
"def",
"get_truncation_language",
"(",
")",
"->",
"ParserElement",
":",
"l1",
"=",
"truncation_tag",
"+",
"nest",
"(",
"amino_acid",
"(",
"AMINO_ACID",
")",
"+",
"ppc",
".",
"integer",
"(",
"TRUNCATION_POSITION",
")",
")",
"l1",
".",
"setParseAction",
"(",
"... | Build a parser for protein truncations. | [
"Build",
"a",
"parser",
"for",
"protein",
"truncations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/truncation.py#L57-L63 | train | 29,796 |
vhf/confusable_homoglyphs | confusable_homoglyphs/categories.py | aliases_categories | def aliases_categories(chr):
"""Retrieves the script block alias and unicode category for a unicode character.
>>> categories.aliases_categories('A')
('LATIN', 'L')
>>> categories.aliases_categories('τ')
('GREEK', 'L')
>>> categories.aliases_categories('-')
('COMMON', 'Pd')
:param chr: A unicode character
:type chr: str
:return: The script block alias and unicode category for a unicode character.
:rtype: (str, str)
"""
l = 0
r = len(categories_data['code_points_ranges']) - 1
c = ord(chr)
# binary search
while r >= l:
m = (l + r) // 2
if c < categories_data['code_points_ranges'][m][0]:
r = m - 1
elif c > categories_data['code_points_ranges'][m][1]:
l = m + 1
else:
return (
categories_data['iso_15924_aliases'][categories_data['code_points_ranges'][m][2]],
categories_data['categories'][categories_data['code_points_ranges'][m][3]])
return 'Unknown', 'Zzzz' | python | def aliases_categories(chr):
"""Retrieves the script block alias and unicode category for a unicode character.
>>> categories.aliases_categories('A')
('LATIN', 'L')
>>> categories.aliases_categories('τ')
('GREEK', 'L')
>>> categories.aliases_categories('-')
('COMMON', 'Pd')
:param chr: A unicode character
:type chr: str
:return: The script block alias and unicode category for a unicode character.
:rtype: (str, str)
"""
l = 0
r = len(categories_data['code_points_ranges']) - 1
c = ord(chr)
# binary search
while r >= l:
m = (l + r) // 2
if c < categories_data['code_points_ranges'][m][0]:
r = m - 1
elif c > categories_data['code_points_ranges'][m][1]:
l = m + 1
else:
return (
categories_data['iso_15924_aliases'][categories_data['code_points_ranges'][m][2]],
categories_data['categories'][categories_data['code_points_ranges'][m][3]])
return 'Unknown', 'Zzzz' | [
"def",
"aliases_categories",
"(",
"chr",
")",
":",
"l",
"=",
"0",
"r",
"=",
"len",
"(",
"categories_data",
"[",
"'code_points_ranges'",
"]",
")",
"-",
"1",
"c",
"=",
"ord",
"(",
"chr",
")",
"# binary search",
"while",
"r",
">=",
"l",
":",
"m",
"=",
... | Retrieves the script block alias and unicode category for a unicode character.
>>> categories.aliases_categories('A')
('LATIN', 'L')
>>> categories.aliases_categories('τ')
('GREEK', 'L')
>>> categories.aliases_categories('-')
('COMMON', 'Pd')
:param chr: A unicode character
:type chr: str
:return: The script block alias and unicode category for a unicode character.
:rtype: (str, str) | [
"Retrieves",
"the",
"script",
"block",
"alias",
"and",
"unicode",
"category",
"for",
"a",
"unicode",
"character",
"."
] | 14f43ddd74099520ddcda29fac557c27a28190e6 | https://github.com/vhf/confusable_homoglyphs/blob/14f43ddd74099520ddcda29fac557c27a28190e6/confusable_homoglyphs/categories.py#L8-L38 | train | 29,797 |
vhf/confusable_homoglyphs | confusable_homoglyphs/confusables.py | is_mixed_script | def is_mixed_script(string, allowed_aliases=['COMMON']):
"""Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excluded by default.
>>> confusables.is_mixed_script('Abç')
False
>>> confusables.is_mixed_script('ρτ.τ')
False
>>> confusables.is_mixed_script('ρτ.τ', allowed_aliases=[])
True
>>> confusables.is_mixed_script('Alloτ')
True
:param string: A unicode string
:type string: str
:param allowed_aliases: Script blocks aliases not to consider.
:type allowed_aliases: list(str)
:return: Whether ``string`` is considered mixed-scripts or not.
:rtype: bool
"""
allowed_aliases = [a.upper() for a in allowed_aliases]
cats = unique_aliases(string) - set(allowed_aliases)
return len(cats) > 1 | python | def is_mixed_script(string, allowed_aliases=['COMMON']):
"""Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excluded by default.
>>> confusables.is_mixed_script('Abç')
False
>>> confusables.is_mixed_script('ρτ.τ')
False
>>> confusables.is_mixed_script('ρτ.τ', allowed_aliases=[])
True
>>> confusables.is_mixed_script('Alloτ')
True
:param string: A unicode string
:type string: str
:param allowed_aliases: Script blocks aliases not to consider.
:type allowed_aliases: list(str)
:return: Whether ``string`` is considered mixed-scripts or not.
:rtype: bool
"""
allowed_aliases = [a.upper() for a in allowed_aliases]
cats = unique_aliases(string) - set(allowed_aliases)
return len(cats) > 1 | [
"def",
"is_mixed_script",
"(",
"string",
",",
"allowed_aliases",
"=",
"[",
"'COMMON'",
"]",
")",
":",
"allowed_aliases",
"=",
"[",
"a",
".",
"upper",
"(",
")",
"for",
"a",
"in",
"allowed_aliases",
"]",
"cats",
"=",
"unique_aliases",
"(",
"string",
")",
"... | Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excluded by default.
>>> confusables.is_mixed_script('Abç')
False
>>> confusables.is_mixed_script('ρτ.τ')
False
>>> confusables.is_mixed_script('ρτ.τ', allowed_aliases=[])
True
>>> confusables.is_mixed_script('Alloτ')
True
:param string: A unicode string
:type string: str
:param allowed_aliases: Script blocks aliases not to consider.
:type allowed_aliases: list(str)
:return: Whether ``string`` is considered mixed-scripts or not.
:rtype: bool | [
"Checks",
"if",
"string",
"contains",
"mixed",
"-",
"scripts",
"content",
"excluding",
"script",
"blocks",
"aliases",
"in",
"allowed_aliases",
"."
] | 14f43ddd74099520ddcda29fac557c27a28190e6 | https://github.com/vhf/confusable_homoglyphs/blob/14f43ddd74099520ddcda29fac557c27a28190e6/confusable_homoglyphs/confusables.py#L13-L38 | train | 29,798 |
vhf/confusable_homoglyphs | confusable_homoglyphs/confusables.py | is_confusable | def is_confusable(string, greedy=False, preferred_aliases=[]):
"""Checks if ``string`` contains characters which might be confusable with
characters from ``preferred_aliases``.
If ``greedy=False``, it will only return the first confusable character
found without looking at the rest of the string, ``greedy=True`` returns
all of them.
``preferred_aliases=[]`` can take an array of unicode block aliases to
be considered as your 'base' unicode blocks:
- considering ``paρa``,
- with ``preferred_aliases=['latin']``, the 3rd character ``ρ``
would be returned because this greek letter can be confused with
latin ``p``.
- with ``preferred_aliases=['greek']``, the 1st character ``p``
would be returned because this latin letter can be confused with
greek ``ρ``.
- with ``preferred_aliases=[]`` and ``greedy=True``, you'll discover
the 29 characters that can be confused with ``p``, the 23
characters that look like ``a``, and the one that looks like ``ρ``
(which is, of course, *p* aka *LATIN SMALL LETTER P*).
>>> confusables.is_confusable('paρa', preferred_aliases=['latin'])[0]['character']
'ρ'
>>> confusables.is_confusable('paρa', preferred_aliases=['greek'])[0]['character']
'p'
>>> confusables.is_confusable('Abç', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('AlloΓ', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('ρττ', preferred_aliases=['greek'])
False
>>> confusables.is_confusable('ρτ.τ', preferred_aliases=['greek', 'common'])
False
>>> confusables.is_confusable('ρττp')
[{'homoglyphs': [{'c': 'p', 'n': 'LATIN SMALL LETTER P'}], 'alias': 'GREEK', 'character': 'ρ'}]
:param string: A unicode string
:type string: str
:param greedy: Don't stop on finding one confusable character - find all of them.
:type greedy: bool
:param preferred_aliases: Script blocks aliases which we don't want ``string``'s characters
to be confused with.
:type preferred_aliases: list(str)
:return: False if not confusable, all confusable characters and with what they are confusable
otherwise.
:rtype: bool or list
"""
preferred_aliases = [a.upper() for a in preferred_aliases]
outputs = []
checked = set()
for char in string:
if char in checked:
continue
checked.add(char)
char_alias = alias(char)
if char_alias in preferred_aliases:
# it's safe if the character might be confusable with homoglyphs from other
# categories than our preferred categories (=aliases)
continue
found = confusables_data.get(char, False)
if found is False:
continue
# character λ is considered confusable if λ can be confused with a character from
# preferred_aliases, e.g. if 'LATIN', 'ρ' is confusable with 'p' from LATIN.
# if 'LATIN', 'Γ' is not confusable because in all the characters confusable with Γ,
# none of them is LATIN.
if preferred_aliases:
potentially_confusable = []
try:
for d in found:
aliases = [alias(glyph) for glyph in d['c']]
for a in aliases:
if a in preferred_aliases:
potentially_confusable = found
raise Found()
except Found:
pass
else:
potentially_confusable = found
if potentially_confusable: # we found homoglyphs
output = {
'character': char,
'alias': char_alias,
'homoglyphs': potentially_confusable,
}
if not greedy:
return [output]
outputs.append(output)
return outputs or False | python | def is_confusable(string, greedy=False, preferred_aliases=[]):
"""Checks if ``string`` contains characters which might be confusable with
characters from ``preferred_aliases``.
If ``greedy=False``, it will only return the first confusable character
found without looking at the rest of the string, ``greedy=True`` returns
all of them.
``preferred_aliases=[]`` can take an array of unicode block aliases to
be considered as your 'base' unicode blocks:
- considering ``paρa``,
- with ``preferred_aliases=['latin']``, the 3rd character ``ρ``
would be returned because this greek letter can be confused with
latin ``p``.
- with ``preferred_aliases=['greek']``, the 1st character ``p``
would be returned because this latin letter can be confused with
greek ``ρ``.
- with ``preferred_aliases=[]`` and ``greedy=True``, you'll discover
the 29 characters that can be confused with ``p``, the 23
characters that look like ``a``, and the one that looks like ``ρ``
(which is, of course, *p* aka *LATIN SMALL LETTER P*).
>>> confusables.is_confusable('paρa', preferred_aliases=['latin'])[0]['character']
'ρ'
>>> confusables.is_confusable('paρa', preferred_aliases=['greek'])[0]['character']
'p'
>>> confusables.is_confusable('Abç', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('AlloΓ', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('ρττ', preferred_aliases=['greek'])
False
>>> confusables.is_confusable('ρτ.τ', preferred_aliases=['greek', 'common'])
False
>>> confusables.is_confusable('ρττp')
[{'homoglyphs': [{'c': 'p', 'n': 'LATIN SMALL LETTER P'}], 'alias': 'GREEK', 'character': 'ρ'}]
:param string: A unicode string
:type string: str
:param greedy: Don't stop on finding one confusable character - find all of them.
:type greedy: bool
:param preferred_aliases: Script blocks aliases which we don't want ``string``'s characters
to be confused with.
:type preferred_aliases: list(str)
:return: False if not confusable, all confusable characters and with what they are confusable
otherwise.
:rtype: bool or list
"""
preferred_aliases = [a.upper() for a in preferred_aliases]
outputs = []
checked = set()
for char in string:
if char in checked:
continue
checked.add(char)
char_alias = alias(char)
if char_alias in preferred_aliases:
# it's safe if the character might be confusable with homoglyphs from other
# categories than our preferred categories (=aliases)
continue
found = confusables_data.get(char, False)
if found is False:
continue
# character λ is considered confusable if λ can be confused with a character from
# preferred_aliases, e.g. if 'LATIN', 'ρ' is confusable with 'p' from LATIN.
# if 'LATIN', 'Γ' is not confusable because in all the characters confusable with Γ,
# none of them is LATIN.
if preferred_aliases:
potentially_confusable = []
try:
for d in found:
aliases = [alias(glyph) for glyph in d['c']]
for a in aliases:
if a in preferred_aliases:
potentially_confusable = found
raise Found()
except Found:
pass
else:
potentially_confusable = found
if potentially_confusable: # we found homoglyphs
output = {
'character': char,
'alias': char_alias,
'homoglyphs': potentially_confusable,
}
if not greedy:
return [output]
outputs.append(output)
return outputs or False | [
"def",
"is_confusable",
"(",
"string",
",",
"greedy",
"=",
"False",
",",
"preferred_aliases",
"=",
"[",
"]",
")",
":",
"preferred_aliases",
"=",
"[",
"a",
".",
"upper",
"(",
")",
"for",
"a",
"in",
"preferred_aliases",
"]",
"outputs",
"=",
"[",
"]",
"ch... | Checks if ``string`` contains characters which might be confusable with
characters from ``preferred_aliases``.
If ``greedy=False``, it will only return the first confusable character
found without looking at the rest of the string, ``greedy=True`` returns
all of them.
``preferred_aliases=[]`` can take an array of unicode block aliases to
be considered as your 'base' unicode blocks:
- considering ``paρa``,
- with ``preferred_aliases=['latin']``, the 3rd character ``ρ``
would be returned because this greek letter can be confused with
latin ``p``.
- with ``preferred_aliases=['greek']``, the 1st character ``p``
would be returned because this latin letter can be confused with
greek ``ρ``.
- with ``preferred_aliases=[]`` and ``greedy=True``, you'll discover
the 29 characters that can be confused with ``p``, the 23
characters that look like ``a``, and the one that looks like ``ρ``
(which is, of course, *p* aka *LATIN SMALL LETTER P*).
>>> confusables.is_confusable('paρa', preferred_aliases=['latin'])[0]['character']
'ρ'
>>> confusables.is_confusable('paρa', preferred_aliases=['greek'])[0]['character']
'p'
>>> confusables.is_confusable('Abç', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('AlloΓ', preferred_aliases=['latin'])
False
>>> confusables.is_confusable('ρττ', preferred_aliases=['greek'])
False
>>> confusables.is_confusable('ρτ.τ', preferred_aliases=['greek', 'common'])
False
>>> confusables.is_confusable('ρττp')
[{'homoglyphs': [{'c': 'p', 'n': 'LATIN SMALL LETTER P'}], 'alias': 'GREEK', 'character': 'ρ'}]
:param string: A unicode string
:type string: str
:param greedy: Don't stop on finding one confusable character - find all of them.
:type greedy: bool
:param preferred_aliases: Script blocks aliases which we don't want ``string``'s characters
to be confused with.
:type preferred_aliases: list(str)
:return: False if not confusable, all confusable characters and with what they are confusable
otherwise.
:rtype: bool or list | [
"Checks",
"if",
"string",
"contains",
"characters",
"which",
"might",
"be",
"confusable",
"with",
"characters",
"from",
"preferred_aliases",
"."
] | 14f43ddd74099520ddcda29fac557c27a28190e6 | https://github.com/vhf/confusable_homoglyphs/blob/14f43ddd74099520ddcda29fac557c27a28190e6/confusable_homoglyphs/confusables.py#L41-L133 | train | 29,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.