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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
plivo/plivo-python | plivo/utils/__init__.py | validate_signature | def validate_signature(uri, nonce, signature, auth_token=''):
"""
Validates requests made by Plivo to your servers.
:param uri: Your server URL
:param nonce: X-Plivo-Signature-V2-Nonce
:param signature: X-Plivo-Signature-V2 header
:param auth_token: Plivo Auth token
:return: True if the request matches signature, False otherwise
"""
auth_token = bytes(auth_token.encode('utf-8'))
nonce = bytes(nonce.encode('utf-8'))
signature = bytes(signature.encode('utf-8'))
parsed_uri = urlparse(uri.encode('utf-8'))
base_url = urlunparse((parsed_uri.scheme.decode('utf-8'),
parsed_uri.netloc.decode('utf-8'),
parsed_uri.path.decode('utf-8'), '', '',
'')).encode('utf-8')
return encodestring(hnew(auth_token, base_url + nonce, sha256)
.digest()).strip() == signature | python | def validate_signature(uri, nonce, signature, auth_token=''):
"""
Validates requests made by Plivo to your servers.
:param uri: Your server URL
:param nonce: X-Plivo-Signature-V2-Nonce
:param signature: X-Plivo-Signature-V2 header
:param auth_token: Plivo Auth token
:return: True if the request matches signature, False otherwise
"""
auth_token = bytes(auth_token.encode('utf-8'))
nonce = bytes(nonce.encode('utf-8'))
signature = bytes(signature.encode('utf-8'))
parsed_uri = urlparse(uri.encode('utf-8'))
base_url = urlunparse((parsed_uri.scheme.decode('utf-8'),
parsed_uri.netloc.decode('utf-8'),
parsed_uri.path.decode('utf-8'), '', '',
'')).encode('utf-8')
return encodestring(hnew(auth_token, base_url + nonce, sha256)
.digest()).strip() == signature | [
"def",
"validate_signature",
"(",
"uri",
",",
"nonce",
",",
"signature",
",",
"auth_token",
"=",
"''",
")",
":",
"auth_token",
"=",
"bytes",
"(",
"auth_token",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"nonce",
"=",
"bytes",
"(",
"nonce",
".",
"encode",
... | Validates requests made by Plivo to your servers.
:param uri: Your server URL
:param nonce: X-Plivo-Signature-V2-Nonce
:param signature: X-Plivo-Signature-V2 header
:param auth_token: Plivo Auth token
:return: True if the request matches signature, False otherwise | [
"Validates",
"requests",
"made",
"by",
"Plivo",
"to",
"your",
"servers",
"."
] | f09a1fc63e378bf17269011a071e093aa83930d0 | https://github.com/plivo/plivo-python/blob/f09a1fc63e378bf17269011a071e093aa83930d0/plivo/utils/__init__.py#L16-L38 | train | 29,400 |
plivo/plivo-python | plivo/rest/client.py | fetch_credentials | def fetch_credentials(auth_id, auth_token):
"""Fetches the right credentials either from params or from environment"""
if not (auth_id and auth_token):
try:
auth_id = os.environ['PLIVO_AUTH_ID']
auth_token = os.environ['PLIVO_AUTH_TOKEN']
except KeyError:
raise AuthenticationError('The Plivo Python SDK '
'could not find your auth credentials.')
if not (is_valid_mainaccount(auth_id) or is_valid_subaccount(auth_id)):
raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id)
return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token) | python | def fetch_credentials(auth_id, auth_token):
"""Fetches the right credentials either from params or from environment"""
if not (auth_id and auth_token):
try:
auth_id = os.environ['PLIVO_AUTH_ID']
auth_token = os.environ['PLIVO_AUTH_TOKEN']
except KeyError:
raise AuthenticationError('The Plivo Python SDK '
'could not find your auth credentials.')
if not (is_valid_mainaccount(auth_id) or is_valid_subaccount(auth_id)):
raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id)
return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token) | [
"def",
"fetch_credentials",
"(",
"auth_id",
",",
"auth_token",
")",
":",
"if",
"not",
"(",
"auth_id",
"and",
"auth_token",
")",
":",
"try",
":",
"auth_id",
"=",
"os",
".",
"environ",
"[",
"'PLIVO_AUTH_ID'",
"]",
"auth_token",
"=",
"os",
".",
"environ",
"... | Fetches the right credentials either from params or from environment | [
"Fetches",
"the",
"right",
"credentials",
"either",
"from",
"params",
"or",
"from",
"environment"
] | f09a1fc63e378bf17269011a071e093aa83930d0 | https://github.com/plivo/plivo-python/blob/f09a1fc63e378bf17269011a071e093aa83930d0/plivo/rest/client.py#L35-L49 | train | 29,401 |
plivo/plivo-python | plivo/rest/client.py | Client.process_response | def process_response(self,
method,
response,
response_type=None,
objects_type=None):
"""Processes the API response based on the status codes and method used
to access the API
"""
try:
response_json = response.json(
object_hook=
lambda x: ResponseObject(x) if isinstance(x, dict) else x)
if response_type:
r = response_type(self, response_json.__dict__)
response_json = r
if 'objects' in response_json and objects_type:
response_json.objects = [
objects_type(self, obj.__dict__)
for obj in response_json.objects
]
except ValueError:
response_json = None
if response.status_code == 400:
if response_json and 'error' in response_json:
raise ValidationError(response_json.error)
raise ValidationError(
'A parameter is missing or is invalid while accessing resource'
'at: {url}'.format(url=response.url))
if response.status_code == 401:
if response_json and 'error' in response_json:
raise AuthenticationError(response_json.error)
raise AuthenticationError(
'Failed to authenticate while accessing resource at: '
'{url}'.format(url=response.url))
if response.status_code == 404:
if response_json and 'error' in response_json:
raise ResourceNotFoundError(response_json.error)
raise ResourceNotFoundError(
'Resource not found at: {url}'.format(url=response.url))
if response.status_code == 405:
if response_json and 'error' in response_json:
raise InvalidRequestError(response_json.error)
raise InvalidRequestError(
'HTTP method "{method}" not allowed to access resource at: '
'{url}'.format(method=method, url=response.url))
if response.status_code == 500:
if response_json and 'error' in response_json:
raise PlivoServerError(response_json.error)
raise PlivoServerError(
'A server error occurred while accessing resource at: '
'{url}'.format(url=response.url))
if method == 'DELETE':
if response.status_code != 204:
raise PlivoRestError('Resource at {url} could not be '
'deleted'.format(url=response.url))
elif response.status_code not in [200, 201, 202]:
raise PlivoRestError(
'Received status code {status_code} for the HTTP method '
'"{method}"'.format(
status_code=response.status_code, method=method))
return response_json | python | def process_response(self,
method,
response,
response_type=None,
objects_type=None):
"""Processes the API response based on the status codes and method used
to access the API
"""
try:
response_json = response.json(
object_hook=
lambda x: ResponseObject(x) if isinstance(x, dict) else x)
if response_type:
r = response_type(self, response_json.__dict__)
response_json = r
if 'objects' in response_json and objects_type:
response_json.objects = [
objects_type(self, obj.__dict__)
for obj in response_json.objects
]
except ValueError:
response_json = None
if response.status_code == 400:
if response_json and 'error' in response_json:
raise ValidationError(response_json.error)
raise ValidationError(
'A parameter is missing or is invalid while accessing resource'
'at: {url}'.format(url=response.url))
if response.status_code == 401:
if response_json and 'error' in response_json:
raise AuthenticationError(response_json.error)
raise AuthenticationError(
'Failed to authenticate while accessing resource at: '
'{url}'.format(url=response.url))
if response.status_code == 404:
if response_json and 'error' in response_json:
raise ResourceNotFoundError(response_json.error)
raise ResourceNotFoundError(
'Resource not found at: {url}'.format(url=response.url))
if response.status_code == 405:
if response_json and 'error' in response_json:
raise InvalidRequestError(response_json.error)
raise InvalidRequestError(
'HTTP method "{method}" not allowed to access resource at: '
'{url}'.format(method=method, url=response.url))
if response.status_code == 500:
if response_json and 'error' in response_json:
raise PlivoServerError(response_json.error)
raise PlivoServerError(
'A server error occurred while accessing resource at: '
'{url}'.format(url=response.url))
if method == 'DELETE':
if response.status_code != 204:
raise PlivoRestError('Resource at {url} could not be '
'deleted'.format(url=response.url))
elif response.status_code not in [200, 201, 202]:
raise PlivoRestError(
'Received status code {status_code} for the HTTP method '
'"{method}"'.format(
status_code=response.status_code, method=method))
return response_json | [
"def",
"process_response",
"(",
"self",
",",
"method",
",",
"response",
",",
"response_type",
"=",
"None",
",",
"objects_type",
"=",
"None",
")",
":",
"try",
":",
"response_json",
"=",
"response",
".",
"json",
"(",
"object_hook",
"=",
"lambda",
"x",
":",
... | Processes the API response based on the status codes and method used
to access the API | [
"Processes",
"the",
"API",
"response",
"based",
"on",
"the",
"status",
"codes",
"and",
"method",
"used",
"to",
"access",
"the",
"API"
] | f09a1fc63e378bf17269011a071e093aa83930d0 | https://github.com/plivo/plivo-python/blob/f09a1fc63e378bf17269011a071e093aa83930d0/plivo/rest/client.py#L98-L168 | train | 29,402 |
cgevans/scikits-bootstrap | scikits/bootstrap/bootstrap.py | jackknife_indexes | def jackknife_indexes(data):
"""
Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is a set of jackknife indexes.
For a given set of data Y, the jackknife sample J[i] is defined as the data set
Y with the ith data point deleted.
"""
base = np.arange(0,len(data))
return (np.delete(base,i) for i in base) | python | def jackknife_indexes(data):
"""
Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is a set of jackknife indexes.
For a given set of data Y, the jackknife sample J[i] is defined as the data set
Y with the ith data point deleted.
"""
base = np.arange(0,len(data))
return (np.delete(base,i) for i in base) | [
"def",
"jackknife_indexes",
"(",
"data",
")",
":",
"base",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"data",
")",
")",
"return",
"(",
"np",
".",
"delete",
"(",
"base",
",",
"i",
")",
"for",
"i",
"in",
"base",
")"
] | Given data points data, where axis 0 is considered to delineate points, return
a list of arrays where each array is a set of jackknife indexes.
For a given set of data Y, the jackknife sample J[i] is defined as the data set
Y with the ith data point deleted. | [
"Given",
"data",
"points",
"data",
"where",
"axis",
"0",
"is",
"considered",
"to",
"delineate",
"points",
"return",
"a",
"list",
"of",
"arrays",
"where",
"each",
"array",
"is",
"a",
"set",
"of",
"jackknife",
"indexes",
"."
] | b84cd2c7973fca0a6ed34430040788bc2e3f8f73 | https://github.com/cgevans/scikits-bootstrap/blob/b84cd2c7973fca0a6ed34430040788bc2e3f8f73/scikits/bootstrap/bootstrap.py#L309-L318 | train | 29,403 |
cgevans/scikits-bootstrap | scikits/bootstrap/bootstrap.py | bootstrap_indexes_moving_block | def bootstrap_indexes_moving_block(data, n_samples=10000,
block_length=3, wrap=False):
"""Generate moving-block bootstrap samples.
Given data points `data`, where axis 0 is considered to delineate points,
return a generator for sets of bootstrap indexes. This can be used as a
list of bootstrap indexes (with list(bootstrap_indexes_moving_block(data))) as
well.
Parameters
----------
n_samples [default 10000]: the number of subsamples to generate.
block_length [default 3]: the length of block.
wrap [default False]: if false, choose only blocks within the data, making
the last block for data of length L start at L-block_length. If true, choose
blocks starting anywhere, and if they extend past the end of the data, wrap
around to the beginning of the data again.
"""
n_obs = data.shape[0]
n_blocks = int(ceil(n_obs / block_length))
nexts = np.repeat(np.arange(0, block_length)[None, :], n_blocks, axis=0)
if wrap:
last_block = n_obs
else:
last_block = n_obs - block_length
for _ in xrange(n_samples):
blocks = np.random.randint(0, last_block, size=n_blocks)
if not wrap:
yield (blocks[:, None]+nexts).ravel()[:n_obs]
else:
yield np.mod((blocks[:, None]+nexts).ravel()[:n_obs], n_obs) | python | def bootstrap_indexes_moving_block(data, n_samples=10000,
block_length=3, wrap=False):
"""Generate moving-block bootstrap samples.
Given data points `data`, where axis 0 is considered to delineate points,
return a generator for sets of bootstrap indexes. This can be used as a
list of bootstrap indexes (with list(bootstrap_indexes_moving_block(data))) as
well.
Parameters
----------
n_samples [default 10000]: the number of subsamples to generate.
block_length [default 3]: the length of block.
wrap [default False]: if false, choose only blocks within the data, making
the last block for data of length L start at L-block_length. If true, choose
blocks starting anywhere, and if they extend past the end of the data, wrap
around to the beginning of the data again.
"""
n_obs = data.shape[0]
n_blocks = int(ceil(n_obs / block_length))
nexts = np.repeat(np.arange(0, block_length)[None, :], n_blocks, axis=0)
if wrap:
last_block = n_obs
else:
last_block = n_obs - block_length
for _ in xrange(n_samples):
blocks = np.random.randint(0, last_block, size=n_blocks)
if not wrap:
yield (blocks[:, None]+nexts).ravel()[:n_obs]
else:
yield np.mod((blocks[:, None]+nexts).ravel()[:n_obs], n_obs) | [
"def",
"bootstrap_indexes_moving_block",
"(",
"data",
",",
"n_samples",
"=",
"10000",
",",
"block_length",
"=",
"3",
",",
"wrap",
"=",
"False",
")",
":",
"n_obs",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"n_blocks",
"=",
"int",
"(",
"ceil",
"(",
"n_ob... | Generate moving-block bootstrap samples.
Given data points `data`, where axis 0 is considered to delineate points,
return a generator for sets of bootstrap indexes. This can be used as a
list of bootstrap indexes (with list(bootstrap_indexes_moving_block(data))) as
well.
Parameters
----------
n_samples [default 10000]: the number of subsamples to generate.
block_length [default 3]: the length of block.
wrap [default False]: if false, choose only blocks within the data, making
the last block for data of length L start at L-block_length. If true, choose
blocks starting anywhere, and if they extend past the end of the data, wrap
around to the beginning of the data again. | [
"Generate",
"moving",
"-",
"block",
"bootstrap",
"samples",
"."
] | b84cd2c7973fca0a6ed34430040788bc2e3f8f73 | https://github.com/cgevans/scikits-bootstrap/blob/b84cd2c7973fca0a6ed34430040788bc2e3f8f73/scikits/bootstrap/bootstrap.py#L342-L377 | train | 29,404 |
pybel/pybel | src/pybel/parser/modifiers/protein_substitution.py | get_protein_substitution_language | def get_protein_substitution_language() -> ParserElement:
"""Build a protein substitution parser."""
parser_element = psub_tag + nest(
amino_acid(PSUB_REFERENCE),
ppc.integer(PSUB_POSITION),
amino_acid(PSUB_VARIANT),
)
parser_element.setParseAction(_handle_psub)
return parser_element | python | def get_protein_substitution_language() -> ParserElement:
"""Build a protein substitution parser."""
parser_element = psub_tag + nest(
amino_acid(PSUB_REFERENCE),
ppc.integer(PSUB_POSITION),
amino_acid(PSUB_VARIANT),
)
parser_element.setParseAction(_handle_psub)
return parser_element | [
"def",
"get_protein_substitution_language",
"(",
")",
"->",
"ParserElement",
":",
"parser_element",
"=",
"psub_tag",
"+",
"nest",
"(",
"amino_acid",
"(",
"PSUB_REFERENCE",
")",
",",
"ppc",
".",
"integer",
"(",
"PSUB_POSITION",
")",
",",
"amino_acid",
"(",
"PSUB_... | Build a protein substitution parser. | [
"Build",
"a",
"protein",
"substitution",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/protein_substitution.py#L53-L61 | train | 29,405 |
pybel/pybel | src/pybel/canonicalize.py | postpend_location | def postpend_location(bel_string: str, location_model) -> str:
"""Rip off the closing parentheses and adds canonicalized modification.
I did this because writing a whole new parsing model for the data would be sad and difficult
:param bel_string: BEL string representing node
:param dict location_model: A dictionary containing keys :code:`pybel.constants.TO_LOC` and
:code:`pybel.constants.FROM_LOC`
:return: A part of a BEL string representing the location
"""
if not all(k in location_model for k in {NAMESPACE, NAME}):
raise ValueError('Location model missing namespace and/or name keys: {}'.format(location_model))
return "{}, loc({}:{}))".format(
bel_string[:-1],
location_model[NAMESPACE],
ensure_quotes(location_model[NAME])
) | python | def postpend_location(bel_string: str, location_model) -> str:
"""Rip off the closing parentheses and adds canonicalized modification.
I did this because writing a whole new parsing model for the data would be sad and difficult
:param bel_string: BEL string representing node
:param dict location_model: A dictionary containing keys :code:`pybel.constants.TO_LOC` and
:code:`pybel.constants.FROM_LOC`
:return: A part of a BEL string representing the location
"""
if not all(k in location_model for k in {NAMESPACE, NAME}):
raise ValueError('Location model missing namespace and/or name keys: {}'.format(location_model))
return "{}, loc({}:{}))".format(
bel_string[:-1],
location_model[NAMESPACE],
ensure_quotes(location_model[NAME])
) | [
"def",
"postpend_location",
"(",
"bel_string",
":",
"str",
",",
"location_model",
")",
"->",
"str",
":",
"if",
"not",
"all",
"(",
"k",
"in",
"location_model",
"for",
"k",
"in",
"{",
"NAMESPACE",
",",
"NAME",
"}",
")",
":",
"raise",
"ValueError",
"(",
"... | Rip off the closing parentheses and adds canonicalized modification.
I did this because writing a whole new parsing model for the data would be sad and difficult
:param bel_string: BEL string representing node
:param dict location_model: A dictionary containing keys :code:`pybel.constants.TO_LOC` and
:code:`pybel.constants.FROM_LOC`
:return: A part of a BEL string representing the location | [
"Rip",
"off",
"the",
"closing",
"parentheses",
"and",
"adds",
"canonicalized",
"modification",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L35-L52 | train | 29,406 |
pybel/pybel | src/pybel/canonicalize.py | _decanonicalize_edge_node | def _decanonicalize_edge_node(node: BaseEntity, edge_data: EdgeData, node_position: str) -> str:
"""Canonicalize a node with its modifiers stored in the given edge to a BEL string.
:param node: A PyBEL node data dictionary
:param edge_data: A PyBEL edge data dictionary
:param node_position: Either :data:`pybel.constants.SUBJECT` or :data:`pybel.constants.OBJECT`
"""
node_str = node.as_bel()
if node_position not in edge_data:
return node_str
node_edge_data = edge_data[node_position]
if LOCATION in node_edge_data:
node_str = postpend_location(node_str, node_edge_data[LOCATION])
modifier = node_edge_data.get(MODIFIER)
if modifier is None:
return node_str
if DEGRADATION == modifier:
return "deg({})".format(node_str)
effect = node_edge_data.get(EFFECT)
if ACTIVITY == modifier:
if effect is None:
return "act({})".format(node_str)
if effect[NAMESPACE] == BEL_DEFAULT_NAMESPACE:
return "act({}, ma({}))".format(node_str, effect[NAME])
return "act({}, ma({}:{}))".format(node_str, effect[NAMESPACE], ensure_quotes(effect[NAME]))
if TRANSLOCATION == modifier:
if effect is None:
return 'tloc({})'.format(node_str)
to_loc_data = effect[TO_LOC]
from_loc_data = effect[FROM_LOC]
if from_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and from_loc_data[NAME] == INTRACELLULAR:
if to_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and to_loc_data[NAME] == EXTRACELLULAR:
return 'sec({})'.format(node_str)
if to_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and to_loc_data[NAME] == CELL_SURFACE:
return 'surf({})'.format(node_str)
from_loc = _get_tloc_terminal('fromLoc', from_loc_data)
to_loc = _get_tloc_terminal('toLoc', to_loc_data)
return "tloc({}, {}, {})".format(node_str, from_loc, to_loc)
raise ValueError('invalid modifier: {}'.format(modifier)) | python | def _decanonicalize_edge_node(node: BaseEntity, edge_data: EdgeData, node_position: str) -> str:
"""Canonicalize a node with its modifiers stored in the given edge to a BEL string.
:param node: A PyBEL node data dictionary
:param edge_data: A PyBEL edge data dictionary
:param node_position: Either :data:`pybel.constants.SUBJECT` or :data:`pybel.constants.OBJECT`
"""
node_str = node.as_bel()
if node_position not in edge_data:
return node_str
node_edge_data = edge_data[node_position]
if LOCATION in node_edge_data:
node_str = postpend_location(node_str, node_edge_data[LOCATION])
modifier = node_edge_data.get(MODIFIER)
if modifier is None:
return node_str
if DEGRADATION == modifier:
return "deg({})".format(node_str)
effect = node_edge_data.get(EFFECT)
if ACTIVITY == modifier:
if effect is None:
return "act({})".format(node_str)
if effect[NAMESPACE] == BEL_DEFAULT_NAMESPACE:
return "act({}, ma({}))".format(node_str, effect[NAME])
return "act({}, ma({}:{}))".format(node_str, effect[NAMESPACE], ensure_quotes(effect[NAME]))
if TRANSLOCATION == modifier:
if effect is None:
return 'tloc({})'.format(node_str)
to_loc_data = effect[TO_LOC]
from_loc_data = effect[FROM_LOC]
if from_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and from_loc_data[NAME] == INTRACELLULAR:
if to_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and to_loc_data[NAME] == EXTRACELLULAR:
return 'sec({})'.format(node_str)
if to_loc_data[NAMESPACE] == BEL_DEFAULT_NAMESPACE and to_loc_data[NAME] == CELL_SURFACE:
return 'surf({})'.format(node_str)
from_loc = _get_tloc_terminal('fromLoc', from_loc_data)
to_loc = _get_tloc_terminal('toLoc', to_loc_data)
return "tloc({}, {}, {})".format(node_str, from_loc, to_loc)
raise ValueError('invalid modifier: {}'.format(modifier)) | [
"def",
"_decanonicalize_edge_node",
"(",
"node",
":",
"BaseEntity",
",",
"edge_data",
":",
"EdgeData",
",",
"node_position",
":",
"str",
")",
"->",
"str",
":",
"node_str",
"=",
"node",
".",
"as_bel",
"(",
")",
"if",
"node_position",
"not",
"in",
"edge_data",... | Canonicalize a node with its modifiers stored in the given edge to a BEL string.
:param node: A PyBEL node data dictionary
:param edge_data: A PyBEL edge data dictionary
:param node_position: Either :data:`pybel.constants.SUBJECT` or :data:`pybel.constants.OBJECT` | [
"Canonicalize",
"a",
"node",
"with",
"its",
"modifiers",
"stored",
"in",
"the",
"given",
"edge",
"to",
"a",
"BEL",
"string",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L55-L109 | train | 29,407 |
pybel/pybel | src/pybel/canonicalize.py | edge_to_bel | def edge_to_bel(u: BaseEntity, v: BaseEntity, data: EdgeData, sep: Optional[str] = None) -> str:
"""Take two nodes and gives back a BEL string representing the statement.
:param u: The edge's source's PyBEL node data dictionary
:param v: The edge's target's PyBEL node data dictionary
:param data: The edge's data dictionary
:param sep: The separator between the source, relation, and target. Defaults to ' '
"""
sep = sep or ' '
u_str = _decanonicalize_edge_node(u, data, node_position=SUBJECT)
v_str = _decanonicalize_edge_node(v, data, node_position=OBJECT)
return sep.join((u_str, data[RELATION], v_str)) | python | def edge_to_bel(u: BaseEntity, v: BaseEntity, data: EdgeData, sep: Optional[str] = None) -> str:
"""Take two nodes and gives back a BEL string representing the statement.
:param u: The edge's source's PyBEL node data dictionary
:param v: The edge's target's PyBEL node data dictionary
:param data: The edge's data dictionary
:param sep: The separator between the source, relation, and target. Defaults to ' '
"""
sep = sep or ' '
u_str = _decanonicalize_edge_node(u, data, node_position=SUBJECT)
v_str = _decanonicalize_edge_node(v, data, node_position=OBJECT)
return sep.join((u_str, data[RELATION], v_str)) | [
"def",
"edge_to_bel",
"(",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"data",
":",
"EdgeData",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"sep",
"=",
"sep",
"or",
"' '",
"u_str",
"=",
"_decanoni... | Take two nodes and gives back a BEL string representing the statement.
:param u: The edge's source's PyBEL node data dictionary
:param v: The edge's target's PyBEL node data dictionary
:param data: The edge's data dictionary
:param sep: The separator between the source, relation, and target. Defaults to ' ' | [
"Take",
"two",
"nodes",
"and",
"gives",
"back",
"a",
"BEL",
"string",
"representing",
"the",
"statement",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L120-L132 | train | 29,408 |
pybel/pybel | src/pybel/canonicalize.py | sort_qualified_edges | def sort_qualified_edges(graph) -> Iterable[EdgeTuple]:
"""Return the qualified edges, sorted first by citation, then by evidence, then by annotations.
:param BELGraph graph: A BEL graph
"""
qualified_edges = (
(u, v, k, d)
for u, v, k, d in graph.edges(keys=True, data=True)
if graph.has_edge_citation(u, v, k) and graph.has_edge_evidence(u, v, k)
)
return sorted(qualified_edges, key=_sort_qualified_edges_helper) | python | def sort_qualified_edges(graph) -> Iterable[EdgeTuple]:
"""Return the qualified edges, sorted first by citation, then by evidence, then by annotations.
:param BELGraph graph: A BEL graph
"""
qualified_edges = (
(u, v, k, d)
for u, v, k, d in graph.edges(keys=True, data=True)
if graph.has_edge_citation(u, v, k) and graph.has_edge_evidence(u, v, k)
)
return sorted(qualified_edges, key=_sort_qualified_edges_helper) | [
"def",
"sort_qualified_edges",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"EdgeTuple",
"]",
":",
"qualified_edges",
"=",
"(",
"(",
"u",
",",
"v",
",",
"k",
",",
"d",
")",
"for",
"u",
",",
"v",
",",
"k",
",",
"d",
"in",
"graph",
".",
"edges",
"(",
... | Return the qualified edges, sorted first by citation, then by evidence, then by annotations.
:param BELGraph graph: A BEL graph | [
"Return",
"the",
"qualified",
"edges",
"sorted",
"first",
"by",
"citation",
"then",
"by",
"evidence",
"then",
"by",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L143-L153 | train | 29,409 |
pybel/pybel | src/pybel/canonicalize.py | _citation_sort_key | def _citation_sort_key(t: EdgeTuple) -> str:
"""Make a confusing 4 tuple sortable by citation."""
return '"{}", "{}"'.format(t[3][CITATION][CITATION_TYPE], t[3][CITATION][CITATION_REFERENCE]) | python | def _citation_sort_key(t: EdgeTuple) -> str:
"""Make a confusing 4 tuple sortable by citation."""
return '"{}", "{}"'.format(t[3][CITATION][CITATION_TYPE], t[3][CITATION][CITATION_REFERENCE]) | [
"def",
"_citation_sort_key",
"(",
"t",
":",
"EdgeTuple",
")",
"->",
"str",
":",
"return",
"'\"{}\", \"{}\"'",
".",
"format",
"(",
"t",
"[",
"3",
"]",
"[",
"CITATION",
"]",
"[",
"CITATION_TYPE",
"]",
",",
"t",
"[",
"3",
"]",
"[",
"CITATION",
"]",
"[",... | Make a confusing 4 tuple sortable by citation. | [
"Make",
"a",
"confusing",
"4",
"tuple",
"sortable",
"by",
"citation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L156-L158 | train | 29,410 |
pybel/pybel | src/pybel/canonicalize.py | _set_annotation_to_str | def _set_annotation_to_str(annotation_data: Mapping[str, Mapping[str, bool]], key: str) -> str:
"""Return a set annotation string."""
value = annotation_data[key]
if len(value) == 1:
return 'SET {} = "{}"'.format(key, list(value)[0])
x = ('"{}"'.format(v) for v in sorted(value))
return 'SET {} = {{{}}}'.format(key, ', '.join(x)) | python | def _set_annotation_to_str(annotation_data: Mapping[str, Mapping[str, bool]], key: str) -> str:
"""Return a set annotation string."""
value = annotation_data[key]
if len(value) == 1:
return 'SET {} = "{}"'.format(key, list(value)[0])
x = ('"{}"'.format(v) for v in sorted(value))
return 'SET {} = {{{}}}'.format(key, ', '.join(x)) | [
"def",
"_set_annotation_to_str",
"(",
"annotation_data",
":",
"Mapping",
"[",
"str",
",",
"Mapping",
"[",
"str",
",",
"bool",
"]",
"]",
",",
"key",
":",
"str",
")",
"->",
"str",
":",
"value",
"=",
"annotation_data",
"[",
"key",
"]",
"if",
"len",
"(",
... | Return a set annotation string. | [
"Return",
"a",
"set",
"annotation",
"string",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L166-L175 | train | 29,411 |
pybel/pybel | src/pybel/canonicalize.py | _unset_annotation_to_str | def _unset_annotation_to_str(keys: List[str]) -> str:
"""Return an unset annotation string."""
if len(keys) == 1:
return 'UNSET {}'.format(list(keys)[0])
return 'UNSET {{{}}}'.format(', '.join('{}'.format(key) for key in keys)) | python | def _unset_annotation_to_str(keys: List[str]) -> str:
"""Return an unset annotation string."""
if len(keys) == 1:
return 'UNSET {}'.format(list(keys)[0])
return 'UNSET {{{}}}'.format(', '.join('{}'.format(key) for key in keys)) | [
"def",
"_unset_annotation_to_str",
"(",
"keys",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"return",
"'UNSET {}'",
".",
"format",
"(",
"list",
"(",
"keys",
")",
"[",
"0",
"]",
")",
"return",
... | Return an unset annotation string. | [
"Return",
"an",
"unset",
"annotation",
"string",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L178-L183 | train | 29,412 |
pybel/pybel | src/pybel/canonicalize.py | _to_bel_lines_header | def _to_bel_lines_header(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's header.
:param pybel.BELGraph graph: A BEL graph
"""
yield '# This document was created by PyBEL v{} and bel-resources v{} on {}\n'.format(
VERSION, bel_resources.constants.VERSION, time.asctime()
)
yield from make_knowledge_header(
namespace_url=graph.namespace_url,
namespace_patterns=graph.namespace_pattern,
annotation_url=graph.annotation_url,
annotation_patterns=graph.annotation_pattern,
annotation_list=graph.annotation_list,
**graph.document
) | python | def _to_bel_lines_header(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's header.
:param pybel.BELGraph graph: A BEL graph
"""
yield '# This document was created by PyBEL v{} and bel-resources v{} on {}\n'.format(
VERSION, bel_resources.constants.VERSION, time.asctime()
)
yield from make_knowledge_header(
namespace_url=graph.namespace_url,
namespace_patterns=graph.namespace_pattern,
annotation_url=graph.annotation_url,
annotation_patterns=graph.annotation_pattern,
annotation_list=graph.annotation_list,
**graph.document
) | [
"def",
"_to_bel_lines_header",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"yield",
"'# This document was created by PyBEL v{} and bel-resources v{} on {}\\n'",
".",
"format",
"(",
"VERSION",
",",
"bel_resources",
".",
"constants",
".",
"VERSION",
",",
... | Iterate the lines of a BEL graph's corresponding BEL script's header.
:param pybel.BELGraph graph: A BEL graph | [
"Iterate",
"the",
"lines",
"of",
"a",
"BEL",
"graph",
"s",
"corresponding",
"BEL",
"script",
"s",
"header",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L186-L201 | train | 29,413 |
pybel/pybel | src/pybel/canonicalize.py | group_citation_edges | def group_citation_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]:
"""Return an iterator over pairs of citation values and their corresponding edge iterators."""
return itt.groupby(edges, key=_citation_sort_key) | python | def group_citation_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]:
"""Return an iterator over pairs of citation values and their corresponding edge iterators."""
return itt.groupby(edges, key=_citation_sort_key) | [
"def",
"group_citation_edges",
"(",
"edges",
":",
"Iterable",
"[",
"EdgeTuple",
"]",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Iterable",
"[",
"EdgeTuple",
"]",
"]",
"]",
":",
"return",
"itt",
".",
"groupby",
"(",
"edges",
",",
"key",
"=",... | Return an iterator over pairs of citation values and their corresponding edge iterators. | [
"Return",
"an",
"iterator",
"over",
"pairs",
"of",
"citation",
"values",
"and",
"their",
"corresponding",
"edge",
"iterators",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L204-L206 | train | 29,414 |
pybel/pybel | src/pybel/canonicalize.py | group_evidence_edges | def group_evidence_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]:
"""Return an iterator over pairs of evidence values and their corresponding edge iterators."""
return itt.groupby(edges, key=_evidence_sort_key) | python | def group_evidence_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]:
"""Return an iterator over pairs of evidence values and their corresponding edge iterators."""
return itt.groupby(edges, key=_evidence_sort_key) | [
"def",
"group_evidence_edges",
"(",
"edges",
":",
"Iterable",
"[",
"EdgeTuple",
"]",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Iterable",
"[",
"EdgeTuple",
"]",
"]",
"]",
":",
"return",
"itt",
".",
"groupby",
"(",
"edges",
",",
"key",
"=",... | Return an iterator over pairs of evidence values and their corresponding edge iterators. | [
"Return",
"an",
"iterator",
"over",
"pairs",
"of",
"evidence",
"values",
"and",
"their",
"corresponding",
"edge",
"iterators",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L209-L211 | train | 29,415 |
pybel/pybel | src/pybel/canonicalize.py | _to_bel_lines_body | def _to_bel_lines_body(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's body.
:param pybel.BELGraph graph: A BEL graph
"""
qualified_edges = sort_qualified_edges(graph)
for citation, citation_edges in group_citation_edges(qualified_edges):
yield 'SET Citation = {{{}}}\n'.format(citation)
for evidence, evidence_edges in group_evidence_edges(citation_edges):
yield 'SET SupportingText = "{}"'.format(evidence)
for u, v, _, data in evidence_edges:
annotations_data = data.get(ANNOTATIONS)
keys = sorted(annotations_data) if annotations_data is not None else tuple()
for key in keys:
yield _set_annotation_to_str(annotations_data, key)
yield graph.edge_to_bel(u, v, data)
if keys:
yield _unset_annotation_to_str(keys)
yield 'UNSET SupportingText'
yield 'UNSET Citation\n'
yield '#' * 80 | python | def _to_bel_lines_body(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's body.
:param pybel.BELGraph graph: A BEL graph
"""
qualified_edges = sort_qualified_edges(graph)
for citation, citation_edges in group_citation_edges(qualified_edges):
yield 'SET Citation = {{{}}}\n'.format(citation)
for evidence, evidence_edges in group_evidence_edges(citation_edges):
yield 'SET SupportingText = "{}"'.format(evidence)
for u, v, _, data in evidence_edges:
annotations_data = data.get(ANNOTATIONS)
keys = sorted(annotations_data) if annotations_data is not None else tuple()
for key in keys:
yield _set_annotation_to_str(annotations_data, key)
yield graph.edge_to_bel(u, v, data)
if keys:
yield _unset_annotation_to_str(keys)
yield 'UNSET SupportingText'
yield 'UNSET Citation\n'
yield '#' * 80 | [
"def",
"_to_bel_lines_body",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"qualified_edges",
"=",
"sort_qualified_edges",
"(",
"graph",
")",
"for",
"citation",
",",
"citation_edges",
"in",
"group_citation_edges",
"(",
"qualified_edges",
")",
":",
"... | Iterate the lines of a BEL graph's corresponding BEL script's body.
:param pybel.BELGraph graph: A BEL graph | [
"Iterate",
"the",
"lines",
"of",
"a",
"BEL",
"graph",
"s",
"corresponding",
"BEL",
"script",
"s",
"body",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L214-L241 | train | 29,416 |
pybel/pybel | src/pybel/canonicalize.py | _to_bel_lines_footer | def _to_bel_lines_footer(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph
"""
unqualified_edges_to_serialize = [
(u, v, d)
for u, v, d in graph.edges(data=True)
if d[RELATION] in UNQUALIFIED_EDGES and EVIDENCE not in d
]
isolated_nodes_to_serialize = [
node
for node in graph
if not graph.pred[node] and not graph.succ[node]
]
if unqualified_edges_to_serialize or isolated_nodes_to_serialize:
yield '###############################################\n'
yield 'SET Citation = {"PubMed","Added by PyBEL","29048466"}'
yield 'SET SupportingText = "{}"'.format(PYBEL_AUTOEVIDENCE)
for u, v, data in unqualified_edges_to_serialize:
yield '{} {} {}'.format(u.as_bel(), data[RELATION], v.as_bel())
for node in isolated_nodes_to_serialize:
yield node.as_bel()
yield 'UNSET SupportingText'
yield 'UNSET Citation' | python | def _to_bel_lines_footer(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph
"""
unqualified_edges_to_serialize = [
(u, v, d)
for u, v, d in graph.edges(data=True)
if d[RELATION] in UNQUALIFIED_EDGES and EVIDENCE not in d
]
isolated_nodes_to_serialize = [
node
for node in graph
if not graph.pred[node] and not graph.succ[node]
]
if unqualified_edges_to_serialize or isolated_nodes_to_serialize:
yield '###############################################\n'
yield 'SET Citation = {"PubMed","Added by PyBEL","29048466"}'
yield 'SET SupportingText = "{}"'.format(PYBEL_AUTOEVIDENCE)
for u, v, data in unqualified_edges_to_serialize:
yield '{} {} {}'.format(u.as_bel(), data[RELATION], v.as_bel())
for node in isolated_nodes_to_serialize:
yield node.as_bel()
yield 'UNSET SupportingText'
yield 'UNSET Citation' | [
"def",
"_to_bel_lines_footer",
"(",
"graph",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"unqualified_edges_to_serialize",
"=",
"[",
"(",
"u",
",",
"v",
",",
"d",
")",
"for",
"u",
",",
"v",
",",
"d",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
... | Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph | [
"Iterate",
"the",
"lines",
"of",
"a",
"BEL",
"graph",
"s",
"corresponding",
"BEL",
"script",
"s",
"footer",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L244-L273 | train | 29,417 |
pybel/pybel | src/pybel/canonicalize.py | to_bel_path | def to_bel_path(graph, path: str, mode: str = 'w', **kwargs) -> None:
"""Write the BEL graph as a canonical BEL Script to the given path.
:param BELGraph graph: the BEL Graph to output as a BEL Script
:param path: A file path
:param mode: The file opening mode. Defaults to 'w'
"""
with open(path, mode=mode, **kwargs) as bel_file:
to_bel(graph, bel_file) | python | def to_bel_path(graph, path: str, mode: str = 'w', **kwargs) -> None:
"""Write the BEL graph as a canonical BEL Script to the given path.
:param BELGraph graph: the BEL Graph to output as a BEL Script
:param path: A file path
:param mode: The file opening mode. Defaults to 'w'
"""
with open(path, mode=mode, **kwargs) as bel_file:
to_bel(graph, bel_file) | [
"def",
"to_bel_path",
"(",
"graph",
",",
"path",
":",
"str",
",",
"mode",
":",
"str",
"=",
"'w'",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"with",
"open",
"(",
"path",
",",
"mode",
"=",
"mode",
",",
"*",
"*",
"kwargs",
")",
"as",
"bel_f... | Write the BEL graph as a canonical BEL Script to the given path.
:param BELGraph graph: the BEL Graph to output as a BEL Script
:param path: A file path
:param mode: The file opening mode. Defaults to 'w' | [
"Write",
"the",
"BEL",
"graph",
"as",
"a",
"canonical",
"BEL",
"Script",
"to",
"the",
"given",
"path",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L298-L306 | train | 29,418 |
pybel/pybel | src/pybel/canonicalize.py | calculate_canonical_name | def calculate_canonical_name(data: BaseEntity) -> str:
"""Calculate the canonical name for a given node.
If it is a simple node, uses the already given name. Otherwise, it uses the BEL string.
"""
if data[FUNCTION] == COMPLEX and NAMESPACE in data:
return data[NAME]
if VARIANTS in data:
return data.as_bel()
if FUSION in data:
return data.as_bel()
if data[FUNCTION] in {REACTION, COMPOSITE, COMPLEX}:
return data.as_bel()
if VARIANTS not in data and FUSION not in data: # this is should be a simple node
if IDENTIFIER in data and NAME in data:
return '{namespace}:{identifier} ({name})'.format(**data)
if IDENTIFIER in data:
return '{namespace}:{identifier}'.format(namespace=data[NAMESPACE], identifier=data[IDENTIFIER])
return data[NAME]
raise ValueError('Unexpected node data: {}'.format(data)) | python | def calculate_canonical_name(data: BaseEntity) -> str:
"""Calculate the canonical name for a given node.
If it is a simple node, uses the already given name. Otherwise, it uses the BEL string.
"""
if data[FUNCTION] == COMPLEX and NAMESPACE in data:
return data[NAME]
if VARIANTS in data:
return data.as_bel()
if FUSION in data:
return data.as_bel()
if data[FUNCTION] in {REACTION, COMPOSITE, COMPLEX}:
return data.as_bel()
if VARIANTS not in data and FUSION not in data: # this is should be a simple node
if IDENTIFIER in data and NAME in data:
return '{namespace}:{identifier} ({name})'.format(**data)
if IDENTIFIER in data:
return '{namespace}:{identifier}'.format(namespace=data[NAMESPACE], identifier=data[IDENTIFIER])
return data[NAME]
raise ValueError('Unexpected node data: {}'.format(data)) | [
"def",
"calculate_canonical_name",
"(",
"data",
":",
"BaseEntity",
")",
"->",
"str",
":",
"if",
"data",
"[",
"FUNCTION",
"]",
"==",
"COMPLEX",
"and",
"NAMESPACE",
"in",
"data",
":",
"return",
"data",
"[",
"NAME",
"]",
"if",
"VARIANTS",
"in",
"data",
":",... | Calculate the canonical name for a given node.
If it is a simple node, uses the already given name. Otherwise, it uses the BEL string. | [
"Calculate",
"the",
"canonical",
"name",
"for",
"a",
"given",
"node",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/canonicalize.py#L309-L335 | train | 29,419 |
pybel/pybel | src/pybel/manager/query_manager.py | graph_from_edges | def graph_from_edges(edges: Iterable[Edge], **kwargs) -> BELGraph:
"""Build a BEL graph from edges."""
graph = BELGraph(**kwargs)
for edge in edges:
edge.insert_into_graph(graph)
return graph | python | def graph_from_edges(edges: Iterable[Edge], **kwargs) -> BELGraph:
"""Build a BEL graph from edges."""
graph = BELGraph(**kwargs)
for edge in edges:
edge.insert_into_graph(graph)
return graph | [
"def",
"graph_from_edges",
"(",
"edges",
":",
"Iterable",
"[",
"Edge",
"]",
",",
"*",
"*",
"kwargs",
")",
"->",
"BELGraph",
":",
"graph",
"=",
"BELGraph",
"(",
"*",
"*",
"kwargs",
")",
"for",
"edge",
"in",
"edges",
":",
"edge",
".",
"insert_into_graph"... | Build a BEL graph from edges. | [
"Build",
"a",
"BEL",
"graph",
"from",
"edges",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L22-L29 | train | 29,420 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.query_nodes | def query_nodes(self,
bel: Optional[str] = None,
type: Optional[str] = None,
namespace: Optional[str] = None,
name: Optional[str] = None,
) -> List[Node]:
"""Query nodes in the database.
:param bel: BEL term that describes the biological entity. e.g. ``p(HGNC:APP)``
:param type: Type of the biological entity. e.g. Protein
:param namespace: Namespace keyword that is used in BEL. e.g. HGNC
:param name: Name of the biological entity. e.g. APP
"""
q = self.session.query(Node)
if bel:
q = q.filter(Node.bel.contains(bel))
if type:
q = q.filter(Node.type == type)
if namespace or name:
q = q.join(NamespaceEntry)
if namespace:
q = q.join(Namespace).filter(Namespace.keyword.contains(namespace))
if name:
q = q.filter(NamespaceEntry.name.contains(name))
return q | python | def query_nodes(self,
bel: Optional[str] = None,
type: Optional[str] = None,
namespace: Optional[str] = None,
name: Optional[str] = None,
) -> List[Node]:
"""Query nodes in the database.
:param bel: BEL term that describes the biological entity. e.g. ``p(HGNC:APP)``
:param type: Type of the biological entity. e.g. Protein
:param namespace: Namespace keyword that is used in BEL. e.g. HGNC
:param name: Name of the biological entity. e.g. APP
"""
q = self.session.query(Node)
if bel:
q = q.filter(Node.bel.contains(bel))
if type:
q = q.filter(Node.type == type)
if namespace or name:
q = q.join(NamespaceEntry)
if namespace:
q = q.join(Namespace).filter(Namespace.keyword.contains(namespace))
if name:
q = q.filter(NamespaceEntry.name.contains(name))
return q | [
"def",
"query_nodes",
"(",
"self",
",",
"bel",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"type",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"namespace",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"name",
":",
"Optional",... | Query nodes in the database.
:param bel: BEL term that describes the biological entity. e.g. ``p(HGNC:APP)``
:param type: Type of the biological entity. e.g. Protein
:param namespace: Namespace keyword that is used in BEL. e.g. HGNC
:param name: Name of the biological entity. e.g. APP | [
"Query",
"nodes",
"in",
"the",
"database",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L39-L69 | train | 29,421 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.get_edges_with_citation | def get_edges_with_citation(self, citation: Citation) -> List[Edge]:
"""Get the edges with the given citation."""
return self.session.query(Edge).join(Evidence).filter(Evidence.citation == citation) | python | def get_edges_with_citation(self, citation: Citation) -> List[Edge]:
"""Get the edges with the given citation."""
return self.session.query(Edge).join(Evidence).filter(Evidence.citation == citation) | [
"def",
"get_edges_with_citation",
"(",
"self",
",",
"citation",
":",
"Citation",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"join",
"(",
"Evidence",
")",
".",
"filter",
"(",
"Evidenc... | Get the edges with the given citation. | [
"Get",
"the",
"edges",
"with",
"the",
"given",
"citation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L75-L77 | train | 29,422 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.get_edges_with_citations | def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]:
"""Get edges with one of the given citations."""
return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all() | python | def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]:
"""Get edges with one of the given citations."""
return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all() | [
"def",
"get_edges_with_citations",
"(",
"self",
",",
"citations",
":",
"Iterable",
"[",
"Citation",
"]",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"join",
"(",
"Evidence",
")",
".",... | Get edges with one of the given citations. | [
"Get",
"edges",
"with",
"one",
"of",
"the",
"given",
"citations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L79-L81 | train | 29,423 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.search_edges_with_evidence | def search_edges_with_evidence(self, evidence: str) -> List[Edge]:
"""Search edges with the given evidence.
:param evidence: A string to search evidences. Can use wildcard percent symbol (%).
"""
return self.session.query(Edge).join(Evidence).filter(Evidence.text.like(evidence)).all() | python | def search_edges_with_evidence(self, evidence: str) -> List[Edge]:
"""Search edges with the given evidence.
:param evidence: A string to search evidences. Can use wildcard percent symbol (%).
"""
return self.session.query(Edge).join(Evidence).filter(Evidence.text.like(evidence)).all() | [
"def",
"search_edges_with_evidence",
"(",
"self",
",",
"evidence",
":",
"str",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"join",
"(",
"Evidence",
")",
".",
"filter",
"(",
"Evidence"... | Search edges with the given evidence.
:param evidence: A string to search evidences. Can use wildcard percent symbol (%). | [
"Search",
"edges",
"with",
"the",
"given",
"evidence",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L83-L88 | train | 29,424 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.search_edges_with_bel | def search_edges_with_bel(self, bel: str) -> List[Edge]:
"""Search edges with given BEL.
:param bel: A BEL string to use as a search
"""
return self.session.query(Edge).filter(Edge.bel.like(bel)) | python | def search_edges_with_bel(self, bel: str) -> List[Edge]:
"""Search edges with given BEL.
:param bel: A BEL string to use as a search
"""
return self.session.query(Edge).filter(Edge.bel.like(bel)) | [
"def",
"search_edges_with_bel",
"(",
"self",
",",
"bel",
":",
"str",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"filter",
"(",
"Edge",
".",
"bel",
".",
"like",
"(",
"bel",
")",
... | Search edges with given BEL.
:param bel: A BEL string to use as a search | [
"Search",
"edges",
"with",
"given",
"BEL",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L90-L95 | train | 29,425 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager._add_edge_function_filter | def _add_edge_function_filter(query, edge_node_id, node_type):
"""See usage in self.query_edges."""
return query.join(Node, edge_node_id == Node.id).filter(Node.type == node_type) | python | def _add_edge_function_filter(query, edge_node_id, node_type):
"""See usage in self.query_edges."""
return query.join(Node, edge_node_id == Node.id).filter(Node.type == node_type) | [
"def",
"_add_edge_function_filter",
"(",
"query",
",",
"edge_node_id",
",",
"node_type",
")",
":",
"return",
"query",
".",
"join",
"(",
"Node",
",",
"edge_node_id",
"==",
"Node",
".",
"id",
")",
".",
"filter",
"(",
"Node",
".",
"type",
"==",
"node_type",
... | See usage in self.query_edges. | [
"See",
"usage",
"in",
"self",
".",
"query_edges",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L104-L106 | train | 29,426 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.query_edges | def query_edges(self,
bel: Optional[str] = None,
source_function: Optional[str] = None,
source: Union[None, str, Node] = None,
target_function: Optional[str] = None,
target: Union[None, str, Node] = None,
relation: Optional[str] = None,
):
"""Return a query over the edges in the database.
Usually this means that you should call ``list()`` or ``.all()`` on this result.
:param bel: BEL statement that represents the desired edge.
:param source_function: Filter source nodes with the given BEL function
:param source: BEL term of source node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param target_function: Filter target nodes with the given BEL function
:param target: BEL term of target node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param relation: The relation that should be present between source and target node.
"""
if bel:
return self.search_edges_with_bel(bel)
query = self.session.query(Edge)
if relation:
query = query.filter(Edge.relation.like(relation))
if source_function:
query = self._add_edge_function_filter(query, Edge.source_id, source_function)
if target_function:
query = self._add_edge_function_filter(query, Edge.target_id, target_function)
if source:
if isinstance(source, str):
source = self.query_nodes(bel=source)
if source.count() == 0:
return []
source = source.first() # FIXME what if this matches multiple?
query = query.filter(Edge.source == source)
elif isinstance(source, Node):
query = query.filter(Edge.source == source)
else:
raise TypeError('Invalid type of {}: {}'.format(source, source.__class__.__name__))
if target:
if isinstance(target, str):
targets = self.query_nodes(bel=target).all()
target = targets[0] # FIXME what if this matches multiple?
query = query.filter(Edge.target == target)
elif isinstance(target, Node):
query = query.filter(Edge.target == target)
else:
raise TypeError('Invalid type of {}: {}'.format(target, target.__class__.__name__))
return query | python | def query_edges(self,
bel: Optional[str] = None,
source_function: Optional[str] = None,
source: Union[None, str, Node] = None,
target_function: Optional[str] = None,
target: Union[None, str, Node] = None,
relation: Optional[str] = None,
):
"""Return a query over the edges in the database.
Usually this means that you should call ``list()`` or ``.all()`` on this result.
:param bel: BEL statement that represents the desired edge.
:param source_function: Filter source nodes with the given BEL function
:param source: BEL term of source node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param target_function: Filter target nodes with the given BEL function
:param target: BEL term of target node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param relation: The relation that should be present between source and target node.
"""
if bel:
return self.search_edges_with_bel(bel)
query = self.session.query(Edge)
if relation:
query = query.filter(Edge.relation.like(relation))
if source_function:
query = self._add_edge_function_filter(query, Edge.source_id, source_function)
if target_function:
query = self._add_edge_function_filter(query, Edge.target_id, target_function)
if source:
if isinstance(source, str):
source = self.query_nodes(bel=source)
if source.count() == 0:
return []
source = source.first() # FIXME what if this matches multiple?
query = query.filter(Edge.source == source)
elif isinstance(source, Node):
query = query.filter(Edge.source == source)
else:
raise TypeError('Invalid type of {}: {}'.format(source, source.__class__.__name__))
if target:
if isinstance(target, str):
targets = self.query_nodes(bel=target).all()
target = targets[0] # FIXME what if this matches multiple?
query = query.filter(Edge.target == target)
elif isinstance(target, Node):
query = query.filter(Edge.target == target)
else:
raise TypeError('Invalid type of {}: {}'.format(target, target.__class__.__name__))
return query | [
"def",
"query_edges",
"(",
"self",
",",
"bel",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"source_function",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"source",
":",
"Union",
"[",
"None",
",",
"str",
",",
"Node",
"]",
"=",
"None"... | Return a query over the edges in the database.
Usually this means that you should call ``list()`` or ``.all()`` on this result.
:param bel: BEL statement that represents the desired edge.
:param source_function: Filter source nodes with the given BEL function
:param source: BEL term of source node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param target_function: Filter target nodes with the given BEL function
:param target: BEL term of target node e.g. ``p(HGNC:APP)`` or :class:`Node` object.
:param relation: The relation that should be present between source and target node. | [
"Return",
"a",
"query",
"over",
"the",
"edges",
"in",
"the",
"database",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L108-L163 | train | 29,427 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.query_citations | def query_citations(self,
type: Optional[str] = None,
reference: Optional[str] = None,
name: Optional[str] = None,
author: Union[None, str, List[str]] = None,
date: Union[None, str, datetime.date] = None,
evidence_text: Optional[str] = None,
) -> List[Citation]:
"""Query citations in the database.
:param type: Type of the citation. e.g. PubMed
:param reference: The identifier used for the citation. e.g. PubMed_ID
:param name: Title of the citation.
:param author: The name or a list of names of authors participated in the citation.
:param date: Publishing date of the citation.
:param evidence_text:
"""
query = self.session.query(Citation)
if author is not None:
query = query.join(Author, Citation.authors)
if isinstance(author, str):
query = query.filter(Author.name.like(author))
elif isinstance(author, Iterable):
query = query.filter(Author.has_name_in(set(author)))
else:
raise TypeError
if type and not reference:
query = query.filter(Citation.type.like(type))
elif reference and type:
query = query.filter(Citation.reference == reference)
elif reference and not type:
raise ValueError('reference specified without type')
if name:
query = query.filter(Citation.name.like(name))
if date:
if isinstance(date, datetime.date):
query = query.filter(Citation.date == date)
elif isinstance(date, str):
query = query.filter(Citation.date == parse_datetime(date))
if evidence_text:
query = query.join(Evidence).filter(Evidence.text.like(evidence_text))
return query.all() | python | def query_citations(self,
type: Optional[str] = None,
reference: Optional[str] = None,
name: Optional[str] = None,
author: Union[None, str, List[str]] = None,
date: Union[None, str, datetime.date] = None,
evidence_text: Optional[str] = None,
) -> List[Citation]:
"""Query citations in the database.
:param type: Type of the citation. e.g. PubMed
:param reference: The identifier used for the citation. e.g. PubMed_ID
:param name: Title of the citation.
:param author: The name or a list of names of authors participated in the citation.
:param date: Publishing date of the citation.
:param evidence_text:
"""
query = self.session.query(Citation)
if author is not None:
query = query.join(Author, Citation.authors)
if isinstance(author, str):
query = query.filter(Author.name.like(author))
elif isinstance(author, Iterable):
query = query.filter(Author.has_name_in(set(author)))
else:
raise TypeError
if type and not reference:
query = query.filter(Citation.type.like(type))
elif reference and type:
query = query.filter(Citation.reference == reference)
elif reference and not type:
raise ValueError('reference specified without type')
if name:
query = query.filter(Citation.name.like(name))
if date:
if isinstance(date, datetime.date):
query = query.filter(Citation.date == date)
elif isinstance(date, str):
query = query.filter(Citation.date == parse_datetime(date))
if evidence_text:
query = query.join(Evidence).filter(Evidence.text.like(evidence_text))
return query.all() | [
"def",
"query_citations",
"(",
"self",
",",
"type",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"reference",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"author",
":",
"Uni... | Query citations in the database.
:param type: Type of the citation. e.g. PubMed
:param reference: The identifier used for the citation. e.g. PubMed_ID
:param name: Title of the citation.
:param author: The name or a list of names of authors participated in the citation.
:param date: Publishing date of the citation.
:param evidence_text: | [
"Query",
"citations",
"in",
"the",
"database",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L165-L212 | train | 29,428 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.query_edges_by_pubmed_identifiers | def query_edges_by_pubmed_identifiers(self, pubmed_identifiers: List[str]) -> List[Edge]:
"""Get all edges annotated to the documents identified by the given PubMed identifiers."""
fi = and_(Citation.type == CITATION_TYPE_PUBMED, Citation.reference.in_(pubmed_identifiers))
return self.session.query(Edge).join(Evidence).join(Citation).filter(fi).all() | python | def query_edges_by_pubmed_identifiers(self, pubmed_identifiers: List[str]) -> List[Edge]:
"""Get all edges annotated to the documents identified by the given PubMed identifiers."""
fi = and_(Citation.type == CITATION_TYPE_PUBMED, Citation.reference.in_(pubmed_identifiers))
return self.session.query(Edge).join(Evidence).join(Citation).filter(fi).all() | [
"def",
"query_edges_by_pubmed_identifiers",
"(",
"self",
",",
"pubmed_identifiers",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"fi",
"=",
"and_",
"(",
"Citation",
".",
"type",
"==",
"CITATION_TYPE_PUBMED",
",",
"Citation",
".",
... | Get all edges annotated to the documents identified by the given PubMed identifiers. | [
"Get",
"all",
"edges",
"annotated",
"to",
"the",
"documents",
"identified",
"by",
"the",
"given",
"PubMed",
"identifiers",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L214-L217 | train | 29,429 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager._edge_both_nodes | def _edge_both_nodes(nodes: List[Node]):
"""Get edges where both the source and target are in the list of nodes."""
node_ids = [node.id for node in nodes]
return and_(
Edge.source_id.in_(node_ids),
Edge.target_id.in_(node_ids),
) | python | def _edge_both_nodes(nodes: List[Node]):
"""Get edges where both the source and target are in the list of nodes."""
node_ids = [node.id for node in nodes]
return and_(
Edge.source_id.in_(node_ids),
Edge.target_id.in_(node_ids),
) | [
"def",
"_edge_both_nodes",
"(",
"nodes",
":",
"List",
"[",
"Node",
"]",
")",
":",
"node_ids",
"=",
"[",
"node",
".",
"id",
"for",
"node",
"in",
"nodes",
"]",
"return",
"and_",
"(",
"Edge",
".",
"source_id",
".",
"in_",
"(",
"node_ids",
")",
",",
"E... | Get edges where both the source and target are in the list of nodes. | [
"Get",
"edges",
"where",
"both",
"the",
"source",
"and",
"target",
"are",
"in",
"the",
"list",
"of",
"nodes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L220-L227 | train | 29,430 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager._edge_one_node | def _edge_one_node(nodes: List[Node]):
"""Get edges where either the source or target are in the list of nodes.
Note: doing this with the nodes directly is not yet supported by SQLAlchemy
.. code-block:: python
return or_(
Edge.source.in_(nodes),
Edge.target.in_(nodes),
)
"""
node_ids = [node.id for node in nodes]
return or_(
Edge.source_id.in_(node_ids),
Edge.target_id.in_(node_ids),
) | python | def _edge_one_node(nodes: List[Node]):
"""Get edges where either the source or target are in the list of nodes.
Note: doing this with the nodes directly is not yet supported by SQLAlchemy
.. code-block:: python
return or_(
Edge.source.in_(nodes),
Edge.target.in_(nodes),
)
"""
node_ids = [node.id for node in nodes]
return or_(
Edge.source_id.in_(node_ids),
Edge.target_id.in_(node_ids),
) | [
"def",
"_edge_one_node",
"(",
"nodes",
":",
"List",
"[",
"Node",
"]",
")",
":",
"node_ids",
"=",
"[",
"node",
".",
"id",
"for",
"node",
"in",
"nodes",
"]",
"return",
"or_",
"(",
"Edge",
".",
"source_id",
".",
"in_",
"(",
"node_ids",
")",
",",
"Edge... | Get edges where either the source or target are in the list of nodes.
Note: doing this with the nodes directly is not yet supported by SQLAlchemy
.. code-block:: python
return or_(
Edge.source.in_(nodes),
Edge.target.in_(nodes),
) | [
"Get",
"edges",
"where",
"either",
"the",
"source",
"or",
"target",
"are",
"in",
"the",
"list",
"of",
"nodes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L237-L254 | train | 29,431 |
pybel/pybel | src/pybel/manager/query_manager.py | QueryManager.query_neighbors | def query_neighbors(self, nodes: List[Node]) -> List[Edge]:
"""Get all edges incident to any of the given nodes."""
return self.session.query(Edge).filter(self._edge_one_node(nodes)).all() | python | def query_neighbors(self, nodes: List[Node]) -> List[Edge]:
"""Get all edges incident to any of the given nodes."""
return self.session.query(Edge).filter(self._edge_one_node(nodes)).all() | [
"def",
"query_neighbors",
"(",
"self",
",",
"nodes",
":",
"List",
"[",
"Node",
"]",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"filter",
"(",
"self",
".",
"_edge_one_node",
"(",
... | Get all edges incident to any of the given nodes. | [
"Get",
"all",
"edges",
"incident",
"to",
"any",
"of",
"the",
"given",
"nodes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L256-L258 | train | 29,432 |
pybel/pybel | src/pybel/struct/grouping/annotations.py | get_subgraphs_by_annotation | def get_subgraphs_by_annotation(graph, annotation, sentinel=None):
"""Stratify the given graph into sub-graphs based on the values for edges' annotations.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to group by
:param Optional[str] sentinel: The value to stick unannotated edges into. If none, does not keep undefined.
:rtype: dict[str,pybel.BELGraph]
"""
if sentinel is not None:
subgraphs = _get_subgraphs_by_annotation_keep_undefined(graph, annotation, sentinel)
else:
subgraphs = _get_subgraphs_by_annotation_disregard_undefined(graph, annotation)
cleanup(graph, subgraphs)
return subgraphs | python | def get_subgraphs_by_annotation(graph, annotation, sentinel=None):
"""Stratify the given graph into sub-graphs based on the values for edges' annotations.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to group by
:param Optional[str] sentinel: The value to stick unannotated edges into. If none, does not keep undefined.
:rtype: dict[str,pybel.BELGraph]
"""
if sentinel is not None:
subgraphs = _get_subgraphs_by_annotation_keep_undefined(graph, annotation, sentinel)
else:
subgraphs = _get_subgraphs_by_annotation_disregard_undefined(graph, annotation)
cleanup(graph, subgraphs)
return subgraphs | [
"def",
"get_subgraphs_by_annotation",
"(",
"graph",
",",
"annotation",
",",
"sentinel",
"=",
"None",
")",
":",
"if",
"sentinel",
"is",
"not",
"None",
":",
"subgraphs",
"=",
"_get_subgraphs_by_annotation_keep_undefined",
"(",
"graph",
",",
"annotation",
",",
"senti... | Stratify the given graph into sub-graphs based on the values for edges' annotations.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to group by
:param Optional[str] sentinel: The value to stick unannotated edges into. If none, does not keep undefined.
:rtype: dict[str,pybel.BELGraph] | [
"Stratify",
"the",
"given",
"graph",
"into",
"sub",
"-",
"graphs",
"based",
"on",
"the",
"values",
"for",
"edges",
"annotations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/grouping/annotations.py#L51-L66 | train | 29,433 |
pybel/pybel | src/pybel/manager/utils.py | extract_shared_optional | def extract_shared_optional(bel_resource, definition_header: str = 'Namespace'):
"""Get the optional annotations shared by BEL namespace and annotation resource documents.
:param dict bel_resource: A configuration dictionary representing a BEL resource
:param definition_header: ``Namespace`` or ``AnnotationDefinition``
:rtype: dict
"""
shared_mapping = {
'description': (definition_header, 'DescriptionString'),
'version': (definition_header, 'VersionString'),
'author': ('Author', 'NameString'),
'license': ('Author', 'CopyrightString'),
'contact': ('Author', 'ContactInfoString'),
'citation': ('Citation', 'NameString'),
'citation_description': ('Citation', 'DescriptionString'),
'citation_version': ('Citation', 'PublishedVersionString'),
'citation_url': ('Citation', 'ReferenceURL'),
}
result = {}
update_insert_values(bel_resource, shared_mapping, result)
if 'PublishedDate' in bel_resource.get('Citation', {}):
result['citation_published'] = parse_datetime(bel_resource['Citation']['PublishedDate'])
return result | python | def extract_shared_optional(bel_resource, definition_header: str = 'Namespace'):
"""Get the optional annotations shared by BEL namespace and annotation resource documents.
:param dict bel_resource: A configuration dictionary representing a BEL resource
:param definition_header: ``Namespace`` or ``AnnotationDefinition``
:rtype: dict
"""
shared_mapping = {
'description': (definition_header, 'DescriptionString'),
'version': (definition_header, 'VersionString'),
'author': ('Author', 'NameString'),
'license': ('Author', 'CopyrightString'),
'contact': ('Author', 'ContactInfoString'),
'citation': ('Citation', 'NameString'),
'citation_description': ('Citation', 'DescriptionString'),
'citation_version': ('Citation', 'PublishedVersionString'),
'citation_url': ('Citation', 'ReferenceURL'),
}
result = {}
update_insert_values(bel_resource, shared_mapping, result)
if 'PublishedDate' in bel_resource.get('Citation', {}):
result['citation_published'] = parse_datetime(bel_resource['Citation']['PublishedDate'])
return result | [
"def",
"extract_shared_optional",
"(",
"bel_resource",
",",
"definition_header",
":",
"str",
"=",
"'Namespace'",
")",
":",
"shared_mapping",
"=",
"{",
"'description'",
":",
"(",
"definition_header",
",",
"'DescriptionString'",
")",
",",
"'version'",
":",
"(",
"def... | Get the optional annotations shared by BEL namespace and annotation resource documents.
:param dict bel_resource: A configuration dictionary representing a BEL resource
:param definition_header: ``Namespace`` or ``AnnotationDefinition``
:rtype: dict | [
"Get",
"the",
"optional",
"annotations",
"shared",
"by",
"BEL",
"namespace",
"and",
"annotation",
"resource",
"documents",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/utils.py#L23-L49 | train | 29,434 |
pybel/pybel | src/pybel/manager/utils.py | update_insert_values | def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
"""Update the value dictionary with a BEL resource dictionary."""
for database_column, (section, key) in mapping.items():
if section in bel_resource and key in bel_resource[section]:
values[database_column] = bel_resource[section][key] | python | def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
"""Update the value dictionary with a BEL resource dictionary."""
for database_column, (section, key) in mapping.items():
if section in bel_resource and key in bel_resource[section]:
values[database_column] = bel_resource[section][key] | [
"def",
"update_insert_values",
"(",
"bel_resource",
":",
"Mapping",
",",
"mapping",
":",
"Mapping",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"values",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"None",
":",
"for",
... | Update the value dictionary with a BEL resource dictionary. | [
"Update",
"the",
"value",
"dictionary",
"with",
"a",
"BEL",
"resource",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/utils.py#L52-L56 | train | 29,435 |
pybel/pybel | src/pybel/manager/utils.py | int_or_str | def int_or_str(v: Optional[str]) -> Union[None, int, str]:
"""Safe converts an string represent an integer to an integer or passes through ``None``."""
if v is None:
return
try:
return int(v)
except ValueError:
return v | python | def int_or_str(v: Optional[str]) -> Union[None, int, str]:
"""Safe converts an string represent an integer to an integer or passes through ``None``."""
if v is None:
return
try:
return int(v)
except ValueError:
return v | [
"def",
"int_or_str",
"(",
"v",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Union",
"[",
"None",
",",
"int",
",",
"str",
"]",
":",
"if",
"v",
"is",
"None",
":",
"return",
"try",
":",
"return",
"int",
"(",
"v",
")",
"except",
"ValueError",
":",
... | Safe converts an string represent an integer to an integer or passes through ``None``. | [
"Safe",
"converts",
"an",
"string",
"represent",
"an",
"integer",
"to",
"an",
"integer",
"or",
"passes",
"through",
"None",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/utils.py#L59-L66 | train | 29,436 |
pybel/pybel | src/pybel/io/web.py | from_web | def from_web(network_id: int, host: Optional[str] = None) -> BELGraph:
"""Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or the environment as ``PYBEL_REMOTE_HOST`` Defaults to
:data:`pybel.constants.DEFAULT_SERVICE_URL`
:rtype: pybel.BELGraph
"""
if host is None:
host = _get_host()
url = host + GET_ENDPOINT.format(network_id)
res = requests.get(url)
graph_json = res.json()
graph = from_json(graph_json)
return graph | python | def from_web(network_id: int, host: Optional[str] = None) -> BELGraph:
"""Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or the environment as ``PYBEL_REMOTE_HOST`` Defaults to
:data:`pybel.constants.DEFAULT_SERVICE_URL`
:rtype: pybel.BELGraph
"""
if host is None:
host = _get_host()
url = host + GET_ENDPOINT.format(network_id)
res = requests.get(url)
graph_json = res.json()
graph = from_json(graph_json)
return graph | [
"def",
"from_web",
"(",
"network_id",
":",
"int",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"BELGraph",
":",
"if",
"host",
"is",
"None",
":",
"host",
"=",
"_get_host",
"(",
")",
"url",
"=",
"host",
"+",
"GET_ENDPOINT",
... | Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or the environment as ``PYBEL_REMOTE_HOST`` Defaults to
:data:`pybel.constants.DEFAULT_SERVICE_URL`
:rtype: pybel.BELGraph | [
"Retrieve",
"a",
"public",
"network",
"from",
"BEL",
"Commons",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/web.py#L103-L121 | train | 29,437 |
pybel/pybel | src/pybel/parser/modifiers/fusion.py | get_fusion_language | def get_fusion_language(identifier: ParserElement, permissive: bool = True) -> ParserElement:
"""Build a fusion parser."""
range_coordinate = Suppress('"') + range_coordinate_unquoted + Suppress('"')
if permissive: # permissive to wrong quoting
range_coordinate = range_coordinate | range_coordinate_unquoted
return fusion_tags + nest(
Group(identifier)(PARTNER_5P),
Group(range_coordinate)(RANGE_5P),
Group(identifier)(PARTNER_3P),
Group(range_coordinate)(RANGE_3P),
) | python | def get_fusion_language(identifier: ParserElement, permissive: bool = True) -> ParserElement:
"""Build a fusion parser."""
range_coordinate = Suppress('"') + range_coordinate_unquoted + Suppress('"')
if permissive: # permissive to wrong quoting
range_coordinate = range_coordinate | range_coordinate_unquoted
return fusion_tags + nest(
Group(identifier)(PARTNER_5P),
Group(range_coordinate)(RANGE_5P),
Group(identifier)(PARTNER_3P),
Group(range_coordinate)(RANGE_3P),
) | [
"def",
"get_fusion_language",
"(",
"identifier",
":",
"ParserElement",
",",
"permissive",
":",
"bool",
"=",
"True",
")",
"->",
"ParserElement",
":",
"range_coordinate",
"=",
"Suppress",
"(",
"'\"'",
")",
"+",
"range_coordinate_unquoted",
"+",
"Suppress",
"(",
"'... | Build a fusion parser. | [
"Build",
"a",
"fusion",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/fusion.py#L74-L86 | train | 29,438 |
pybel/pybel | src/pybel/parser/modifiers/fusion.py | get_legacy_fusion_langauge | def get_legacy_fusion_langauge(identifier: ParserElement, reference: str) -> ParserElement:
"""Build a legacy fusion parser."""
break_start = (ppc.integer | '?').setParseAction(_fusion_break_handler_wrapper(reference, start=True))
break_end = (ppc.integer | '?').setParseAction(_fusion_break_handler_wrapper(reference, start=False))
res = (
identifier(PARTNER_5P) +
WCW +
fusion_tags +
nest(
identifier(PARTNER_3P) +
Optional(WCW + Group(break_start)(RANGE_5P) + WCW + Group(break_end)(RANGE_3P))
)
)
res.setParseAction(_fusion_legacy_handler)
return res | python | def get_legacy_fusion_langauge(identifier: ParserElement, reference: str) -> ParserElement:
"""Build a legacy fusion parser."""
break_start = (ppc.integer | '?').setParseAction(_fusion_break_handler_wrapper(reference, start=True))
break_end = (ppc.integer | '?').setParseAction(_fusion_break_handler_wrapper(reference, start=False))
res = (
identifier(PARTNER_5P) +
WCW +
fusion_tags +
nest(
identifier(PARTNER_3P) +
Optional(WCW + Group(break_start)(RANGE_5P) + WCW + Group(break_end)(RANGE_3P))
)
)
res.setParseAction(_fusion_legacy_handler)
return res | [
"def",
"get_legacy_fusion_langauge",
"(",
"identifier",
":",
"ParserElement",
",",
"reference",
":",
"str",
")",
"->",
"ParserElement",
":",
"break_start",
"=",
"(",
"ppc",
".",
"integer",
"|",
"'?'",
")",
".",
"setParseAction",
"(",
"_fusion_break_handler_wrapper... | Build a legacy fusion parser. | [
"Build",
"a",
"legacy",
"fusion",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/fusion.py#L89-L106 | train | 29,439 |
pybel/pybel | src/pybel/parser/modifiers/fusion.py | _fusion_legacy_handler | def _fusion_legacy_handler(_, __, tokens):
"""Handle a legacy fusion."""
if RANGE_5P not in tokens:
tokens[RANGE_5P] = {FUSION_MISSING: '?'}
if RANGE_3P not in tokens:
tokens[RANGE_3P] = {FUSION_MISSING: '?'}
return tokens | python | def _fusion_legacy_handler(_, __, tokens):
"""Handle a legacy fusion."""
if RANGE_5P not in tokens:
tokens[RANGE_5P] = {FUSION_MISSING: '?'}
if RANGE_3P not in tokens:
tokens[RANGE_3P] = {FUSION_MISSING: '?'}
return tokens | [
"def",
"_fusion_legacy_handler",
"(",
"_",
",",
"__",
",",
"tokens",
")",
":",
"if",
"RANGE_5P",
"not",
"in",
"tokens",
":",
"tokens",
"[",
"RANGE_5P",
"]",
"=",
"{",
"FUSION_MISSING",
":",
"'?'",
"}",
"if",
"RANGE_3P",
"not",
"in",
"tokens",
":",
"tok... | Handle a legacy fusion. | [
"Handle",
"a",
"legacy",
"fusion",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/fusion.py#L109-L115 | train | 29,440 |
pybel/pybel | src/pybel/io/extras.py | to_csv | def to_csv(graph: BELGraph, file: Optional[TextIO] = None, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated edge list.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
4. Edge data dictionary
See the Data Models section of the documentation for which data are stored in the edge data dictionary, such
as queryable information about transforms on the subject and object and their associated metadata.
"""
if sep is None:
sep = '\t'
for u, v, data in graph.edges(data=True):
print(
graph.edge_to_bel(u, v, edge_data=data, sep=sep),
json.dumps(data),
sep=sep,
file=file,
) | python | def to_csv(graph: BELGraph, file: Optional[TextIO] = None, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated edge list.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
4. Edge data dictionary
See the Data Models section of the documentation for which data are stored in the edge data dictionary, such
as queryable information about transforms on the subject and object and their associated metadata.
"""
if sep is None:
sep = '\t'
for u, v, data in graph.edges(data=True):
print(
graph.edge_to_bel(u, v, edge_data=data, sep=sep),
json.dumps(data),
sep=sep,
file=file,
) | [
"def",
"to_csv",
"(",
"graph",
":",
"BELGraph",
",",
"file",
":",
"Optional",
"[",
"TextIO",
"]",
"=",
"None",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"sep",
"is",
"None",
":",
"sep",
"=",
"'\\t'",... | Write the graph as a tab-separated edge list.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
4. Edge data dictionary
See the Data Models section of the documentation for which data are stored in the edge data dictionary, such
as queryable information about transforms on the subject and object and their associated metadata. | [
"Write",
"the",
"graph",
"as",
"a",
"tab",
"-",
"separated",
"edge",
"list",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/extras.py#L46-L68 | train | 29,441 |
pybel/pybel | src/pybel/io/extras.py | to_csv_path | def to_csv_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated edge list to a file at the given path."""
with open(path, 'w') as file:
to_csv(graph, file, sep=sep) | python | def to_csv_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated edge list to a file at the given path."""
with open(path, 'w') as file:
to_csv(graph, file, sep=sep) | [
"def",
"to_csv_path",
"(",
"graph",
":",
"BELGraph",
",",
"path",
":",
"str",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"file",
":",
"to_csv",
"(",
"grap... | Write the graph as a tab-separated edge list to a file at the given path. | [
"Write",
"the",
"graph",
"as",
"a",
"tab",
"-",
"separated",
"edge",
"list",
"to",
"a",
"file",
"at",
"the",
"given",
"path",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/extras.py#L71-L74 | train | 29,442 |
pybel/pybel | src/pybel/io/extras.py | to_sif | def to_sif(graph: BELGraph, file: Optional[TextIO] = None, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated SIF file.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
This format is simple and can be used readily with many applications, but is lossy in that it does not include
relation metadata.
"""
if sep is None:
sep = '\t'
for u, v, data in graph.edges(data=True):
print(
graph.edge_to_bel(u, v, edge_data=data, sep=sep),
file=file,
) | python | def to_sif(graph: BELGraph, file: Optional[TextIO] = None, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated SIF file.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
This format is simple and can be used readily with many applications, but is lossy in that it does not include
relation metadata.
"""
if sep is None:
sep = '\t'
for u, v, data in graph.edges(data=True):
print(
graph.edge_to_bel(u, v, edge_data=data, sep=sep),
file=file,
) | [
"def",
"to_sif",
"(",
"graph",
":",
"BELGraph",
",",
"file",
":",
"Optional",
"[",
"TextIO",
"]",
"=",
"None",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"sep",
"is",
"None",
":",
"sep",
"=",
"'\\t'",... | Write the graph as a tab-separated SIF file.
The resulting file will contain the following columns:
1. Source BEL term
2. Relation
3. Target BEL term
This format is simple and can be used readily with many applications, but is lossy in that it does not include
relation metadata. | [
"Write",
"the",
"graph",
"as",
"a",
"tab",
"-",
"separated",
"SIF",
"file",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/extras.py#L77-L96 | train | 29,443 |
pybel/pybel | src/pybel/io/extras.py | to_sif_path | def to_sif_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated SIF file. to a file at the given path."""
with open(path, 'w') as file:
to_sif(graph, file, sep=sep) | python | def to_sif_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
"""Write the graph as a tab-separated SIF file. to a file at the given path."""
with open(path, 'w') as file:
to_sif(graph, file, sep=sep) | [
"def",
"to_sif_path",
"(",
"graph",
":",
"BELGraph",
",",
"path",
":",
"str",
",",
"sep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"file",
":",
"to_sif",
"(",
"grap... | Write the graph as a tab-separated SIF file. to a file at the given path. | [
"Write",
"the",
"graph",
"as",
"a",
"tab",
"-",
"separated",
"SIF",
"file",
".",
"to",
"a",
"file",
"at",
"the",
"given",
"path",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/extras.py#L99-L102 | train | 29,444 |
pybel/pybel | src/pybel/struct/query/seeding.py | Seeding.append_sample | def append_sample(self, **kwargs) -> 'Seeding':
"""Add seed induction methods.
Kwargs can have ``number_edges`` or ``number_seed_nodes``.
:returns: self for fluid API
"""
data = {
'seed': random.randint(0, 1000000)
}
data.update(kwargs)
return self._append_seed(SEED_TYPE_SAMPLE, data) | python | def append_sample(self, **kwargs) -> 'Seeding':
"""Add seed induction methods.
Kwargs can have ``number_edges`` or ``number_seed_nodes``.
:returns: self for fluid API
"""
data = {
'seed': random.randint(0, 1000000)
}
data.update(kwargs)
return self._append_seed(SEED_TYPE_SAMPLE, data) | [
"def",
"append_sample",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Seeding'",
":",
"data",
"=",
"{",
"'seed'",
":",
"random",
".",
"randint",
"(",
"0",
",",
"1000000",
")",
"}",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
"... | Add seed induction methods.
Kwargs can have ``number_edges`` or ``number_seed_nodes``.
:returns: self for fluid API | [
"Add",
"seed",
"induction",
"methods",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/seeding.py#L57-L69 | train | 29,445 |
pybel/pybel | src/pybel/struct/query/seeding.py | Seeding.run | def run(self, graph):
"""Seed the graph or return none if not possible.
:type graph: pybel.BELGraph
:rtype: Optional[pybel.BELGraph]
"""
if not self:
log.debug('no seeding, returning graph: %s', graph)
return graph
subgraphs = []
for seed in self:
seed_method, seed_data = seed[SEED_METHOD], seed[SEED_DATA]
log.debug('seeding with %s: %s', seed_method, seed_data)
subgraph = get_subgraph(graph, seed_method=seed_method, seed_data=seed_data)
if subgraph is None:
log.debug('seed returned empty graph: %s', seed)
continue
subgraphs.append(subgraph)
if not subgraphs:
log.debug('no subgraphs returned')
return
return union(subgraphs) | python | def run(self, graph):
"""Seed the graph or return none if not possible.
:type graph: pybel.BELGraph
:rtype: Optional[pybel.BELGraph]
"""
if not self:
log.debug('no seeding, returning graph: %s', graph)
return graph
subgraphs = []
for seed in self:
seed_method, seed_data = seed[SEED_METHOD], seed[SEED_DATA]
log.debug('seeding with %s: %s', seed_method, seed_data)
subgraph = get_subgraph(graph, seed_method=seed_method, seed_data=seed_data)
if subgraph is None:
log.debug('seed returned empty graph: %s', seed)
continue
subgraphs.append(subgraph)
if not subgraphs:
log.debug('no subgraphs returned')
return
return union(subgraphs) | [
"def",
"run",
"(",
"self",
",",
"graph",
")",
":",
"if",
"not",
"self",
":",
"log",
".",
"debug",
"(",
"'no seeding, returning graph: %s'",
",",
"graph",
")",
"return",
"graph",
"subgraphs",
"=",
"[",
"]",
"for",
"seed",
"in",
"self",
":",
"seed_method",... | Seed the graph or return none if not possible.
:type graph: pybel.BELGraph
:rtype: Optional[pybel.BELGraph] | [
"Seed",
"the",
"graph",
"or",
"return",
"none",
"if",
"not",
"possible",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/seeding.py#L91-L119 | train | 29,446 |
pybel/pybel | src/pybel/struct/query/seeding.py | Seeding.dump | def dump(self, file, sort_keys: bool = True, **kwargs) -> None:
"""Dump this seeding container to a file as JSON."""
json.dump(self.to_json(), file, sort_keys=sort_keys, **kwargs) | python | def dump(self, file, sort_keys: bool = True, **kwargs) -> None:
"""Dump this seeding container to a file as JSON."""
json.dump(self.to_json(), file, sort_keys=sort_keys, **kwargs) | [
"def",
"dump",
"(",
"self",
",",
"file",
",",
"sort_keys",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"json",
".",
"dump",
"(",
"self",
".",
"to_json",
"(",
")",
",",
"file",
",",
"sort_keys",
"=",
"sort_keys",
","... | Dump this seeding container to a file as JSON. | [
"Dump",
"this",
"seeding",
"container",
"to",
"a",
"file",
"as",
"JSON",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/seeding.py#L125-L127 | train | 29,447 |
pybel/pybel | src/pybel/struct/query/seeding.py | Seeding.dumps | def dumps(self, sort_keys: bool = True, **kwargs) -> str:
"""Dump this query to a string as JSON."""
return json.dumps(self.to_json(), sort_keys=sort_keys, **kwargs) | python | def dumps(self, sort_keys: bool = True, **kwargs) -> str:
"""Dump this query to a string as JSON."""
return json.dumps(self.to_json(), sort_keys=sort_keys, **kwargs) | [
"def",
"dumps",
"(",
"self",
",",
"sort_keys",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_json",
"(",
")",
",",
"sort_keys",
"=",
"sort_keys",
",",
"*",
"*",
"kw... | Dump this query to a string as JSON. | [
"Dump",
"this",
"query",
"to",
"a",
"string",
"as",
"JSON",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/seeding.py#L129-L131 | train | 29,448 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | _single_function_inclusion_filter_builder | def _single_function_inclusion_filter_builder(func: str) -> NodePredicate: # noqa: D202
"""Build a function inclusion filter for a single function."""
def function_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has the enclosed function."""
return node.function == func
return function_inclusion_filter | python | def _single_function_inclusion_filter_builder(func: str) -> NodePredicate: # noqa: D202
"""Build a function inclusion filter for a single function."""
def function_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has the enclosed function."""
return node.function == func
return function_inclusion_filter | [
"def",
"_single_function_inclusion_filter_builder",
"(",
"func",
":",
"str",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"def",
"function_inclusion_filter",
"(",
"_",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"\"\"\"Pass only for ... | Build a function inclusion filter for a single function. | [
"Build",
"a",
"function",
"inclusion",
"filter",
"for",
"a",
"single",
"function",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L38-L45 | train | 29,449 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | _collection_function_inclusion_builder | def _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate:
"""Build a function inclusion filter for a collection of functions."""
funcs = set(funcs)
if not funcs:
raise ValueError('can not build function inclusion filter with empty list of functions')
def functions_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that is one of the enclosed functions."""
return node.function in funcs
return functions_inclusion_filter | python | def _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate:
"""Build a function inclusion filter for a collection of functions."""
funcs = set(funcs)
if not funcs:
raise ValueError('can not build function inclusion filter with empty list of functions')
def functions_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that is one of the enclosed functions."""
return node.function in funcs
return functions_inclusion_filter | [
"def",
"_collection_function_inclusion_builder",
"(",
"funcs",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"NodePredicate",
":",
"funcs",
"=",
"set",
"(",
"funcs",
")",
"if",
"not",
"funcs",
":",
"raise",
"ValueError",
"(",
"'can not build function inclusion filt... | Build a function inclusion filter for a collection of functions. | [
"Build",
"a",
"function",
"inclusion",
"filter",
"for",
"a",
"collection",
"of",
"functions",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L48-L59 | train | 29,450 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | data_missing_key_builder | def data_missing_key_builder(key: str) -> NodePredicate: # noqa: D202
"""Build a filter that passes only on nodes that don't have the given key in their data dictionary.
:param str key: A key for the node's data dictionary
"""
def data_does_not_contain_key(graph: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that doesn't contain the enclosed key in its data dictionary."""
return key not in graph.nodes[node]
return data_does_not_contain_key | python | def data_missing_key_builder(key: str) -> NodePredicate: # noqa: D202
"""Build a filter that passes only on nodes that don't have the given key in their data dictionary.
:param str key: A key for the node's data dictionary
"""
def data_does_not_contain_key(graph: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that doesn't contain the enclosed key in its data dictionary."""
return key not in graph.nodes[node]
return data_does_not_contain_key | [
"def",
"data_missing_key_builder",
"(",
"key",
":",
"str",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"def",
"data_does_not_contain_key",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"\"\"\"Pass only for a node that do... | Build a filter that passes only on nodes that don't have the given key in their data dictionary.
:param str key: A key for the node's data dictionary | [
"Build",
"a",
"filter",
"that",
"passes",
"only",
"on",
"nodes",
"that",
"don",
"t",
"have",
"the",
"given",
"key",
"in",
"their",
"data",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L62-L72 | train | 29,451 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | build_node_data_search | def build_node_data_search(key: str, data_predicate: Callable[[Any], bool]) -> NodePredicate: # noqa: D202
"""Build a filter for nodes whose associated data with the given key passes the given predicate.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary
"""
def node_data_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass if the given node has a given data annotated and passes the contained filter."""
value = node.get(key)
return value is not None and data_predicate(value)
return node_data_filter | python | def build_node_data_search(key: str, data_predicate: Callable[[Any], bool]) -> NodePredicate: # noqa: D202
"""Build a filter for nodes whose associated data with the given key passes the given predicate.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary
"""
def node_data_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass if the given node has a given data annotated and passes the contained filter."""
value = node.get(key)
return value is not None and data_predicate(value)
return node_data_filter | [
"def",
"build_node_data_search",
"(",
"key",
":",
"str",
",",
"data_predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"def",
"node_data_filter",
"(",
"_",
":",
"BELGraph",
",",
"node",
":"... | Build a filter for nodes whose associated data with the given key passes the given predicate.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary | [
"Build",
"a",
"filter",
"for",
"nodes",
"whose",
"associated",
"data",
"with",
"the",
"given",
"key",
"passes",
"the",
"given",
"predicate",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L75-L87 | train | 29,452 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | build_node_graph_data_search | def build_node_graph_data_search(key: str, data_predicate: Callable[[Any], bool]): # noqa: D202
"""Build a function for testing data associated with the node in the graph.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary
"""
def node_data_filter(graph: BELGraph, node: BaseEntity) -> bool:
"""Pass if the given node has a given data annotated and passes the contained filter."""
value = graph.nodes[node].get(key)
return value is not None and data_predicate(value)
return node_data_filter | python | def build_node_graph_data_search(key: str, data_predicate: Callable[[Any], bool]): # noqa: D202
"""Build a function for testing data associated with the node in the graph.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary
"""
def node_data_filter(graph: BELGraph, node: BaseEntity) -> bool:
"""Pass if the given node has a given data annotated and passes the contained filter."""
value = graph.nodes[node].get(key)
return value is not None and data_predicate(value)
return node_data_filter | [
"def",
"build_node_graph_data_search",
"(",
"key",
":",
"str",
",",
"data_predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
")",
":",
"# noqa: D202",
"def",
"node_data_filter",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",... | Build a function for testing data associated with the node in the graph.
:param key: The node data dictionary key to check
:param data_predicate: The filter to apply to the node data dictionary | [
"Build",
"a",
"function",
"for",
"testing",
"data",
"associated",
"with",
"the",
"node",
"in",
"the",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L90-L102 | train | 29,453 |
pybel/pybel | src/pybel/struct/filters/node_predicate_builders.py | namespace_inclusion_builder | def namespace_inclusion_builder(namespace: Strings) -> NodePredicate:
"""Build a predicate for namespace inclusion."""
if isinstance(namespace, str):
def namespace_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has the enclosed namespace."""
return NAMESPACE in node and node[NAMESPACE] == namespace
elif isinstance(namespace, Iterable):
namespaces = set(namespace)
def namespace_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has a namespace in the enclosed set."""
return NAMESPACE in node and node[NAMESPACE] in namespaces
else:
raise TypeError('Invalid type for argument: {}'.format(namespace))
return namespace_filter | python | def namespace_inclusion_builder(namespace: Strings) -> NodePredicate:
"""Build a predicate for namespace inclusion."""
if isinstance(namespace, str):
def namespace_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has the enclosed namespace."""
return NAMESPACE in node and node[NAMESPACE] == namespace
elif isinstance(namespace, Iterable):
namespaces = set(namespace)
def namespace_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has a namespace in the enclosed set."""
return NAMESPACE in node and node[NAMESPACE] in namespaces
else:
raise TypeError('Invalid type for argument: {}'.format(namespace))
return namespace_filter | [
"def",
"namespace_inclusion_builder",
"(",
"namespace",
":",
"Strings",
")",
"->",
"NodePredicate",
":",
"if",
"isinstance",
"(",
"namespace",
",",
"str",
")",
":",
"def",
"namespace_filter",
"(",
"_",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"-... | Build a predicate for namespace inclusion. | [
"Build",
"a",
"predicate",
"for",
"namespace",
"inclusion",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicate_builders.py#L131-L148 | train | 29,454 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.has_namespace | def has_namespace(self, namespace: str) -> bool:
"""Check that the namespace has either been defined by an enumeration or a regular expression."""
return self.has_enumerated_namespace(namespace) or self.has_regex_namespace(namespace) | python | def has_namespace(self, namespace: str) -> bool:
"""Check that the namespace has either been defined by an enumeration or a regular expression."""
return self.has_enumerated_namespace(namespace) or self.has_regex_namespace(namespace) | [
"def",
"has_namespace",
"(",
"self",
",",
"namespace",
":",
"str",
")",
"->",
"bool",
":",
"return",
"self",
".",
"has_enumerated_namespace",
"(",
"namespace",
")",
"or",
"self",
".",
"has_regex_namespace",
"(",
"namespace",
")"
] | Check that the namespace has either been defined by an enumeration or a regular expression. | [
"Check",
"that",
"the",
"namespace",
"has",
"either",
"been",
"defined",
"by",
"an",
"enumeration",
"or",
"a",
"regular",
"expression",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L70-L72 | train | 29,455 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.has_enumerated_namespace_name | def has_enumerated_namespace_name(self, namespace: str, name: str) -> bool:
"""Check that the namespace is defined by an enumeration and that the name is a member."""
return self.has_enumerated_namespace(namespace) and name in self.namespace_to_terms[namespace] | python | def has_enumerated_namespace_name(self, namespace: str, name: str) -> bool:
"""Check that the namespace is defined by an enumeration and that the name is a member."""
return self.has_enumerated_namespace(namespace) and name in self.namespace_to_terms[namespace] | [
"def",
"has_enumerated_namespace_name",
"(",
"self",
",",
"namespace",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"return",
"self",
".",
"has_enumerated_namespace",
"(",
"namespace",
")",
"and",
"name",
"in",
"self",
".",
"namespace_to_terms"... | Check that the namespace is defined by an enumeration and that the name is a member. | [
"Check",
"that",
"the",
"namespace",
"is",
"defined",
"by",
"an",
"enumeration",
"and",
"that",
"the",
"name",
"is",
"a",
"member",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L74-L76 | train | 29,456 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.has_regex_namespace_name | def has_regex_namespace_name(self, namespace: str, name: str) -> bool:
"""Check that the namespace is defined as a regular expression and the name matches it."""
return self.has_regex_namespace(namespace) and self.namespace_to_pattern[namespace].match(name) | python | def has_regex_namespace_name(self, namespace: str, name: str) -> bool:
"""Check that the namespace is defined as a regular expression and the name matches it."""
return self.has_regex_namespace(namespace) and self.namespace_to_pattern[namespace].match(name) | [
"def",
"has_regex_namespace_name",
"(",
"self",
",",
"namespace",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"return",
"self",
".",
"has_regex_namespace",
"(",
"namespace",
")",
"and",
"self",
".",
"namespace_to_pattern",
"[",
"namespace",
... | Check that the namespace is defined as a regular expression and the name matches it. | [
"Check",
"that",
"the",
"namespace",
"is",
"defined",
"as",
"a",
"regular",
"expression",
"and",
"the",
"name",
"matches",
"it",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L78-L80 | train | 29,457 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.has_namespace_name | def has_namespace_name(self, line: str, position: int, namespace: str, name: str) -> bool:
"""Check that the namespace is defined and has the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
return self.has_enumerated_namespace_name(namespace, name) or self.has_regex_namespace_name(namespace, name) | python | def has_namespace_name(self, line: str, position: int, namespace: str, name: str) -> bool:
"""Check that the namespace is defined and has the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
return self.has_enumerated_namespace_name(namespace, name) or self.has_regex_namespace_name(namespace, name) | [
"def",
"has_namespace_name",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"namespace",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"self",
".",
"raise_for_missing_namespace",
"(",
"line",
",",
"position",
",",
... | Check that the namespace is defined and has the given name. | [
"Check",
"that",
"the",
"namespace",
"is",
"defined",
"and",
"has",
"the",
"given",
"name",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L82-L85 | train | 29,458 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.raise_for_missing_namespace | def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined."""
if not self.has_namespace(namespace):
raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name) | python | def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined."""
if not self.has_namespace(namespace):
raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name) | [
"def",
"raise_for_missing_namespace",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"namespace",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"has_namespace",
"(",
"namespace",
")",
":... | Raise an exception if the namespace is not defined. | [
"Raise",
"an",
"exception",
"if",
"the",
"namespace",
"is",
"not",
"defined",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L87-L90 | train | 29,459 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.raise_for_missing_name | def raise_for_missing_name(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined or if it does not validate the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
if self.has_enumerated_namespace(namespace) and not self.has_enumerated_namespace_name(namespace, name):
raise MissingNamespaceNameWarning(self.get_line_number(), line, position, namespace, name)
if self.has_regex_namespace(namespace) and not self.has_regex_namespace_name(namespace, name):
raise MissingNamespaceRegexWarning(self.get_line_number(), line, position, namespace, name) | python | def raise_for_missing_name(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined or if it does not validate the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
if self.has_enumerated_namespace(namespace) and not self.has_enumerated_namespace_name(namespace, name):
raise MissingNamespaceNameWarning(self.get_line_number(), line, position, namespace, name)
if self.has_regex_namespace(namespace) and not self.has_regex_namespace_name(namespace, name):
raise MissingNamespaceRegexWarning(self.get_line_number(), line, position, namespace, name) | [
"def",
"raise_for_missing_name",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"namespace",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"raise_for_missing_namespace",
"(",
"line",
",",
"position",
"... | Raise an exception if the namespace is not defined or if it does not validate the given name. | [
"Raise",
"an",
"exception",
"if",
"the",
"namespace",
"is",
"not",
"defined",
"or",
"if",
"it",
"does",
"not",
"validate",
"the",
"given",
"name",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L92-L100 | train | 29,460 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.raise_for_missing_default | def raise_for_missing_default(self, line: str, position: int, name: str) -> None:
"""Raise an exeception if the name does not belong to the default namespace."""
if not self.default_namespace:
raise ValueError('Default namespace is not set')
if name not in self.default_namespace:
raise MissingDefaultNameWarning(self.get_line_number(), line, position, name) | python | def raise_for_missing_default(self, line: str, position: int, name: str) -> None:
"""Raise an exeception if the name does not belong to the default namespace."""
if not self.default_namespace:
raise ValueError('Default namespace is not set')
if name not in self.default_namespace:
raise MissingDefaultNameWarning(self.get_line_number(), line, position, name) | [
"def",
"raise_for_missing_default",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"default_namespace",
":",
"raise",
"ValueError",
"(",
"'Default namespace is not... | Raise an exeception if the name does not belong to the default namespace. | [
"Raise",
"an",
"exeception",
"if",
"the",
"name",
"does",
"not",
"belong",
"to",
"the",
"default",
"namespace",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L102-L108 | train | 29,461 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.handle_identifier_qualified | def handle_identifier_qualified(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing a qualified identifier."""
namespace, name = tokens[NAMESPACE], tokens[NAME]
self.raise_for_missing_namespace(line, position, namespace, name)
self.raise_for_missing_name(line, position, namespace, name)
return tokens | python | def handle_identifier_qualified(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing a qualified identifier."""
namespace, name = tokens[NAMESPACE], tokens[NAME]
self.raise_for_missing_namespace(line, position, namespace, name)
self.raise_for_missing_name(line, position, namespace, name)
return tokens | [
"def",
"handle_identifier_qualified",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"namespace",
",",
"name",
"=",
"tokens",
"[",
"NAMESPACE",
"]",
",",
"tokens",
"[",... | Handle parsing a qualified identifier. | [
"Handle",
"parsing",
"a",
"qualified",
"identifier",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L110-L117 | train | 29,462 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.handle_namespace_default | def handle_namespace_default(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing an identifier for the default namespace."""
name = tokens[NAME]
self.raise_for_missing_default(line, position, name)
return tokens | python | def handle_namespace_default(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing an identifier for the default namespace."""
name = tokens[NAME]
self.raise_for_missing_default(line, position, name)
return tokens | [
"def",
"handle_namespace_default",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"name",
"=",
"tokens",
"[",
"NAME",
"]",
"self",
".",
"raise_for_missing_default",
"(",
... | Handle parsing an identifier for the default namespace. | [
"Handle",
"parsing",
"an",
"identifier",
"for",
"the",
"default",
"namespace",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L119-L123 | train | 29,463 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.handle_namespace_lenient | def handle_namespace_lenient(line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing an identifier for name missing a namespac ethat are outside the default namespace."""
tokens[NAMESPACE] = DIRTY
log.debug('Naked namespace: [%d] %s', position, line)
return tokens | python | def handle_namespace_lenient(line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle parsing an identifier for name missing a namespac ethat are outside the default namespace."""
tokens[NAMESPACE] = DIRTY
log.debug('Naked namespace: [%d] %s', position, line)
return tokens | [
"def",
"handle_namespace_lenient",
"(",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"tokens",
"[",
"NAMESPACE",
"]",
"=",
"DIRTY",
"log",
".",
"debug",
"(",
"'Naked namespace: [%d] %s'",
... | Handle parsing an identifier for name missing a namespac ethat are outside the default namespace. | [
"Handle",
"parsing",
"an",
"identifier",
"for",
"name",
"missing",
"a",
"namespac",
"ethat",
"are",
"outside",
"the",
"default",
"namespace",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L126-L130 | train | 29,464 |
pybel/pybel | src/pybel/parser/parse_identifier.py | IdentifierParser.handle_namespace_invalid | def handle_namespace_invalid(self, line: str, position: int, tokens: ParseResults) -> None:
"""Raise an exception when parsing a name missing a namespace."""
name = tokens[NAME]
raise NakedNameWarning(self.get_line_number(), line, position, name) | python | def handle_namespace_invalid(self, line: str, position: int, tokens: ParseResults) -> None:
"""Raise an exception when parsing a name missing a namespace."""
name = tokens[NAME]
raise NakedNameWarning(self.get_line_number(), line, position, name) | [
"def",
"handle_namespace_invalid",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"None",
":",
"name",
"=",
"tokens",
"[",
"NAME",
"]",
"raise",
"NakedNameWarning",
"(",
"self",
".",
"get... | Raise an exception when parsing a name missing a namespace. | [
"Raise",
"an",
"exception",
"when",
"parsing",
"a",
"name",
"missing",
"a",
"namespace",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_identifier.py#L132-L135 | train | 29,465 |
pybel/pybel | src/pybel/constants.py | hbp_namespace | def hbp_namespace(name: str, sha: Optional[str] = None) -> str:
"""Format a namespace URL."""
return HBP_NAMESPACE_URL.format(sha=sha or LAST_HASH, keyword=name) | python | def hbp_namespace(name: str, sha: Optional[str] = None) -> str:
"""Format a namespace URL."""
return HBP_NAMESPACE_URL.format(sha=sha or LAST_HASH, keyword=name) | [
"def",
"hbp_namespace",
"(",
"name",
":",
"str",
",",
"sha",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return",
"HBP_NAMESPACE_URL",
".",
"format",
"(",
"sha",
"=",
"sha",
"or",
"LAST_HASH",
",",
"keyword",
"=",
"name",
"... | Format a namespace URL. | [
"Format",
"a",
"namespace",
"URL",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/constants.py#L23-L25 | train | 29,466 |
pybel/pybel | src/pybel/struct/filters/edge_predicates.py | edge_predicate | def edge_predicate(func: DictEdgePredicate) -> EdgePredicate: # noqa: D202
"""Decorate an edge predicate function that only takes a dictionary as its singular argument.
Apply this as a decorator to a function that takes a single argument, a PyBEL node data dictionary, to make
sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node tuple as well.
"""
@wraps(func)
def _wrapped(*args):
x = args[0]
if isinstance(x, BELGraph):
u, v, k = args[1:4]
return func(x[u][v][k])
return func(*args)
return _wrapped | python | def edge_predicate(func: DictEdgePredicate) -> EdgePredicate: # noqa: D202
"""Decorate an edge predicate function that only takes a dictionary as its singular argument.
Apply this as a decorator to a function that takes a single argument, a PyBEL node data dictionary, to make
sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node tuple as well.
"""
@wraps(func)
def _wrapped(*args):
x = args[0]
if isinstance(x, BELGraph):
u, v, k = args[1:4]
return func(x[u][v][k])
return func(*args)
return _wrapped | [
"def",
"edge_predicate",
"(",
"func",
":",
"DictEdgePredicate",
")",
"->",
"EdgePredicate",
":",
"# noqa: D202",
"@",
"wraps",
"(",
"func",
")",
"def",
"_wrapped",
"(",
"*",
"args",
")",
":",
"x",
"=",
"args",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"x... | Decorate an edge predicate function that only takes a dictionary as its singular argument.
Apply this as a decorator to a function that takes a single argument, a PyBEL node data dictionary, to make
sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node tuple as well. | [
"Decorate",
"an",
"edge",
"predicate",
"function",
"that",
"only",
"takes",
"a",
"dictionary",
"as",
"its",
"singular",
"argument",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicates.py#L39-L56 | train | 29,467 |
pybel/pybel | src/pybel/struct/filters/edge_predicates.py | has_pubmed | def has_pubmed(edge_data: EdgeData) -> bool:
"""Check if the edge has a PubMed citation."""
return CITATION in edge_data and CITATION_TYPE_PUBMED == edge_data[CITATION][CITATION_TYPE] | python | def has_pubmed(edge_data: EdgeData) -> bool:
"""Check if the edge has a PubMed citation."""
return CITATION in edge_data and CITATION_TYPE_PUBMED == edge_data[CITATION][CITATION_TYPE] | [
"def",
"has_pubmed",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"bool",
":",
"return",
"CITATION",
"in",
"edge_data",
"and",
"CITATION_TYPE_PUBMED",
"==",
"edge_data",
"[",
"CITATION",
"]",
"[",
"CITATION_TYPE",
"]"
] | Check if the edge has a PubMed citation. | [
"Check",
"if",
"the",
"edge",
"has",
"a",
"PubMed",
"citation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicates.py#L75-L77 | train | 29,468 |
pybel/pybel | src/pybel/struct/filters/edge_predicates.py | has_authors | def has_authors(edge_data: EdgeData) -> bool:
"""Check if the edge contains author information for its citation."""
return CITATION in edge_data and CITATION_AUTHORS in edge_data[CITATION] and edge_data[CITATION][CITATION_AUTHORS] | python | def has_authors(edge_data: EdgeData) -> bool:
"""Check if the edge contains author information for its citation."""
return CITATION in edge_data and CITATION_AUTHORS in edge_data[CITATION] and edge_data[CITATION][CITATION_AUTHORS] | [
"def",
"has_authors",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"bool",
":",
"return",
"CITATION",
"in",
"edge_data",
"and",
"CITATION_AUTHORS",
"in",
"edge_data",
"[",
"CITATION",
"]",
"and",
"edge_data",
"[",
"CITATION",
"]",
"[",
"CITATION_AUTHORS",
"]"... | Check if the edge contains author information for its citation. | [
"Check",
"if",
"the",
"edge",
"contains",
"author",
"information",
"for",
"its",
"citation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicates.py#L81-L83 | train | 29,469 |
pybel/pybel | src/pybel/struct/filters/edge_predicates.py | _has_modifier | def _has_modifier(edge_data: EdgeData, modifier: str) -> bool:
"""Check if the edge has the given modifier.
:param edge_data: The edge data dictionary
:param modifier: The modifier to check. One of :data:`pybel.constants.ACTIVITY`,
:data:`pybel.constants.DEGRADATION`, or :data:`pybel.constants.TRANSLOCATION`.
:return: Does either the subject or object have the given modifier
"""
return part_has_modifier(edge_data, SUBJECT, modifier) or part_has_modifier(edge_data, OBJECT, modifier) | python | def _has_modifier(edge_data: EdgeData, modifier: str) -> bool:
"""Check if the edge has the given modifier.
:param edge_data: The edge data dictionary
:param modifier: The modifier to check. One of :data:`pybel.constants.ACTIVITY`,
:data:`pybel.constants.DEGRADATION`, or :data:`pybel.constants.TRANSLOCATION`.
:return: Does either the subject or object have the given modifier
"""
return part_has_modifier(edge_data, SUBJECT, modifier) or part_has_modifier(edge_data, OBJECT, modifier) | [
"def",
"_has_modifier",
"(",
"edge_data",
":",
"EdgeData",
",",
"modifier",
":",
"str",
")",
"->",
"bool",
":",
"return",
"part_has_modifier",
"(",
"edge_data",
",",
"SUBJECT",
",",
"modifier",
")",
"or",
"part_has_modifier",
"(",
"edge_data",
",",
"OBJECT",
... | Check if the edge has the given modifier.
:param edge_data: The edge data dictionary
:param modifier: The modifier to check. One of :data:`pybel.constants.ACTIVITY`,
:data:`pybel.constants.DEGRADATION`, or :data:`pybel.constants.TRANSLOCATION`.
:return: Does either the subject or object have the given modifier | [
"Check",
"if",
"the",
"edge",
"has",
"the",
"given",
"modifier",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicates.py#L110-L118 | train | 29,470 |
pybel/pybel | src/pybel/struct/filters/edge_predicates.py | edge_has_annotation | def edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]:
"""Check if an edge has the given annotation.
:param edge_data: The data dictionary from a BELGraph's edge
:param key: An annotation key
:return: If the annotation key is present in the current data dictionary
For example, it might be useful to print all edges that are annotated with 'Subgraph':
>>> from pybel.examples import sialic_acid_graph
>>> for u, v, data in sialic_acid_graph.edges(data=True):
>>> if edge_has_annotation(data, 'Species')
>>> print(u, v, data)
"""
annotations = edge_data.get(ANNOTATIONS)
if annotations is None:
return None
return annotations.get(key) | python | def edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]:
"""Check if an edge has the given annotation.
:param edge_data: The data dictionary from a BELGraph's edge
:param key: An annotation key
:return: If the annotation key is present in the current data dictionary
For example, it might be useful to print all edges that are annotated with 'Subgraph':
>>> from pybel.examples import sialic_acid_graph
>>> for u, v, data in sialic_acid_graph.edges(data=True):
>>> if edge_has_annotation(data, 'Species')
>>> print(u, v, data)
"""
annotations = edge_data.get(ANNOTATIONS)
if annotations is None:
return None
return annotations.get(key) | [
"def",
"edge_has_annotation",
"(",
"edge_data",
":",
"EdgeData",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"Any",
"]",
":",
"annotations",
"=",
"edge_data",
".",
"get",
"(",
"ANNOTATIONS",
")",
"if",
"annotations",
"is",
"None",
":",
"return",
... | Check if an edge has the given annotation.
:param edge_data: The data dictionary from a BELGraph's edge
:param key: An annotation key
:return: If the annotation key is present in the current data dictionary
For example, it might be useful to print all edges that are annotated with 'Subgraph':
>>> from pybel.examples import sialic_acid_graph
>>> for u, v, data in sialic_acid_graph.edges(data=True):
>>> if edge_has_annotation(data, 'Species')
>>> print(u, v, data) | [
"Check",
"if",
"an",
"edge",
"has",
"the",
"given",
"annotation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/edge_predicates.py#L139-L158 | train | 29,471 |
pybel/pybel | src/pybel/parser/modifiers/gene_substitution.py | get_gene_substitution_language | def get_gene_substitution_language() -> ParserElement:
"""Build a gene substitution parser."""
parser_element = gsub_tag + nest(
dna_nucleotide(GSUB_REFERENCE),
ppc.integer(GSUB_POSITION),
dna_nucleotide(GSUB_VARIANT),
)
parser_element.setParseAction(_handle_gsub)
return parser_element | python | def get_gene_substitution_language() -> ParserElement:
"""Build a gene substitution parser."""
parser_element = gsub_tag + nest(
dna_nucleotide(GSUB_REFERENCE),
ppc.integer(GSUB_POSITION),
dna_nucleotide(GSUB_VARIANT),
)
parser_element.setParseAction(_handle_gsub)
return parser_element | [
"def",
"get_gene_substitution_language",
"(",
")",
"->",
"ParserElement",
":",
"parser_element",
"=",
"gsub_tag",
"+",
"nest",
"(",
"dna_nucleotide",
"(",
"GSUB_REFERENCE",
")",
",",
"ppc",
".",
"integer",
"(",
"GSUB_POSITION",
")",
",",
"dna_nucleotide",
"(",
"... | Build a gene substitution parser. | [
"Build",
"a",
"gene",
"substitution",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/gene_substitution.py#L51-L59 | train | 29,472 |
pybel/pybel | src/pybel/struct/query/query.py | Query.append_seeding_induction | def append_seeding_induction(self, nodes: Union[BaseEntity, List[BaseEntity], List[Dict]]) -> Seeding:
"""Add a seed induction method.
:returns: seeding container for fluid API
"""
return self.seeding.append_induction(nodes) | python | def append_seeding_induction(self, nodes: Union[BaseEntity, List[BaseEntity], List[Dict]]) -> Seeding:
"""Add a seed induction method.
:returns: seeding container for fluid API
"""
return self.seeding.append_induction(nodes) | [
"def",
"append_seeding_induction",
"(",
"self",
",",
"nodes",
":",
"Union",
"[",
"BaseEntity",
",",
"List",
"[",
"BaseEntity",
"]",
",",
"List",
"[",
"Dict",
"]",
"]",
")",
"->",
"Seeding",
":",
"return",
"self",
".",
"seeding",
".",
"append_induction",
... | Add a seed induction method.
:returns: seeding container for fluid API | [
"Add",
"a",
"seed",
"induction",
"method",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L65-L70 | train | 29,473 |
pybel/pybel | src/pybel/struct/query/query.py | Query.append_seeding_neighbors | def append_seeding_neighbors(self, nodes: Union[BaseEntity, List[BaseEntity], List[Dict]]) -> Seeding:
"""Add a seed by neighbors.
:returns: seeding container for fluid API
"""
return self.seeding.append_neighbors(nodes) | python | def append_seeding_neighbors(self, nodes: Union[BaseEntity, List[BaseEntity], List[Dict]]) -> Seeding:
"""Add a seed by neighbors.
:returns: seeding container for fluid API
"""
return self.seeding.append_neighbors(nodes) | [
"def",
"append_seeding_neighbors",
"(",
"self",
",",
"nodes",
":",
"Union",
"[",
"BaseEntity",
",",
"List",
"[",
"BaseEntity",
"]",
",",
"List",
"[",
"Dict",
"]",
"]",
")",
"->",
"Seeding",
":",
"return",
"self",
".",
"seeding",
".",
"append_neighbors",
... | Add a seed by neighbors.
:returns: seeding container for fluid API | [
"Add",
"a",
"seed",
"by",
"neighbors",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L72-L77 | train | 29,474 |
pybel/pybel | src/pybel/struct/query/query.py | Query.run | def run(self, manager):
"""Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph]
"""
universe = self._get_universe(manager)
graph = self.seeding.run(universe)
return self.pipeline.run(graph, universe=universe) | python | def run(self, manager):
"""Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph]
"""
universe = self._get_universe(manager)
graph = self.seeding.run(universe)
return self.pipeline.run(graph, universe=universe) | [
"def",
"run",
"(",
"self",
",",
"manager",
")",
":",
"universe",
"=",
"self",
".",
"_get_universe",
"(",
"manager",
")",
"graph",
"=",
"self",
".",
"seeding",
".",
"run",
"(",
"universe",
")",
"return",
"self",
".",
"pipeline",
".",
"run",
"(",
"grap... | Run this query and returns the resulting BEL graph.
:param manager: A cache manager
:rtype: Optional[pybel.BELGraph] | [
"Run",
"this",
"query",
"and",
"returns",
"the",
"resulting",
"BEL",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L111-L119 | train | 29,475 |
pybel/pybel | src/pybel/struct/query/query.py | Query.to_json | def to_json(self) -> Dict:
"""Return this query as a JSON object."""
rv = {
'network_ids': self.network_ids,
}
if self.seeding:
rv['seeding'] = self.seeding.to_json()
if self.pipeline:
rv['pipeline'] = self.pipeline.to_json()
return rv | python | def to_json(self) -> Dict:
"""Return this query as a JSON object."""
rv = {
'network_ids': self.network_ids,
}
if self.seeding:
rv['seeding'] = self.seeding.to_json()
if self.pipeline:
rv['pipeline'] = self.pipeline.to_json()
return rv | [
"def",
"to_json",
"(",
"self",
")",
"->",
"Dict",
":",
"rv",
"=",
"{",
"'network_ids'",
":",
"self",
".",
"network_ids",
",",
"}",
"if",
"self",
".",
"seeding",
":",
"rv",
"[",
"'seeding'",
"]",
"=",
"self",
".",
"seeding",
".",
"to_json",
"(",
")"... | Return this query as a JSON object. | [
"Return",
"this",
"query",
"as",
"a",
"JSON",
"object",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L132-L144 | train | 29,476 |
pybel/pybel | src/pybel/struct/query/query.py | Query.from_json | def from_json(data: Mapping) -> 'Query':
"""Load a query from a JSON dictionary.
:param data: A JSON dictionary
:raises: QueryMissingNetworksError
"""
network_ids = data.get('network_ids')
if network_ids is None:
raise QueryMissingNetworksError('query JSON did not have key "network_ids"')
seeding_data = data.get('seeding')
seeding = (
Seeding.from_json(seeding_data)
if seeding_data is not None else
None
)
pipeline_data = data.get('pipeline')
pipeline = (
Pipeline.from_json(pipeline_data)
if pipeline_data is not None else
None
)
return Query(
network_ids=network_ids,
seeding=seeding,
pipeline=pipeline,
) | python | def from_json(data: Mapping) -> 'Query':
"""Load a query from a JSON dictionary.
:param data: A JSON dictionary
:raises: QueryMissingNetworksError
"""
network_ids = data.get('network_ids')
if network_ids is None:
raise QueryMissingNetworksError('query JSON did not have key "network_ids"')
seeding_data = data.get('seeding')
seeding = (
Seeding.from_json(seeding_data)
if seeding_data is not None else
None
)
pipeline_data = data.get('pipeline')
pipeline = (
Pipeline.from_json(pipeline_data)
if pipeline_data is not None else
None
)
return Query(
network_ids=network_ids,
seeding=seeding,
pipeline=pipeline,
) | [
"def",
"from_json",
"(",
"data",
":",
"Mapping",
")",
"->",
"'Query'",
":",
"network_ids",
"=",
"data",
".",
"get",
"(",
"'network_ids'",
")",
"if",
"network_ids",
"is",
"None",
":",
"raise",
"QueryMissingNetworksError",
"(",
"'query JSON did not have key \"networ... | Load a query from a JSON dictionary.
:param data: A JSON dictionary
:raises: QueryMissingNetworksError | [
"Load",
"a",
"query",
"from",
"a",
"JSON",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L155-L183 | train | 29,477 |
pybel/pybel | src/pybel/parser/parse_bel.py | handle_molecular_activity_default | def handle_molecular_activity_default(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle a BEL 2.0 style molecular activity with BEL default names."""
upgraded = language.activity_labels[tokens[0]]
tokens[NAMESPACE] = BEL_DEFAULT_NAMESPACE
tokens[NAME] = upgraded
return tokens | python | def handle_molecular_activity_default(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle a BEL 2.0 style molecular activity with BEL default names."""
upgraded = language.activity_labels[tokens[0]]
tokens[NAMESPACE] = BEL_DEFAULT_NAMESPACE
tokens[NAME] = upgraded
return tokens | [
"def",
"handle_molecular_activity_default",
"(",
"_",
":",
"str",
",",
"__",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"upgraded",
"=",
"language",
".",
"activity_labels",
"[",
"tokens",
"[",
"0",
"]",
"]",
"tokens",
"... | Handle a BEL 2.0 style molecular activity with BEL default names. | [
"Handle",
"a",
"BEL",
"2",
".",
"0",
"style",
"molecular",
"activity",
"with",
"BEL",
"default",
"names",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L837-L842 | train | 29,478 |
pybel/pybel | src/pybel/parser/parse_bel.py | handle_activity_legacy | def handle_activity_legacy(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle BEL 1.0 activities."""
legacy_cls = language.activity_labels[tokens[MODIFIER]]
tokens[MODIFIER] = ACTIVITY
tokens[EFFECT] = {
NAME: legacy_cls,
NAMESPACE: BEL_DEFAULT_NAMESPACE
}
log.log(5, 'upgraded legacy activity to %s', legacy_cls)
return tokens | python | def handle_activity_legacy(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle BEL 1.0 activities."""
legacy_cls = language.activity_labels[tokens[MODIFIER]]
tokens[MODIFIER] = ACTIVITY
tokens[EFFECT] = {
NAME: legacy_cls,
NAMESPACE: BEL_DEFAULT_NAMESPACE
}
log.log(5, 'upgraded legacy activity to %s', legacy_cls)
return tokens | [
"def",
"handle_activity_legacy",
"(",
"_",
":",
"str",
",",
"__",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"legacy_cls",
"=",
"language",
".",
"activity_labels",
"[",
"tokens",
"[",
"MODIFIER",
"]",
"]",
"tokens",
"["... | Handle BEL 1.0 activities. | [
"Handle",
"BEL",
"1",
".",
"0",
"activities",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L845-L854 | train | 29,479 |
pybel/pybel | src/pybel/parser/parse_bel.py | handle_legacy_tloc | def handle_legacy_tloc(line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle translocations that lack the ``fromLoc`` and ``toLoc`` entries."""
log.log(5, 'legacy translocation statement: %s [%d]', line, position)
return tokens | python | def handle_legacy_tloc(line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle translocations that lack the ``fromLoc`` and ``toLoc`` entries."""
log.log(5, 'legacy translocation statement: %s [%d]', line, position)
return tokens | [
"def",
"handle_legacy_tloc",
"(",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"log",
".",
"log",
"(",
"5",
",",
"'legacy translocation statement: %s [%d]'",
",",
"line",
",",
"position",
... | Handle translocations that lack the ``fromLoc`` and ``toLoc`` entries. | [
"Handle",
"translocations",
"that",
"lack",
"the",
"fromLoc",
"and",
"toLoc",
"entries",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L857-L860 | train | 29,480 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser.handle_nested_relation | def handle_nested_relation(self, line: str, position: int, tokens: ParseResults):
"""Handle nested statements.
If :code:`allow_nested` is False, raises a ``NestedRelationWarning``.
:raises: NestedRelationWarning
"""
if not self.allow_nested:
raise NestedRelationWarning(self.get_line_number(), line, position)
self._handle_relation_harness(line, position, {
SUBJECT: tokens[SUBJECT],
RELATION: tokens[RELATION],
OBJECT: tokens[OBJECT][SUBJECT],
})
self._handle_relation_harness(line, position, {
SUBJECT: tokens[OBJECT][SUBJECT],
RELATION: tokens[OBJECT][RELATION],
OBJECT: tokens[OBJECT][OBJECT],
})
return tokens | python | def handle_nested_relation(self, line: str, position: int, tokens: ParseResults):
"""Handle nested statements.
If :code:`allow_nested` is False, raises a ``NestedRelationWarning``.
:raises: NestedRelationWarning
"""
if not self.allow_nested:
raise NestedRelationWarning(self.get_line_number(), line, position)
self._handle_relation_harness(line, position, {
SUBJECT: tokens[SUBJECT],
RELATION: tokens[RELATION],
OBJECT: tokens[OBJECT][SUBJECT],
})
self._handle_relation_harness(line, position, {
SUBJECT: tokens[OBJECT][SUBJECT],
RELATION: tokens[OBJECT][RELATION],
OBJECT: tokens[OBJECT][OBJECT],
})
return tokens | [
"def",
"handle_nested_relation",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
":",
"if",
"not",
"self",
".",
"allow_nested",
":",
"raise",
"NestedRelationWarning",
"(",
"self",
".",
"get_line_num... | Handle nested statements.
If :code:`allow_nested` is False, raises a ``NestedRelationWarning``.
:raises: NestedRelationWarning | [
"Handle",
"nested",
"statements",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L630-L651 | train | 29,481 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser.check_function_semantics | def check_function_semantics(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Raise an exception if the function used on the tokens is wrong.
:raises: InvalidFunctionSemantic
"""
if not self._namespace_dict or NAMESPACE not in tokens:
return tokens
namespace, name = tokens[NAMESPACE], tokens[NAME]
if namespace in self.identifier_parser.namespace_to_pattern:
return tokens
if self._allow_naked_names and tokens[NAMESPACE] == DIRTY: # Don't check dirty names in lenient mode
return tokens
valid_functions = set(itt.chain.from_iterable(
belns_encodings.get(k, set())
for k in self._namespace_dict[namespace][name]
))
if not valid_functions:
raise InvalidEntity(self.get_line_number(), line, position, namespace, name)
if tokens[FUNCTION] not in valid_functions:
raise InvalidFunctionSemantic(self.get_line_number(), line, position, tokens[FUNCTION], namespace, name,
valid_functions)
return tokens | python | def check_function_semantics(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Raise an exception if the function used on the tokens is wrong.
:raises: InvalidFunctionSemantic
"""
if not self._namespace_dict or NAMESPACE not in tokens:
return tokens
namespace, name = tokens[NAMESPACE], tokens[NAME]
if namespace in self.identifier_parser.namespace_to_pattern:
return tokens
if self._allow_naked_names and tokens[NAMESPACE] == DIRTY: # Don't check dirty names in lenient mode
return tokens
valid_functions = set(itt.chain.from_iterable(
belns_encodings.get(k, set())
for k in self._namespace_dict[namespace][name]
))
if not valid_functions:
raise InvalidEntity(self.get_line_number(), line, position, namespace, name)
if tokens[FUNCTION] not in valid_functions:
raise InvalidFunctionSemantic(self.get_line_number(), line, position, tokens[FUNCTION], namespace, name,
valid_functions)
return tokens | [
"def",
"check_function_semantics",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"if",
"not",
"self",
".",
"_namespace_dict",
"or",
"NAMESPACE",
"not",
"in",
"tokens",
... | Raise an exception if the function used on the tokens is wrong.
:raises: InvalidFunctionSemantic | [
"Raise",
"an",
"exception",
"if",
"the",
"function",
"used",
"on",
"the",
"tokens",
"is",
"wrong",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L653-L681 | train | 29,482 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser._add_qualified_edge_helper | def _add_qualified_edge_helper(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add a qualified edge from the internal aspects of the parser."""
return self.graph.add_qualified_edge(
u,
v,
relation=relation,
evidence=self.control_parser.evidence,
citation=self.control_parser.citation.copy(),
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
**{LINE: self.get_line_number()}
) | python | def _add_qualified_edge_helper(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add a qualified edge from the internal aspects of the parser."""
return self.graph.add_qualified_edge(
u,
v,
relation=relation,
evidence=self.control_parser.evidence,
citation=self.control_parser.citation.copy(),
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
**{LINE: self.get_line_number()}
) | [
"def",
"_add_qualified_edge_helper",
"(",
"self",
",",
"u",
",",
"v",
",",
"relation",
",",
"annotations",
",",
"subject_modifier",
",",
"object_modifier",
")",
"->",
"str",
":",
"return",
"self",
".",
"graph",
".",
"add_qualified_edge",
"(",
"u",
",",
"v",
... | Add a qualified edge from the internal aspects of the parser. | [
"Add",
"a",
"qualified",
"edge",
"from",
"the",
"internal",
"aspects",
"of",
"the",
"parser",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L706-L718 | train | 29,483 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser._add_qualified_edge | def _add_qualified_edge(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add an edge, then adds the opposite direction edge if it should."""
sha512 = self._add_qualified_edge_helper(
u,
v,
relation=relation,
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
)
if relation in TWO_WAY_RELATIONS:
self._add_qualified_edge_helper(
v,
u,
relation=relation,
annotations=annotations,
object_modifier=subject_modifier,
subject_modifier=object_modifier,
)
return sha512 | python | def _add_qualified_edge(self, u, v, relation, annotations, subject_modifier, object_modifier) -> str:
"""Add an edge, then adds the opposite direction edge if it should."""
sha512 = self._add_qualified_edge_helper(
u,
v,
relation=relation,
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
)
if relation in TWO_WAY_RELATIONS:
self._add_qualified_edge_helper(
v,
u,
relation=relation,
annotations=annotations,
object_modifier=subject_modifier,
subject_modifier=object_modifier,
)
return sha512 | [
"def",
"_add_qualified_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"relation",
",",
"annotations",
",",
"subject_modifier",
",",
"object_modifier",
")",
"->",
"str",
":",
"sha512",
"=",
"self",
".",
"_add_qualified_edge_helper",
"(",
"u",
",",
"v",
",",
"... | Add an edge, then adds the opposite direction edge if it should. | [
"Add",
"an",
"edge",
"then",
"adds",
"the",
"opposite",
"direction",
"edge",
"if",
"it",
"should",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L720-L741 | train | 29,484 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser._handle_relation | def _handle_relation(self, tokens: ParseResults) -> str:
"""Handle a relation."""
subject_node_dsl = self.ensure_node(tokens[SUBJECT])
object_node_dsl = self.ensure_node(tokens[OBJECT])
subject_modifier = modifier_po_to_dict(tokens[SUBJECT])
object_modifier = modifier_po_to_dict(tokens[OBJECT])
annotations = {
annotation_name: (
{
ae: True
for ae in annotation_entry
}
if isinstance(annotation_entry, set) else
{
annotation_entry: True
}
)
for annotation_name, annotation_entry in self.control_parser.annotations.items()
}
return self._add_qualified_edge(
subject_node_dsl,
object_node_dsl,
relation=tokens[RELATION],
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
) | python | def _handle_relation(self, tokens: ParseResults) -> str:
"""Handle a relation."""
subject_node_dsl = self.ensure_node(tokens[SUBJECT])
object_node_dsl = self.ensure_node(tokens[OBJECT])
subject_modifier = modifier_po_to_dict(tokens[SUBJECT])
object_modifier = modifier_po_to_dict(tokens[OBJECT])
annotations = {
annotation_name: (
{
ae: True
for ae in annotation_entry
}
if isinstance(annotation_entry, set) else
{
annotation_entry: True
}
)
for annotation_name, annotation_entry in self.control_parser.annotations.items()
}
return self._add_qualified_edge(
subject_node_dsl,
object_node_dsl,
relation=tokens[RELATION],
annotations=annotations,
subject_modifier=subject_modifier,
object_modifier=object_modifier,
) | [
"def",
"_handle_relation",
"(",
"self",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"str",
":",
"subject_node_dsl",
"=",
"self",
".",
"ensure_node",
"(",
"tokens",
"[",
"SUBJECT",
"]",
")",
"object_node_dsl",
"=",
"self",
".",
"ensure_node",
"(",
"tokens"... | Handle a relation. | [
"Handle",
"a",
"relation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L743-L772 | train | 29,485 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser._handle_relation_harness | def _handle_relation_harness(self, line: str, position: int, tokens: Union[ParseResults, Dict]) -> ParseResults:
"""Handle BEL relations based on the policy specified on instantiation.
Note: this can't be changed after instantiation!
"""
if not self.control_parser.citation:
raise MissingCitationException(self.get_line_number(), line, position)
if not self.control_parser.evidence:
raise MissingSupportWarning(self.get_line_number(), line, position)
missing_required_annotations = self.control_parser.get_missing_required_annotations()
if missing_required_annotations:
raise MissingAnnotationWarning(self.get_line_number(), line, position, missing_required_annotations)
self._handle_relation(tokens)
return tokens | python | def _handle_relation_harness(self, line: str, position: int, tokens: Union[ParseResults, Dict]) -> ParseResults:
"""Handle BEL relations based on the policy specified on instantiation.
Note: this can't be changed after instantiation!
"""
if not self.control_parser.citation:
raise MissingCitationException(self.get_line_number(), line, position)
if not self.control_parser.evidence:
raise MissingSupportWarning(self.get_line_number(), line, position)
missing_required_annotations = self.control_parser.get_missing_required_annotations()
if missing_required_annotations:
raise MissingAnnotationWarning(self.get_line_number(), line, position, missing_required_annotations)
self._handle_relation(tokens)
return tokens | [
"def",
"_handle_relation_harness",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"Union",
"[",
"ParseResults",
",",
"Dict",
"]",
")",
"->",
"ParseResults",
":",
"if",
"not",
"self",
".",
"control_parser",
".",
"ci... | Handle BEL relations based on the policy specified on instantiation.
Note: this can't be changed after instantiation! | [
"Handle",
"BEL",
"relations",
"based",
"on",
"the",
"policy",
"specified",
"on",
"instantiation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L774-L790 | train | 29,486 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser.handle_unqualified_relation | def handle_unqualified_relation(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle unqualified relations."""
subject_node_dsl = self.ensure_node(tokens[SUBJECT])
object_node_dsl = self.ensure_node(tokens[OBJECT])
relation = tokens[RELATION]
self.graph.add_unqualified_edge(subject_node_dsl, object_node_dsl, relation)
return tokens | python | def handle_unqualified_relation(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle unqualified relations."""
subject_node_dsl = self.ensure_node(tokens[SUBJECT])
object_node_dsl = self.ensure_node(tokens[OBJECT])
relation = tokens[RELATION]
self.graph.add_unqualified_edge(subject_node_dsl, object_node_dsl, relation)
return tokens | [
"def",
"handle_unqualified_relation",
"(",
"self",
",",
"_",
",",
"__",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"subject_node_dsl",
"=",
"self",
".",
"ensure_node",
"(",
"tokens",
"[",
"SUBJECT",
"]",
")",
"object_node_dsl",
"=",
... | Handle unqualified relations. | [
"Handle",
"unqualified",
"relations",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L792-L798 | train | 29,487 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser.ensure_node | def ensure_node(self, tokens: ParseResults) -> BaseEntity:
"""Turn parsed tokens into canonical node name and makes sure its in the graph."""
if MODIFIER in tokens:
return self.ensure_node(tokens[TARGET])
node = parse_result_to_dsl(tokens)
self.graph.add_node_from_data(node)
return node | python | def ensure_node(self, tokens: ParseResults) -> BaseEntity:
"""Turn parsed tokens into canonical node name and makes sure its in the graph."""
if MODIFIER in tokens:
return self.ensure_node(tokens[TARGET])
node = parse_result_to_dsl(tokens)
self.graph.add_node_from_data(node)
return node | [
"def",
"ensure_node",
"(",
"self",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"BaseEntity",
":",
"if",
"MODIFIER",
"in",
"tokens",
":",
"return",
"self",
".",
"ensure_node",
"(",
"tokens",
"[",
"TARGET",
"]",
")",
"node",
"=",
"parse_result_to_dsl",
"(... | Turn parsed tokens into canonical node name and makes sure its in the graph. | [
"Turn",
"parsed",
"tokens",
"into",
"canonical",
"node",
"name",
"and",
"makes",
"sure",
"its",
"in",
"the",
"graph",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L821-L828 | train | 29,488 |
pybel/pybel | src/pybel/parser/parse_bel.py | BELParser.handle_translocation_illegal | def handle_translocation_illegal(self, line: str, position: int, tokens: ParseResults) -> None:
"""Handle a malformed translocation."""
raise MalformedTranslocationWarning(self.get_line_number(), line, position, tokens) | python | def handle_translocation_illegal(self, line: str, position: int, tokens: ParseResults) -> None:
"""Handle a malformed translocation."""
raise MalformedTranslocationWarning(self.get_line_number(), line, position, tokens) | [
"def",
"handle_translocation_illegal",
"(",
"self",
",",
"line",
":",
"str",
",",
"position",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"None",
":",
"raise",
"MalformedTranslocationWarning",
"(",
"self",
".",
"get_line_number",
"(",
")",
",",
... | Handle a malformed translocation. | [
"Handle",
"a",
"malformed",
"translocation",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L830-L832 | train | 29,489 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_dsl_by_hash | def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]:
"""Look up a node by the hash and returns the corresponding PyBEL node tuple."""
node = self.get_node_by_hash(node_hash)
if node is not None:
return node.as_bel() | python | def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]:
"""Look up a node by the hash and returns the corresponding PyBEL node tuple."""
node = self.get_node_by_hash(node_hash)
if node is not None:
return node.as_bel() | [
"def",
"get_dsl_by_hash",
"(",
"self",
",",
"node_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"BaseEntity",
"]",
":",
"node",
"=",
"self",
".",
"get_node_by_hash",
"(",
"node_hash",
")",
"if",
"node",
"is",
"not",
"None",
":",
"return",
"node",
".",
... | Look up a node by the hash and returns the corresponding PyBEL node tuple. | [
"Look",
"up",
"a",
"node",
"by",
"the",
"hash",
"and",
"returns",
"the",
"corresponding",
"PyBEL",
"node",
"tuple",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L17-L21 | train | 29,490 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_node_by_hash | def get_node_by_hash(self, node_hash: str) -> Optional[Node]:
"""Look up a node by its hash."""
return self.session.query(Node).filter(Node.sha512 == node_hash).one_or_none() | python | def get_node_by_hash(self, node_hash: str) -> Optional[Node]:
"""Look up a node by its hash."""
return self.session.query(Node).filter(Node.sha512 == node_hash).one_or_none() | [
"def",
"get_node_by_hash",
"(",
"self",
",",
"node_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"Node",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Node",
")",
".",
"filter",
"(",
"Node",
".",
"sha512",
"==",
"node_hash",
")",
"... | Look up a node by its hash. | [
"Look",
"up",
"a",
"node",
"by",
"its",
"hash",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L23-L25 | train | 29,491 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_nodes_by_hashes | def get_nodes_by_hashes(self, node_hashes: List[str]) -> List[Node]:
"""Look up several nodes by their hashes."""
return self.session.query(Node).filter(Node.sha512.in_(node_hashes)).all() | python | def get_nodes_by_hashes(self, node_hashes: List[str]) -> List[Node]:
"""Look up several nodes by their hashes."""
return self.session.query(Node).filter(Node.sha512.in_(node_hashes)).all() | [
"def",
"get_nodes_by_hashes",
"(",
"self",
",",
"node_hashes",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Node",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Node",
")",
".",
"filter",
"(",
"Node",
".",
"sha512",
".",
... | Look up several nodes by their hashes. | [
"Look",
"up",
"several",
"nodes",
"by",
"their",
"hashes",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L27-L29 | train | 29,492 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_edge_by_hash | def get_edge_by_hash(self, edge_hash: str) -> Optional[Edge]:
"""Look up an edge by the hash of a PyBEL edge data dictionary."""
return self.session.query(Edge).filter(Edge.sha512 == edge_hash).one_or_none() | python | def get_edge_by_hash(self, edge_hash: str) -> Optional[Edge]:
"""Look up an edge by the hash of a PyBEL edge data dictionary."""
return self.session.query(Edge).filter(Edge.sha512 == edge_hash).one_or_none() | [
"def",
"get_edge_by_hash",
"(",
"self",
",",
"edge_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"filter",
"(",
"Edge",
".",
"sha512",
"==",
"edge_hash",
")",
"... | Look up an edge by the hash of a PyBEL edge data dictionary. | [
"Look",
"up",
"an",
"edge",
"by",
"the",
"hash",
"of",
"a",
"PyBEL",
"edge",
"data",
"dictionary",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L35-L37 | train | 29,493 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_edges_by_hashes | def get_edges_by_hashes(self, edge_hashes: List[str]) -> List[Edge]:
"""Look up several edges by hashes of their PyBEL edge data dictionaries."""
return self.session.query(Edge).filter(Edge.sha512.in_(edge_hashes)).all() | python | def get_edges_by_hashes(self, edge_hashes: List[str]) -> List[Edge]:
"""Look up several edges by hashes of their PyBEL edge data dictionaries."""
return self.session.query(Edge).filter(Edge.sha512.in_(edge_hashes)).all() | [
"def",
"get_edges_by_hashes",
"(",
"self",
",",
"edge_hashes",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"filter",
"(",
"Edge",
".",
"sha512",
".",
... | Look up several edges by hashes of their PyBEL edge data dictionaries. | [
"Look",
"up",
"several",
"edges",
"by",
"hashes",
"of",
"their",
"PyBEL",
"edge",
"data",
"dictionaries",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L39-L41 | train | 29,494 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_citation_by_pmid | def get_citation_by_pmid(self, pubmed_identifier: str) -> Optional[Citation]:
"""Get a citation object by its PubMed identifier."""
return self.get_citation_by_reference(reference=pubmed_identifier, type=CITATION_TYPE_PUBMED) | python | def get_citation_by_pmid(self, pubmed_identifier: str) -> Optional[Citation]:
"""Get a citation object by its PubMed identifier."""
return self.get_citation_by_reference(reference=pubmed_identifier, type=CITATION_TYPE_PUBMED) | [
"def",
"get_citation_by_pmid",
"(",
"self",
",",
"pubmed_identifier",
":",
"str",
")",
"->",
"Optional",
"[",
"Citation",
"]",
":",
"return",
"self",
".",
"get_citation_by_reference",
"(",
"reference",
"=",
"pubmed_identifier",
",",
"type",
"=",
"CITATION_TYPE_PUB... | Get a citation object by its PubMed identifier. | [
"Get",
"a",
"citation",
"object",
"by",
"its",
"PubMed",
"identifier",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L43-L45 | train | 29,495 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_citation_by_reference | def get_citation_by_reference(self, type: str, reference: str) -> Optional[Citation]:
"""Get a citation object by its type and reference."""
citation_hash = hash_citation(type=type, reference=reference)
return self.get_citation_by_hash(citation_hash) | python | def get_citation_by_reference(self, type: str, reference: str) -> Optional[Citation]:
"""Get a citation object by its type and reference."""
citation_hash = hash_citation(type=type, reference=reference)
return self.get_citation_by_hash(citation_hash) | [
"def",
"get_citation_by_reference",
"(",
"self",
",",
"type",
":",
"str",
",",
"reference",
":",
"str",
")",
"->",
"Optional",
"[",
"Citation",
"]",
":",
"citation_hash",
"=",
"hash_citation",
"(",
"type",
"=",
"type",
",",
"reference",
"=",
"reference",
"... | Get a citation object by its type and reference. | [
"Get",
"a",
"citation",
"object",
"by",
"its",
"type",
"and",
"reference",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L47-L50 | train | 29,496 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_citation_by_hash | def get_citation_by_hash(self, citation_hash: str) -> Optional[Citation]:
"""Get a citation object by its hash."""
return self.session.query(Citation).filter(Citation.sha512 == citation_hash).one_or_none() | python | def get_citation_by_hash(self, citation_hash: str) -> Optional[Citation]:
"""Get a citation object by its hash."""
return self.session.query(Citation).filter(Citation.sha512 == citation_hash).one_or_none() | [
"def",
"get_citation_by_hash",
"(",
"self",
",",
"citation_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"Citation",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Citation",
")",
".",
"filter",
"(",
"Citation",
".",
"sha512",
"==",
"ci... | Get a citation object by its hash. | [
"Get",
"a",
"citation",
"object",
"by",
"its",
"hash",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L52-L54 | train | 29,497 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_author_by_name | def get_author_by_name(self, name: str) -> Optional[Author]:
"""Get an author by name, if it exists in the database."""
return self.session.query(Author).filter(Author.has_name(name)).one_or_none() | python | def get_author_by_name(self, name: str) -> Optional[Author]:
"""Get an author by name, if it exists in the database."""
return self.session.query(Author).filter(Author.has_name(name)).one_or_none() | [
"def",
"get_author_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"Author",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Author",
")",
".",
"filter",
"(",
"Author",
".",
"has_name",
"(",
"name",
")",
")... | Get an author by name, if it exists in the database. | [
"Get",
"an",
"author",
"by",
"name",
"if",
"it",
"exists",
"in",
"the",
"database",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L56-L58 | train | 29,498 |
pybel/pybel | src/pybel/manager/lookup_manager.py | LookupManager.get_evidence_by_hash | def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() | python | def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() | [
"def",
"get_evidence_by_hash",
"(",
"self",
",",
"evidence_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"Evidence",
"]",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Evidence",
")",
".",
"filter",
"(",
"Evidence",
".",
"sha512",
"==",
"ev... | Look up an evidence by its hash. | [
"Look",
"up",
"an",
"evidence",
"by",
"its",
"hash",
"."
] | c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0 | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/lookup_manager.py#L60-L62 | train | 29,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.