idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
17,300 | def get_all_events ( self ) : self . all_events = { } events = self . tree . findall ( 'EVENT' ) events += self . tree . findall ( 'CC' ) for e in events : event_id = e . attrib [ 'id' ] if event_id in self . _static_events : continue event_type = e . find ( 'type' ) . text try : self . all_events [ event_type ] . append ( event_id ) except KeyError : self . all_events [ event_type ] = [ event_id ] | Make a list of all events in the TRIPS EKB . | 129 | 13 |
17,301 | def get_activations ( self ) : act_events = self . tree . findall ( "EVENT/[type='ONT::ACTIVATE']" ) inact_events = self . tree . findall ( "EVENT/[type='ONT::DEACTIVATE']" ) inact_events += self . tree . findall ( "EVENT/[type='ONT::INHIBIT']" ) for event in ( act_events + inact_events ) : event_id = event . attrib [ 'id' ] if event_id in self . _static_events : continue # Get the activating agent in the event agent = event . find ( ".//*[@role=':AGENT']" ) if agent is None : continue agent_id = agent . attrib . get ( 'id' ) if agent_id is None : logger . debug ( 'Skipping activation with missing activator agent' ) continue activator_agent = self . _get_agent_by_id ( agent_id , event_id ) if activator_agent is None : continue # Get the activated agent in the event affected = event . find ( ".//*[@role=':AFFECTED']" ) if affected is None : logger . debug ( 'Skipping activation with missing affected agent' ) continue affected_id = affected . attrib . get ( 'id' ) if affected_id is None : logger . debug ( 'Skipping activation with missing affected agent' ) continue affected_agent = self . _get_agent_by_id ( affected_id , event_id ) if affected_agent is None : logger . debug ( 'Skipping activation with missing affected agent' ) continue is_activation = True if _is_type ( event , 'ONT::ACTIVATE' ) : self . _add_extracted ( 'ONT::ACTIVATE' , event . attrib [ 'id' ] ) elif _is_type ( event , 'ONT::INHIBIT' ) : is_activation = False self . _add_extracted ( 'ONT::INHIBIT' , event . attrib [ 'id' ] ) elif _is_type ( event , 'ONT::DEACTIVATE' ) : is_activation = False self . _add_extracted ( 'ONT::DEACTIVATE' , event . attrib [ 'id' ] ) ev = self . _get_evidence ( event ) location = self . _get_event_location ( event ) for a1 , a2 in _agent_list_product ( ( activator_agent , affected_agent ) ) : if is_activation : st = Activation ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) else : st = Inhibition ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) | Extract direct Activation INDRA Statements . | 641 | 9 |
17,302 | def get_activations_causal ( self ) : # Search for causal connectives of type ONT::CAUSE ccs = self . tree . findall ( "CC/[type='ONT::CAUSE']" ) for cc in ccs : factor = cc . find ( "arg/[@role=':FACTOR']" ) outcome = cc . find ( "arg/[@role=':OUTCOME']" ) # If either the factor or the outcome is missing, skip if factor is None or outcome is None : continue factor_id = factor . attrib . get ( 'id' ) # Here, implicitly, we require that the factor is a TERM # and not an EVENT factor_term = self . tree . find ( "TERM/[@id='%s']" % factor_id ) outcome_id = outcome . attrib . get ( 'id' ) # Here it is implicit that the outcome is an event not # a TERM outcome_event = self . tree . find ( "EVENT/[@id='%s']" % outcome_id ) if factor_term is None or outcome_event is None : continue factor_term_type = factor_term . find ( 'type' ) # The factor term must be a molecular entity if factor_term_type is None or factor_term_type . text not in molecule_types : continue factor_agent = self . _get_agent_by_id ( factor_id , None ) if factor_agent is None : continue outcome_event_type = outcome_event . find ( 'type' ) if outcome_event_type is None : continue # Construct evidence ev = self . _get_evidence ( cc ) ev . epistemics [ 'direct' ] = False location = self . _get_event_location ( outcome_event ) if outcome_event_type . text in [ 'ONT::ACTIVATE' , 'ONT::ACTIVITY' , 'ONT::DEACTIVATE' ] : if outcome_event_type . text in [ 'ONT::ACTIVATE' , 'ONT::DEACTIVATE' ] : agent_tag = outcome_event . find ( ".//*[@role=':AFFECTED']" ) elif outcome_event_type . text == 'ONT::ACTIVITY' : agent_tag = outcome_event . find ( ".//*[@role=':AGENT']" ) if agent_tag is None or agent_tag . attrib . get ( 'id' ) is None : continue outcome_agent = self . _get_agent_by_id ( agent_tag . attrib [ 'id' ] , outcome_id ) if outcome_agent is None : continue if outcome_event_type . text == 'ONT::DEACTIVATE' : is_activation = False else : is_activation = True for a1 , a2 in _agent_list_product ( ( factor_agent , outcome_agent ) ) : if is_activation : st = Activation ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) else : st = Inhibition ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) | Extract causal Activation INDRA Statements . | 712 | 9 |
17,303 | def get_activations_stimulate ( self ) : # TODO: extract to other patterns: # - Stimulation by EGF activates ERK # - Stimulation by EGF leads to ERK activation # Search for stimulation event stim_events = self . tree . findall ( "EVENT/[type='ONT::STIMULATE']" ) for event in stim_events : event_id = event . attrib . get ( 'id' ) if event_id in self . _static_events : continue controller = event . find ( "arg1/[@role=':AGENT']" ) affected = event . find ( "arg2/[@role=':AFFECTED']" ) # If either the controller or the affected is missing, skip if controller is None or affected is None : continue controller_id = controller . attrib . get ( 'id' ) # Here, implicitly, we require that the controller is a TERM # and not an EVENT controller_term = self . tree . find ( "TERM/[@id='%s']" % controller_id ) affected_id = affected . attrib . get ( 'id' ) # Here it is implicit that the affected is an event not # a TERM affected_event = self . tree . find ( "EVENT/[@id='%s']" % affected_id ) if controller_term is None or affected_event is None : continue controller_term_type = controller_term . find ( 'type' ) # The controller term must be a molecular entity if controller_term_type is None or controller_term_type . text not in molecule_types : continue controller_agent = self . _get_agent_by_id ( controller_id , None ) if controller_agent is None : continue affected_event_type = affected_event . find ( 'type' ) if affected_event_type is None : continue # Construct evidence ev = self . _get_evidence ( event ) ev . epistemics [ 'direct' ] = False location = self . _get_event_location ( affected_event ) if affected_event_type . text == 'ONT::ACTIVATE' : affected = affected_event . find ( ".//*[@role=':AFFECTED']" ) if affected is None : continue affected_agent = self . _get_agent_by_id ( affected . attrib [ 'id' ] , affected_id ) if affected_agent is None : continue for a1 , a2 in _agent_list_product ( ( controller_agent , affected_agent ) ) : st = Activation ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) elif affected_event_type . text == 'ONT::ACTIVITY' : agent_tag = affected_event . find ( ".//*[@role=':AGENT']" ) if agent_tag is None : continue affected_agent = self . _get_agent_by_id ( agent_tag . attrib [ 'id' ] , affected_id ) if affected_agent is None : continue for a1 , a2 in _agent_list_product ( ( controller_agent , affected_agent ) ) : st = Activation ( a1 , a2 , evidence = [ deepcopy ( ev ) ] ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) | Extract Activation INDRA Statements via stimulation . | 758 | 10 |
17,304 | def get_degradations ( self ) : deg_events = self . tree . findall ( "EVENT/[type='ONT::CONSUME']" ) for event in deg_events : if event . attrib [ 'id' ] in self . _static_events : continue affected = event . find ( ".//*[@role=':AFFECTED']" ) if affected is None : msg = 'Skipping degradation event with no affected term.' logger . debug ( msg ) continue # Make sure the degradation is affecting a molecule type # Temporarily removed for CwC compatibility with no type tag #affected_type = affected.find('type') #if affected_type is None or \ # affected_type.text not in molecule_types: # continue affected_id = affected . attrib . get ( 'id' ) if affected_id is None : logger . debug ( 'Skipping degradation event with missing affected agent' ) continue affected_agent = self . _get_agent_by_id ( affected_id , event . attrib [ 'id' ] ) if affected_agent is None : logger . debug ( 'Skipping degradation event with missing affected agent' ) continue agent = event . find ( ".//*[@role=':AGENT']" ) if agent is None : agent_agent = None else : agent_id = agent . attrib . get ( 'id' ) if agent_id is None : agent_agent = None else : agent_agent = self . _get_agent_by_id ( agent_id , event . attrib [ 'id' ] ) ev = self . _get_evidence ( event ) location = self . _get_event_location ( event ) for subj , obj in _agent_list_product ( ( agent_agent , affected_agent ) ) : st = DecreaseAmount ( subj , obj , evidence = deepcopy ( ev ) ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) self . _add_extracted ( _get_type ( event ) , event . attrib [ 'id' ] ) | Extract Degradation INDRA Statements . | 462 | 8 |
17,305 | def get_complexes ( self ) : bind_events = self . tree . findall ( "EVENT/[type='ONT::BIND']" ) bind_events += self . tree . findall ( "EVENT/[type='ONT::INTERACT']" ) for event in bind_events : if event . attrib [ 'id' ] in self . _static_events : continue arg1 = event . find ( "arg1" ) arg2 = event . find ( "arg2" ) # EKB-AGENT if arg1 is None and arg2 is None : args = list ( event . findall ( 'arg' ) ) if len ( args ) < 2 : continue arg1 = args [ 0 ] arg2 = args [ 1 ] if ( arg1 is None or arg1 . attrib . get ( 'id' ) is None ) or ( arg2 is None or arg2 . attrib . get ( 'id' ) is None ) : logger . debug ( 'Skipping complex with less than 2 members' ) continue agent1 = self . _get_agent_by_id ( arg1 . attrib [ 'id' ] , event . attrib [ 'id' ] ) agent2 = self . _get_agent_by_id ( arg2 . attrib [ 'id' ] , event . attrib [ 'id' ] ) if agent1 is None or agent2 is None : logger . debug ( 'Skipping complex with less than 2 members' ) continue # Information on binding site is either attached to the agent term # in a features/site tag or attached to the event itself in # a site tag ''' site_feature = self._find_in_term(arg1.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site_feature = self._find_in_term(arg2.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site = event.find("site") if site is not None: sites, positions = self._get_site_by_id(site.attrib['id']) print sites, positions ''' ev = self . _get_evidence ( event ) location = self . _get_event_location ( event ) for a1 , a2 in _agent_list_product ( ( agent1 , agent2 ) ) : st = Complex ( [ a1 , a2 ] , evidence = deepcopy ( ev ) ) _stmt_location_to_agents ( st , location ) self . statements . append ( st ) self . _add_extracted ( _get_type ( event ) , event . attrib [ 'id' ] ) | Extract Complex INDRA Statements . | 624 | 7 |
17,306 | def get_modifications ( self ) : # Get all the specific mod types mod_event_types = list ( ont_to_mod_type . keys ( ) ) # Add ONT::PTMs as a special case mod_event_types += [ 'ONT::PTM' ] mod_events = [ ] for mod_event_type in mod_event_types : events = self . tree . findall ( "EVENT/[type='%s']" % mod_event_type ) mod_extracted = self . extracted_events . get ( mod_event_type , [ ] ) for event in events : event_id = event . attrib . get ( 'id' ) if event_id not in mod_extracted : mod_events . append ( event ) # Iterate over all modification events for event in mod_events : stmts = self . _get_modification_event ( event ) if stmts : for stmt in stmts : self . statements . append ( stmt ) | Extract all types of Modification INDRA Statements . | 220 | 11 |
17,307 | def get_agents ( self ) : agents_dict = self . get_term_agents ( ) agents = [ a for a in agents_dict . values ( ) if a is not None ] return agents | Return list of INDRA Agents corresponding to TERMs in the EKB . | 43 | 15 |
17,308 | def get_term_agents ( self ) : terms = self . tree . findall ( 'TERM' ) agents = { } assoc_links = [ ] for term in terms : term_id = term . attrib . get ( 'id' ) if term_id : agent = self . _get_agent_by_id ( term_id , None ) agents [ term_id ] = agent # Handle assoc-with links aw = term . find ( 'assoc-with' ) if aw is not None : aw_id = aw . attrib . get ( 'id' ) if aw_id : assoc_links . append ( ( term_id , aw_id ) ) # We only keep the target end of assoc with links if both # source and target are in the list for source , target in assoc_links : if target in agents and source in agents : agents . pop ( source ) return agents | Return dict of INDRA Agents keyed by corresponding TERMs in the EKB . | 199 | 17 |
17,309 | def _get_evidence_text ( self , event_tag ) : par_id = event_tag . attrib . get ( 'paragraph' ) uttnum = event_tag . attrib . get ( 'uttnum' ) event_text = event_tag . find ( 'text' ) if self . sentences is not None and uttnum is not None : sentence = self . sentences [ uttnum ] elif event_text is not None : sentence = event_text . text else : sentence = None return sentence | Extract the evidence for an event . | 112 | 8 |
17,310 | def get_causal_edge ( stmt , activates ) : any_contact = any ( evidence . epistemics . get ( 'direct' , False ) for evidence in stmt . evidence ) if any_contact : return pc . DIRECTLY_INCREASES if activates else pc . DIRECTLY_DECREASES return pc . INCREASES if activates else pc . DECREASES | Returns the causal polar edge with the correct contact . | 85 | 10 |
17,311 | def to_database ( self , manager = None ) : network = pybel . to_database ( self . model , manager = manager ) return network | Send the model to the PyBEL database | 31 | 9 |
17,312 | def get_binding_site_name ( agent ) : # Try to construct a binding site name based on parent grounding = agent . get_grounding ( ) if grounding != ( None , None ) : uri = hierarchies [ 'entity' ] . get_uri ( grounding [ 0 ] , grounding [ 1 ] ) # Get highest level parents in hierarchy parents = hierarchies [ 'entity' ] . get_parents ( uri , 'top' ) if parents : # Choose the first parent if there are more than one parent_uri = sorted ( parents ) [ 0 ] parent_agent = _agent_from_uri ( parent_uri ) binding_site = _n ( parent_agent . name ) . lower ( ) return binding_site # Fall back to Agent's own name if one from parent can't be constructed binding_site = _n ( agent . name ) . lower ( ) return binding_site | Return a binding site name from a given agent . | 191 | 10 |
17,313 | def get_mod_site_name ( mod_condition ) : if mod_condition . residue is None : mod_str = abbrevs [ mod_condition . mod_type ] else : mod_str = mod_condition . residue mod_pos = mod_condition . position if mod_condition . position is not None else '' name = ( '%s%s' % ( mod_str , mod_pos ) ) return name | Return site names for a modification . | 91 | 7 |
17,314 | def process_flat_files ( id_mappings_file , complexes_file = None , ptm_file = None , ppi_file = None , seq_file = None , motif_window = 7 ) : id_df = pd . read_csv ( id_mappings_file , delimiter = '\t' , names = _hprd_id_cols , dtype = 'str' ) id_df = id_df . set_index ( 'HPRD_ID' ) if complexes_file is None and ptm_file is None and ppi_file is None : raise ValueError ( 'At least one of complexes_file, ptm_file, or ' 'ppi_file must be given.' ) if ptm_file and not seq_file : raise ValueError ( 'If ptm_file is given, seq_file must also be given.' ) # Load complexes into dataframe cplx_df = None if complexes_file : cplx_df = pd . read_csv ( complexes_file , delimiter = '\t' , names = _cplx_cols , dtype = 'str' , na_values = [ '-' , 'None' ] ) # Load ptm data into dataframe ptm_df = None seq_dict = None if ptm_file : ptm_df = pd . read_csv ( ptm_file , delimiter = '\t' , names = _ptm_cols , dtype = 'str' , na_values = '-' ) # Load protein sequences as a dict keyed by RefSeq ID seq_dict = load_fasta_sequences ( seq_file , id_index = 2 ) # Load the PPI data into dataframe ppi_df = None if ppi_file : ppi_df = pd . read_csv ( ppi_file , delimiter = '\t' , names = _ppi_cols , dtype = 'str' ) # Create the processor return HprdProcessor ( id_df , cplx_df , ptm_df , ppi_df , seq_dict , motif_window ) | Get INDRA Statements from HPRD data . | 479 | 10 |
17,315 | def _gather_active_forms ( self ) : for stmt in self . statements : if isinstance ( stmt , ActiveForm ) : base_agent = self . agent_set . get_create_base_agent ( stmt . agent ) # Handle the case where an activity flag is set agent_to_add = stmt . agent if stmt . agent . activity : new_agent = fast_deepcopy ( stmt . agent ) new_agent . activity = None agent_to_add = new_agent base_agent . add_activity_form ( agent_to_add , stmt . is_active ) | Collect all the active forms of each Agent in the Statements . | 135 | 12 |
17,316 | def replace_activities ( self ) : logger . debug ( 'Running PySB Preassembler replace activities' ) # TODO: handle activity hierarchies new_stmts = [ ] def has_agent_activity ( stmt ) : """Return True if any agents in the Statement have activity.""" for agent in stmt . agent_list ( ) : if isinstance ( agent , Agent ) and agent . activity is not None : return True return False # First collect all explicit active forms self . _gather_active_forms ( ) # Iterate over all statements for j , stmt in enumerate ( self . statements ) : logger . debug ( '%d/%d %s' % ( j + 1 , len ( self . statements ) , stmt ) ) # If the Statement doesn't have any activities, we can just # keep it and move on if not has_agent_activity ( stmt ) : new_stmts . append ( stmt ) continue stmt_agents = stmt . agent_list ( ) num_agents = len ( stmt_agents ) # Make a list with an empty list for each Agent so that later # we can build combinations of Agent forms agent_forms = [ [ ] for a in stmt_agents ] for i , agent in enumerate ( stmt_agents ) : # This is the case where there is an activity flag on an # Agent which we will attempt to replace with an explicit # active form if agent is not None and isinstance ( agent , Agent ) and agent . activity is not None : base_agent = self . agent_set . get_create_base_agent ( agent ) # If it is an "active" state if agent . activity . is_active : active_forms = base_agent . active_forms # If no explicit active forms are known then we use # the generic one if not active_forms : active_forms = [ agent ] # If it is an "inactive" state else : active_forms = base_agent . inactive_forms # If no explicit inactive forms are known then we use # the generic one if not active_forms : active_forms = [ agent ] # We now iterate over the active agent forms and create # new agents for af in active_forms : new_agent = fast_deepcopy ( agent ) self . _set_agent_context ( af , new_agent ) agent_forms [ i ] . append ( new_agent ) # Otherwise we just copy over the agent as is else : agent_forms [ i ] . append ( agent ) # Now create all possible combinations of the agents and create new # statements as needed agent_combs = itertools . product ( * agent_forms ) for agent_comb in agent_combs : new_stmt = fast_deepcopy ( stmt ) new_stmt . set_agent_list ( agent_comb ) new_stmts . append ( new_stmt ) self . statements = new_stmts | Replace ative flags with Agent states when possible . | 634 | 11 |
17,317 | def add_reverse_effects ( self ) : # TODO: generalize to other modification sites pos_mod_sites = { } neg_mod_sites = { } syntheses = [ ] degradations = [ ] for stmt in self . statements : if isinstance ( stmt , Phosphorylation ) : agent = stmt . sub . name try : pos_mod_sites [ agent ] . append ( ( stmt . residue , stmt . position ) ) except KeyError : pos_mod_sites [ agent ] = [ ( stmt . residue , stmt . position ) ] elif isinstance ( stmt , Dephosphorylation ) : agent = stmt . sub . name try : neg_mod_sites [ agent ] . append ( ( stmt . residue , stmt . position ) ) except KeyError : neg_mod_sites [ agent ] = [ ( stmt . residue , stmt . position ) ] elif isinstance ( stmt , Influence ) : if stmt . overall_polarity ( ) == 1 : syntheses . append ( stmt . obj . name ) elif stmt . overall_polarity ( ) == - 1 : degradations . append ( stmt . obj . name ) elif isinstance ( stmt , IncreaseAmount ) : syntheses . append ( stmt . obj . name ) elif isinstance ( stmt , DecreaseAmount ) : degradations . append ( stmt . obj . name ) new_stmts = [ ] for agent_name , pos_sites in pos_mod_sites . items ( ) : neg_sites = neg_mod_sites . get ( agent_name , [ ] ) no_neg_site = set ( pos_sites ) . difference ( set ( neg_sites ) ) for residue , position in no_neg_site : st = Dephosphorylation ( Agent ( 'phosphatase' ) , Agent ( agent_name ) , residue , position ) new_stmts . append ( st ) for agent_name in syntheses : if agent_name not in degradations : st = DecreaseAmount ( None , Agent ( agent_name ) ) new_stmts . append ( st ) self . statements += new_stmts | Add Statements for the reverse effects of some Statements . | 487 | 10 |
17,318 | def _get_uniprot_id ( agent ) : up_id = agent . db_refs . get ( 'UP' ) hgnc_id = agent . db_refs . get ( 'HGNC' ) if up_id is None : if hgnc_id is None : # If both UniProt and HGNC refs are missing we can't # sequence check and so don't report a failure. return None # Try to get UniProt ID from HGNC up_id = hgnc_client . get_uniprot_id ( hgnc_id ) # If this fails, again, we can't sequence check if up_id is None : return None # If the UniProt ID is a list then choose the first one. if not isinstance ( up_id , basestring ) and isinstance ( up_id [ 0 ] , basestring ) : up_id = up_id [ 0 ] return up_id | Return the UniProt ID for an agent looking up in HGNC if necessary . | 208 | 16 |
17,319 | def map_sites ( self , stmts ) : valid_statements = [ ] mapped_statements = [ ] for stmt in stmts : mapped_stmt = self . map_stmt_sites ( stmt ) # If we got a MappedStatement as a return value, we add that to the # list of mapped statements, otherwise, the original Statement is # not invalid so we add it to the other list directly. if mapped_stmt is not None : mapped_statements . append ( mapped_stmt ) else : valid_statements . append ( stmt ) return valid_statements , mapped_statements | Check a set of statements for invalid modification sites . | 137 | 10 |
17,320 | def _map_agent_sites ( self , agent ) : # If there are no modifications on this agent, then we can return the # copy of the agent if agent is None or not agent . mods : return [ ] , agent new_agent = deepcopy ( agent ) mapped_sites = [ ] # Now iterate over all the modifications and map each one for idx , mod_condition in enumerate ( agent . mods ) : mapped_site = self . _map_agent_mod ( agent , mod_condition ) # If we couldn't do the mapping or the mapped site isn't invalid # then we don't need to change the existing ModCondition if not mapped_site or mapped_site . not_invalid ( ) : continue # Otherwise, if there is a mapping, we replace the old ModCondition # with the new one where only the residue and position are updated, # the mod type and the is modified flag are kept. if mapped_site . has_mapping ( ) : mc = ModCondition ( mod_condition . mod_type , mapped_site . mapped_res , mapped_site . mapped_pos , mod_condition . is_modified ) new_agent . mods [ idx ] = mc # Finally, whether or not we have a mapping, we keep track of mapped # sites and make them available to the caller mapped_sites . append ( mapped_site ) return mapped_sites , new_agent | Check an agent for invalid sites and update if necessary . | 299 | 11 |
17,321 | def _map_agent_mod ( self , agent , mod_condition ) : # Get the UniProt ID of the agent, if not found, return up_id = _get_uniprot_id ( agent ) if not up_id : logger . debug ( "No uniprot ID for %s" % agent . name ) return None # If no site information for this residue, skip if mod_condition . position is None or mod_condition . residue is None : return None # Otherwise, try to map it and return the mapped site mapped_site = self . map_to_human_ref ( up_id , 'uniprot' , mod_condition . residue , mod_condition . position , do_methionine_offset = self . do_methionine_offset , do_orthology_mapping = self . do_orthology_mapping , do_isoform_mapping = self . do_isoform_mapping ) return mapped_site | Map a single modification condition on an agent . | 211 | 9 |
17,322 | def _get_graph_reductions ( graph ) : def frontier ( g , nd ) : """Return the nodes after nd in the topological sort that are at the lowest possible level of the topological sort.""" if g . out_degree ( nd ) == 0 : return set ( [ nd ] ) else : frontiers = set ( ) for n in g . successors ( nd ) : frontiers = frontiers . union ( frontier ( graph , n ) ) return frontiers reductions = { } nodes_sort = list ( networkx . algorithms . dag . topological_sort ( graph ) ) frontiers = [ frontier ( graph , n ) for n in nodes_sort ] # This loop ensures that if a node n2 comes after node n1 in the topological # sort, and their frontiers are identical then n1 can be reduced to n2. # If their frontiers aren't identical, the reduction cannot be done. for i , n1 in enumerate ( nodes_sort ) : for j , n2 in enumerate ( nodes_sort ) : if i > j : continue if frontiers [ i ] == frontiers [ j ] : reductions [ n1 ] = n2 return reductions | Return transitive reductions on a DAG . | 257 | 9 |
17,323 | def gather_explicit_activities ( self ) : for stmt in self . statements : agents = stmt . agent_list ( ) # Activity types given as ActivityConditions for agent in agents : if agent is not None and agent . activity is not None : agent_base = self . _get_base ( agent ) agent_base . add_activity ( agent . activity . activity_type ) # Object activities given in RegulateActivity statements if isinstance ( stmt , RegulateActivity ) : if stmt . obj is not None : obj_base = self . _get_base ( stmt . obj ) obj_base . add_activity ( stmt . obj_activity ) # Activity types given in ActiveForms elif isinstance ( stmt , ActiveForm ) : agent_base = self . _get_base ( stmt . agent ) agent_base . add_activity ( stmt . activity ) if stmt . is_active : agent_base . add_active_state ( stmt . activity , stmt . agent , stmt . evidence ) else : agent_base . add_inactive_state ( stmt . activity , stmt . agent , stmt . evidence ) | Aggregate all explicit activities and active forms of Agents . | 256 | 11 |
17,324 | def gather_implicit_activities ( self ) : for stmt in self . statements : if isinstance ( stmt , Phosphorylation ) or isinstance ( stmt , Transphosphorylation ) or isinstance ( stmt , Autophosphorylation ) : if stmt . enz is not None : enz_base = self . _get_base ( stmt . enz ) enz_base . add_activity ( 'kinase' ) enz_base . add_active_state ( 'kinase' , stmt . enz . mods ) elif isinstance ( stmt , Dephosphorylation ) : if stmt . enz is not None : enz_base = self . _get_base ( stmt . enz ) enz_base . add_activity ( 'phosphatase' ) enz_base . add_active_state ( 'phosphatase' , stmt . enz . mods ) elif isinstance ( stmt , Modification ) : if stmt . enz is not None : enz_base = self . _get_base ( stmt . enz ) enz_base . add_activity ( 'catalytic' ) enz_base . add_active_state ( 'catalytic' , stmt . enz . mods ) elif isinstance ( stmt , SelfModification ) : if stmt . enz is not None : enz_base = self . _get_base ( stmt . enz ) enz_base . add_activity ( 'catalytic' ) enz_base . add_active_state ( 'catalytic' , stmt . enz . mods ) elif isinstance ( stmt , Gef ) : if stmt . gef is not None : gef_base = self . _get_base ( stmt . gef ) gef_base . add_activity ( 'gef' ) if stmt . gef . activity is not None : act = stmt . gef . activity . activity_type else : act = 'activity' gef_base . add_active_state ( act , stmt . gef . mods ) elif isinstance ( stmt , Gap ) : if stmt . gap is not None : gap_base = self . _get_base ( stmt . gap ) gap_base . add_activity ( 'gap' ) if stmt . gap . activity is not None : act = stmt . gap . activity . activity_type else : act = 'activity' gap_base . add_active_state ( 'act' , stmt . gap . mods ) elif isinstance ( stmt , RegulateActivity ) : if stmt . subj is not None : subj_base = self . _get_base ( stmt . subj ) subj_base . add_activity ( stmt . j ) | Aggregate all implicit activities and active forms of Agents . | 608 | 11 |
17,325 | def require_active_forms ( self ) : logger . info ( 'Setting required active forms on %d statements...' % len ( self . statements ) ) new_stmts = [ ] for stmt in self . statements : if isinstance ( stmt , Modification ) : if stmt . enz is None : new_stmts . append ( stmt ) continue enz_base = self . _get_base ( stmt . enz ) active_forms = enz_base . get_active_forms ( ) if not active_forms : new_stmts . append ( stmt ) else : for af in active_forms : new_stmt = fast_deepcopy ( stmt ) new_stmt . uuid = str ( uuid . uuid4 ( ) ) evs = af . apply_to ( new_stmt . enz ) new_stmt . partial_evidence = evs new_stmts . append ( new_stmt ) elif isinstance ( stmt , RegulateAmount ) or isinstance ( stmt , RegulateActivity ) : if stmt . subj is None : new_stmts . append ( stmt ) continue subj_base = self . _get_base ( stmt . subj ) active_forms = subj_base . get_active_forms ( ) if not active_forms : new_stmts . append ( stmt ) else : for af in active_forms : new_stmt = fast_deepcopy ( stmt ) new_stmt . uuid = str ( uuid . uuid4 ( ) ) evs = af . apply_to ( new_stmt . subj ) new_stmt . partial_evidence = evs new_stmts . append ( new_stmt ) else : new_stmts . append ( stmt ) self . statements = new_stmts return new_stmts | Rewrites Statements with Agents active forms in active positions . | 415 | 11 |
17,326 | def reduce_activities ( self ) : for stmt in self . statements : agents = stmt . agent_list ( ) for agent in agents : if agent is not None and agent . activity is not None : agent_base = self . _get_base ( agent ) act_red = agent_base . get_activity_reduction ( agent . activity . activity_type ) if act_red is not None : agent . activity . activity_type = act_red if isinstance ( stmt , RegulateActivity ) : if stmt . obj is not None : obj_base = self . _get_base ( stmt . obj ) act_red = obj_base . get_activity_reduction ( stmt . obj_activity ) if act_red is not None : stmt . obj_activity = act_red elif isinstance ( stmt , ActiveForm ) : agent_base = self . _get_base ( stmt . agent ) act_red = agent_base . get_activity_reduction ( stmt . activity ) if act_red is not None : stmt . activity = act_red | Rewrite the activity types referenced in Statements for consistency . | 241 | 11 |
17,327 | def infer_complexes ( stmts ) : interact_stmts = _get_statements_by_type ( stmts , Modification ) linked_stmts = [ ] for mstmt in interact_stmts : if mstmt . enz is None : continue st = Complex ( [ mstmt . enz , mstmt . sub ] , evidence = mstmt . evidence ) linked_stmts . append ( st ) return linked_stmts | Return inferred Complex from Statements implying physical interaction . | 105 | 9 |
17,328 | def infer_activations ( stmts ) : linked_stmts = [ ] af_stmts = _get_statements_by_type ( stmts , ActiveForm ) mod_stmts = _get_statements_by_type ( stmts , Modification ) for af_stmt , mod_stmt in itertools . product ( * ( af_stmts , mod_stmts ) ) : # There has to be an enzyme and the substrate and the # agent of the active form have to match if mod_stmt . enz is None or ( not af_stmt . agent . entity_matches ( mod_stmt . sub ) ) : continue # We now check the modifications to make sure they are consistent if not af_stmt . agent . mods : continue found = False for mc in af_stmt . agent . mods : if mc . mod_type == modclass_to_modtype [ mod_stmt . __class__ ] and mc . residue == mod_stmt . residue and mc . position == mod_stmt . position : found = True if not found : continue # Collect evidence ev = mod_stmt . evidence # Finally, check the polarity of the ActiveForm if af_stmt . is_active : st = Activation ( mod_stmt . enz , mod_stmt . sub , af_stmt . activity , evidence = ev ) else : st = Inhibition ( mod_stmt . enz , mod_stmt . sub , af_stmt . activity , evidence = ev ) linked_stmts . append ( LinkedStatement ( [ af_stmt , mod_stmt ] , st ) ) return linked_stmts | Return inferred RegulateActivity from Modification + ActiveForm . | 374 | 12 |
17,329 | def infer_active_forms ( stmts ) : linked_stmts = [ ] for act_stmt in _get_statements_by_type ( stmts , RegulateActivity ) : # TODO: revise the conditions here if not ( act_stmt . subj . activity is not None and act_stmt . subj . activity . activity_type == 'kinase' and act_stmt . subj . activity . is_active ) : continue matching = [ ] ev = act_stmt . evidence for mod_stmt in _get_statements_by_type ( stmts , Modification ) : if mod_stmt . enz is not None : if mod_stmt . enz . entity_matches ( act_stmt . subj ) and mod_stmt . sub . entity_matches ( act_stmt . obj ) : matching . append ( mod_stmt ) ev . extend ( mod_stmt . evidence ) if not matching : continue mods = [ ] for mod_stmt in matching : mod_type_name = mod_stmt . __class__ . __name__ . lower ( ) if isinstance ( mod_stmt , AddModification ) : is_modified = True else : is_modified = False mod_type_name = mod_type_name [ 2 : ] mc = ModCondition ( mod_type_name , mod_stmt . residue , mod_stmt . position , is_modified ) mods . append ( mc ) source_stmts = [ act_stmt ] + [ m for m in matching ] st = ActiveForm ( Agent ( act_stmt . obj . name , mods = mods , db_refs = act_stmt . obj . db_refs ) , act_stmt . obj_activity , act_stmt . is_activation , evidence = ev ) linked_stmts . append ( LinkedStatement ( source_stmts , st ) ) logger . info ( 'inferred: %s' % st ) return linked_stmts | Return inferred ActiveForm from RegulateActivity + Modification . | 449 | 12 |
17,330 | def infer_modifications ( stmts ) : linked_stmts = [ ] for act_stmt in _get_statements_by_type ( stmts , RegulateActivity ) : for af_stmt in _get_statements_by_type ( stmts , ActiveForm ) : if not af_stmt . agent . entity_matches ( act_stmt . obj ) : continue mods = af_stmt . agent . mods # Make sure the ActiveForm only involves modified sites if af_stmt . agent . mutations or af_stmt . agent . bound_conditions or af_stmt . agent . location : continue if not af_stmt . agent . mods : continue for mod in af_stmt . agent . mods : evs = act_stmt . evidence + af_stmt . evidence for ev in evs : ev . epistemics [ 'direct' ] = False if mod . is_modified : mod_type_name = mod . mod_type else : mod_type_name = modtype_to_inverse [ mod . mod_type ] mod_class = modtype_to_modclass [ mod_type_name ] if not mod_class : continue st = mod_class ( act_stmt . subj , act_stmt . obj , mod . residue , mod . position , evidence = evs ) ls = LinkedStatement ( [ act_stmt , af_stmt ] , st ) linked_stmts . append ( ls ) logger . info ( 'inferred: %s' % st ) return linked_stmts | Return inferred Modification from RegulateActivity + ActiveForm . | 350 | 12 |
17,331 | def replace_complexes ( self , linked_stmts = None ) : if linked_stmts is None : linked_stmts = self . infer_complexes ( self . statements ) new_stmts = [ ] for stmt in self . statements : if not isinstance ( stmt , Complex ) : new_stmts . append ( stmt ) continue found = False for linked_stmt in linked_stmts : if linked_stmt . refinement_of ( stmt , hierarchies ) : found = True if not found : new_stmts . append ( stmt ) else : logger . info ( 'Removing complex: %s' % stmt ) self . statements = new_stmts | Remove Complex Statements that can be inferred out . | 159 | 9 |
17,332 | def replace_activations ( self , linked_stmts = None ) : if linked_stmts is None : linked_stmts = self . infer_activations ( self . statements ) new_stmts = [ ] for stmt in self . statements : if not isinstance ( stmt , RegulateActivity ) : new_stmts . append ( stmt ) continue found = False for linked_stmt in linked_stmts : inferred_stmt = linked_stmt . inferred_stmt if stmt . is_activation == inferred_stmt . is_activation and stmt . subj . entity_matches ( inferred_stmt . subj ) and stmt . obj . entity_matches ( inferred_stmt . obj ) : found = True if not found : new_stmts . append ( stmt ) else : logger . info ( 'Removing regulate activity: %s' % stmt ) self . statements = new_stmts | Remove RegulateActivity Statements that can be inferred out . | 214 | 11 |
17,333 | def get_create_base_agent ( self , agent ) : try : base_agent = self . agents [ agent . name ] except KeyError : base_agent = BaseAgent ( agent . name ) self . agents [ agent . name ] = base_agent return base_agent | Return BaseAgent from an Agent creating it if needed . | 59 | 11 |
17,334 | def apply_to ( self , agent ) : agent . bound_conditions = self . bound_conditions agent . mods = self . mods agent . mutations = self . mutations agent . location = self . location return self . evidence | Apply this object s state to an Agent . | 48 | 9 |
17,335 | def submit_curation ( ) : if request . json is None : abort ( Response ( 'Missing application/json header.' , 415 ) ) # Get input parameters corpus_id = request . json . get ( 'corpus_id' ) curations = request . json . get ( 'curations' , { } ) try : curator . submit_curation ( corpus_id , curations ) except InvalidCorpusError : abort ( Response ( 'The corpus_id "%s" is unknown.' % corpus_id , 400 ) ) return return jsonify ( { } ) | Submit curations for a given corpus . | 122 | 8 |
17,336 | def update_beliefs ( ) : if request . json is None : abort ( Response ( 'Missing application/json header.' , 415 ) ) # Get input parameters corpus_id = request . json . get ( 'corpus_id' ) try : belief_dict = curator . update_beliefs ( corpus_id ) except InvalidCorpusError : abort ( Response ( 'The corpus_id "%s" is unknown.' % corpus_id , 400 ) ) return return jsonify ( belief_dict ) | Return updated beliefs based on current probability model . | 109 | 9 |
17,337 | def reset_scorer ( self ) : self . scorer = get_eidos_bayesian_scorer ( ) for corpus_id , corpus in self . corpora . items ( ) : corpus . curations = { } | Reset the scorer used for couration . | 49 | 9 |
17,338 | def get_corpus ( self , corpus_id ) : try : corpus = self . corpora [ corpus_id ] return corpus except KeyError : raise InvalidCorpusError | Return a corpus given an ID . | 38 | 7 |
17,339 | def update_beliefs ( self , corpus_id ) : corpus = self . get_corpus ( corpus_id ) be = BeliefEngine ( self . scorer ) stmts = list ( corpus . statements . values ( ) ) be . set_prior_probs ( stmts ) # Here we set beliefs based on actual curation for uuid , correct in corpus . curations . items ( ) : stmt = corpus . statements . get ( uuid ) if stmt is None : logger . warning ( '%s is not in the corpus.' % uuid ) continue stmt . belief = correct belief_dict = { st . uuid : st . belief for st in stmts } return belief_dict | Return updated belief scores for a given corpus . | 156 | 9 |
17,340 | def get_python_list ( scala_list ) : python_list = [ ] for i in range ( scala_list . length ( ) ) : python_list . append ( scala_list . apply ( i ) ) return python_list | Return list from elements of scala . collection . immutable . List | 54 | 13 |
17,341 | def get_python_dict ( scala_map ) : python_dict = { } keys = get_python_list ( scala_map . keys ( ) . toList ( ) ) for key in keys : python_dict [ key ] = scala_map . apply ( key ) return python_dict | Return a dict from entries in a scala . collection . immutable . Map | 66 | 15 |
17,342 | def get_python_json ( scala_json ) : def convert_node ( node ) : if node . __class__ . __name__ in ( 'org.json4s.JsonAST$JValue' , 'org.json4s.JsonAST$JObject' ) : # Make a dictionary and then convert each value values_raw = get_python_dict ( node . values ( ) ) values = { } for k , v in values_raw . items ( ) : values [ k ] = convert_node ( v ) return values elif node . __class__ . __name__ . startswith ( 'scala.collection.immutable.Map' ) or node . __class__ . __name__ == 'scala.collection.immutable.HashMap$HashTrieMap' : values_raw = get_python_dict ( node ) values = { } for k , v in values_raw . items ( ) : values [ k ] = convert_node ( v ) return values elif node . __class__ . __name__ == 'org.json4s.JsonAST$JArray' : entries_raw = get_python_list ( node . values ( ) ) entries = [ ] for entry in entries_raw : entries . append ( convert_node ( entry ) ) return entries elif node . __class__ . __name__ == 'scala.collection.immutable.$colon$colon' : entries_raw = get_python_list ( node ) entries = [ ] for entry in entries_raw : entries . append ( convert_node ( entry ) ) return entries elif node . __class__ . __name__ == 'scala.math.BigInt' : return node . intValue ( ) elif node . __class__ . __name__ == 'scala.None$' : return None elif node . __class__ . __name__ == 'scala.collection.immutable.Nil$' : return [ ] elif isinstance ( node , ( str , int , float ) ) : return node else : logger . error ( 'Cannot convert %s into Python' % node . __class__ . __name__ ) return node . __class__ . __name__ python_json = convert_node ( scala_json ) return python_json | Return a JSON dict from a org . json4s . JsonAST | 500 | 15 |
17,343 | def get_heat_kernel ( network_id ) : url = ndex_relevance + '/%s/generate_ndex_heat_kernel' % network_id res = ndex_client . send_request ( url , { } , is_json = True , use_get = True ) if res is None : logger . error ( 'Could not get heat kernel for network %s.' % network_id ) return None kernel_id = res . get ( 'kernel_id' ) if kernel_id is None : logger . error ( 'Could not get heat kernel for network %s.' % network_id ) return None return kernel_id | Return the identifier of a heat kernel calculated for a given network . | 143 | 13 |
17,344 | def get_relevant_nodes ( network_id , query_nodes ) : url = ndex_relevance + '/rank_entities' kernel_id = get_heat_kernel ( network_id ) if kernel_id is None : return None if isinstance ( query_nodes , basestring ) : query_nodes = [ query_nodes ] params = { 'identifier_set' : query_nodes , 'kernel_id' : kernel_id } res = ndex_client . send_request ( url , params , is_json = True ) if res is None : logger . error ( "ndex_client.send_request returned None." ) return None ranked_entities = res . get ( 'ranked_entities' ) if ranked_entities is None : logger . error ( 'Could not get ranked entities.' ) return None return ranked_entities | Return a set of network nodes relevant to a given query set . | 196 | 13 |
17,345 | def _get_belief_package ( stmt ) : # This list will contain the belief packages for the given statement belief_packages = [ ] # Iterate over all the support parents for st in stmt . supports : # Recursively get all the belief packages of the parent parent_packages = _get_belief_package ( st ) package_stmt_keys = [ pkg . statement_key for pkg in belief_packages ] for package in parent_packages : # Only add this belief package if it hasn't already been added if package . statement_key not in package_stmt_keys : belief_packages . append ( package ) # Now make the Statement's own belief package and append it to the list belief_package = BeliefPackage ( stmt . matches_key ( ) , stmt . evidence ) belief_packages . append ( belief_package ) return belief_packages | Return the belief packages of a given statement recursively . | 188 | 12 |
17,346 | def sample_statements ( stmts , seed = None ) : if seed : numpy . random . seed ( seed ) new_stmts = [ ] r = numpy . random . rand ( len ( stmts ) ) for i , stmt in enumerate ( stmts ) : if r [ i ] < stmt . belief : new_stmts . append ( stmt ) return new_stmts | Return statements sampled according to belief . | 93 | 7 |
17,347 | def evidence_random_noise_prior ( evidence , type_probs , subtype_probs ) : ( stype , subtype ) = tag_evidence_subtype ( evidence ) # Get the subtype, if available # Return the subtype random noise prior, if available if subtype_probs is not None : if stype in subtype_probs : if subtype in subtype_probs [ stype ] : return subtype_probs [ stype ] [ subtype ] # Fallback to just returning the overall evidence type random noise prior return type_probs [ stype ] | Determines the random - noise prior probability for this evidence . | 131 | 13 |
17,348 | def tag_evidence_subtype ( evidence ) : source_api = evidence . source_api annotations = evidence . annotations if source_api == 'biopax' : subtype = annotations . get ( 'source_sub_id' ) elif source_api in ( 'reach' , 'eidos' ) : if 'found_by' in annotations : from indra . sources . reach . processor import determine_reach_subtype if source_api == 'reach' : subtype = determine_reach_subtype ( annotations [ 'found_by' ] ) elif source_api == 'eidos' : subtype = annotations [ 'found_by' ] else : subtype = None else : logger . debug ( 'Could not find found_by attribute in reach ' 'statement annoations' ) subtype = None elif source_api == 'geneways' : subtype = annotations [ 'actiontype' ] else : subtype = None return ( source_api , subtype ) | Returns the type and subtype of an evidence object as a string typically the extraction rule or database from which the statement was generated . | 215 | 26 |
17,349 | def score_evidence_list ( self , evidences ) : def _score ( evidences ) : if not evidences : return 0 # Collect all unique sources sources = [ ev . source_api for ev in evidences ] uniq_sources = numpy . unique ( sources ) # Calculate the systematic error factors given unique sources syst_factors = { s : self . prior_probs [ 'syst' ] [ s ] for s in uniq_sources } # Calculate the radom error factors for each source rand_factors = { k : [ ] for k in uniq_sources } for ev in evidences : rand_factors [ ev . source_api ] . append ( evidence_random_noise_prior ( ev , self . prior_probs [ 'rand' ] , self . subtype_probs ) ) # The probability of incorrectness is the product of the # source-specific probabilities neg_prob_prior = 1 for s in uniq_sources : neg_prob_prior *= ( syst_factors [ s ] + numpy . prod ( rand_factors [ s ] ) ) # Finally, the probability of correctness is one minus incorrect prob_prior = 1 - neg_prob_prior return prob_prior pos_evidence = [ ev for ev in evidences if not ev . epistemics . get ( 'negated' ) ] neg_evidence = [ ev for ev in evidences if ev . epistemics . get ( 'negated' ) ] pp = _score ( pos_evidence ) np = _score ( neg_evidence ) # The basic assumption is that the positive and negative evidence # can't simultaneously be correct. # There are two cases to consider. (1) If the positive evidence is # incorrect then there is no Statement and the belief should be 0, # irrespective of the negative evidence. # (2) If the positive evidence is correct and the negative evidence # is incorrect. # This amounts to the following formula: # 0 * (1-pp) + 1 * (pp * (1-np)) which we simplify below score = pp * ( 1 - np ) return score | Return belief score given a list of supporting evidences . | 469 | 11 |
17,350 | def score_statement ( self , st , extra_evidence = None ) : if extra_evidence is None : extra_evidence = [ ] all_evidence = st . evidence + extra_evidence return self . score_evidence_list ( all_evidence ) | Computes the prior belief probability for an INDRA Statement . | 53 | 12 |
17,351 | def check_prior_probs ( self , statements ) : sources = set ( ) for stmt in statements : sources |= set ( [ ev . source_api for ev in stmt . evidence ] ) for err_type in ( 'rand' , 'syst' ) : for source in sources : if source not in self . prior_probs [ err_type ] : msg = 'BeliefEngine missing probability parameter' + ' for source: %s' % source raise Exception ( msg ) | Throw Exception if BeliefEngine parameter is missing . | 107 | 9 |
17,352 | def update_probs ( self ) : # We deal with the prior probsfirst # This is a fixed assumed value for systematic error syst_error = 0.05 prior_probs = { 'syst' : { } , 'rand' : { } } for source , ( p , n ) in self . prior_counts . items ( ) : # Skip if there are no actual counts if n + p == 0 : continue prior_probs [ 'syst' ] [ source ] = syst_error prior_probs [ 'rand' ] [ source ] = 1 - min ( ( float ( p ) / ( n + p ) , 1 - syst_error ) ) - syst_error # Next we deal with subtype probs based on counts subtype_probs = { } for source , entry in self . subtype_counts . items ( ) : for rule , ( p , n ) in entry . items ( ) : # Skip if there are no actual counts if n + p == 0 : continue if source not in subtype_probs : subtype_probs [ source ] = { } subtype_probs [ source ] [ rule ] = 1 - min ( ( float ( p ) / ( n + p ) , 1 - syst_error ) ) - syst_error # Finally we propagate this into the full probability # data structures of the parent class super ( BayesianScorer , self ) . update_probs ( prior_probs , subtype_probs ) | Update the internal probability values given the counts . | 325 | 9 |
17,353 | def update_counts ( self , prior_counts , subtype_counts ) : for source , ( pos , neg ) in prior_counts . items ( ) : if source not in self . prior_counts : self . prior_counts [ source ] = [ 0 , 0 ] self . prior_counts [ source ] [ 0 ] += pos self . prior_counts [ source ] [ 1 ] += neg for source , subtype_dict in subtype_counts . items ( ) : if source not in self . subtype_counts : self . subtype_counts [ source ] = { } for subtype , ( pos , neg ) in subtype_dict . items ( ) : if subtype not in self . subtype_counts [ source ] : self . subtype_counts [ source ] [ subtype ] = [ 0 , 0 ] self . subtype_counts [ source ] [ subtype ] [ 0 ] += pos self . subtype_counts [ source ] [ subtype ] [ 1 ] += neg self . update_probs ( ) | Update the internal counts based on given new counts . | 236 | 10 |
17,354 | def set_prior_probs ( self , statements ) : self . scorer . check_prior_probs ( statements ) for st in statements : st . belief = self . scorer . score_statement ( st ) | Sets the prior belief probabilities for a list of INDRA Statements . | 47 | 14 |
17,355 | def set_hierarchy_probs ( self , statements ) : def build_hierarchy_graph ( stmts ) : """Return a DiGraph based on matches keys and Statement supports""" g = networkx . DiGraph ( ) for st1 in stmts : g . add_node ( st1 . matches_key ( ) , stmt = st1 ) for st2 in st1 . supported_by : g . add_node ( st2 . matches_key ( ) , stmt = st2 ) g . add_edge ( st2 . matches_key ( ) , st1 . matches_key ( ) ) return g def get_ranked_stmts ( g ) : """Return a topological sort of statement matches keys from a graph. """ node_ranks = networkx . algorithms . dag . topological_sort ( g ) node_ranks = reversed ( list ( node_ranks ) ) stmts = [ g . node [ n ] [ 'stmt' ] for n in node_ranks ] return stmts def assert_no_cycle ( g ) : """If the graph has cycles, throws AssertionError.""" try : cyc = networkx . algorithms . cycles . find_cycle ( g ) except networkx . exception . NetworkXNoCycle : return msg = 'Cycle found in hierarchy graph: %s' % cyc assert False , msg g = build_hierarchy_graph ( statements ) assert_no_cycle ( g ) ranked_stmts = get_ranked_stmts ( g ) for st in ranked_stmts : bps = _get_belief_package ( st ) supporting_evidences = [ ] # NOTE: the last belief package in the list is this statement's own for bp in bps [ : - 1 ] : # Iterate over all the parent evidences and add only # non-negated ones for ev in bp . evidences : if not ev . epistemics . get ( 'negated' ) : supporting_evidences . append ( ev ) # Now add the Statement's own evidence # Now score all the evidences belief = self . scorer . score_statement ( st , supporting_evidences ) st . belief = belief | Sets hierarchical belief probabilities for INDRA Statements . | 484 | 10 |
17,356 | def set_linked_probs ( self , linked_statements ) : for st in linked_statements : source_probs = [ s . belief for s in st . source_stmts ] st . inferred_stmt . belief = numpy . prod ( source_probs ) | Sets the belief probabilities for a list of linked INDRA Statements . | 63 | 14 |
17,357 | def extract_statements ( self ) : for p_info in self . _json : para = RlimspParagraph ( p_info , self . doc_id_type ) self . statements . extend ( para . get_statements ( ) ) return | Extract the statements from the json . | 55 | 8 |
17,358 | def _get_agent ( self , entity_id ) : if entity_id is None : return None entity_info = self . _entity_dict . get ( entity_id ) if entity_info is None : logger . warning ( "Entity key did not resolve to entity." ) return None return get_agent_from_entity_info ( entity_info ) | Convert the entity dictionary into an INDRA Agent . | 77 | 11 |
17,359 | def _get_evidence ( self , trigger_id , args , agent_coords , site_coords ) : trigger_info = self . _entity_dict [ trigger_id ] # Get the sentence index from the trigger word. s_idx_set = { self . _entity_dict [ eid ] [ 'sentenceIndex' ] for eid in args . values ( ) if 'sentenceIndex' in self . _entity_dict [ eid ] } if s_idx_set : i_min = min ( s_idx_set ) i_max = max ( s_idx_set ) text = '. ' . join ( self . _sentences [ i_min : ( i_max + 1 ) ] ) + '.' s_start = self . _sentence_starts [ i_min ] annotations = { 'agents' : { 'coords' : [ _fix_coords ( coords , s_start ) for coords in agent_coords ] } , 'trigger' : { 'coords' : _fix_coords ( [ trigger_info [ 'charStart' ] , trigger_info [ 'charEnd' ] ] , s_start ) } } else : logger . info ( 'Unable to get sentence index' ) annotations = { } text = None if site_coords : annotations [ 'site' ] = { 'coords' : _fix_coords ( site_coords , s_start ) } return Evidence ( text_refs = self . _text_refs . copy ( ) , text = text , source_api = 'rlimsp' , pmid = self . _text_refs . get ( 'PMID' ) , annotations = annotations ) | Get the evidence using the info in the trigger entity . | 378 | 11 |
17,360 | def get_reader_classes ( parent = Reader ) : children = parent . __subclasses__ ( ) descendants = children [ : ] for child in children : grandchildren = get_reader_classes ( child ) if grandchildren : descendants . remove ( child ) descendants . extend ( grandchildren ) return descendants | Get all childless the descendants of a parent class recursively . | 60 | 14 |
17,361 | def get_reader_class ( reader_name ) : for reader_class in get_reader_classes ( ) : if reader_class . name . lower ( ) == reader_name . lower ( ) : return reader_class else : logger . error ( "No such reader: %s" % reader_name ) return None | Get a particular reader class by name . | 69 | 8 |
17,362 | def from_file ( cls , file_path , compressed = False , encoded = False ) : file_id = '.' . join ( path . basename ( file_path ) . split ( '.' ) [ : - 1 ] ) file_format = file_path . split ( '.' ) [ - 1 ] content = cls ( file_id , file_format , compressed , encoded ) content . file_exists = True content . _location = path . dirname ( file_path ) return content | Create a content object from a file path . | 109 | 9 |
17,363 | def change_id ( self , new_id ) : self . _load_raw_content ( ) self . _id = new_id self . get_filename ( renew = True ) self . get_filepath ( renew = True ) return | Change the id of this content . | 52 | 7 |
17,364 | def change_format ( self , new_format ) : self . _load_raw_content ( ) self . _format = new_format self . get_filename ( renew = True ) self . get_filepath ( renew = True ) return | Change the format label of this content . | 52 | 8 |
17,365 | def get_text ( self ) : self . _load_raw_content ( ) if self . _text is None : assert self . _raw_content is not None ret_cont = self . _raw_content if self . compressed : ret_cont = zlib . decompress ( ret_cont , zlib . MAX_WBITS + 16 ) if self . encoded : ret_cont = ret_cont . decode ( 'utf-8' ) self . _text = ret_cont assert self . _text is not None return self . _text | Get the loaded decompressed and decoded text of this content . | 118 | 13 |
17,366 | def get_filename ( self , renew = False ) : if self . _fname is None or renew : self . _fname = '%s.%s' % ( self . _id , self . _format ) return self . _fname | Get the filename of this content . | 54 | 7 |
17,367 | def get_filepath ( self , renew = False ) : if self . _location is None or renew : self . _location = '.' return path . join ( self . _location , self . get_filename ( ) ) | Get the file path joining the name and location for this file . | 48 | 13 |
17,368 | def get_statements ( self , reprocess = False ) : if self . _statements is None or reprocess : # Handle the case that there is no content. if self . content is None : self . _statements = [ ] return [ ] # Map to the different processors. if self . reader == ReachReader . name : if self . format == formats . JSON : # Process the reach json into statements. json_str = json . dumps ( self . content ) processor = reach . process_json_str ( json_str ) else : raise ReadingError ( "Incorrect format for Reach output: %s." % self . format ) elif self . reader == SparserReader . name : if self . format == formats . JSON : # Process the sparser content into statements processor = sparser . process_json_dict ( self . content ) if processor is not None : processor . set_statements_pmid ( None ) else : raise ReadingError ( "Sparser should only ever be JSON, not " "%s." % self . format ) elif self . reader == TripsReader . name : processor = trips . process_xml ( self . content ) else : raise ReadingError ( "Unknown reader: %s." % self . reader ) # Get the statements from the processor, if it was resolved. if processor is None : logger . error ( "Production of statements from %s failed for %s." % ( self . reader , self . content_id ) ) stmts = [ ] else : stmts = processor . statements self . _statements = stmts [ : ] else : stmts = self . _statements [ : ] return stmts | General method to create statements . | 357 | 6 |
17,369 | def add_result ( self , content_id , content , * * kwargs ) : result_object = self . ResultClass ( content_id , self . name , self . version , formats . JSON , content , * * kwargs ) self . results . append ( result_object ) return | Add a result to the list of results . | 64 | 9 |
17,370 | def _check_content ( self , content_str ) : if self . do_content_check : space_ratio = float ( content_str . count ( ' ' ) ) / len ( content_str ) if space_ratio > self . max_space_ratio : return "space-ratio: %f > %f" % ( space_ratio , self . max_space_ratio ) if len ( content_str ) > self . input_character_limit : return "too long: %d > %d" % ( len ( content_str ) , self . input_character_limit ) return None | Check if the content is likely to be successfully read . | 136 | 11 |
17,371 | def _check_reach_env ( ) : # Get the path to the REACH JAR path_to_reach = get_config ( 'REACHPATH' ) if path_to_reach is None : path_to_reach = environ . get ( 'REACHPATH' , None ) if path_to_reach is None or not path . exists ( path_to_reach ) : raise ReachError ( 'Reach path unset or invalid. Check REACHPATH environment var ' 'and/or config file.' ) logger . debug ( 'Using REACH jar at: %s' % path_to_reach ) # Get the reach version. reach_version = get_config ( 'REACH_VERSION' ) if reach_version is None : reach_version = environ . get ( 'REACH_VERSION' , None ) if reach_version is None : logger . debug ( 'REACH version not set in REACH_VERSION' ) m = re . match ( 'reach-(.*?)\.jar' , path . basename ( path_to_reach ) ) reach_version = re . sub ( '-SNAP.*?$' , '' , m . groups ( ) [ 0 ] ) logger . debug ( 'Using REACH version: %s' % reach_version ) return path_to_reach , reach_version | Check that the environment supports runnig reach . | 290 | 10 |
17,372 | def prep_input ( self , read_list ) : logger . info ( "Prepping input." ) i = 0 for content in read_list : # Check the quality of the text, and skip if there are any issues. quality_issue = self . _check_content ( content . get_text ( ) ) if quality_issue is not None : logger . warning ( "Skipping %d due to: %s" % ( content . get_id ( ) , quality_issue ) ) continue # Look for things that are more like file names, rather than ids. cid = content . get_id ( ) if isinstance ( cid , str ) and re . match ( '^\w*?\d+$' , cid ) is None : new_id = 'FILE%06d' % i i += 1 self . id_maps [ new_id ] = cid content . change_id ( new_id ) new_fpath = content . copy_to ( self . input_dir ) else : # Put the content in the appropriate directory. new_fpath = content . copy_to ( self . input_dir ) self . num_input += 1 logger . debug ( '%s saved for reading by reach.' % new_fpath ) return | Apply the readers to the content . | 275 | 7 |
17,373 | def get_output ( self ) : logger . info ( "Getting outputs." ) # Get the set of prefixes (each will correspond to three json files.) json_files = glob . glob ( path . join ( self . output_dir , '*.json' ) ) json_prefixes = set ( ) for json_file in json_files : # Remove .uaz.<subfile type>.json prefix = '.' . join ( path . basename ( json_file ) . split ( '.' ) [ : - 3 ] ) json_prefixes . add ( path . join ( self . output_dir , prefix ) ) # Join each set of json files and store the json dict. for prefix in json_prefixes : base_prefix = path . basename ( prefix ) if base_prefix . isdecimal ( ) : base_prefix = int ( base_prefix ) elif base_prefix in self . id_maps . keys ( ) : base_prefix = self . id_maps [ base_prefix ] try : content = self . _join_json_files ( prefix , clear = True ) except Exception as e : logger . exception ( e ) logger . error ( "Could not load result for prefix %s." % prefix ) content = None self . add_result ( base_prefix , content ) logger . debug ( 'Joined files for prefix %s.' % base_prefix ) return self . results | Get the output of a reading job as a list of filenames . | 299 | 15 |
17,374 | def read ( self , read_list , verbose = False , log = False ) : ret = [ ] mem_tot = _get_mem_total ( ) if mem_tot is not None and mem_tot <= self . REACH_MEM + self . MEM_BUFFER : logger . error ( "Too little memory to run reach. At least %s required." % ( self . REACH_MEM + self . MEM_BUFFER ) ) logger . info ( "REACH not run." ) return ret # Prep the content self . prep_input ( read_list ) if self . num_input > 0 : # Run REACH! logger . info ( "Beginning reach." ) args = [ 'java' , '-Dconfig.file=%s' % self . conf_file_path , '-jar' , self . exec_path ] p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) log_file_str = '' for line in iter ( p . stdout . readline , b'' ) : log_line = 'REACH: ' + line . strip ( ) . decode ( 'utf8' ) if verbose : logger . info ( log_line ) if log : log_file_str += log_line + '\n' if log : with open ( 'reach_run.log' , 'ab' ) as f : f . write ( log_file_str . encode ( 'utf8' ) ) p_out , p_err = p . communicate ( ) if p . returncode : logger . error ( 'Problem running REACH:' ) logger . error ( 'Stdout: %s' % p_out . decode ( 'utf-8' ) ) logger . error ( 'Stderr: %s' % p_err . decode ( 'utf-8' ) ) raise ReachError ( "Problem running REACH" ) logger . info ( "Reach finished." ) ret = self . get_output ( ) self . clear_input ( ) return ret | Read the content returning a list of ReadingData objects . | 455 | 11 |
17,375 | def prep_input ( self , read_list ) : logger . info ( 'Prepping input for sparser.' ) self . file_list = [ ] for content in read_list : quality_issue = self . _check_content ( content . get_text ( ) ) if quality_issue is not None : logger . warning ( "Skipping %d due to: %s" % ( content . get_id ( ) , quality_issue ) ) continue if content . is_format ( 'nxml' ) : # If it is already an nxml, we just need to adjust the # name a bit, if anything. if not content . get_filename ( ) . startswith ( 'PMC' ) : content . change_id ( 'PMC' + str ( content . get_id ( ) ) ) fpath = content . copy_to ( self . tmp_dir ) self . file_list . append ( fpath ) elif content . is_format ( 'txt' , 'text' ) : # Otherwise we need to frame the content in xml and put it # in a new file with the appropriate name. nxml_str = sparser . make_nxml_from_text ( content . get_text ( ) ) new_content = Content . from_string ( 'PMC' + str ( content . get_id ( ) ) , 'nxml' , nxml_str ) fpath = new_content . copy_to ( self . tmp_dir ) self . file_list . append ( fpath ) else : raise SparserError ( "Unrecognized format %s." % content . format ) return | Prepare the list of files or text content objects to be read . | 353 | 14 |
17,376 | def get_output ( self , output_files , clear = True ) : patt = re . compile ( r'(.*?)-semantics.*?' ) for outpath in output_files : if outpath is None : logger . warning ( "Found outpath with value None. Skipping." ) continue re_out = patt . match ( path . basename ( outpath ) ) if re_out is None : raise SparserError ( "Could not get prefix from output path %s." % outpath ) prefix = re_out . groups ( ) [ 0 ] if prefix . startswith ( 'PMC' ) : prefix = prefix [ 3 : ] if prefix . isdecimal ( ) : # In this case we assume the prefix is a tcid. prefix = int ( prefix ) try : with open ( outpath , 'rt' ) as f : content = json . load ( f ) except Exception as e : logger . exception ( e ) logger . error ( "Could not load reading content from %s." % outpath ) content = None self . add_result ( prefix , content ) if clear : input_path = outpath . replace ( '-semantics.json' , '.nxml' ) try : remove ( outpath ) remove ( input_path ) except Exception as e : logger . exception ( e ) logger . error ( "Could not remove sparser files %s and %s." % ( outpath , input_path ) ) return self . results | Get the output files as an id indexed dict . | 315 | 10 |
17,377 | def read_some ( self , fpath_list , outbuf = None , verbose = False ) : outpath_list = [ ] for fpath in fpath_list : output , outbuf = self . read_one ( fpath , outbuf , verbose ) if output is not None : outpath_list . append ( output ) return outpath_list , outbuf | Perform a few readings . | 82 | 6 |
17,378 | def read ( self , read_list , verbose = False , log = False , n_per_proc = None ) : ret = [ ] self . prep_input ( read_list ) L = len ( self . file_list ) if L == 0 : return ret logger . info ( "Beginning to run sparser." ) output_file_list = [ ] if log : log_name = 'sparser_run_%s.log' % _time_stamp ( ) outbuf = open ( log_name , 'wb' ) else : outbuf = None try : if self . n_proc == 1 : for fpath in self . file_list : outpath , _ = self . read_one ( fpath , outbuf , verbose ) if outpath is not None : output_file_list . append ( outpath ) else : if n_per_proc is None : n_per_proc = max ( 1 , min ( 1000 , L // self . n_proc // 2 ) ) pool = None try : pool = Pool ( self . n_proc ) if n_per_proc is not 1 : batches = [ self . file_list [ n * n_per_proc : ( n + 1 ) * n_per_proc ] for n in range ( L // n_per_proc + 1 ) ] out_lists_and_buffs = pool . map ( self . read_some , batches ) else : out_files_and_buffs = pool . map ( self . read_one , self . file_list ) out_lists_and_buffs = [ ( [ out_files ] , buffs ) for out_files , buffs in out_files_and_buffs ] finally : if pool is not None : pool . close ( ) pool . join ( ) for i , ( out_list , buff ) in enumerate ( out_lists_and_buffs ) : if out_list is not None : output_file_list += out_list if log : outbuf . write ( b'Log for producing output %d/%d.\n' % ( i , len ( out_lists_and_buffs ) ) ) if buff is not None : buff . seek ( 0 ) outbuf . write ( buff . read ( ) + b'\n' ) else : outbuf . write ( b'ERROR: no buffer was None. ' b'No logs available.\n' ) outbuf . flush ( ) finally : if log : outbuf . close ( ) if verbose : logger . info ( "Sparser logs may be found at %s." % log_name ) ret = self . get_output ( output_file_list ) return ret | Perform the actual reading . | 583 | 6 |
17,379 | def process_text ( text , pmid = None , cleanup = True , add_grounding = True ) : # Create a temporary directory to store the proprocessed input pp_dir = tempfile . mkdtemp ( 'indra_isi_pp_output' ) pp = IsiPreprocessor ( pp_dir ) extra_annotations = { } pp . preprocess_plain_text_string ( text , pmid , extra_annotations ) # Run the ISI reader and extract statements ip = process_preprocessed ( pp ) if add_grounding : ip . add_grounding ( ) if cleanup : # Remove temporary directory with processed input shutil . rmtree ( pp_dir ) else : logger . info ( 'Not cleaning up %s' % pp_dir ) return ip | Process a string using the ISI reader and extract INDRA statements . | 170 | 13 |
17,380 | def process_nxml ( nxml_filename , pmid = None , extra_annotations = None , cleanup = True , add_grounding = True ) : if extra_annotations is None : extra_annotations = { } # Create a temporary directory to store the proprocessed input pp_dir = tempfile . mkdtemp ( 'indra_isi_pp_output' ) pp = IsiPreprocessor ( pp_dir ) extra_annotations = { } pp . preprocess_nxml_file ( nxml_filename , pmid , extra_annotations ) # Run the ISI reader and extract statements ip = process_preprocessed ( pp ) if add_grounding : ip . add_grounding ( ) if cleanup : # Remove temporary directory with processed input shutil . rmtree ( pp_dir ) else : logger . info ( 'Not cleaning up %s' % pp_dir ) return ip | Process an NXML file using the ISI reader | 198 | 9 |
17,381 | def process_output_folder ( folder_path , pmids = None , extra_annotations = None , add_grounding = True ) : pmids = pmids if pmids is not None else { } extra_annotations = extra_annotations if extra_annotations is not None else { } ips = [ ] for entry in glob . glob ( os . path . join ( folder_path , '*.json' ) ) : entry_key = os . path . splitext ( os . path . basename ( entry ) ) [ 0 ] # Extract the corresponding file id pmid = pmids . get ( entry_key ) extra_annotation = extra_annotations . get ( entry_key ) ip = process_json_file ( entry , pmid , extra_annotation , False ) ips . append ( ip ) if len ( ips ) > 1 : for ip in ips [ 1 : ] : ips [ 0 ] . statements += ip . statements if ips : if add_grounding : ips [ 0 ] . add_grounding ( ) return ips [ 0 ] else : return None | Recursively extracts statements from all ISI output files in the given directory and subdirectories . | 242 | 19 |
17,382 | def process_json_file ( file_path , pmid = None , extra_annotations = None , add_grounding = True ) : logger . info ( 'Extracting from %s' % file_path ) with open ( file_path , 'rb' ) as fh : jd = json . load ( fh ) ip = IsiProcessor ( jd , pmid , extra_annotations ) ip . get_statements ( ) if add_grounding : ip . add_grounding ( ) return ip | Extracts statements from the given ISI output file . | 115 | 11 |
17,383 | def process_text ( text , save_xml = 'cwms_output.xml' ) : xml = client . send_query ( text , 'cwmsreader' ) # There are actually two EKBs in the xml document. Extract the second. first_end = xml . find ( '</ekb>' ) # End of first EKB second_start = xml . find ( '<ekb' , first_end ) # Start of second EKB second_end = xml . find ( '</ekb>' , second_start ) # End of second EKB second_ekb = xml [ second_start : second_end + len ( '</ekb>' ) ] # second EKB if save_xml : with open ( save_xml , 'wb' ) as fh : fh . write ( second_ekb . encode ( 'utf-8' ) ) return process_ekb ( second_ekb ) | Processes text using the CWMS web service . | 205 | 10 |
17,384 | def process_ekb_file ( fname ) : # Process EKB XML file into statements with open ( fname , 'rb' ) as fh : ekb_str = fh . read ( ) . decode ( 'utf-8' ) return process_ekb ( ekb_str ) | Processes an EKB file produced by CWMS . | 65 | 11 |
17,385 | def im_json_to_graph ( im_json ) : imap_data = im_json [ 'influence map' ] [ 'map' ] # Initialize the graph graph = MultiDiGraph ( ) id_node_dict = { } # Add each node to the graph for node_dict in imap_data [ 'nodes' ] : # There is always just one entry here with the node type e.g. "rule" # as key, and all the node data as the value node_type , node = list ( node_dict . items ( ) ) [ 0 ] # Add the node to the graph with its label and type attrs = { 'fillcolor' : '#b7d2ff' if node_type == 'rule' else '#cdffc9' , 'shape' : 'box' if node_type == 'rule' else 'oval' , 'style' : 'filled' } graph . add_node ( node [ 'label' ] , node_type = node_type , * * attrs ) # Save the key of the node to refer to it later new_key = '%s%s' % ( node_type , node [ 'id' ] ) id_node_dict [ new_key ] = node [ 'label' ] def add_edges ( link_list , edge_sign ) : attrs = { 'sign' : edge_sign , 'color' : 'green' if edge_sign == 1 else 'red' , 'arrowhead' : 'normal' if edge_sign == 1 else 'tee' } for link_dict in link_list : source = link_dict [ 'source' ] for target_dict in link_dict [ 'target map' ] : target = target_dict [ 'target' ] src_id = '%s%s' % list ( source . items ( ) ) [ 0 ] tgt_id = '%s%s' % list ( target . items ( ) ) [ 0 ] graph . add_edge ( id_node_dict [ src_id ] , id_node_dict [ tgt_id ] , * * attrs ) # Add all the edges from the positive and negative influences add_edges ( imap_data [ 'wake-up map' ] , 1 ) add_edges ( imap_data [ 'inhibition map' ] , - 1 ) return graph | Return networkx graph from Kappy s influence map JSON . | 520 | 12 |
17,386 | def cm_json_to_graph ( im_json ) : cmap_data = im_json [ 'contact map' ] [ 'map' ] # Initialize the graph graph = AGraph ( ) # In this loop we add sites as nodes and clusters around sites to the # graph. We also collect edges to be added between sites later. edges = [ ] for node_idx , node in enumerate ( cmap_data ) : sites_in_node = [ ] for site_idx , site in enumerate ( node [ 'node_sites' ] ) : # We map the unique ID of the site to its name site_key = ( node_idx , site_idx ) sites_in_node . append ( site_key ) graph . add_node ( site_key , label = site [ 'site_name' ] , style = 'filled' , shape = 'ellipse' ) # Each port link is an edge from the current site to the # specified site if not site [ 'site_type' ] or not site [ 'site_type' ] [ 0 ] == 'port' : continue for port_link in site [ 'site_type' ] [ 1 ] [ 'port_links' ] : edge = ( site_key , tuple ( port_link ) ) edges . append ( edge ) graph . add_subgraph ( sites_in_node , name = 'cluster_%s' % node [ 'node_type' ] , label = node [ 'node_type' ] ) # Finally we add the edges between the sites for source , target in edges : graph . add_edge ( source , target ) return graph | Return pygraphviz Agraph from Kappy s contact map JSON . | 357 | 15 |
17,387 | def fetch_email ( M , msg_id ) : res , data = M . fetch ( msg_id , '(RFC822)' ) if res == 'OK' : # Data here is a list with 1 element containing a tuple # whose 2nd element is a long string containing the email # The content is a bytes that must be decoded raw_msg_txt = data [ 0 ] [ 1 ] # In Python3, we call message_from_bytes, but this function doesn't # exist in Python 2. try : msg = email . message_from_bytes ( raw_msg_txt ) except AttributeError : msg = email . message_from_string ( raw_msg_txt ) # At this point, we have a message containing bytes (not unicode) # fields that will still need to be decoded, ideally according to the # character set specified in the message. return msg else : return None | Returns the given email message as a unicode string . | 193 | 11 |
17,388 | def get_headers ( msg ) : headers = { } for k in msg . keys ( ) : # decode_header decodes header but does not convert charset, so these # may still be bytes, even in Python 3. However, if it's ASCII # only (hence unambiguous encoding), the header fields come back # as str (unicode) in Python 3. ( header_txt , charset ) = email . header . decode_header ( msg [ k ] ) [ 0 ] if charset is not None : header_txt = header_txt . decode ( charset ) headers [ k ] = header_txt return headers | Takes email . message . Message object initialized from unicode string returns dict with header fields . | 134 | 19 |
17,389 | def populate_config_dict ( config_path ) : try : config_dict = { } parser = RawConfigParser ( ) parser . optionxform = lambda x : x parser . read ( config_path ) sections = parser . sections ( ) for section in sections : options = parser . options ( section ) for option in options : config_dict [ option ] = str ( parser . get ( section , option ) ) except Exception as e : logger . warning ( "Could not load configuration file due to exception. " "Only environment variable equivalents will be used." ) return None for key in config_dict . keys ( ) : if config_dict [ key ] == '' : config_dict [ key ] = None elif isinstance ( config_dict [ key ] , str ) : config_dict [ key ] = os . path . expanduser ( config_dict [ key ] ) return config_dict | Load the configuration file into the config_file dictionary | 189 | 10 |
17,390 | def get_config ( key , failure_ok = True ) : err_msg = "Key %s not in environment or config file." % key if key in os . environ : return os . environ [ key ] elif key in CONFIG_DICT : val = CONFIG_DICT [ key ] # We interpret an empty value in the config file as a failure if val is None and not failure_ok : msg = 'Key %s is set to an empty value in config file.' % key raise IndraConfigError ( msg ) else : return val elif not failure_ok : raise IndraConfigError ( err_msg ) else : logger . warning ( err_msg ) return None | Get value by key from config file or environment . | 145 | 10 |
17,391 | def read_unicode_csv_fileobj ( fileobj , delimiter = ',' , quotechar = '"' , quoting = csv . QUOTE_MINIMAL , lineterminator = '\n' , encoding = 'utf-8' , skiprows = 0 ) : # Python 3 version if sys . version_info [ 0 ] >= 3 : # Next, get the csv reader, with unicode delimiter and quotechar csv_reader = csv . reader ( fileobj , delimiter = delimiter , quotechar = quotechar , quoting = quoting , lineterminator = lineterminator ) # Now, return the (already decoded) unicode csv_reader generator # Skip rows if necessary for skip_ix in range ( skiprows ) : next ( csv_reader ) for row in csv_reader : yield row # Python 2 version else : # Next, get the csv reader, passing delimiter and quotechar as # bytestrings rather than unicode csv_reader = csv . reader ( fileobj , delimiter = delimiter . encode ( encoding ) , quotechar = quotechar . encode ( encoding ) , quoting = quoting , lineterminator = lineterminator ) # Iterate over the file and decode each string into unicode # Skip rows if necessary for skip_ix in range ( skiprows ) : next ( csv_reader ) for row in csv_reader : yield [ cell . decode ( encoding ) for cell in row ] | fileobj can be a StringIO in Py3 but should be a BytesIO in Py2 . | 316 | 21 |
17,392 | def fast_deepcopy ( obj ) : with BytesIO ( ) as buf : pickle . dump ( obj , buf ) buf . seek ( 0 ) obj_new = pickle . load ( buf ) return obj_new | This is a faster implementation of deepcopy via pickle . | 48 | 12 |
17,393 | def batch_iter ( iterator , batch_size , return_func = None , padding = None ) : for batch in zip_longest ( * [ iter ( iterator ) ] * batch_size , fillvalue = padding ) : gen = ( thing for thing in batch if thing is not padding ) if return_func is None : yield gen else : yield return_func ( gen ) | Break an iterable into batches of size batch_size | 80 | 11 |
17,394 | def read_pmid_sentences ( pmid_sentences , * * drum_args ) : def _set_pmid ( statements , pmid ) : for stmt in statements : for evidence in stmt . evidence : evidence . pmid = pmid # See if we need to start DRUM as a subprocess run_drum = drum_args . get ( 'run_drum' , False ) drum_process = None all_statements = { } # Iterate over all the keys and sentences to read for pmid , sentences in pmid_sentences . items ( ) : logger . info ( '================================' ) logger . info ( 'Processing %d sentences for %s' % ( len ( sentences ) , pmid ) ) ts = time . time ( ) # Make a DrumReader instance drum_args [ 'name' ] = 'DrumReader%s' % pmid dr = DrumReader ( * * drum_args ) time . sleep ( 3 ) # If there is no DRUM process set yet, we get the one that was # just started by the DrumReader if run_drum and drum_process is None : drum_args . pop ( 'run_drum' , None ) drum_process = dr . drum_system # By setting this, we ensuer that the reference to the # process is passed in to all future DrumReaders drum_args [ 'drum_system' ] = drum_process # Now read each sentence for this key for sentence in sentences : dr . read_text ( sentence ) # Start receiving results and exit when done try : dr . start ( ) except SystemExit : pass statements = [ ] # Process all the extractions into INDRA Statements for extraction in dr . extractions : # Sometimes we get nothing back if not extraction : continue tp = process_xml ( extraction ) statements += tp . statements # Set the PMIDs for the evidences of the Statements _set_pmid ( statements , pmid ) te = time . time ( ) logger . info ( 'Reading took %d seconds and produced %d Statements.' % ( te - ts , len ( statements ) ) ) all_statements [ pmid ] = statements # If we were running a DRUM process, we should kill it if drum_process and dr . drum_system : dr . _kill_drum ( ) return all_statements | Read sentences from a PMID - keyed dictonary and return all Statements | 505 | 16 |
17,395 | def graph_query ( kind , source , target = None , neighbor_limit = 1 , database_filter = None ) : default_databases = [ 'wp' , 'smpdb' , 'reconx' , 'reactome' , 'psp' , 'pid' , 'panther' , 'netpath' , 'msigdb' , 'mirtarbase' , 'kegg' , 'intact' , 'inoh' , 'humancyc' , 'hprd' , 'drugbank' , 'dip' , 'corum' ] if not database_filter : query_databases = default_databases else : query_databases = database_filter # excluded: ctd params = { } params [ 'format' ] = 'BIOPAX' params [ 'organism' ] = '9606' params [ 'datasource' ] = query_databases # Get the "kind" string kind_str = kind . lower ( ) if kind not in [ 'neighborhood' , 'pathsbetween' , 'pathsfromto' ] : logger . warn ( 'Invalid query type %s' % kind_str ) return None params [ 'kind' ] = kind_str # Get the source string if isinstance ( source , basestring ) : source_str = source else : source_str = ',' . join ( source ) params [ 'source' ] = source_str try : neighbor_limit = int ( neighbor_limit ) params [ 'limit' ] = neighbor_limit except ( TypeError , ValueError ) : logger . warn ( 'Invalid neighborhood limit %s' % neighbor_limit ) return None if target is not None : if isinstance ( target , basestring ) : target_str = target else : target_str = ',' . join ( target ) params [ 'target' ] = target_str logger . info ( 'Sending Pathway Commons query with parameters: ' ) for k , v in params . items ( ) : logger . info ( ' %s: %s' % ( k , v ) ) logger . info ( 'Sending Pathway Commons query...' ) res = requests . get ( pc2_url + 'graph' , params = params ) if not res . status_code == 200 : logger . error ( 'Response is HTTP code %d.' % res . status_code ) if res . status_code == 500 : logger . error ( 'Note: HTTP code 500 can mean empty ' 'results for a valid query.' ) return None # We don't decode to Unicode here because owl_str_to_model expects # a byte stream model = owl_str_to_model ( res . content ) if model is not None : logger . info ( 'Pathway Commons query returned a model...' ) return model | Perform a graph query on PathwayCommons . | 605 | 11 |
17,396 | def owl_str_to_model ( owl_str ) : io_class = autoclass ( 'org.biopax.paxtools.io.SimpleIOHandler' ) io = io_class ( autoclass ( 'org.biopax.paxtools.model.BioPAXLevel' ) . L3 ) bais = autoclass ( 'java.io.ByteArrayInputStream' ) scs = autoclass ( 'java.nio.charset.StandardCharsets' ) jstr = autoclass ( 'java.lang.String' ) istream = bais ( owl_str ) biopax_model = io . convertFromOWL ( istream ) return biopax_model | Return a BioPAX model object from an OWL string . | 163 | 13 |
17,397 | def owl_to_model ( fname ) : io_class = autoclass ( 'org.biopax.paxtools.io.SimpleIOHandler' ) io = io_class ( autoclass ( 'org.biopax.paxtools.model.BioPAXLevel' ) . L3 ) try : file_is = autoclass ( 'java.io.FileInputStream' ) ( fname ) except JavaException : logger . error ( 'Could not open data file %s' % fname ) return try : biopax_model = io . convertFromOWL ( file_is ) except JavaException as e : logger . error ( 'Could not convert data file %s to BioPax model' % fname ) logger . error ( e ) return file_is . close ( ) return biopax_model | Return a BioPAX model object from an OWL file . | 183 | 13 |
17,398 | def model_to_owl ( model , fname ) : io_class = autoclass ( 'org.biopax.paxtools.io.SimpleIOHandler' ) io = io_class ( autoclass ( 'org.biopax.paxtools.model.BioPAXLevel' ) . L3 ) try : fileOS = autoclass ( 'java.io.FileOutputStream' ) ( fname ) except JavaException : logger . error ( 'Could not open data file %s' % fname ) return l3_factory = autoclass ( 'org.biopax.paxtools.model.BioPAXLevel' ) . L3 . getDefaultFactory ( ) model_out = l3_factory . createModel ( ) for r in model . getObjects ( ) . toArray ( ) : model_out . add ( r ) io . convertToOWL ( model_out , fileOS ) fileOS . close ( ) | Save a BioPAX model object as an OWL file . | 213 | 13 |
17,399 | def make_model ( self , * args , * * kwargs ) : for stmt in self . statements : if isinstance ( stmt , RegulateActivity ) : self . _add_regulate_activity ( stmt ) elif isinstance ( stmt , RegulateAmount ) : self . _add_regulate_amount ( stmt ) elif isinstance ( stmt , Modification ) : self . _add_modification ( stmt ) elif isinstance ( stmt , SelfModification ) : self . _add_selfmodification ( stmt ) elif isinstance ( stmt , Gef ) : self . _add_gef ( stmt ) elif isinstance ( stmt , Gap ) : self . _add_gap ( stmt ) elif isinstance ( stmt , Complex ) : self . _add_complex ( stmt ) else : logger . warning ( 'Unhandled statement type: %s' % stmt . __class__ . __name__ ) if kwargs . get ( 'grouping' ) : self . _group_nodes ( ) self . _group_edges ( ) return self . print_cyjs_graph ( ) | Assemble a Cytoscape JS network from INDRA Statements . | 258 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.