code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
jobs_to_queue = list()
for job in jobs:
if job.should_start:
job.status = JobStatus.QUEUED
else:
job.status = JobStatus.WAITING
jobs_to_queue.append(job.serialize())
if jobs_to_queue:
self._run_script(
... | def enqueue_jobs(self, jobs: Iterable[Job]) | Enqueue a batch of jobs. | 4.299309 | 4.111172 | 1.045762 |
jobs_json_string = self._run_script(
self._get_jobs_from_queue,
self._to_namespaced(queue),
self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)),
JobStatus.RUNNING.value,
max_jobs
)
jobs = json.loads(jobs_json_string.decode(... | def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job] | Get jobs from a queue. | 4.719943 | 4.504072 | 1.047928 |
tasks = [task.serialize() for task in tasks]
self._number_periodic_tasks = len(tasks)
self._run_script(
self._register_periodic_tasks,
math.ceil(datetime.now(timezone.utc).timestamp()),
self._to_namespaced(PERIODIC_TASKS_HASH_KEY),
self._t... | def register_periodic_tasks(self, tasks: Iterable[Task]) | Register tasks that need to be scheduled periodically. | 6.074549 | 5.280072 | 1.150467 |
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', withscores=True
)
return [(int(r[1]), r[0].decode()) for r in rv] | def inspect_periodic_tasks(self) -> List[Tuple[int, str]] | Get the next periodic task schedule.
Used only for debugging and during tests. | 4.54925 | 4.459418 | 1.020144 |
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', start=0, num=1, withscores=True,
score_cast_func=int
)
if not rv:
return None
now = datetime.now(timezone.utc).timestamp()
next_eve... | def next_future_periodic_delta(self) -> Optional[float] | Give the amount of seconds before the next periodic task is due. | 3.531928 | 3.242059 | 1.089409 |
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, now running... ")
hnv_agent.daemon_loop() | def main() | The entry point for the HNV Agent. | 5.700446 | 3.79089 | 1.503723 |
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_network)
vswitch_map = {
'network_type': network_type,
'vswitch_name': vswitch_name,
'ports': [],
'vlan_id': segmentation_id}
... | def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id) | Provision the network with the received information. | 2.551954 | 2.53501 | 1.006684 |
super(HNVAgent, self)._port_bound(port_id, network_id, network_type,
physical_network, segmentation_id,
port_security_enabled,
set_port_sriov)
LOG.debug("Getting the pro... | 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. | 2.877543 | 2.859715 | 1.006234 |
# This is implemented as a single burst packet sent using the bursty
# interface. This significantly reduces code duplication.
# Construct a callable to retain the returned packet for us
class Callback(object):
def __init__(self):
self.packet = None
... | def send_scp(self, buffer_size, x, y, p, cmd, arg1=0, arg2=0, arg3=0,
data=b'', expected_args=3, timeout=0.0) | 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... | 5.222591 | 5.376061 | 0.971453 |
# Prepare the buffer to receive the incoming data
data = bytearray(length_bytes)
mem = memoryview(data)
# Create a callback which will write the data from a packet into a
# memoryview.
def callback(mem, data):
mem[:] = data[6 + consts.SDP_HEADER_LENG... | def read(self, buffer_size, window_size, x, y, p, address, length_bytes) | 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
... | 5.795754 | 5.442326 | 1.064941 |
# While there is still data perform a write: get the block to write
# this time around, determine the data type, perform the write and
# increment the address
def packets(address, data):
end = len(data)
pos = 0
while pos < end:
... | def write(self, buffer_size, window_size, x, y, p, address, data) | 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
... | 7.447281 | 7.40029 | 1.00635 |
msg = re.sub("\n", "<br />", msg, flags=re.MULTILINE)
return msg | def convert_msg_to_html(msg) | Convert \n into a <BR> for an HTML formatted message | 4.26771 | 3.642225 | 1.171732 |
spec_dir = config["bel"]["lang"]["specifications"]
spec_dict = {}
bel_versions = get_bel_versions()
if version not in bel_versions:
log.error("Cannot get unknown version BEL specification")
return {"error": "unknown version of BEL"}
# use this variable to find our parser file... | def get_specification(version: str) -> Mapping[str, Any] | 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 | 6.244405 | 5.729205 | 1.089925 |
spec_dir = config["bel"]["lang"]["specifications"]
fn = f"{spec_dir}/versions.json"
with open(fn, "r") as f:
versions = json.load(f)
return versions | def get_bel_versions() -> List[str] | 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... | 5.496603 | 4.844041 | 1.134714 |
spec_dir = config["bel"]["lang"]["specifications"]
if not os.path.isdir(spec_dir):
os.mkdir(spec_dir)
log.info(f"Updating BEL Specifications - stored in {spec_dir}")
# Collect new specifications from Git repository
if config["bel"]["lang"]["specification_github_repo"]:
github... | def update_specifications(force: bool = False) | 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. | 4.194986 | 3.649746 | 1.149391 |
if not force:
dtnow = datetime.datetime.utcnow()
delta = datetime.timedelta(1)
yesterday = dtnow - delta
for fn in glob.glob(f"{spec_dir}/bel*yaml"):
if datetime.datetime.fromtimestamp(os.path.getmtime(fn)) > yesterday:
log.info("Skipping BEL Specif... | def github_belspec_files(spec_dir, force: bool = False) | 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 | 2.503093 | 2.298213 | 1.089147 |
try:
spec_dict = yaml.load(open(yaml_fn, "r").read(), Loader=yaml.SafeLoader)
# admin-related keys
spec_dict["admin"] = {}
spec_dict["admin"]["version_underscored"] = spec_dict["version"].replace(".", "_")
spec_dict["admin"]["parser_fn"] = yaml_fn.replace(".yaml", "_pa... | def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str | 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... | 3.79454 | 3.568368 | 1.063382 |
for f in spec_dict["functions"]["signatures"]:
for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatures"]):
args_summary = ""
args_list = []
arg_idx = 0
for arg_idx, arg in enumerate(
spec_dict["functions"]["... | def add_function_signature_help(spec_dict: dict) -> dict | Add function signature help
Simplify the function signatures for presentation to BEL Editor users | 2.013346 | 1.974376 | 1.019738 |
# Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances
spec_dict["relations"]["list"] = []
spec_dict["relations"]["list_short"] = []
spec_dict["relations"]["list_long"] = []
spec_dict["relations"]["to_short"] = {}
spec_dict["relations"]["to_lo... | def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any] | 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 | 2.191484 | 2.231435 | 0.982096 |
# Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances
spec_dict["functions"]["list"] = []
spec_dict["functions"]["list_long"] = []
spec_dict["functions"]["list_short"] = []
spec_dict["functions"]["primary"] = {}
spec_dict["functions"]["prima... | def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any] | 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 | 1.782292 | 1.803816 | 0.988068 |
for ns in spec_dict["namespaces"]:
spec_dict["namespaces"][ns]["list"] = []
spec_dict["namespaces"][ns]["list_long"] = []
spec_dict["namespaces"][ns]["list_short"] = []
spec_dict["namespaces"][ns]["to_short"] = {}
spec_dict["namespaces"][ns]["to_long"] = {}
fo... | def add_namespaces(spec_dict) | Add namespace convenience keys, list, list_{short|long}, to_{short|long} | 1.806142 | 1.675538 | 1.077947 |
for func in spec_dict["functions"]["signatures"]:
for i, sig in enumerate(spec_dict["functions"]["signatures"][func]["signatures"]):
args = sig["arguments"]
req_args = []
pos_args = []
opt_args = []
mult_args = []
for arg in args:... | def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any] | 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 | 2.142244 | 2.091956 | 1.024039 |
spec_dir = config["bel"]["lang"]["specifications"]
local_fp = f"{spec_dir}/bel.ebnf.j2"
repo_url = (
"https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2"
)
params = {}
github_access_token = os.getenv("GITHUB_ACCESS_TOKEN", "")
if github_acce... | def get_ebnf_template() | Get EBNF template from Github belbio/bel_specifications repo | 2.788697 | 2.451134 | 1.137717 |
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_ebnf_template()
# Check if EBNF file is more recent than belspec_fn
ebnf_fn = belspec_fn.replace(".yaml",... | def create_ebnf_parser(files) | Create EBNF files and EBNF-based parsers | 2.560016 | 2.541679 | 1.007215 |
function_long = bel_spec["functions"]["to_long"].get(function)
function_help = []
if function_long:
for signature in bel_spec["functions"]["signatures"][function_long]["signatures"]:
function_help.append(
{
"function_summary": signature["argumen... | def get_function_help(function: str, bel_spec: BELSpec) | Get function_help given function name
This will get the function summary template (argument summary in signature)
and the argument help listing. | 4.67968 | 3.655113 | 1.280311 |
if loc >= span[0] and loc <= span[1]:
return True
else:
return False | def in_span(loc: int, span: Span) -> bool | Checks if loc is inside span | 3.545019 | 2.563724 | 1.382762 |
minimal_nsarg_completion_len = 1
species = [species_id]
namespaces = [namespace]
replace_list = []
if len(completion_text) >= minimal_nsarg_completion_len:
# Use BEL.bio API module if running bel module in BEL.bio API, otherwise call BEL.bio API endpoint
# is there a better... | def nsarg_completions(
completion_text: str,
entity_types: list,
bel_spec: BELSpec,
namespace: str,
species_id: str,
bel_fmt: str,
size: int,
) | 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... | 3.662225 | 3.52508 | 1.038905 |
if bel_fmt == "short":
relation_list = bel_spec["relations"]["list_short"]
else:
relation_list = bel_spec["relations"]["list_long"]
matches = []
for r in relation_list:
if re.match(completion_text, r):
matches.append(r)
replace_list = []
for match in m... | def relation_completions(
completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int
) -> list | 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 | 2.763247 | 2.612005 | 1.057903 |
# Convert provided function list to correct bel_fmt
if isinstance(function_list, list):
if bel_fmt in ["short", "medium"]:
function_list = [
bel_spec["functions"]["to_short"][fn] for fn in function_list
]
else:
function_list = [
... | def function_completions(
completion_text: str,
bel_spec: BELSpec,
function_list: list,
bel_fmt: str,
size: int,
) -> list | 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 | 2.761942 | 2.663226 | 1.037067 |
completions = []
for r in replace_list:
# if '(' not in belstr:
# replacement = f'{r["replacement"]}()'
# cursor_loc = len(replacement) - 1 # inside parenthesis
# elif r['type'] == 'Function' and replace_span[1] == len(belstr) - 1:
if len(belstr) > 0:
... | def add_completions(
replace_list: list, belstr: str, replace_span: Span, completion_text: str
) -> List[Mapping[str, Any]] | 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:
[{
... | 2.379937 | 2.264901 | 1.050791 |
ast, errors = pparse.get_ast_dict(belstr)
spans = pparse.collect_spans(ast)
completion_text = ""
completions = []
function_help = []
log.debug(f"Cursor location BELstr: {belstr} Cursor idx: {cursor_loc}")
cursor_results = cursor(belstr, ast, cursor_loc)
log.debug(f"Cursor resul... | 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: | 3.086569 | 3.049667 | 1.0121 |
bel_spec = bel_specification.get_specification(bel_version)
belstrlen = len(belstr)
if cursor_loc == -1:
cursor_loc = belstrlen - 1
elif cursor_loc >= belstrlen:
cursor_loc = belstrlen - 1
# with timy.Timer() as timer:
# (completion_text, completions, function_he... | def bel_completion(
belstr: str,
cursor_loc: int = -1,
bel_version: str = default_bel_version,
bel_comp: str = None,
bel_fmt: str = "medium",
species_id: str = None,
size: int = 20,
) -> Mapping[str, Any] | 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... | 2.50627 | 2.107382 | 1.189281 |
pstack, qstack, nested_pstack = [], [], []
parens, nested_parens, quotes, commas = {}, {}, {}, {}
notquoted_flag = True
for i, c in enumerate(bels):
prior_char = i - 1
# print('BEL', prior_char, b[prior_char])
# Find starting quote
if c == '"' and bels[prior_char]... | def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors] | 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 | 2.149175 | 2.104758 | 1.021103 |
parens = char_locs["parens"]
# Handle partial top-level function name
if not parens:
bels_len = len(bels) - 1
span = (0, bels_len)
parsed[span] = {
"name": "".join(bels),
"type": "Function",
"span": span,
"name_span": (span),
... | def parse_functions(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors] | 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... | 2.731946 | 2.784174 | 0.981241 |
commas = char_locs["commas"]
# Process each span key in parsed from beginning
for span in parsed:
if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]:
continue # Skip if not argument-less
sp, ep = parsed[span]["parens_span"]
# calculate arg... | def parse_args(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors] | 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 | 3.976016 | 3.757816 | 1.058066 |
func_pattern = re.compile(r"\s*[a-zA-Z]+\(")
nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$")
for span in parsed:
if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]:
continue
for i, arg in enumerate(parsed[span]["args"]):
nsarg_mat... | def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors] | 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 | 2.337534 | 2.321624 | 1.006853 |
quotes = char_locs["quotes"]
quoted_range = set([i for start, end in quotes.items() for i in range(start, end)])
for match in relations_pattern_middle.finditer(belstr):
(start, end) = match.span(1)
# log.debug(f'Relation-middle {match}')
end = end - 1 # adjust end to match act... | def parse_relations(
belstr: str, char_locs: CharLocs, 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): | 2.288405 | 2.376408 | 0.962968 |
for sp in char_locs[
"nested_parens"
]: # sp = start parenthesis, ep = end parenthesis
ep, level = char_locs["nested_parens"][sp]
if ep == -1:
ep = len(bels) + 1
parsed[(sp, ep)] = {"type": "Nested", "span": (sp, ep)}
return parsed, errors | def parse_nested(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors] | Parse nested BEL object | 5.583987 | 5.486292 | 1.017807 |
import json
k = d.keys()
v = d.values()
k1 = [str(i) for i in k]
return json.dumps(dict(zip(*[k1, v])), indent=4) | 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 | 4.725785 | 3.947001 | 1.19731 |
spans = []
if ast.get("subject", False):
spans.extend(collect_spans(ast["subject"]))
if ast.get("object", False):
spans.extend(collect_spans(ast["object"]))
if ast.get("nested", False):
spans.extend(collect_spans(ast["nested"]))
if ast.get("function", False):
... | def collect_spans(ast: AST) -> List[Tuple[str, Tuple[int, int]]] | 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... | 2.798738 | 2.563544 | 1.091746 |
bel_spans = [" "] * (max_idx + 3)
for val, span in spans:
if val in ["Nested", "NSArg"]:
continue
for i in range(span[0], span[1] + 1):
bel_spans[i] = val[0]
# print(''.join(bel_spans))
# Add second layer for Nested Objects if available
bel_spans = [" ... | def print_spans(spans, max_idx: int) -> None | Quick test to show how character spans match original BEL String
Mostly for debugging purposes | 4.004357 | 3.6578 | 1.094745 |
sub = parsed[parsed_key]
subtree = {
"type": "Function",
"span": sub["span"],
"function": {
"name": sub["name"],
"name_span": sub["name_span"],
"parens_span": sub.get("parens_span", []),
},
}
args = []
for arg in parsed[pars... | def parsed_function_to_ast(parsed: Parsed, parsed_key) | Create AST for top-level functions | 2.408199 | 2.26309 | 1.06412 |
# Error check
fn_cnt = 0
rel_cnt = 0
nested_cnt = 0
for key in parsed:
if parsed[key]["type"] == "Function":
fn_cnt += 1
if parsed[key]["type"] == "Relation":
rel_cnt += 1
if parsed[key]["type"] == "Nested":
nested_cnt += 1
if no... | def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors | 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 | 1.929545 | 1.860351 | 1.037194 |
ast = {}
sorted_keys = sorted(parsed.keys())
# Setup top-level tree
for key in sorted_keys:
if parsed[key]["type"] == "Nested":
nested_component_stack = ["subject", "object"]
if component_type:
component_stack = [component_type]
else:
component_stack =... | def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = "") | 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 | 2.360112 | 2.355704 | 1.001871 |
errors = []
parsed = {}
bels = list(belstr)
char_locs, errors = parse_chars(bels, errors)
parsed, errors = parse_functions(belstr, char_locs, parsed, errors)
parsed, errors = parse_args(bels, char_locs, parsed, errors)
parsed, errors = arg_types(parsed, errors)
parsed, errors = par... | def get_ast_dict(belstr, component_type: str = "") | 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 | 3.351612 | 3.382269 | 0.990936 |
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation = None
obj = None
if "relation" in ast_dict:
relation = ast_dict["relation"]["name"]
if... | def get_ast_obj(belstr, bel_version, component_type: str = "") | Convert AST partialparse dict to BELAst | 2.123457 | 2.004783 | 1.059195 |
if d["type"] == "Function":
ast_fn = Function(d["function"]["name"], spec, parent_function=parent_function)
for arg in d["args"]:
if arg["type"] == "Function":
ast_fn.add_argument(add_ast_fn(arg, spec, parent_function=ast_fn))
elif arg["type"] == "NSArg"... | def add_ast_fn(d, spec, parent_function=None) | Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn | 2.549253 | 2.487865 | 1.024675 |
if not api_url:
api_url = config["bel_api"]["servers"]["api_url"]
if not api_url:
log.error("Missing api url - cannot convert namespace")
return None
params = None
if namespace_targets:
namespace_targets_str = json.dumps(namespace_targets)
param... | def convert_nsarg(
nsarg: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str | [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... | 3.516428 | 3.297373 | 1.066433 |
# pattern - look for capitalized namespace followed by colon
# and either a quoted string or a string that
# can include any char other than space, comma or ')'
matches = re.findall(r'([A-Z]+:"(?:\\.|[^"\\])*"|[A-Z]+:(?:[^\),\s]+))', bel_str)
for nsarg in matches:
i... | def convert_namespaces_str(
bel_str: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str | 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... | 4.520471 | 4.170123 | 1.084014 |
if isinstance(ast, NSArg):
given_term_id = "{}:{}".format(ast.namespace, ast.value)
# Get normalized term if necessary
if (canonicalize and not ast.canonical) or (
decanonicalize and not ast.decanonical
):
normalized_term = convert_nsarg(
... | def convert_namespaces_ast(
ast,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) | 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... | 2.830561 | 2.724353 | 1.038985 |
if isinstance(ast, NSArg):
given_term_id = "{}:{}".format(ast.namespace, ast.value)
r = bel.terms.terms.get_normalized_terms(given_term_id)
ast.canonical = r["canonical"]
ast.decanonical = r["decanonical"]
r = bel.terms.terms.get_terms(ast.canonical)
if len(r... | def populate_ast_nsarg_defaults(ast, belast, species_id=None) | 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 | 4.041897 | 3.884929 | 1.040404 |
# if species_id == 'TAX:9606' and str(ast) == 'MGI:Sult2a1':
# import pdb; pdb.set_trace()
if not species_id:
bo.validation_messages.append(
("WARNING", "No species id was provided for orthologization")
)
return ast
if isinstance(ast, NSArg):
if as... | def orthologize(ast, bo, species_id: str) | 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... | 3.753613 | 3.881107 | 0.96715 |
ortholog_namespace = "EG"
if isinstance(ast, NSArg):
if re.match(ortholog_namespace, ast.canonical):
orthologs = bel.terms.orthologs.get_orthologs(
ast.canonical, list(species.keys())
)
for species_id in species:
if species_id in... | def populate_ast_nsarg_orthologs(ast, species) | 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 | 4.532074 | 4.091389 | 1.10771 |
stmt = stmt.strip() # remove newline at end of stmt
stmt = re.sub(r",+", ",", stmt) # remove multiple commas
stmt = re.sub(r",", ", ", stmt) # add space after each comma
stmt = re.sub(r" +", " ", stmt) # remove multiple spaces
return stmt | def preprocess_bel_stmt(stmt: str) -> str | Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement | 3.209234 | 3.142015 | 1.021394 |
quoted = re.findall(r'^"(.*)"$', nsarg_value)
if re.search(
r"[),\s]", nsarg_value
): # quote only if it contains whitespace, comma or ')'
if quoted:
return nsarg_value
else:
return f'"{nsarg_value}"'
else:
if quoted:
return quot... | 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. | 4.191476 | 3.044983 | 1.376519 |
with open("spec.yaml", "w") as f:
yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False) | def _dump_spec(spec) | 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. | 2.591267 | 2.798672 | 0.925892 |
edges = []
if ast.bel_object.__class__.__name__ == "BELAst":
edges.append(ast.bel_object)
process_ast(edges, ast, spec)
return edges | def compute_edges(ast: BELAst, spec: BELSpec) -> Edges | Compute edges | 6.830239 | 6.56067 | 1.041089 |
ast_type = ast.__class__.__name__
trigger_functions = rule.get("trigger_function", [])
trigger_types = rule.get("trigger_type", [])
rule_subject = rule.get("subject")
rule_relation = rule.get("relation")
rule_object = rule.get("object")
log.debug(f"Running {rule_relation} Type: {ast_t... | def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec) | Process computed edge rule
Recursively processes BELAst versus a single computed edge rule
Args:
edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs
ast (Function): BEL Function AST
rule (Mapping[str, Any]: computed edge rule | 2.00286 | 1.976959 | 1.013101 |
version = metadata["metadata"]["version"]
# LOAD ORTHOLOGS INTO ArangoDB
with timy.Timer("Load Orthologs") as timer:
arango_client = arangodb.get_client()
belns_db = arangodb.get_belns_handle(arango_client)
arangodb.batch_load_docs(
belns_db, orthologs_iterator(fo,... | def load_orthologs(fo: IO, metadata: dict) | Load orthologs into ArangoDB
Args:
fo: file obj - orthologs file
metadata: dict containing the metadata for orthologs | 4.341555 | 4.154544 | 1.045014 |
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
edge = json.loads(line)
if "metadata" in edge:
source = edge["metadata"]["source"]
continue
if "ortholog... | def orthologs_iterator(fo, version) | Ortholog node and edge iterator | 2.263777 | 2.226656 | 1.016671 |
species_id = "None"
species_label = "None"
species = [
(species_id, species_label) for (species_id, species_label) in ast.species if species_id
]
if len(species) == 1:
(species_id, species_label) = species[0]
if not species_id:
species_id = "None"
species_... | def extract_ast_species(ast) | Extract species from ast.species set of tuples (id, label) | 2.551933 | 2.367103 | 1.078083 |
url = f'{config["bel_api"]["servers"]["api_url"]}/terms/{orthologize_target}'
r = utils.get_url(url)
species_label = r.json().get("label", "unlabeled")
orthologized_from = {}
for idx, annotation in enumerate(annotations):
if annotation["type"] == "Species":
orthologized_fr... | def orthologize_context(
orthologize_target: str, annotations: Mapping[str, Any]
) -> Mapping[str, Any] | Orthologize context
Replace Species context with new orthologize target and add a annotation type of OrthologizedFrom | 3.174009 | 3.097078 | 1.02484 |
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_string() | def migrate(belstr: str) -> str | Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2 | 19.974678 | 18.84244 | 1.06009 |
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_triple() | def migrate_into_triple(belstr: str) -> str | Migrate BEL1 assertion into BEL 2.0.0 SRO triple | 21.262228 | 14.082199 | 1.509866 |
if ast and ast.type == "Function":
# Activity function conversion
if (
ast.name != "molecularActivity"
and ast.name in spec["namespaces"]["Activity"]["list"]
):
print("name", ast.name, "type", ast.type)
ast = convert_activity(ast)
... | def convert(ast) | Convert BEL1 AST Function to BEL2 AST Function | 4.461997 | 4.105108 | 1.086938 |
from_loc_arg = ast.args[1]
to_loc_arg = ast.args[2]
from_loc = Function("fromLoc", spec, parent_function=ast)
from_loc.add_argument(
NSArg(from_loc_arg.namespace, from_loc_arg.value, parent_function=from_loc)
)
to_loc = Function("toLoc", spec, parent_function=ast)
to_loc.add_ar... | def convert_tloc(ast) | Convert BEL1 tloc() to BEL2 | 2.630941 | 2.517035 | 1.045254 |
if len(ast.args) > 1:
log.error(f"Activity should not have more than 1 argument {ast.to_string()}")
p_arg = ast.args[0] # protein argument
print("p_arg", p_arg)
ma_arg = Function("ma", bo.spec)
ma_arg.add_argument(StrArg(ast.name, ma_arg))
p_arg.change_parent_fn(ma_arg)
ast =... | def convert_activity(ast) | Convert BEL1 activities to BEL2 act() | 4.698185 | 4.694686 | 1.000745 |
if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]:
pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][
pmod.args[0].value
]
return pmod | def convert_pmod(pmod) | Update BEL1 pmod() protein modification term | 6.435684 | 4.339412 | 1.483077 |
parent_fn_name = ast.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
fus1_ns = ast.args[0].namespace
fus1_val = ast.args[0].value
arg_fus = ast.args[1]
fus_args = [None, "?", "?"]
for idx, arg in enumerate(arg_fus.args):
fus... | def convert_fus(ast) | Convert BEL1 fus() to BEL2 fus() | 2.895163 | 2.754526 | 1.051057 |
args = sub.args
(ref_aa, pos, new_aa) = args
parent_fn_name = sub.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"{prefix}{spec["namespaces"]["AminoAcid"]["to_short"][ref_aa.value]}{pos.value}{spec["namespac... | def convert_sub(sub) | Convert BEL1 sub() to BEL2 var() | 8.267393 | 6.859434 | 1.205259 |
parent_fn_name = trunc.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"truncated at {trunc.args[0].value}"'
new_var = bel.lang.ast.Function("var", bo.spec)
new_var.add_argument(StrArg(new_var_arg, new_var))... | def convert_trunc(trunc) | Convert BEL1 trunc() to BEL2 var() | 9.464113 | 7.82591 | 1.209331 |
username = utils.first_true(
[username, config["bel_api"]["servers"]["arangodb_username"]], default=""
)
password = utils.first_true(
[password, config["secrets"]["bel_api"]["servers"].get("arangodb_password")],
default="",
)
return username, password | def get_user_creds(username, password) | Get username/password
Use provided username and password OR in config OR blank in that order | 7.428438 | 6.386791 | 1.163094 |
host = utils.first_true(
[host, config["bel_api"]["servers"]["arangodb_host"], "localhost"]
)
port = utils.first_true([port, config["bel_api"]["servers"]["arangodb_port"], 8529])
username = utils.first_true(
[username, config["bel_api"]["servers"]["arangodb_username"], ""]
)
... | def get_client(host=None, port=None, username=None, password=None, enable_logging=True) | Get arango client and edgestore db handle | 2.844542 | 2.69639 | 1.054944 |
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "edgestore"
try:
if username and password:
edgestore_db = sys_db.create_database(
name=edgestore_db_name... | def get_edgestore_handle(
client: arango.client.ArangoClient,
username=None,
password=None,
edgestore_db_name: str = edgestore_db_name,
edgestore_edges_name: str = edgestore_edges_name,
edgestore_nodes_name: str = edgestore_nodes_name,
edgestore_pipeline_name: str = edgestore_pipeline_name,
... | Get Edgestore arangodb database handle
Args:
client (arango.client.ArangoClient): Description
username (None, optional): Description
password (None, optional): Description
edgestore_db_name (str, optional): Description
edgestore_edges_name (str, optional): Description
... | 2.259059 | 2.248156 | 1.00485 |
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belns"
try:
if username and password:
belns_db = sys_db.create_database(
name=belns_db_name,
... | def get_belns_handle(client, username=None, password=None) | Get BEL namespace arango db handle | 2.052763 | 1.928696 | 1.064327 |
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belapi"
try:
if username and password:
belapi_db = sys_db.create_database(
name=belapi_db_name,
... | def get_belapi_handle(client, username=None, password=None) | Get BEL API arango db handle | 2.384703 | 2.168013 | 1.099949 |
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
try:
return sys_db.delete_database(db_name)
except Exception:
log.warn("No arango database {db_name} to delete, does not exist") | def delete_database(client, db_name, username=None, password=None) | Delete Arangodb database | 4.694481 | 4.097144 | 1.145794 |
batch_size = 100
counter = 0
collections = {}
docs = {}
if on_duplicate not in ["error", "update", "replace", "ignore"]:
log.error(f"Bad parameter for on_duplicate: {on_duplicate}")
return
for (collection_name, doc) in doc_iterator:
if collection_name not in coll... | def batch_load_docs(db, doc_iterator, on_duplicate="replace") | Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
https://python-driver-for-arangodb.readthedocs.io/en/master/specs.html?h... | 2.204514 | 1.993817 | 1.105675 |
key = re.sub(r"[^a-zA-Z0-9\_\-\:\.\@\(\)\+\,\=\;\$\!\*\%]+", r"_", _id)
if len(key) > 254:
log.error(
f"Arango _key cannot be longer than 254 chars: Len={len(key)} Key: {key}"
)
elif len(key) < 1:
log.error(f"Arango _key cannot be an empty string: Len={len(key)} K... | def arango_id_to_key(_id) | Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed | 3.704879 | 3.555927 | 1.041888 |
log.info(f"Loading resource {resource_url}")
try:
# Download resource
fo = bel.utils.download_file(resource_url)
if not fo:
log.error(f"Could not download and open file {resource_url}")
return "Failed to download resource_url"
# Get metadata
... | def load_resource(resource_url: str, forceupdate: bool = False) | Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL API
forceupdate: force full update - e.g. don't leave Elasti... | 3.975442 | 3.633172 | 1.094207 |
search_body = {
"query": {
"bool": {
"should": [
{"term": {"id": term_id}},
{"term": {"alt_ids": term_id}},
{"term": {"obsolete_ids": term_id}},
]
}
}
}
result = es.sear... | def get_terms(term_id) | Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids | 2.182716 | 1.808992 | 1.206592 |
try:
errors = []
terms = get_terms(term_id)
if len(terms) == 0:
return {"equivalents": [], "errors": errors}
elif len(terms) > 1:
errors.append(
f'Too many primary IDs returned. Given term_id: {term_id} matches these term_ids: {[term["id"]... | def get_equivalents(term_id: str) -> List[Mapping[str, Union[str, bool]]] | Get equivalents given ns:id
Args:
term_id (str): term id
Returns:
List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False] | 3.317105 | 3.155225 | 1.051305 |
if equivalents and len(equivalents) > 0:
for start_ns in namespace_targets:
if re.match(start_ns, term_id):
for target_ns in namespace_targets[start_ns]:
for e in equivalents:
if e and target_ns in e["namespace"] and e["primary"]:... | def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str | Get normalized term | 3.456314 | 3.21458 | 1.075199 |
term_labels = {}
for term_id in term_ids:
term = get_terms(term_id)
term_labels[term_id] = term[0].get("label", "")
return term_labels | def get_labels(term_ids: list) -> dict | Get term labels given term ids
This only takes the first term returned for a term_id so use the
unique term_id for a term not an alternate id that might not be unique. | 2.83467 | 2.371081 | 1.195518 |
canonical = term_id
decanonical = term_id
canonical_namespace_targets = config["bel"]["lang"]["canonical"]
decanonical_namespace_targets = config["bel"]["lang"]["decanonical"]
results = get_equivalents(term_id)
equivalents = results["equivalents"]
# log.debug(f'Equivalents: {equivale... | def get_normalized_terms(term_id: str) -> dict | Get normalized terms - canonical/decanonical forms | 3.165254 | 2.786849 | 1.135783 |
params = {'accountNumber': self._service.accountNumber}
# Include object variables that are in field_order
for key, val in self.__dict__.iteritems():
if key in self.field_order:
# Turn into Unicode
if isinsta... | def _get_params(self) | Generate SOAP parameters. | 3.724176 | 3.514773 | 1.059578 |
self.hash = None
str_hash = ''
for key, val in self._get_params().iteritems():
str_hash += smart_str(val)
# Append the encryption string
str_hash += self._service.encryption_key
# Set md5 hash on the object
... | def _generate_hash(self) | Generates a hash based on the specific fields for the method. | 5.820033 | 5.02889 | 1.15732 |
# Generate the hash variable and parameters
self._generate_hash()
params = self._get_params()
# Make the SOAP request
try:
resp = self._endpoint(**params)
logger.debug(resp)
except WebFault, e:
logger.exceptio... | def _send_request(self) | Make the SOAP request and convert the result to a dictionary. | 5.658853 | 5.059223 | 1.118522 |
if self._service.production:
url = self.production_url
else:
url = self.testing_url
proxy_options = dict()
https_proxy_setting = os.environ.get('PAYEX_HTTPS_PROXY') or os.environ.get('https_proxy')
http_proxy_setting = os.environ... | def client_factory(self) | Custom client factory to set proxy options. | 2.495921 | 2.368395 | 1.053845 |
accepted_actions = ('link', 'js')
for action in accepted_actions:
if action in combination:
return {action: combination[action]}
return {} | def get_combination_action(combination) | Prepares the action for a keyboard combination, also filters another
"strange" actions declared by the user. | 7.707881 | 6.570568 | 1.173092 |
hotkeys = hotkeys or ks_settings.HOTKEYS
processed_hotkeys = AutoVivification()
if not hotkeys:
return processed_hotkeys
for combination in hotkeys:
key_codes = get_key_codes(combination['keys'])
if len(key_codes) == 1:
processed_hotkeys[key_codes[0]] = get_comb... | def get_processed_hotkeys(hotkeys=None) | Process passed dict with key combinations or the HOTKEYS dict from
settings. | 2.328693 | 2.398452 | 0.970915 |
keys = keys.strip().upper().split('+')
codes = list()
for key in keys:
code = ks_settings.KEY_CODES.get(key.strip())
if code:
codes.append(code)
return codes | def get_key_codes(keys) | Calculates the list of key codes from a string with key combinations.
Ex: 'CTRL+A' will produce the output (17, 65) | 3.768064 | 3.796419 | 0.992531 |
self.ast = None
self.parse_valid = False
self.parse_visualize_error = ""
self.validation_messages = [] # Reset messages when parsing a new BEL Statement
if isinstance(assertion, dict):
if assertion.get("relation", False) and assertion.get("object", False):... | def parse(
self,
assertion: Union[str, Mapping[str, str]],
strict: bool = False,
parseinfo: bool = False,
rule_name: str = "start",
error_level: str = "WARNING",
) -> "BEL" | Parse and semantically validate BEL statement
Parses a BEL statement given as a string and returns an AST, Abstract Syntax Tree (defined in ast.py)
if the statement is valid, self.parse_valid. Else, the AST attribute is None and there will be validation error messages
in self.validation_message... | 3.672254 | 3.391686 | 1.082722 |
# TODO Need to order position independent args
if not self.ast:
return self
# Collect canonical/decanonical NSArg values
if not self.ast.collected_nsarg_norms:
self = self.collect_nsarg_norms()
# TODO Need to pass namespace target overrides fo... | def canonicalize(self, namespace_targets: Mapping[str, List[str]] = None) -> "BEL" | Takes an AST and returns a canonicalized BEL statement string.
Args:
namespace_targets (Mapping[str, List[str]]): override default canonicalization
settings of BEL.bio API api_url - see {api_url}/status to get default canonicalization settings
Returns:
BEL: retu... | 10.128181 | 9.200106 | 1.100877 |
start_time = datetime.datetime.now()
self.ast = bel_utils.populate_ast_nsarg_defaults(self.ast, self.ast)
self.ast.collected_nsarg_norms = True
if (
hasattr(self.ast, "bel_object")
and self.ast.bel_object
and self.ast.bel_object.type == "BELA... | def collect_nsarg_norms(self) | Adds canonical and decanonical values to NSArgs in AST
This prepares the AST object for (de)canonicalization | 3.985667 | 3.63048 | 1.097835 |
if not self.ast:
return self
# Collect canonical/decanonical NSArg values
if not self.ast.collected_orthologs:
self = self.collect_orthologs([species_id])
self.ast.species = set()
self.ast = bel_utils.orthologize(self.ast, self, species_id)
... | def orthologize(self, species_id: str) -> "BEL" | Orthologize BEL AST to given species_id
Will return original entity (ns:value) if no ortholog found.
Args:
species_id (str): species id to convert genes/rna/proteins into
Returns:
BEL: returns self | 8.960594 | 9.451551 | 0.948055 |
if not species:
return self
species_labels = bel.terms.terms.get_labels(species)
# Collect canonical/decanonical NSArg values
if not self.ast.collected_nsarg_norms:
self = self.collect_nsarg_norms()
start_time = datetime.datetime.now()
... | def collect_orthologs(self, species: list) -> "BEL" | Add NSArg orthologs for given species (TAX:<number format)
This will add orthologs to the AST for all of the given species (as available).
NOTE: This will run self.collect_nsarg_norms() first if not already available
as we need the canonical forms of the NSArgs | 4.561458 | 3.775691 | 1.208112 |
if not self.ast:
return self
edges_asts = bel.edge.computed.compute_edges(self.ast, self.spec)
if ast_result:
return edges_asts
edges = []
for ast in edges_asts:
edges.append(
{
"subject": ast.be... | def compute_edges(
self, rules: List[str] = None, ast_result=False, fmt="medium"
) -> List[Mapping[str, Any]] | Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of computed edge rules if given.
Args:
rules (list): a list of rules to filter; only the rules in this list will be ap... | 3.791309 | 3.279223 | 1.156161 |
if self.ast:
return self.ast.to_triple(ast_obj=self.ast, fmt=fmt)
else:
return {} | def to_triple(self, fmt: str = "medium") -> dict | Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Ret... | 6.469039 | 5.727915 | 1.129388 |
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | def print_tree(self) -> str | Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST | 7.552445 | 5.388883 | 1.401486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.