Esempio n. 1
0
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_ast = add_ast_fn(subj, spec)

    relation = None
    obj = None

    if 'relation' in ast_dict:
        relation = ast_dict['relation']['name']

    if 'object' in ast_dict:
        obj = ast_dict['object']
        obj_ast = add_ast_fn(obj, spec)

        return BELAst(subj_ast, relation, obj_ast, spec)
    elif 'nested' in ast_dict:
        nested_subj = ast_dict['nested']['subject']
        nested_subj_ast = add_ast_fn(nested_subj, spec)
        nested_relation = ast_dict['nested']['relation']['name']
        nested_obj = ast_dict['nested']['object']
        nested_obj_ast = add_ast_fn(nested_obj, spec)

        return BELAst(subj_ast, relation, BELAst(nested_subj_ast, nested_relation, nested_obj_ast, spec), spec)

    return BELAst(subj_ast, None, None, spec)
Esempio n. 2
0
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_ast = add_ast_fn(subj, spec)

    relation = None
    obj = None

    if "relation" in ast_dict:
        relation = ast_dict["relation"]["name"]

    if "object" in ast_dict:
        obj = ast_dict["object"]
        obj_ast = add_ast_fn(obj, spec)

        return BELAst(subj_ast, relation, obj_ast, spec)
    elif "nested" in ast_dict:
        nested_subj = ast_dict["nested"]["subject"]
        nested_subj_ast = add_ast_fn(nested_subj, spec)
        nested_relation = ast_dict["nested"]["relation"]["name"]
        nested_obj = ast_dict["nested"]["object"]
        nested_obj_ast = add_ast_fn(nested_obj, spec)

        return BELAst(
            subj_ast, relation,
            BELAst(nested_subj_ast, nested_relation, nested_obj_ast, spec),
            spec)

    return BELAst(subj_ast, None, None, spec)
Esempio n. 3
0
    def __init__(self, version: str = None, api_url: str = None) -> None:
        """Initialize BEL object used for validating/processing/etc BEL statements

        Args:
            version (str): BEL Version, defaults to config['bel']['lang']['default_bel_version']
            api_url (str): BEL API endpoint,  defaults to config['bel_api']['servers']['api_url']
        """

        bel_versions = bel_specification.get_bel_versions()

        # use bel_utils._default_to_version to check if valid version, and if it exists or not
        if not version:
            self.version = config["bel"]["lang"]["default_bel_version"]
        else:
            self.version = version

        if self.version not in bel_versions:
            log.warning(
                f"Cannot validate with invalid version: {self.version} in BEL Versions: {bel_versions}"
            )

        if not api_url:
            self.api_url = config["bel_api"]["servers"]["api_url"]
        else:
            self.api_url = api_url

        # Validation error/warning messages
        # List[Tuple[str, str]], e.g. [('ERROR', 'this is an error msg'), ('WARNING', 'this is a warning'), ]
        self.validation_messages = []

        # self.semantics = BELSemantics()  # each instance also instantiates a BELSemantics object used in parsing statements
        self.spec = bel_specification.get_specification(self.version)

        # bel_utils._dump_spec(self.spec)

        # Import Tatsu parser
        # use importlib to import our parser (a .py file) and set the BELParse object as an instance variable
        try:
            parser_fn = self.spec["admin"]["parser_fn"]

            parser_name = os.path.basename(parser_fn).replace(".py", "")
            module_spec = importlib.util.spec_from_file_location(
                parser_name, parser_fn)
            imported_parser = importlib.util.module_from_spec(module_spec)
            module_spec.loader.exec_module(imported_parser)
            self.parser = imported_parser.BELParser()
        except Exception as e:
            # if not found, we raise the NoParserFound exception which can be found in bel.lang.exceptions
            raise bel_ex.NoParserFound(f"Version: {self.version} Msg: {e}")
Esempio n. 4
0
def main():

    bel_version = "2.0.0"
    bel_spec = bel_specification.get_specification(bel_version)

    belstr = "compositeAbundance(proteinAbundance(HGNC:FN1), proteinAbundance(HGNC:VEGFA)) increases translocation(proteinAbundance(HGNC:PRKCA), fromLoc(MESH:Intracellular Space), toLoc(MESH:Cell Membrane))"
    belstr = 'proteinAbundance(HGNC:VEGFA) increases (compositeAbundance(proteinAbundance(HGNC:ITGB1), proteinAbundance(HGNC:PRKCA, ma(kin))) increases biologicalProcess(GO:"cell-matrix adhesion"))'
    belstr = "complex(p(HGNC:EGFR))"
    # belstr = 'p(HGNC:AKT)'

    cursor_loc = 18
    completions = bel_completion(belstr, cursor_loc, bel_fmt="long")
    print("Completions:\n", json.dumps(completions, indent=4))

    quit()
    ast, errors = pparse.get_ast_dict(belstr)
    # print('AST:\n', json.dumps(ast, indent=4))
    # quit()
    cursor_loc = 8
    results = cursor(belstr, ast, cursor_loc)
    print(f"Cursor{cursor_loc}:\n", json.dumps(results, indent=4))
    quit()

    bel_comp = ""
    bel_fmt = "long"
    species_id = "TAX:9606"
    completions = get_completions(belstr, cursor_loc, functions, bel_spec,
                                  bel_comp, bel_fmt, species_id)
    print("Completions:\n", json.dumps(completions, indent=4))
    quit()

    completions = ns_completions("AKT", ["Protein"], "TAX:9606", 10)
    print("Completions:\n", json.dumps(completions, indent=4))
    quit()

    # completions = bel_completion('pa', bel_fmt='long')
    # print('DumpVar:\n', json.dumps(completions, indent=4))

    completions = bel_completion("path(", cursor_loc=1, bel_fmt="medium")
    print("DumpVar:\n", json.dumps(completions, indent=4))
Esempio n. 5
0
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 be found in object or full statement
        bel_fmt (str): ['short', 'medium', 'long'] BEL function/relation format
        species_id (str): optional, species id is used to filter namespace values if applicable (e.g. Gene, RNA, ... entity_types)
        size: how many completions to return, defaults to 20

    Returns:
        Mapping[str, Any]:
            {
                'completions': completions,
                'function_help': function_help,
                'entity_spans': spans
            }
    """
    """
    Completion object: {
        completions: [
            {
                'replacement': <replacement text field string,
                'cursor_loc': <new cursor location>
                'highlight': <highlighted match>
                'label': <label for completion>
            },
        ],
        function_help: [{
            "function_summary": <template>,
            "argument_help": [<argument help>],
            "description": <desc>
        }],
        "entity_spans": {<span info>}
    }

    """
    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_help, spans) = get_completions(belstr, cursor_loc, bel_spec, bel_comp, bel_fmt, species_id, size)

    (completion_text, completions, function_help,
     spans) = get_completions(belstr, cursor_loc, bel_spec, bel_comp, bel_fmt,
                              species_id, size)

    return {
        "completion_text": completion_text,
        "completions": completions,
        "function_help": function_help,
        "entity_spans": spans,
    }