idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
17,700
def process_pubmed_abstract ( pubmed_id , offline = False , output_fname = default_output_fname , ** kwargs ) : abs_txt = pubmed_client . get_abstract ( pubmed_id ) if abs_txt is None : return None rp = process_text ( abs_txt , citation = pubmed_id , offline = offline , output_fname = output_fname , ** kwargs ) if rp a...
Return a ReachProcessor by processing an abstract with a given Pubmed id .
17,701
def process_text ( text , citation = None , offline = False , output_fname = default_output_fname , timeout = None ) : if offline : if not try_offline : logger . error ( 'Offline reading is not available.' ) return None try : api_ruler = reach_reader . get_api_ruler ( ) except ReachOfflineReadingError as e : logger . e...
Return a ReachProcessor by processing the given text .
17,702
def process_nxml_str ( nxml_str , citation = None , offline = False , output_fname = default_output_fname ) : if offline : if not try_offline : logger . error ( 'Offline reading is not available.' ) return None try : api_ruler = reach_reader . get_api_ruler ( ) except ReachOfflineReadingError as e : logger . error ( e ...
Return a ReachProcessor by processing the given NXML string .
17,703
def process_nxml_file ( file_name , citation = None , offline = False , output_fname = default_output_fname ) : with open ( file_name , 'rb' ) as f : nxml_str = f . read ( ) . decode ( 'utf-8' ) return process_nxml_str ( nxml_str , citation , False , output_fname )
Return a ReachProcessor by processing the given NXML file .
17,704
def process_json_file ( file_name , citation = None ) : try : with open ( file_name , 'rb' ) as fh : json_str = fh . read ( ) . decode ( 'utf-8' ) return process_json_str ( json_str , citation ) except IOError : logger . error ( 'Could not read file %s.' % file_name )
Return a ReachProcessor by processing the given REACH json file .
17,705
def process_json_str ( json_str , citation = None ) : if not isinstance ( json_str , basestring ) : raise TypeError ( '{} is {} instead of {}' . format ( json_str , json_str . __class__ , basestring ) ) json_str = json_str . replace ( 'frame-id' , 'frame_id' ) json_str = json_str . replace ( 'argument-label' , 'argumen...
Return a ReachProcessor by processing the given REACH json string .
17,706
def make_parser ( ) : parser = ArgumentParser ( 'wait_for_complete.py' , usage = '%(prog)s [-h] queue_name [options]' , description = ( 'Wait for a set of batch jobs to complete, and monitor ' 'them as they run.' ) , epilog = ( 'Jobs can also be monitored, terminated, and otherwise ' 'managed on the AWS website. Howeve...
Generate the parser for this script .
17,707
def id_lookup ( paper_id , idtype ) : if idtype not in ( 'pmid' , 'pmcid' , 'doi' ) : raise ValueError ( "Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype ) ids = { 'doi' : None , 'pmid' : None , 'pmcid' : None } pmc_id_results = pmc_client . id_lookup ( paper_id , idtype ) ids [ 'pmid' ] = pmc_id_res...
Take an ID of type PMID PMCID or DOI and lookup the other IDs .
17,708
def get_full_text ( paper_id , idtype , preferred_content_type = 'text/xml' ) : if preferred_content_type not in ( 'text/xml' , 'text/plain' , 'application/pdf' ) : raise ValueError ( "preferred_content_type must be one of 'text/xml', " "'text/plain', or 'application/pdf'." ) ids = id_lookup ( paper_id , idtype ) pmcid...
Return the content and the content type of an article .
17,709
def get_api_ruler ( self ) : if self . api_ruler is None : try : self . api_ruler = autoclass ( 'org.clulab.reach.export.apis.ApiRuler' ) except JavaException as e : raise ReachOfflineReadingError ( e ) return self . api_ruler
Return the existing reader if it exists or launch a new one .
17,710
def _download_biogrid_data ( url ) : res = requests . get ( biogrid_file_url ) if res . status_code != 200 : raise Exception ( 'Unable to download Biogrid data: status code %s' % res . status_code ) zip_bytes = BytesIO ( res . content ) zip_file = ZipFile ( zip_bytes ) zip_info_list = zip_file . infolist ( ) if len ( z...
Downloads zipped tab - separated Biogrid data in . tab2 format .
17,711
def _make_agent ( self , entrez_id , text_id ) : hgnc_name , db_refs = self . _make_db_refs ( entrez_id , text_id ) if hgnc_name is not None : name = hgnc_name elif text_id is not None : name = text_id else : return None return Agent ( name , db_refs = db_refs )
Make an Agent object appropriately grounded .
17,712
def _make_db_refs ( self , entrez_id , text_id ) : db_refs = { } if text_id != '-' and text_id is not None : db_refs [ 'TEXT' ] = text_id hgnc_id = hgnc_client . get_hgnc_from_entrez ( entrez_id ) hgnc_name = hgnc_client . get_hgnc_name ( hgnc_id ) if hgnc_id is not None : db_refs [ 'HGNC' ] = hgnc_id up_id = hgnc_clie...
Looks up the HGNC ID and name as well as the Uniprot ID .
17,713
def make_model ( self , policies = None , initial_conditions = True , reverse_effects = False ) : self . processed_policies = self . process_policies ( policies ) ppa = PysbPreassembler ( self . statements ) ppa . replace_activities ( ) if reverse_effects : ppa . add_reverse_effects ( ) self . statements = ppa . statem...
Assemble the Kami model from the collected INDRA Statements .
17,714
def add_agent ( self , agent ) : agent_id = self . add_node ( agent . name ) self . add_typing ( agent_id , 'agent' ) for bc in agent . bound_conditions : if bc . is_bound : test_type = 'is_bnd' else : test_type = 'is_free' bound_name = bc . agent . name agent_bs = get_binding_site_name ( bc . agent ) test_name = '%s_b...
Add an INDRA Agent and its conditions to the Nugget .
17,715
def add_node ( self , name_base , attrs = None ) : if name_base not in self . counters : node_id = name_base else : node_id = '%s_%d' % ( name_base , self . counters [ name_base ] ) node = { 'id' : node_id } if attrs : node [ 'attrs' ] = attrs self . nodes . append ( node ) self . counters [ node_id ] += 1 return node_...
Add a node with a given base name to the Nugget and return ID .
17,716
def get_nugget_dict ( self ) : nugget_dict = { 'id' : self . id , 'graph' : { 'nodes' : self . nodes , 'edges' : self . edges } , 'attrs' : { 'name' : self . name , 'rate' : self . rate } } return nugget_dict
Return the Nugget as a dictionary .
17,717
def process_text ( text , pmid = None , python2_path = None ) : if python2_path is None : for path in os . environ [ "PATH" ] . split ( os . pathsep ) : proposed_python2_path = os . path . join ( path , 'python2.7' ) if os . path . isfile ( proposed_python2_path ) : python2_path = proposed_python2_path print ( 'Found p...
Processes the specified plain text with TEES and converts output to supported INDRA statements . Check for the TEES installation is the TEES_PATH environment variable and configuration file ; if not found checks candidate paths in tees_candidate_paths . Raises an exception if TEES cannot be found in any of these places...
17,718
def run_on_text ( text , python2_path ) : tees_path = get_config ( 'TEES_PATH' ) if tees_path is None : for cpath in tees_candidate_paths : cpath = os . path . expanduser ( cpath ) if os . path . isdir ( cpath ) : has_expected_files = True for f in tees_installation_files : fpath = os . path . join ( cpath , f ) presen...
Runs TEES on the given text in a temporary directory and returns a temporary directory with TEES output . The caller should delete this directory when done with it . This function runs TEES and produces TEES output files but does not process TEES output into INDRA statements .
17,719
def extract_output ( output_dir ) : sentences_glob = os . path . join ( output_dir , '*-preprocessed.xml.gz' ) sentences_filename_candidates = glob . glob ( sentences_glob ) if len ( sentences_filename_candidates ) != 1 : m = 'Looking for exactly one file matching %s but found %d matches' raise Exception ( m % ( senten...
Extract the text of the a1 a2 and sentence segmentation files from the TEES output directory . These files are located within a compressed archive .
17,720
def _list_to_seq ( lst ) : ml = autoclass ( 'scala.collection.mutable.MutableList' ) ( ) for element in lst : ml . appendElem ( element ) return ml
Return a scala . collection . Seq from a Python list .
17,721
def process_text ( self , text , format = 'json' ) : if self . eidos_reader is None : self . initialize_reader ( ) default_arg = lambda x : autoclass ( 'scala.Some' ) ( x ) today = datetime . date . today ( ) . strftime ( "%Y-%m-%d" ) fname = 'default_file_name' annot_doc = self . eidos_reader . extractFromText ( text ...
Return a mentions JSON object given text .
17,722
def process_text ( text , out_format = 'json_ld' , save_json = 'eidos_output.json' , webservice = None ) : if not webservice : if eidos_reader is None : logger . error ( 'Eidos reader is not available.' ) return None json_dict = eidos_reader . process_text ( text , out_format ) else : res = requests . post ( '%s/proces...
Return an EidosProcessor by processing the given text .
17,723
def process_json_file ( file_name ) : try : with open ( file_name , 'rb' ) as fh : json_str = fh . read ( ) . decode ( 'utf-8' ) return process_json_str ( json_str ) except IOError : logger . exception ( 'Could not read file %s.' % file_name )
Return an EidosProcessor by processing the given Eidos JSON - LD file .
17,724
def process_json ( json_dict ) : ep = EidosProcessor ( json_dict ) ep . extract_causal_relations ( ) ep . extract_correlations ( ) ep . extract_events ( ) return ep
Return an EidosProcessor by processing a Eidos JSON - LD dict .
17,725
def get_drug_inhibition_stmts ( drug ) : chebi_id = drug . db_refs . get ( 'CHEBI' ) mesh_id = drug . db_refs . get ( 'MESH' ) if chebi_id : drug_chembl_id = chebi_client . get_chembl_id ( chebi_id ) elif mesh_id : drug_chembl_id = get_chembl_id ( mesh_id ) else : logger . error ( 'Drug missing ChEBI or MESH grounding....
Query ChEMBL for kinetics data given drug as Agent get back statements
17,726
def send_query ( query_dict ) : query = query_dict [ 'query' ] params = query_dict [ 'params' ] url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json' r = requests . get ( url , params = params ) r . raise_for_status ( ) js = r . json ( ) return js
Query ChEMBL API
17,727
def query_target ( target_chembl_id ) : query_dict = { 'query' : 'target' , 'params' : { 'target_chembl_id' : target_chembl_id , 'limit' : 1 } } res = send_query ( query_dict ) target = res [ 'targets' ] [ 0 ] return target
Query ChEMBL API target by id
17,728
def activities_by_target ( activities ) : targ_act_dict = defaultdict ( lambda : [ ] ) for activity in activities : target_chembl_id = activity [ 'target_chembl_id' ] activity_id = activity [ 'activity_id' ] targ_act_dict [ target_chembl_id ] . append ( activity_id ) for target_chembl_id in targ_act_dict : targ_act_dic...
Get back lists of activities in a dict keyed by ChEMBL target id
17,729
def get_protein_targets_only ( target_chembl_ids ) : protein_targets = { } for target_chembl_id in target_chembl_ids : target = query_target ( target_chembl_id ) if 'SINGLE PROTEIN' in target [ 'target_type' ] : protein_targets [ target_chembl_id ] = target return protein_targets
Given list of ChEMBL target ids return dict of SINGLE PROTEIN targets
17,730
def get_evidence ( assay ) : kin = get_kinetics ( assay ) source_id = assay . get ( 'assay_chembl_id' ) if not kin : return None annotations = { 'kinetics' : kin } chembl_doc_id = str ( assay . get ( 'document_chembl_id' ) ) pmid = get_pmid ( chembl_doc_id ) ev = Evidence ( source_api = 'chembl' , pmid = pmid , source_...
Given an activity return an INDRA Evidence object .
17,731
def get_kinetics ( assay ) : try : val = float ( assay . get ( 'standard_value' ) ) except TypeError : logger . warning ( 'Invalid assay value: %s' % assay . get ( 'standard_value' ) ) return None unit = assay . get ( 'standard_units' ) if unit == 'nM' : unit_sym = 1e-9 * units . mol / units . liter elif unit == 'uM' :...
Given an activity return its kinetics values .
17,732
def get_pmid ( doc_id ) : url_pmid = 'https://www.ebi.ac.uk/chembl/api/data/document.json' params = { 'document_chembl_id' : doc_id } res = requests . get ( url_pmid , params = params ) js = res . json ( ) pmid = str ( js [ 'documents' ] [ 0 ] [ 'pubmed_id' ] ) return pmid
Get PMID from document_chembl_id
17,733
def get_target_chemblid ( target_upid ) : url = 'https://www.ebi.ac.uk/chembl/api/data/target.json' params = { 'target_components__accession' : target_upid } r = requests . get ( url , params = params ) r . raise_for_status ( ) js = r . json ( ) target_chemblid = js [ 'targets' ] [ 0 ] [ 'target_chembl_id' ] return tar...
Get ChEMBL ID from UniProt upid
17,734
def get_mesh_id ( nlm_mesh ) : url_nlm2mesh = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi' params = { 'db' : 'mesh' , 'term' : nlm_mesh , 'retmode' : 'JSON' } r = requests . get ( url_nlm2mesh , params = params ) res = r . json ( ) mesh_id = res [ 'esearchresult' ] [ 'idlist' ] [ 0 ] return mesh_id
Get MESH ID from NLM MESH
17,735
def get_pcid ( mesh_id ) : url_mesh2pcid = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi' params = { 'dbfrom' : 'mesh' , 'id' : mesh_id , 'db' : 'pccompound' , 'retmode' : 'JSON' } r = requests . get ( url_mesh2pcid , params = params ) res = r . json ( ) pcid = res [ 'linksets' ] [ 0 ] [ 'linksetdbs' ] [ 0 ]...
Get PC ID from MESH ID
17,736
def get_chembl_id ( nlm_mesh ) : mesh_id = get_mesh_id ( nlm_mesh ) pcid = get_pcid ( mesh_id ) url_mesh2pcid = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/' + 'cid/%s/synonyms/JSON' % pcid r = requests . get ( url_mesh2pcid ) res = r . json ( ) synonyms = res [ 'InformationList' ] [ 'Information' ] [ 0 ] [ 'Sy...
Get ChEMBL ID from NLM MESH
17,737
def get_sentences ( self , root_element , block_tags ) : sentences = [ ] for element in root_element : if not self . any_ends_with ( block_tags , element . tag ) : if element . text is not None and not re . match ( '^\s*$' , element . text ) : sentences . extend ( self . sentence_tokenize ( element . text ) ) sentences...
Returns a list of plain - text sentences by iterating through XML tags except for those listed in block_tags .
17,738
def any_ends_with ( self , string_list , pattern ) : try : s_base = basestring except : s_base = str is_string = isinstance ( pattern , s_base ) if not is_string : return False for s in string_list : if pattern . endswith ( s ) : return True return False
Returns true iff one of the strings in string_list ends in pattern .
17,739
def get_tag_names ( self ) : root = etree . fromstring ( self . xml_full_text . encode ( 'utf-8' ) ) return self . get_children_tag_names ( root )
Returns the set of tag names present in the XML .
17,740
def get_children_tag_names ( self , xml_element ) : tags = set ( ) tags . add ( self . remove_namespace_from_tag ( xml_element . tag ) ) for element in xml_element . iter ( tag = etree . Element ) : if element != xml_element : new_tags = self . get_children_tag_names ( element ) if new_tags is not None : tags . update ...
Returns all tag names of xml element and its children .
17,741
def string_matches_sans_whitespace ( self , str1 , str2_fuzzy_whitespace ) : str2_fuzzy_whitespace = re . sub ( '\s+' , '\s*' , str2_fuzzy_whitespace ) return re . search ( str2_fuzzy_whitespace , str1 ) is not None
Check if two strings match modulo their whitespace .
17,742
def sentence_matches ( self , sentence_text ) : has_upstream = False has_downstream = False has_verb = False actiontype_words = word_tokenize ( self . mention . actiontype ) actiontype_verb_stemmed = stem ( actiontype_words [ 0 ] ) words = word_tokenize ( sentence_text ) if self . string_matches_sans_whitespace ( sente...
Returns true iff the sentence contains this mention s upstream and downstream participants and if one of the stemmed verbs in the sentence is the same as the stemmed action type .
17,743
def get_identifiers_url ( db_name , db_id ) : identifiers_url = 'http://identifiers.org/' bel_scai_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/namespace/' if db_name == 'UP' : url = identifiers_url + 'uniprot/%s' % db_id elif db_name == 'HGNC' : url = identifiers_url + 'hgnc/HGNC:%s' % db_id elif db_name == ...
Return an identifiers . org URL for a given database name and ID .
17,744
def dump_statements ( stmts , fname , protocol = 4 ) : logger . info ( 'Dumping %d statements into %s...' % ( len ( stmts ) , fname ) ) with open ( fname , 'wb' ) as fh : pickle . dump ( stmts , fh , protocol = protocol )
Dump a list of statements into a pickle file .
17,745
def load_statements ( fname , as_dict = False ) : logger . info ( 'Loading %s...' % fname ) with open ( fname , 'rb' ) as fh : if sys . version_info [ 0 ] < 3 : stmts = pickle . load ( fh ) else : stmts = pickle . load ( fh , encoding = 'latin1' ) if isinstance ( stmts , dict ) : if as_dict : return stmts st = [ ] for ...
Load statements from a pickle file .
17,746
def map_grounding ( stmts_in , ** kwargs ) : from indra . preassembler . grounding_mapper import GroundingMapper from indra . preassembler . grounding_mapper import gm as grounding_map from indra . preassembler . grounding_mapper import default_agent_map as agent_map logger . info ( 'Mapping grounding on %d statements....
Map grounding using the GroundingMapper .
17,747
def merge_groundings ( stmts_in ) : def surface_grounding ( stmt ) : for idx , concept in enumerate ( stmt . agent_list ( ) ) : if concept is None : continue aggregate_groundings = { } for ev in stmt . evidence : if 'agents' in ev . annotations : groundings = ev . annotations [ 'agents' ] [ 'raw_grounding' ] [ idx ] fo...
Gather and merge original grounding information from evidences .
17,748
def merge_deltas ( stmts_in ) : stmts_out = [ ] for stmt in stmts_in : if not isinstance ( stmt , Influence ) : stmts_out . append ( stmt ) continue deltas = { } for role in ( 'subj' , 'obj' ) : for info in ( 'polarity' , 'adjectives' ) : key = ( role , info ) deltas [ key ] = [ ] for ev in stmt . evidence : entry = ev...
Gather and merge original Influence delta information from evidence .
17,749
def map_sequence ( stmts_in , ** kwargs ) : from indra . preassembler . sitemapper import SiteMapper , default_site_map logger . info ( 'Mapping sites on %d statements...' % len ( stmts_in ) ) kwarg_list = [ 'do_methionine_offset' , 'do_orthology_mapping' , 'do_isoform_mapping' ] sm = SiteMapper ( default_site_map , us...
Map sequences using the SiteMapper .
17,750
def run_preassembly ( stmts_in , ** kwargs ) : dump_pkl_unique = kwargs . get ( 'save_unique' ) belief_scorer = kwargs . get ( 'belief_scorer' ) use_hierarchies = kwargs [ 'hierarchies' ] if 'hierarchies' in kwargs else hierarchies be = BeliefEngine ( scorer = belief_scorer ) pa = Preassembler ( hierarchies , stmts_in ...
Run preassembly on a list of statements .
17,751
def run_preassembly_duplicate ( preassembler , beliefengine , ** kwargs ) : logger . info ( 'Combining duplicates on %d statements...' % len ( preassembler . stmts ) ) dump_pkl = kwargs . get ( 'save' ) stmts_out = preassembler . combine_duplicates ( ) beliefengine . set_prior_probs ( stmts_out ) logger . info ( '%d un...
Run deduplication stage of preassembly on a list of statements .
17,752
def run_preassembly_related ( preassembler , beliefengine , ** kwargs ) : logger . info ( 'Combining related on %d statements...' % len ( preassembler . unique_stmts ) ) return_toplevel = kwargs . get ( 'return_toplevel' , True ) poolsize = kwargs . get ( 'poolsize' , None ) size_cutoff = kwargs . get ( 'size_cutoff' ,...
Run related stage of preassembly on a list of statements .
17,753
def filter_by_type ( stmts_in , stmt_type , ** kwargs ) : invert = kwargs . get ( 'invert' , False ) logger . info ( 'Filtering %d statements for type %s%s...' % ( len ( stmts_in ) , 'not ' if invert else '' , stmt_type . __name__ ) ) if not invert : stmts_out = [ st for st in stmts_in if isinstance ( st , stmt_type ) ...
Filter to a given statement type .
17,754
def _remove_bound_conditions ( agent , keep_criterion ) : new_bc = [ ] for ind in range ( len ( agent . bound_conditions ) ) : if keep_criterion ( agent . bound_conditions [ ind ] . agent ) : new_bc . append ( agent . bound_conditions [ ind ] ) agent . bound_conditions = new_bc
Removes bound conditions of agent such that keep_criterion is False .
17,755
def _any_bound_condition_fails_criterion ( agent , criterion ) : bc_agents = [ bc . agent for bc in agent . bound_conditions ] for b in bc_agents : if not criterion ( b ) : return True return False
Returns True if any bound condition fails to meet the specified criterion .
17,756
def filter_grounded_only ( stmts_in , ** kwargs ) : remove_bound = kwargs . get ( 'remove_bound' , False ) logger . info ( 'Filtering %d statements for grounded agents...' % len ( stmts_in ) ) stmts_out = [ ] score_threshold = kwargs . get ( 'score_threshold' ) for st in stmts_in : grounded = True for agent in st . age...
Filter to statements that have grounded agents .
17,757
def _agent_is_gene ( agent , specific_only ) : if not specific_only : if not ( agent . db_refs . get ( 'HGNC' ) or agent . db_refs . get ( 'UP' ) or agent . db_refs . get ( 'FPLX' ) ) : return False else : if not ( agent . db_refs . get ( 'HGNC' ) or agent . db_refs . get ( 'UP' ) ) : return False return True
Returns whether an agent is for a gene .
17,758
def filter_genes_only ( stmts_in , ** kwargs ) : remove_bound = 'remove_bound' in kwargs and kwargs [ 'remove_bound' ] specific_only = kwargs . get ( 'specific_only' ) logger . info ( 'Filtering %d statements for ones containing genes only...' % len ( stmts_in ) ) stmts_out = [ ] for st in stmts_in : genes_only = True ...
Filter to statements containing genes only .
17,759
def filter_belief ( stmts_in , belief_cutoff , ** kwargs ) : dump_pkl = kwargs . get ( 'save' ) logger . info ( 'Filtering %d statements to above %f belief' % ( len ( stmts_in ) , belief_cutoff ) ) stmts_out = [ ] for stmt in stmts_in : if stmt . belief < belief_cutoff : continue stmts_out . append ( stmt ) supp_by = [...
Filter to statements with belief above a given cutoff .
17,760
def filter_gene_list ( stmts_in , gene_list , policy , allow_families = False , ** kwargs ) : invert = kwargs . get ( 'invert' , False ) remove_bound = kwargs . get ( 'remove_bound' , False ) if policy not in ( 'one' , 'all' ) : logger . error ( 'Policy %s is invalid, not applying filter.' % policy ) else : genes_str =...
Return statements that contain genes given in a list .
17,761
def filter_by_db_refs ( stmts_in , namespace , values , policy , ** kwargs ) : invert = kwargs . get ( 'invert' , False ) match_suffix = kwargs . get ( 'match_suffix' , False ) if policy not in ( 'one' , 'all' ) : logger . error ( 'Policy %s is invalid, not applying filter.' % policy ) return else : name_str = ', ' . j...
Filter to Statements whose agents are grounded to a matching entry .
17,762
def filter_human_only ( stmts_in , ** kwargs ) : from indra . databases import uniprot_client if 'remove_bound' in kwargs and kwargs [ 'remove_bound' ] : remove_bound = True else : remove_bound = False dump_pkl = kwargs . get ( 'save' ) logger . info ( 'Filtering %d statements for human genes only...' % len ( stmts_in ...
Filter out statements that are grounded but not to a human gene .
17,763
def filter_direct ( stmts_in , ** kwargs ) : def get_is_direct ( stmt ) : any_indirect = False for ev in stmt . evidence : if ev . epistemics . get ( 'direct' ) is True : return True elif ev . epistemics . get ( 'direct' ) is False : any_indirect = True if any_indirect : return False return True logger . info ( 'Filter...
Filter to statements that are direct interactions
17,764
def filter_no_hypothesis ( stmts_in , ** kwargs ) : logger . info ( 'Filtering %d statements to no hypothesis...' % len ( stmts_in ) ) stmts_out = [ ] for st in stmts_in : all_hypotheses = True ev = None for ev in st . evidence : if not ev . epistemics . get ( 'hypothesis' , False ) : all_hypotheses = False break if ev...
Filter to statements that are not marked as hypothesis in epistemics .
17,765
def filter_evidence_source ( stmts_in , source_apis , policy = 'one' , ** kwargs ) : logger . info ( 'Filtering %d statements to evidence source "%s" of: %s...' % ( len ( stmts_in ) , policy , ', ' . join ( source_apis ) ) ) stmts_out = [ ] for st in stmts_in : sources = set ( [ ev . source_api for ev in st . evidence ...
Filter to statements that have evidence from a given set of sources .
17,766
def filter_top_level ( stmts_in , ** kwargs ) : logger . info ( 'Filtering %d statements for top-level...' % len ( stmts_in ) ) stmts_out = [ st for st in stmts_in if not st . supports ] logger . info ( '%d statements after filter...' % len ( stmts_out ) ) dump_pkl = kwargs . get ( 'save' ) if dump_pkl : dump_statement...
Filter to statements that are at the top - level of the hierarchy .
17,767
def filter_inconsequential_mods ( stmts_in , whitelist = None , ** kwargs ) : if whitelist is None : whitelist = { } logger . info ( 'Filtering %d statements to remove' % len ( stmts_in ) + ' inconsequential modifications...' ) states_used = whitelist for stmt in stmts_in : for agent in stmt . agent_list ( ) : if agent...
Filter out Modifications that modify inconsequential sites
17,768
def filter_inconsequential_acts ( stmts_in , whitelist = None , ** kwargs ) : if whitelist is None : whitelist = { } logger . info ( 'Filtering %d statements to remove' % len ( stmts_in ) + ' inconsequential activations...' ) states_used = whitelist for stmt in stmts_in : for agent in stmt . agent_list ( ) : if agent i...
Filter out Activations that modify inconsequential activities
17,769
def filter_enzyme_kinase ( stmts_in , ** kwargs ) : logger . info ( 'Filtering %d statements to remove ' % len ( stmts_in ) + 'phosphorylation by non-kinases...' ) path = os . path . dirname ( os . path . abspath ( __file__ ) ) kinase_table = read_unicode_csv ( path + '/../resources/kinases.tsv' , delimiter = '\t' ) ge...
Filter Phosphorylations to ones where the enzyme is a known kinase .
17,770
def filter_transcription_factor ( stmts_in , ** kwargs ) : logger . info ( 'Filtering %d statements to remove ' % len ( stmts_in ) + 'amount regulations by non-transcription-factors...' ) path = os . path . dirname ( os . path . abspath ( __file__ ) ) tf_table = read_unicode_csv ( path + '/../resources/transcription_fa...
Filter out RegulateAmounts where subject is not a transcription factor .
17,771
def filter_uuid_list ( stmts_in , uuids , ** kwargs ) : invert = kwargs . get ( 'invert' , False ) logger . info ( 'Filtering %d statements for %d UUID%s...' % ( len ( stmts_in ) , len ( uuids ) , 's' if len ( uuids ) > 1 else '' ) ) stmts_out = [ ] for st in stmts_in : if not invert : if st . uuid in uuids : stmts_out...
Filter to Statements corresponding to given UUIDs
17,772
def expand_families ( stmts_in , ** kwargs ) : from indra . tools . expand_families import Expander logger . info ( 'Expanding families on %d statements...' % len ( stmts_in ) ) expander = Expander ( hierarchies ) stmts_out = expander . expand_families ( stmts_in ) logger . info ( '%d statements after expanding familie...
Expand FamPlex Agents to individual genes .
17,773
def reduce_activities ( stmts_in , ** kwargs ) : logger . info ( 'Reducing activities on %d statements...' % len ( stmts_in ) ) stmts_out = [ deepcopy ( st ) for st in stmts_in ] ml = MechLinker ( stmts_out ) ml . gather_explicit_activities ( ) ml . reduce_activities ( ) stmts_out = ml . statements dump_pkl = kwargs . ...
Reduce the activity types in a list of statements
17,774
def strip_agent_context ( stmts_in , ** kwargs ) : logger . info ( 'Stripping agent context on %d statements...' % len ( stmts_in ) ) stmts_out = [ ] for st in stmts_in : new_st = deepcopy ( st ) for agent in new_st . agent_list ( ) : if agent is None : continue agent . mods = [ ] agent . mutations = [ ] agent . activi...
Strip any context on agents within each statement .
17,775
def standardize_names_groundings ( stmts ) : print ( 'Standardize names to groundings' ) for stmt in stmts : for concept in stmt . agent_list ( ) : db_ns , db_id = concept . get_grounding ( ) if db_id is not None : if isinstance ( db_id , list ) : db_id = db_id [ 0 ] [ 0 ] . split ( '/' ) [ - 1 ] else : db_id = db_id ....
Standardize the names of Concepts with respect to an ontology .
17,776
def dump_stmt_strings ( stmts , fname ) : with open ( fname , 'wb' ) as fh : for st in stmts : fh . write ( ( '%s\n' % st ) . encode ( 'utf-8' ) )
Save printed statements in a file .
17,777
def rename_db_ref ( stmts_in , ns_from , ns_to , ** kwargs ) : logger . info ( 'Remapping "%s" to "%s" in db_refs on %d statements...' % ( ns_from , ns_to , len ( stmts_in ) ) ) stmts_out = [ deepcopy ( st ) for st in stmts_in ] for stmt in stmts_out : for agent in stmt . agent_list ( ) : if agent is not None and ns_fr...
Rename an entry in the db_refs of each Agent .
17,778
def align_statements ( stmts1 , stmts2 , keyfun = None ) : def name_keyfun ( stmt ) : return tuple ( a . name if a is not None else None for a in stmt . agent_list ( ) ) if not keyfun : keyfun = name_keyfun matches = [ ] keys1 = [ keyfun ( s ) for s in stmts1 ] keys2 = [ keyfun ( s ) for s in stmts2 ] for stmt , key in...
Return alignment of two lists of statements by key .
17,779
def submit_query_request ( end_point , * args , ** kwargs ) : ev_limit = kwargs . pop ( 'ev_limit' , 10 ) best_first = kwargs . pop ( 'best_first' , True ) tries = kwargs . pop ( 'tries' , 2 ) query_str = '?' + '&' . join ( [ '%s=%s' % ( k , v ) for k , v in kwargs . items ( ) if v is not None ] + list ( args ) ) retur...
Low level function to format the query string .
17,780
def submit_statement_request ( meth , end_point , query_str = '' , data = None , tries = 2 , ** params ) : full_end_point = 'statements/' + end_point . lstrip ( '/' ) return make_db_rest_request ( meth , full_end_point , query_str , data , params , tries )
Even lower level function to make the request .
17,781
def render_stmt_graph ( statements , reduce = True , english = False , rankdir = None , agent_style = None ) : from indra . assemblers . english import EnglishAssembler if agent_style is None : agent_style = { 'color' : 'lightgray' , 'style' : 'filled' , 'fontname' : 'arial' } nodes = set ( [ ] ) edges = set ( [ ] ) st...
Render the statement hierarchy as a pygraphviz graph .
17,782
def flatten_stmts ( stmts ) : total_stmts = set ( stmts ) for stmt in stmts : if stmt . supported_by : children = flatten_stmts ( stmt . supported_by ) total_stmts = total_stmts . union ( children ) return list ( total_stmts )
Return the full set of unique stms in a pre - assembled stmt graph .
17,783
def combine_duplicates ( self ) : if self . unique_stmts is None : self . unique_stmts = self . combine_duplicate_stmts ( self . stmts ) return self . unique_stmts
Combine duplicates among stmts and save result in unique_stmts .
17,784
def _get_stmt_matching_groups ( stmts ) : def match_func ( x ) : return x . matches_key ( ) logger . debug ( '%d statements before removing object duplicates.' % len ( stmts ) ) st = list ( set ( stmts ) ) logger . debug ( '%d statements after removing object duplicates.' % len ( stmts ) ) st . sort ( key = match_func ...
Use the matches_key method to get sets of matching statements .
17,785
def combine_duplicate_stmts ( stmts ) : def _ev_keys ( sts ) : ev_keys = [ ] for stmt in sts : for ev in stmt . evidence : ev_keys . append ( ev . matches_key ( ) ) return ev_keys unique_stmts = [ ] for _ , duplicates in Preassembler . _get_stmt_matching_groups ( stmts ) : ev_keys = set ( ) duplicates = list ( duplicat...
Combine evidence from duplicate Statements .
17,786
def _get_stmt_by_group ( self , stmt_type , stmts_this_type , eh ) : stmt_by_first = collections . defaultdict ( lambda : [ ] ) stmt_by_second = collections . defaultdict ( lambda : [ ] ) none_first = collections . defaultdict ( lambda : [ ] ) none_second = collections . defaultdict ( lambda : [ ] ) stmt_by_group = col...
Group Statements of stmt_type by their hierarchical relations .
17,787
def combine_related ( self , return_toplevel = True , poolsize = None , size_cutoff = 100 ) : if self . related_stmts is not None : if return_toplevel : return self . related_stmts else : assert self . unique_stmts is not None return self . unique_stmts unique_stmts = self . combine_duplicates ( ) idx_map = self . _gen...
Connect related statements based on their refinement relationships .
17,788
def find_contradicts ( self ) : eh = self . hierarchies [ 'entity' ] stmts_by_type = collections . defaultdict ( lambda : [ ] ) for idx , stmt in enumerate ( self . stmts ) : stmts_by_type [ indra_stmt_type ( stmt ) ] . append ( ( idx , stmt ) ) pos_stmts = AddModification . __subclasses__ ( ) neg_stmts = [ modclass_to...
Return pairs of contradicting Statements .
17,789
def get_text_content_for_pmids ( pmids ) : pmc_pmids = set ( pmc_client . filter_pmids ( pmids , source_type = 'fulltext' ) ) pmc_ids = [ ] for pmid in pmc_pmids : pmc_id = pmc_client . id_lookup ( pmid , idtype = 'pmid' ) [ 'pmcid' ] if pmc_id : pmc_ids . append ( pmc_id ) else : pmc_pmids . discard ( pmid ) pmc_xmls ...
Get text content for articles given a list of their pmids
17,790
def universal_extract_paragraphs ( xml ) : try : paragraphs = elsevier_client . extract_paragraphs ( xml ) except Exception : paragraphs = None if paragraphs is None : try : paragraphs = pmc_client . extract_paragraphs ( xml ) except Exception : paragraphs = [ xml ] return paragraphs
Extract paragraphs from xml that could be from different sources
17,791
def filter_paragraphs ( paragraphs , contains = None ) : if contains is None : pattern = '' else : if isinstance ( contains , str ) : contains = [ contains ] pattern = '|' . join ( r'[^\w]%s[^\w]' % shortform for shortform in contains ) paragraphs = [ p for p in paragraphs if re . search ( pattern , p ) ] return '\n' ....
Filter paragraphs to only those containing one of a list of strings
17,792
def get_valid_residue ( residue ) : if residue is not None and amino_acids . get ( residue ) is None : res = amino_acids_reverse . get ( residue . lower ( ) ) if res is None : raise InvalidResidueError ( residue ) else : return res return residue
Check if the given string represents a valid amino acid residue .
17,793
def get_valid_location ( location ) : if location is not None and cellular_components . get ( location ) is None : loc = cellular_components_reverse . get ( location ) if loc is None : raise InvalidLocationError ( location ) else : return loc return location
Check if the given location represents a valid cellular component .
17,794
def _read_activity_types ( ) : this_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) ac_file = os . path . join ( this_dir , os . pardir , 'resources' , 'activity_hierarchy.rdf' ) g = rdflib . Graph ( ) with open ( ac_file , 'r' ) : g . parse ( ac_file , format = 'nt' ) act_types = set ( ) for s , _ , o i...
Read types of valid activities from a resource file .
17,795
def _read_cellular_components ( ) : this_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) cc_file = os . path . join ( this_dir , os . pardir , 'resources' , 'cellular_components.tsv' ) cc_patch_file = os . path . join ( this_dir , os . pardir , 'resources' , 'cellular_components_patch.tsv' ) cellular_com...
Read cellular components from a resource file .
17,796
def _read_amino_acids ( ) : this_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) aa_file = os . path . join ( this_dir , os . pardir , 'resources' , 'amino_acids.tsv' ) amino_acids = { } amino_acids_reverse = { } with open ( aa_file , 'rt' ) as fh : lines = fh . readlines ( ) for lin in lines [ 1 : ] : t...
Read the amino acid information from a resource file .
17,797
def export_sbgn ( model ) : import lxml . etree import lxml . builder from pysb . bng import generate_equations from indra . assemblers . sbgn import SBGNAssembler logger . info ( 'Generating reaction network with BNG for SBGN export. ' + 'This could take a long time.' ) generate_equations ( model ) sa = SBGNAssembler ...
Return an SBGN model string corresponding to the PySB model .
17,798
def export_kappa_im ( model , fname = None ) : from . kappa_util import im_json_to_graph kappa = _prepare_kappa ( model ) imap = kappa . analyses_influence_map ( ) im = im_json_to_graph ( imap ) for param in model . parameters : try : im . remove_node ( param . name ) except : pass if fname : agraph = networkx . nx_agr...
Return a networkx graph representing the model s Kappa influence map .
17,799
def export_kappa_cm ( model , fname = None ) : from . kappa_util import cm_json_to_graph kappa = _prepare_kappa ( model ) cmap = kappa . analyses_contact_map ( ) cm = cm_json_to_graph ( cmap ) if fname : cm . draw ( fname , prog = 'dot' ) return cm
Return a networkx graph representing the model s Kappa contact map .