text stringlengths 81 112k |
|---|
Call the given cmd in a subprocess, piping stdout/err
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than simple text.
def system_piped(self, cmd)... |
Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace.
def var_expand(self, cmd, depth... |
Run a cell via a shell command
The `%%script` line is like the #! line of script,
specifying a program (bash, perl, ruby, etc.) with which to run.
The rest of the cell is run by that program.
Examples
--------
::
In [1]: %%script bash
...: f... |
Generate a listing of each vertex's immedate neighbours in an undirected
interpretation of a graph.
Returns
-------
{vertex: {vertex: weight, ...}), ...}
def _get_vertices_neighbours(nets):
"""Generate a listing of each vertex's immedate neighbours in an undirected
interpretation of a graph.
... |
Generate all the vertices connected to the supplied vertex in
depth-first-search order.
def _dfs(vertex, vertices_neighbours):
"""Generate all the vertices connected to the supplied vertex in
depth-first-search order.
"""
visited = set()
to_visit = deque([vertex])
while to_visit:
ve... |
Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-----... |
Yield the Cuthill-McKee order for a connected, undirected graph.
`Wikipedia
<https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides
a good introduction to the Cuthill-McKee algorithm. The RCM algorithm
attempts to order vertices in a graph such that their adjacency matrix's
bandw... |
A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer.
def rcm_vertex_order(vertices_resources, nets):
"""A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the... |
A generator which iterates over a set of chips in a machine in
Reverse-Cuthill-McKee order.
For use as a chip ordering for the sequential placer.
def rcm_chip_order(machine):
"""A generator which iterates over a set of chips in a machine in
Reverse-Cuthill-McKee order.
For use as a chip ordering ... |
Assigns vertices to chips in Reverse-Cuthill-McKee (RCM) order.
The `RCM <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_
algorithm (in graph-centric terms) is a simple breadth-first-search-like
heuristic which attempts to yield an ordering of vertices which would yield
a 1D placement ... |
Register the Datadog integration.
Exceptions making jobs fail are sent to Sentry.
:param tracer: optionally use a custom ddtrace Tracer instead of the global
one.
:param namespace: optionally only register the Datadog integration for a
particular Spinach :class:`Engine`
:param se... |
A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same name as the resource term
def copy_reference(resource, doc, env... |
A Row generating function that copies all of the references that have the same 'Group' argument as this reference
The 'RefArgs' argument is a comma seperated list of arguments from the references that will be prepended to each
row.
:param resource:
:param doc:
:param env:
:param args:
:par... |
Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns
False if the time of either can't be determined
:param path: Optional extra save path, used in save_path()
def is_older_than_metadata(self):
"""
Return True if the package save fil... |
The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the
CSV package is built from a file system ackage on a publically acessible server.
def _load_resource(self, source_r, abs_path=False):
"""The CSV package has no resources, so we just need to resolve the URLs t... |
Load a single documentation entry
def _load_documentation(self, term, contents, file_name):
"""Load a single documentation entry"""
try:
title = term['title'].value
except KeyError:
self.warn("Documentation has no title, skipping: '{}' ".format(term.value))
... |
JSON serializer for objects not serializable by default json code
def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime.datetime):
serial = obj.isoformat(sep='T')
return serial
if isinstance(obj, uuid.UUID):
serial =... |
The data that will be sent to the RESTful API
def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict__
pid = d.pop('process', 'nopid')
tid = d.pop('thread', 'n... |
record: generated from logger module
This preps the payload to be formatted in whatever content-type is
expected from the RESTful API.
returns: a tuple of the data and the http content-type
def _prepPayload(self, record):
"""
record: generated from logger module
This pr... |
Override emit() method in handler parent for sending log to RESTful API
def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful API
"""
# avoid infinite recursion
if record.name.startswith('requests'):
return
data, hea... |
Override Build Loggly's RESTful API endpoint
def _getEndpoint(self, add_tags=None):
"""
Override Build Loggly's RESTful API endpoint
"""
return 'https://logs-01.loggly.com/bulk/{0}/tag/{1}/'.format(
self.custom_token,
self._implodeTags(add_tags=add_tags)
... |
The data that will be sent to loggly.
def _getPayload(self, record):
"""
The data that will be sent to loggly.
"""
payload = super(LogglyHandler, self)._getPayload(record)
payload['tags'] = self._implodeTags()
return payload |
Override emit() method in handler parent for sending log to RESTful
API
def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful
API
"""
pid = os.getpid()
if pid != self.pid:
self.pid = pid
self.logs... |
Return the non versioned name
def nonver_name(self):
"""Return the non versioned name"""
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv |
Return the Root.Description, possibly combining multiple terms.
:return:
def wrappable_term(self, term):
"""Return the Root.Description, possibly combining multiple terms.
:return:
"""
return ' '.join(e.value.strip() for e in self['Root'].find(term) if e and e.value) |
Set the Root.Description, possibly splitting long descriptions across multiple terms.
def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_t... |
Load the 'lib' directory as a python module, so it can be used to provide functions
for rowpipe transforms. This only works filesystem packages
def get_lib_module_dict(self):
"""Load the 'lib' directory as a python module, so it can be used to provide functions
for rowpipe transforms. This only... |
Produce HTML for Jupyter Notebook
def _repr_html_(self, **kwargs):
"""Produce HTML for Jupyter Notebook"""
from jinja2 import Template
from markdown import markdown as convert_markdown
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition'
... |
Write CSV file. Sorts the sections before calling the superclass write_csv
def write_csv(self, path=None):
"""Write CSV file. Sorts the sections before calling the superclass write_csv"""
# Sort the Sections
self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', '... |
A wizard which attempts to determine the dimensions of a SpiNNaker
system.
.. warning::
Since SC&MP v2.0.0 it is not necessary to know the dimensions of a
SpiNNaker machine in order to boot it. As a result, most applications
will no longer require this wizard step.
Returns ``{"dim... |
A wizard which attempts to determine the IP of a SpiNNaker system.
Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.wizard.Success`
exception.
def ip_address_wizard():
"""A wizard which attempts to determine the IP of a SpiNNaker system.
Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.... |
A higher-order wizard which is the concatenation of a number of other
wizards.
The resulting data is the union of all wizard outputs.
def cat(*wizards):
"""A higher-order wizard which is the concatenation of a number of other
wizards.
The resulting data is the union of all wizard outputs.
"""... |
Given a wizard, implements an interactive command-line human-friendly
interface for it.
Parameters
----------
generator
A generator such as one created by calling
:py:func:`rig.wizard.wizard_generator`.
Returns
-------
dict or None
Returns a dictionary containing th... |
Get the cost of a given net.
This function, in principle at least, should estimate the total network
resources consumed by the given net. In practice this estimate is based on
the size of the bounding-box of the net (i.e. HPWL). This should be
improved at some later time to better account for the effec... |
Get the total cost of the nets connected to the given vertex.
Parameters
----------
vertex
The vertex whose nets we're interested in.
v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...}
placements : {vertex: (x, y), ...}
has_wrap_around_links : bool
machine : :py:class:`rig.plac... |
Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
resources : {resource: value, ...}
The amount of resources which are required at the specified location.
location : ... |
Swap the positions of two sets of vertices.
Parameters
----------
vas : [vertex, ...]
A set of vertices currently at vas_location.
vas_location : (x, y)
vbs : [vertex, ...]
A set of vertices currently at vbs_location.
vbs_location : (x, y)
l2v : {(x, y): [vertex, ...], ...}
... |
Attempt a single swap operation: the kernel of the Simulated Annealing
algorithm.
Parameters
----------
vertices : [vertex, ...]
The set of *movable* vertices.
d_limit : int
The maximum distance over-which swaps are allowed.
temperature : float > 0.0 or None
The temperat... |
Initialization that must happen before the broker is (re)started.
def _reset(self):
"""Initialization that must happen before the broker is (re)started."""
self._subscriber_thread = None
self._must_stop = threading.Event()
self._number_periodic_tasks = 0 |
Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
def _load_script(self, filename: str) -> Script:
"""Load a Lua script.
Read the Lua scr... |
Enqueue a batch of jobs.
def enqueue_jobs(self, jobs: Iterable[Job]):
"""Enqueue a batch of jobs."""
jobs_to_queue = list()
for job in jobs:
if job.should_start:
job.status = JobStatus.QUEUED
else:
job.status = JobStatus.WAITING
... |
Get jobs from a queue.
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]:
"""Get jobs from a queue."""
jobs_json_string = self._run_script(
self._get_jobs_from_queue,
self._to_namespaced(queue),
self._to_namespaced(RUNNING_JOBS_KEY.format(self._id... |
Register tasks that need to be scheduled periodically.
def register_periodic_tasks(self, tasks: Iterable[Task]):
"""Register tasks that need to be scheduled periodically."""
tasks = [task.serialize() for task in tasks]
self._number_periodic_tasks = len(tasks)
self._run_script(
... |
Get the next periodic task schedule.
Used only for debugging and during tests.
def inspect_periodic_tasks(self) -> List[Tuple[int, str]]:
"""Get the next periodic task schedule.
Used only for debugging and during tests.
"""
rv = self._r.zrangebyscore(
self._to_name... |
Give the amount of seconds before the next periodic task is due.
def next_future_periodic_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next periodic task is due."""
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+i... |
The entry point for the HNV Agent.
def main():
"""The entry point for the HNV Agent."""
neutron_config.register_agent_state_opts_helper(CONF)
common_config.init(sys.argv[1:])
neutron_config.setup_logging()
hnv_agent = HNVAgent()
# Start everything.
LOG.info("Agent initialized successfully... |
Provision the network with the received information.
def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_nam... |
Bind the port to the recived network.
def _port_bound(self, port_id, network_id, network_type, physical_network,
segmentation_id, port_security_enabled, set_port_sriov):
"""Bind the port to the recived network."""
super(HNVAgent, self)._port_bound(port_id, network_id, network_type,
... |
Transmit a packet to the SpiNNaker machine and block until an
acknowledgement is received.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, determines how many
bytes will be expected in a socket.
x : int
y : i... |
Send a burst of SCP packets and call a callback for each returned
packet.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, determines how many
bytes will be expected in a socket.
window_size : int
Number o... |
Read a bytestring from an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_.
Parameters
----------
buffer_size : int
... |
Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_.
Parameters
----------
buffer_size : int
... |
Convert \n into a <BR> for an HTML formatted message
def convert_msg_to_html(msg):
"""Convert \n into a <BR> for an HTML formatted message"""
msg = re.sub("\n", "<br />", msg, flags=re.MULTILINE)
return msg |
Validate Nanopub
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
The validation result is a list of objects containing
{
'level': 'Warning|Error',
'section': 'Assertion|Annotation|Structure',
... |
Get BEL Specification
The json file this depends on is generated by belspec_yaml2json as
part of the update_specifications function
Args:
version: e.g. 2.0.0 where the filename
def get_specification(version: str) -> Mapping[str, Any]:
"""Get BEL Specification
The json file this depends o... |
Get BEL Language versions supported
Get the list of all BEL Language versions supported. The file this depends
on is generated by belspec_yaml2json and is kept up to date using
`make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json`
directly as it's added as a command by pip... |
Update BEL specifications
Collect BEL specifications from Github BELBio BEL Specification folder
and store in local directory specified in belbio_conf.yaml
Process all BEL Specifications in YAML into an enhanced JSON version
and capture all BEL versions in a separate file for quick access.
def update... |
Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
def github_belspec_files(spec_dir, force: bool = False):
"""Get belspec files from G... |
Enhance BEL specification and save as JSON file
Load all BEL Specification YAML files and convert to JSON files
after enhancing them. Also create a bel_versions.json file with
all available BEL versions for fast loading.
Args:
yaml_fn: original YAML version of BEL Spec
json_fn: enhanc... |
Add function signature help
Simplify the function signatures for presentation to BEL Editor users
def add_function_signature_help(spec_dict: dict) -> dict:
"""Add function signature help
Simplify the function signatures for presentation to BEL Editor users
"""
for f in spec_dict["functions"]["sig... |
Add relation keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added relation keys
def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add relation keys to spec_dict
A... |
Add function keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added function keys
def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add function keys to spec_dict
A... |
Add namespace convenience keys, list, list_{short|long}, to_{short|long}
def add_namespaces(spec_dict):
"""Add namespace convenience keys, list, list_{short|long}, to_{short|long}"""
for ns in spec_dict["namespaces"]:
spec_dict["namespaces"][ns]["list"] = []
spec_dict["namespaces"][ns]["list_l... |
Enhance function signatures
Add required and optional objects to signatures objects for semantic validation
support.
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: return enhanced bel specification dict
def enhance_function_signatures(sp... |
Get EBNF template from Github belbio/bel_specifications repo
def get_ebnf_template():
"""Get EBNF template from Github belbio/bel_specifications repo"""
spec_dir = config["bel"]["lang"]["specifications"]
local_fp = f"{spec_dir}/bel.ebnf.j2"
repo_url = (
"https://api.github.com/repos/belbio/be... |
Create EBNF files and EBNF-based parsers
def create_ebnf_parser(files):
"""Create EBNF files and EBNF-based parsers"""
flag = False
for belspec_fn in files:
# Get EBNF Jinja template from Github if enabled
if config["bel"]["lang"]["specification_github_repo"]:
tmpl_fn = get_ebn... |
Get function_help given function name
This will get the function summary template (argument summary in signature)
and the argument help listing.
def get_function_help(function: str, bel_spec: BELSpec):
"""Get function_help given function name
This will get the function summary template (argument summ... |
Checks if loc is inside span
def in_span(loc: int, span: Span) -> bool:
"""Checks if loc is inside span"""
if loc >= span[0] and loc <= span[1]:
return True
else:
return False |
Find BEL function or argument at cursor location
Args:
belstr: BEL String used to create the completion_text
ast (Mapping[str, Any]): AST (dict) of BEL String
cursor_loc (int): given cursor location from input field
cursor_loc starts at 0, think of it like a block cursor coverin... |
Namespace completions
Args:
completion_text
entity_types: used to filter namespace search results
bel_spec: used to search default namespaces
namespace: used to filter namespace search results
species_id: used to filter namespace search results
bel_fmt: used to selec... |
Filter BEL relations by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL relations that match prefix
def relation_completions(
completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int... |
Filter BEL functions by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL functions that match prefix
def function_completions(
completion_text: str,
bel_spec: BELSpec,
function_list: ... |
Function argument completion
Only allow legal options for completion given function name, arguments and index of argument
to replace.
Args:
completion_text: text to use for completion - used for creating highlight
parent_function: BEL function containing these args
args: arguments ... |
Create completions to return given replacement list
Args:
replace_list: list of completion replacement values
belstr: BEL String
replace_span: start, stop of belstr to replace
completion_text: text to use for completion - used for creating highlight
Returns:
[{
... |
Get BEL Assertion completions
Args:
Results:
def get_completions(
belstr: str,
cursor_loc: int,
bel_spec: BELSpec,
bel_comp: str,
bel_fmt: str,
species_id: str,
size: int,
):
"""Get BEL Assertion completions
Args:
Results:
"""
ast, errors = pparse.get_ast_d... |
BEL Completion
Args:
belstr (str): BEL String to provide completion for
cursor_loc (int): cursor location - default of -1 means end of string
bel_version (str): BEL Language version to use for completion
bel_comp (str): ['subject', 'object', 'full', None] - a nested statement has to... |
Scan BEL string to map parens, quotes, commas
Args:
bels: bel string as an array of characters
errors: list of error tuples ('<type>', '<msg>')
Returns:
(char_locs, errors): character locations and errors
def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors]:
"""S... |
Parse functions from BEL using paren, comma, quote character locations
Args:
bels: BEL string as list of chars
char_locs: paren, comma, quote character locations
errors: Any error messages generated during the parse
Returns:
(functions, errors): function names and locations and... |
Parse arguments from functions
Args:
bels: BEL string as list of chars
char_locs: char locations for parens, commas and quotes
parsed: function locations
errors: error messages
Returns:
(functions, errors): function and arg locations plus error messages
def parse_args(... |
Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messages
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
... |
Parse relations from BEL string
Args:
belstr: BEL string as one single string (not list of chars)
char_locs: paren, comma and quote char locations
parsed: data structure for parsed functions, relations, nested
errors: error messages
Returns:
(parsed, errors):
def parse... |
Parse nested BEL object
def parse_nested(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
""" Parse nested BEL object """
for sp in char_locs[
"nested_parens"
]: # sp = start parenthesis, ep = end parenthesis
ep, level = char_locs["nested_pa... |
Dump json when using tuples for dictionary keys
Have to convert tuples to strings to dump out as json
def dump_json(d: dict) -> None:
"""Dump json when using tuples for dictionary keys
Have to convert tuples to strings to dump out as json
"""
import json
k = d.keys()
v = d.values()
... |
Collect flattened list of spans of BEL syntax types
Provide simple list of BEL syntax type spans for highlighting.
Function names, NSargs, NS prefix, NS value and StrArgs will be
tagged.
Args:
ast: AST of BEL assertion
Returns:
List[Tuple[str, Tuple[int, int]]]: list of span objec... |
Quick test to show how character spans match original BEL String
Mostly for debugging purposes
def print_spans(spans, max_idx: int) -> None:
"""Quick test to show how character spans match original BEL String
Mostly for debugging purposes
"""
bel_spans = [" "] * (max_idx + 3)
for val, span i... |
Create AST for top-level functions
def parsed_function_to_ast(parsed: Parsed, parsed_key):
"""Create AST for top-level functions"""
sub = parsed[parsed_key]
subtree = {
"type": "Function",
"span": sub["span"],
"function": {
"name": sub["name"],
"name_span":... |
Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
"""Check full parse for... |
Convert parsed data struct to AST dictionary
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = ""):
"""Convert... |
Convert BEL string to AST dictionary
Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
def get_ast_dict(belstr, component_type: str = ""):
"""Convert BEL string to AST dictionary
Arg... |
Convert AST partialparse dict to BELAst
def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_as... |
Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn
def add_ast_fn(d, spec, parent_function=None):
"""Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
... |
[De]Canonicalize NSArg
Args:
nsarg (str): bel statement string or partial string (e.g. subject or object)
api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1
namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example
canonicalize (bool): u... |
Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
updated NSArg from the BEL.bio API terms endpoint.
Args:
bel_str (str): bel statement string or partial string (e.g. subject or object)
api_url (str): BEL.bio api url to use, e.g. https://ap... |
Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.
Args:
ast (BEL): BEL AST
api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicali... |
Recursively populate NSArg AST entries for default (de)canonical values
This was added specifically for the BEL Pipeline. It is designed to
run directly against ArangoDB and not through the BELAPI.
Args:
ast (BEL): BEL AST
Returns:
BEL: BEL AST
def populate_ast_nsarg_defaults(ast, be... |
Recursively orthologize BEL Entities in BEL AST using API endpoint
NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog)
Args:
ast (BEL): BEL AST
endpoint (str): endpoint url with a placeholder for the term_id
Returns:
BEL: BEL A... |
Recursively collect NSArg orthologs for BEL AST
This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available
Args:
ast: AST at recursive point in belobj
species: dictionary of species ids vs labels for or
def populate_ast_nsarg_orthologs(ast, species):
"""Recursi... |
Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement
def preprocess_bel_stmt(stmt: str) -> str:
"""Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
clean... |
Quoting nsargs
If needs quotes (only if it contains whitespace, comma or ')' ), make sure
it is quoted, else don't add them.
def quoting_nsarg(nsarg_value):
"""Quoting nsargs
If needs quotes (only if it contains whitespace, comma or ')' ), make sure
it is quoted, else don't add them.
... |
Dump bel specification dictionary using YAML
Formats this with an extra indentation for lists to make it easier to
use cold folding on the YAML version of the spec dictionary.
def _dump_spec(spec):
"""Dump bel specification dictionary using YAML
Formats this with an extra indentation for lists to mak... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.