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,700 | 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 . | 82 | 17 |
17,701 | 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 . | 55 | 18 |
17,702 | def _get_stmt_matching_groups ( stmts ) : def match_func ( x ) : return x . matches_key ( ) # Remove exact duplicates using a set() call, then make copies: logger . debug ( '%d statements before removing object duplicates.' % len ( stmts ) ) st = list ( set ( stmts ) ) logger . debug ( '%d statements after removing object duplicates.' % len ( stmts ) ) # Group statements according to whether they are matches (differing # only in their evidence). # Sort the statements in place by matches_key() st . sort ( key = match_func ) return itertools . groupby ( st , key = match_func ) | Use the matches_key method to get sets of matching statements . | 158 | 13 |
17,703 | def combine_duplicate_stmts ( stmts ) : # Helper function to get a list of evidence matches keys def _ev_keys ( sts ) : ev_keys = [ ] for stmt in sts : for ev in stmt . evidence : ev_keys . append ( ev . matches_key ( ) ) return ev_keys # Iterate over groups of duplicate statements unique_stmts = [ ] for _ , duplicates in Preassembler . _get_stmt_matching_groups ( stmts ) : ev_keys = set ( ) # Get the first statement and add the evidence of all subsequent # Statements to it duplicates = list ( duplicates ) start_ev_keys = _ev_keys ( duplicates ) for stmt_ix , stmt in enumerate ( duplicates ) : if stmt_ix is 0 : new_stmt = stmt . make_generic_copy ( ) if len ( duplicates ) == 1 : new_stmt . uuid = stmt . uuid raw_text = [ None if ag is None else ag . db_refs . get ( 'TEXT' ) for ag in stmt . agent_list ( deep_sorted = True ) ] raw_grounding = [ None if ag is None else ag . db_refs for ag in stmt . agent_list ( deep_sorted = True ) ] for ev in stmt . evidence : ev_key = ev . matches_key ( ) + str ( raw_text ) + str ( raw_grounding ) if ev_key not in ev_keys : # In case there are already agents annotations, we # just add a new key for raw_text, otherwise create # a new key if 'agents' in ev . annotations : ev . annotations [ 'agents' ] [ 'raw_text' ] = raw_text ev . annotations [ 'agents' ] [ 'raw_grounding' ] = raw_grounding else : ev . annotations [ 'agents' ] = { 'raw_text' : raw_text , 'raw_grounding' : raw_grounding } if 'prior_uuids' not in ev . annotations : ev . annotations [ 'prior_uuids' ] = [ ] ev . annotations [ 'prior_uuids' ] . append ( stmt . uuid ) new_stmt . evidence . append ( ev ) ev_keys . add ( ev_key ) end_ev_keys = _ev_keys ( [ new_stmt ] ) if len ( end_ev_keys ) != len ( start_ev_keys ) : logger . debug ( '%d redundant evidences eliminated.' % ( len ( start_ev_keys ) - len ( end_ev_keys ) ) ) # This should never be None or anything else assert isinstance ( new_stmt , Statement ) unique_stmts . append ( new_stmt ) return unique_stmts | Combine evidence from duplicate Statements . | 635 | 7 |
17,704 | 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 # Call combine_duplicates, which lazily initializes self.unique_stmts unique_stmts = self . combine_duplicates ( ) # Generate the index map, linking related statements. idx_map = self . _generate_id_maps ( unique_stmts , poolsize , size_cutoff ) # Now iterate over all indices and set supports/supported by for ix1 , ix2 in idx_map : unique_stmts [ ix1 ] . supported_by . append ( unique_stmts [ ix2 ] ) unique_stmts [ ix2 ] . supports . append ( unique_stmts [ ix1 ] ) # Get the top level statements self . related_stmts = [ st for st in unique_stmts if not st . supports ] logger . debug ( '%d top level' % len ( self . related_stmts ) ) if return_toplevel : return self . related_stmts else : return unique_stmts | Connect related statements based on their refinement relationships . | 307 | 9 |
17,705 | def find_contradicts ( self ) : eh = self . hierarchies [ 'entity' ] # Make a dict of Statement by type stmts_by_type = collections . defaultdict ( lambda : [ ] ) for idx , stmt in enumerate ( self . stmts ) : stmts_by_type [ indra_stmt_type ( stmt ) ] . append ( ( idx , stmt ) ) # Handle Statements with polarity first pos_stmts = AddModification . __subclasses__ ( ) neg_stmts = [ modclass_to_inverse [ c ] for c in pos_stmts ] pos_stmts += [ Activation , IncreaseAmount ] neg_stmts += [ Inhibition , DecreaseAmount ] contradicts = [ ] for pst , nst in zip ( pos_stmts , neg_stmts ) : poss = stmts_by_type . get ( pst , [ ] ) negs = stmts_by_type . get ( nst , [ ] ) pos_stmt_by_group = self . _get_stmt_by_group ( pst , poss , eh ) neg_stmt_by_group = self . _get_stmt_by_group ( nst , negs , eh ) for key , pg in pos_stmt_by_group . items ( ) : ng = neg_stmt_by_group . get ( key , [ ] ) for ( _ , st1 ) , ( _ , st2 ) in itertools . product ( pg , ng ) : if st1 . contradicts ( st2 , self . hierarchies ) : contradicts . append ( ( st1 , st2 ) ) # Handle neutral Statements next neu_stmts = [ Influence , ActiveForm ] for stt in neu_stmts : stmts = stmts_by_type . get ( stt , [ ] ) for ( _ , st1 ) , ( _ , st2 ) in itertools . combinations ( stmts , 2 ) : if st1 . contradicts ( st2 , self . hierarchies ) : contradicts . append ( ( st1 , st2 ) ) return contradicts | Return pairs of contradicting Statements . | 486 | 7 |
17,706 | 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 = [ ] failed = set ( ) for pmc_id in pmc_ids : if pmc_id is not None : pmc_xmls . append ( pmc_client . get_xml ( pmc_id ) ) else : failed . append ( pmid ) time . sleep ( 0.5 ) remaining_pmids = set ( pmids ) - pmc_pmids | failed abstracts = [ ] for pmid in remaining_pmids : abstract = pubmed_client . get_abstract ( pmid ) abstracts . append ( abstract ) time . sleep ( 0.5 ) return [ text_content for source in ( pmc_xmls , abstracts ) for text_content in source if text_content is not None ] | Get text content for articles given a list of their pmids | 295 | 12 |
17,707 | 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 | 65 | 11 |
17,708 | 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' . join ( paragraphs ) + '\n' | Filter paragraphs to only those containing one of a list of strings | 101 | 12 |
17,709 | 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 . | 67 | 12 |
17,710 | def get_valid_location ( location ) : # If we're given None, return None 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 . | 68 | 11 |
17,711 | 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 in g : subj = s . rpartition ( '/' ) [ - 1 ] obj = o . rpartition ( '/' ) [ - 1 ] act_types . add ( subj ) act_types . add ( obj ) return sorted ( list ( act_types ) ) | Read types of valid activities from a resource file . | 177 | 10 |
17,712 | def _read_cellular_components ( ) : # Here we load a patch file in addition to the current cellular components # file to make sure we don't error with InvalidLocationError with some # deprecated cellular location names 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_components = { } cellular_components_reverse = { } with open ( cc_file , 'rt' ) as fh : lines = list ( fh . readlines ( ) ) # We add the patch to the end of the lines list with open ( cc_patch_file , 'rt' ) as fh : lines += list ( fh . readlines ( ) ) for lin in lines [ 1 : ] : terms = lin . strip ( ) . split ( '\t' ) cellular_components [ terms [ 1 ] ] = terms [ 0 ] # If the GO -> name mapping doesn't exist yet, we add a mapping # but if it already exists (i.e. the try doesn't error) then # we don't add the GO -> name mapping. This ensures that names from # the patch file aren't mapped to in the reverse list. try : cellular_components_reverse [ terms [ 0 ] ] except KeyError : cellular_components_reverse [ terms [ 0 ] ] = terms [ 1 ] return cellular_components , cellular_components_reverse | Read cellular components from a resource file . | 374 | 8 |
17,713 | 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 : ] : terms = lin . strip ( ) . split ( '\t' ) key = terms [ 2 ] val = { 'full_name' : terms [ 0 ] , 'short_name' : terms [ 1 ] , 'indra_name' : terms [ 3 ] } amino_acids [ key ] = val for v in val . values ( ) : amino_acids_reverse [ v ] = key return amino_acids , amino_acids_reverse | Read the amino acid information from a resource file . | 219 | 10 |
17,714 | 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 ( ) glyphs = { } for idx , species in enumerate ( model . species ) : glyph = sa . _glyph_for_complex_pattern ( species ) if glyph is None : continue sa . _map . append ( glyph ) glyphs [ idx ] = glyph for reaction in model . reactions : # Get all the reactions / products / controllers of the reaction reactants = set ( reaction [ 'reactants' ] ) - set ( reaction [ 'products' ] ) products = set ( reaction [ 'products' ] ) - set ( reaction [ 'reactants' ] ) controllers = set ( reaction [ 'reactants' ] ) & set ( reaction [ 'products' ] ) # Add glyph for reaction process_glyph = sa . _process_glyph ( 'process' ) # Connect reactants with arcs if not reactants : glyph_id = sa . _none_glyph ( ) sa . _arc ( 'consumption' , glyph_id , process_glyph ) else : for r in reactants : glyph = glyphs . get ( r ) if glyph is None : glyph_id = sa . _none_glyph ( ) else : glyph_id = glyph . attrib [ 'id' ] sa . _arc ( 'consumption' , glyph_id , process_glyph ) # Connect products with arcs if not products : glyph_id = sa . _none_glyph ( ) sa . _arc ( 'production' , process_glyph , glyph_id ) else : for p in products : glyph = glyphs . get ( p ) if glyph is None : glyph_id = sa . _none_glyph ( ) else : glyph_id = glyph . attrib [ 'id' ] sa . _arc ( 'production' , process_glyph , glyph_id ) # Connect controllers with arcs for c in controllers : glyph = glyphs [ c ] sa . _arc ( 'catalysis' , glyph . attrib [ 'id' ] , process_glyph ) sbgn_str = sa . print_model ( ) . decode ( 'utf-8' ) return sbgn_str | Return an SBGN model string corresponding to the PySB model . | 547 | 13 |
17,715 | 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_agraph . to_agraph ( im ) agraph . draw ( fname , prog = 'dot' ) return im | Return a networkx graph representing the model s Kappa influence map . | 128 | 13 |
17,716 | 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 . | 87 | 13 |
17,717 | def _prepare_kappa ( model ) : import kappy kappa = kappy . KappaStd ( ) model_str = export ( model , 'kappa' ) kappa . add_model_string ( model_str ) kappa . project_parse ( ) return kappa | Return a Kappa STD with the model loaded . | 62 | 9 |
17,718 | def send_request ( * * kwargs ) : skiprows = kwargs . pop ( 'skiprows' , None ) res = requests . get ( cbio_url , params = kwargs ) if res . status_code == 200 : # Adaptively skip rows based on number of comment lines if skiprows == - 1 : lines = res . text . split ( '\n' ) skiprows = 0 for line in lines : if line . startswith ( '#' ) : skiprows += 1 else : break csv_StringIO = StringIO ( res . text ) df = pandas . read_csv ( csv_StringIO , sep = '\t' , skiprows = skiprows ) return df else : logger . error ( 'Request returned with code %d' % res . status_code ) | Return a data frame from a web service request to cBio portal . | 178 | 14 |
17,719 | def get_mutations ( study_id , gene_list , mutation_type = None , case_id = None ) : genetic_profile = get_genetic_profiles ( study_id , 'mutation' ) [ 0 ] gene_list_str = ',' . join ( gene_list ) data = { 'cmd' : 'getMutationData' , 'case_set_id' : study_id , 'genetic_profile_id' : genetic_profile , 'gene_list' : gene_list_str , 'skiprows' : - 1 } df = send_request ( * * data ) if case_id : df = df [ df [ 'case_id' ] == case_id ] res = _filter_data_frame ( df , [ 'gene_symbol' , 'amino_acid_change' ] , 'mutation_type' , mutation_type ) mutations = { 'gene_symbol' : list ( res [ 'gene_symbol' ] . values ( ) ) , 'amino_acid_change' : list ( res [ 'amino_acid_change' ] . values ( ) ) } return mutations | Return mutations as a list of genes and list of amino acid changes . | 258 | 14 |
17,720 | def get_case_lists ( study_id ) : data = { 'cmd' : 'getCaseLists' , 'cancer_study_id' : study_id } df = send_request ( * * data ) case_set_ids = df [ 'case_list_id' ] . tolist ( ) return case_set_ids | Return a list of the case set ids for a particular study . | 75 | 14 |
17,721 | def get_profile_data ( study_id , gene_list , profile_filter , case_set_filter = None ) : genetic_profiles = get_genetic_profiles ( study_id , profile_filter ) if genetic_profiles : genetic_profile = genetic_profiles [ 0 ] else : return { } gene_list_str = ',' . join ( gene_list ) case_set_ids = get_case_lists ( study_id ) if case_set_filter : case_set_id = [ x for x in case_set_ids if case_set_filter in x ] [ 0 ] else : case_set_id = study_id + '_all' # based on looking at the cBioPortal, this is a common case_set_id data = { 'cmd' : 'getProfileData' , 'case_set_id' : case_set_id , 'genetic_profile_id' : genetic_profile , 'gene_list' : gene_list_str , 'skiprows' : - 1 } df = send_request ( * * data ) case_list_df = [ x for x in df . columns . tolist ( ) if x not in [ 'GENE_ID' , 'COMMON' ] ] profile_data = { case : { g : None for g in gene_list } for case in case_list_df } for case in case_list_df : profile_values = df [ case ] . tolist ( ) df_gene_list = df [ 'COMMON' ] . tolist ( ) for g , cv in zip ( df_gene_list , profile_values ) : if not pandas . isnull ( cv ) : profile_data [ case ] [ g ] = cv return profile_data | Return dict of cases and genes and their respective values . | 397 | 11 |
17,722 | def get_num_sequenced ( study_id ) : data = { 'cmd' : 'getCaseLists' , 'cancer_study_id' : study_id } df = send_request ( * * data ) if df . empty : return 0 row_filter = df [ 'case_list_id' ] . str . contains ( 'sequenced' , case = False ) num_case = len ( df [ row_filter ] [ 'case_ids' ] . tolist ( ) [ 0 ] . split ( ' ' ) ) return num_case | Return number of sequenced tumors for given study . | 122 | 10 |
17,723 | def get_cancer_studies ( study_filter = None ) : data = { 'cmd' : 'getCancerStudies' } df = send_request ( * * data ) res = _filter_data_frame ( df , [ 'cancer_study_id' ] , 'cancer_study_id' , study_filter ) study_ids = list ( res [ 'cancer_study_id' ] . values ( ) ) return study_ids | Return a list of cancer study identifiers optionally filtered . | 97 | 10 |
17,724 | def get_cancer_types ( cancer_filter = None ) : data = { 'cmd' : 'getTypesOfCancer' } df = send_request ( * * data ) res = _filter_data_frame ( df , [ 'type_of_cancer_id' ] , 'name' , cancer_filter ) type_ids = list ( res [ 'type_of_cancer_id' ] . values ( ) ) return type_ids | Return a list of cancer types optionally filtered . | 97 | 9 |
17,725 | def get_ccle_mutations ( gene_list , cell_lines , mutation_type = None ) : mutations = { cl : { g : [ ] for g in gene_list } for cl in cell_lines } for cell_line in cell_lines : mutations_cl = get_mutations ( ccle_study , gene_list , mutation_type = mutation_type , case_id = cell_line ) for gene , aa_change in zip ( mutations_cl [ 'gene_symbol' ] , mutations_cl [ 'amino_acid_change' ] ) : aa_change = str ( aa_change ) mutations [ cell_line ] [ gene ] . append ( aa_change ) return mutations | Return a dict of mutations in given genes and cell lines from CCLE . | 160 | 15 |
17,726 | def get_ccle_lines_for_mutation ( gene , amino_acid_change ) : data = { 'cmd' : 'getMutationData' , 'case_set_id' : ccle_study , 'genetic_profile_id' : ccle_study + '_mutations' , 'gene_list' : gene , 'skiprows' : 1 } df = send_request ( * * data ) df = df [ df [ 'amino_acid_change' ] == amino_acid_change ] cell_lines = df [ 'case_id' ] . unique ( ) . tolist ( ) return cell_lines | Return cell lines with a given point mutation in a given gene . | 142 | 13 |
17,727 | def get_ccle_cna ( gene_list , cell_lines ) : profile_data = get_profile_data ( ccle_study , gene_list , 'COPY_NUMBER_ALTERATION' , 'all' ) profile_data = dict ( ( key , value ) for key , value in profile_data . items ( ) if key in cell_lines ) return profile_data | Return a dict of CNAs in given genes and cell lines from CCLE . | 88 | 16 |
17,728 | def get_ccle_mrna ( gene_list , cell_lines ) : gene_list_str = ',' . join ( gene_list ) data = { 'cmd' : 'getProfileData' , 'case_set_id' : ccle_study + '_mrna' , 'genetic_profile_id' : ccle_study + '_mrna' , 'gene_list' : gene_list_str , 'skiprows' : - 1 } df = send_request ( * * data ) mrna_amounts = { cl : { g : [ ] for g in gene_list } for cl in cell_lines } for cell_line in cell_lines : if cell_line in df . columns : for gene in gene_list : value_cell = df [ cell_line ] [ df [ 'COMMON' ] == gene ] if value_cell . empty : mrna_amounts [ cell_line ] [ gene ] = None elif pandas . isnull ( value_cell . values [ 0 ] ) : mrna_amounts [ cell_line ] [ gene ] = None else : value = value_cell . values [ 0 ] mrna_amounts [ cell_line ] [ gene ] = value else : mrna_amounts [ cell_line ] = None return mrna_amounts | Return a dict of mRNA amounts in given genes and cell lines from CCLE . | 298 | 16 |
17,729 | def _filter_data_frame ( df , data_col , filter_col , filter_str = None ) : if filter_str is not None : relevant_cols = data_col + [ filter_col ] df . dropna ( inplace = True , subset = relevant_cols ) row_filter = df [ filter_col ] . str . contains ( filter_str , case = False ) data_list = df [ row_filter ] [ data_col ] . to_dict ( ) else : data_list = df [ data_col ] . to_dict ( ) return data_list | Return a filtered data frame as a dictionary . | 130 | 9 |
17,730 | def allow_cors ( func ) : def wrapper ( * args , * * kwargs ) : response . headers [ 'Access-Control-Allow-Origin' ] = '*' response . headers [ 'Access-Control-Allow-Methods' ] = 'PUT, GET, POST, DELETE, OPTIONS' response . headers [ 'Access-Control-Allow-Headers' ] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' return func ( * args , * * kwargs ) return wrapper | This is a decorator which enable CORS for the specified endpoint . | 122 | 14 |
17,731 | def trips_process_text ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) text = body . get ( 'text' ) tp = trips . process_text ( text ) return _stmts_from_proc ( tp ) | Process text with TRIPS and return INDRA Statements . | 83 | 11 |
17,732 | def trips_process_xml ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) xml_str = body . get ( 'xml_str' ) tp = trips . process_xml ( xml_str ) return _stmts_from_proc ( tp ) | Process TRIPS EKB XML and return INDRA Statements . | 89 | 12 |
17,733 | def reach_process_text ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) text = body . get ( 'text' ) offline = True if body . get ( 'offline' ) else False rp = reach . process_text ( text , offline = offline ) return _stmts_from_proc ( rp ) | Process text with REACH and return INDRA Statements . | 102 | 11 |
17,734 | def reach_process_json ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) json_str = body . get ( 'json' ) rp = reach . process_json_str ( json_str ) return _stmts_from_proc ( rp ) | Process REACH json and return INDRA Statements . | 89 | 10 |
17,735 | def reach_process_pmc ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) pmcid = body . get ( 'pmcid' ) rp = reach . process_pmc ( pmcid ) return _stmts_from_proc ( rp ) | Process PubMedCentral article and return INDRA Statements . | 91 | 10 |
17,736 | def bel_process_pybel_neighborhood ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) genes = body . get ( 'genes' ) bp = bel . process_pybel_neighborhood ( genes ) return _stmts_from_proc ( bp ) | Process BEL Large Corpus neighborhood and return INDRA Statements . | 96 | 11 |
17,737 | def bel_process_belrdf ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) belrdf = body . get ( 'belrdf' ) bp = bel . process_belrdf ( belrdf ) return _stmts_from_proc ( bp ) | Process BEL RDF and return INDRA Statements . | 93 | 10 |
17,738 | def biopax_process_pc_pathsbetween ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) genes = body . get ( 'genes' ) bp = biopax . process_pc_pathsbetween ( genes ) return _stmts_from_proc ( bp ) | Process PathwayCommons paths between genes return INDRA Statements . | 96 | 13 |
17,739 | def biopax_process_pc_pathsfromto ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) source = body . get ( 'source' ) target = body . get ( 'target' ) bp = biopax . process_pc_pathsfromto ( source , target ) return _stmts_from_proc ( bp ) | Process PathwayCommons paths from - to genes return INDRA Statements . | 109 | 15 |
17,740 | def biopax_process_pc_neighborhood ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) genes = body . get ( 'genes' ) bp = biopax . process_pc_neighborhood ( genes ) return _stmts_from_proc ( bp ) | Process PathwayCommons neighborhood return INDRA Statements . | 98 | 11 |
17,741 | def eidos_process_text ( ) : if request . method == 'OPTIONS' : return { } req = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( req ) text = body . get ( 'text' ) webservice = body . get ( 'webservice' ) if not webservice : response . status = 400 response . content_type = 'application/json' return json . dumps ( { 'error' : 'No web service address provided.' } ) ep = eidos . process_text ( text , webservice = webservice ) return _stmts_from_proc ( ep ) | Process text with EIDOS and return INDRA Statements . | 149 | 12 |
17,742 | def eidos_process_jsonld ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) eidos_json = body . get ( 'jsonld' ) ep = eidos . process_json_str ( eidos_json ) return _stmts_from_proc ( ep ) | Process an EIDOS JSON - LD and return INDRA Statements . | 97 | 14 |
17,743 | def cwms_process_text ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) text = body . get ( 'text' ) cp = cwms . process_text ( text ) return _stmts_from_proc ( cp ) | Process text with CWMS and return INDRA Statements . | 85 | 11 |
17,744 | def hume_process_jsonld ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) jsonld_str = body . get ( 'jsonld' ) jsonld = json . loads ( jsonld_str ) hp = hume . process_jsonld ( jsonld ) return _stmts_from_proc ( hp ) | Process Hume JSON - LD and return INDRA Statements . | 102 | 11 |
17,745 | def sofia_process_text ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) text = body . get ( 'text' ) auth = body . get ( 'auth' ) sp = sofia . process_text ( text , auth = auth ) return _stmts_from_proc ( sp ) | Process text with Sofia and return INDRA Statements . | 99 | 11 |
17,746 | def assemble_pysb ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) export_format = body . get ( 'export_format' ) stmts = stmts_from_json ( stmts_json ) pa = PysbAssembler ( ) pa . add_statements ( stmts ) pa . make_model ( ) try : for m in pa . model . monomers : pysb_assembler . set_extended_initial_condition ( pa . model , m , 0 ) except Exception as e : logger . exception ( e ) if not export_format : model_str = pa . print_model ( ) elif export_format in ( 'kappa_im' , 'kappa_cm' ) : fname = 'model_%s.png' % export_format root = os . path . dirname ( os . path . abspath ( fname ) ) graph = pa . export_model ( format = export_format , file_name = fname ) with open ( fname , 'rb' ) as fh : data = 'data:image/png;base64,%s' % base64 . b64encode ( fh . read ( ) ) . decode ( ) return { 'image' : data } else : try : model_str = pa . export_model ( format = export_format ) except Exception as e : logger . exception ( e ) model_str = '' res = { 'model' : model_str } return res | Assemble INDRA Statements and return PySB model string . | 372 | 12 |
17,747 | def assemble_cx ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) ca = CxAssembler ( stmts ) model_str = ca . make_model ( ) res = { 'model' : model_str } return res | Assemble INDRA Statements and return CX network json . | 117 | 12 |
17,748 | def share_model_ndex ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_str = body . get ( 'stmts' ) stmts_json = json . loads ( stmts_str ) stmts = stmts_from_json ( stmts_json [ "statements" ] ) ca = CxAssembler ( stmts ) for n , v in body . items ( ) : ca . cx [ 'networkAttributes' ] . append ( { 'n' : n , 'v' : v , 'd' : 'string' } ) ca . make_model ( ) network_id = ca . upload_model ( private = False ) return { 'network_id' : network_id } | Upload the model to NDEX | 196 | 6 |
17,749 | def fetch_model_ndex ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) network_id = body . get ( 'network_id' ) cx = process_ndex_network ( network_id ) network_attr = [ x for x in cx . cx if x . get ( 'networkAttributes' ) ] network_attr = network_attr [ 0 ] [ 'networkAttributes' ] keep_keys = [ 'txt_input' , 'parser' , 'model_elements' , 'preset_pos' , 'stmts' , 'sentences' , 'evidence' , 'cell_line' , 'mrna' , 'mutations' ] stored_data = { } for d in network_attr : if d [ 'n' ] in keep_keys : stored_data [ d [ 'n' ] ] = d [ 'v' ] return stored_data | Download model and associated pieces from NDEX | 223 | 8 |
17,750 | def assemble_graph ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) ga = GraphAssembler ( stmts ) model_str = ga . make_model ( ) res = { 'model' : model_str } return res | Assemble INDRA Statements and return Graphviz graph dot string . | 115 | 14 |
17,751 | def assemble_cyjs ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) cja = CyJSAssembler ( ) cja . add_statements ( stmts ) cja . make_model ( grouping = True ) model_str = cja . print_cyjs_graph ( ) return model_str | Assemble INDRA Statements and return Cytoscape JS network . | 133 | 14 |
17,752 | def assemble_english ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) sentences = { } for st in stmts : enga = EnglishAssembler ( ) enga . add_statements ( [ st ] ) model_str = enga . make_model ( ) sentences [ st . uuid ] = model_str res = { 'sentences' : sentences } return res | Assemble each statement into | 147 | 5 |
17,753 | def assemble_loopy ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) sa = SifAssembler ( stmts ) sa . make_model ( use_name_as_key = True ) model_str = sa . print_loopy ( as_url = True ) res = { 'loopy_url' : model_str } return res | Assemble INDRA Statements into a Loopy model using SIF Assembler . | 142 | 17 |
17,754 | def get_ccle_mrna_levels ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) gene_list = body . get ( 'gene_list' ) cell_lines = body . get ( 'cell_lines' ) mrna_amounts = cbio_client . get_ccle_mrna ( gene_list , cell_lines ) res = { 'mrna_amounts' : mrna_amounts } return res | Get CCLE mRNA amounts using cBioClient | 131 | 9 |
17,755 | def get_ccle_mutations ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) gene_list = body . get ( 'gene_list' ) cell_lines = body . get ( 'cell_lines' ) mutations = cbio_client . get_ccle_mutations ( gene_list , cell_lines ) res = { 'mutations' : mutations } return res | Get CCLE mutations returns the amino acid changes for a given list of genes and cell lines | 116 | 18 |
17,756 | def map_grounding ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) stmts_out = ac . map_grounding ( stmts ) return _return_stmts ( stmts_out ) | Map grounding on a list of INDRA Statements . | 112 | 10 |
17,757 | def run_preassembly ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) scorer = body . get ( 'scorer' ) return_toplevel = body . get ( 'return_toplevel' ) if scorer == 'wm' : belief_scorer = get_eidos_scorer ( ) else : belief_scorer = None stmts_out = ac . run_preassembly ( stmts , belief_scorer = belief_scorer , return_toplevel = return_toplevel ) return _return_stmts ( stmts_out ) | Run preassembly on a list of INDRA Statements . | 193 | 11 |
17,758 | def map_ontologies ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) om = OntologyMapper ( stmts , wm_ontomap , scored = True , symmetric = False ) om . map_statements ( ) return _return_stmts ( stmts ) | Run ontology mapping on a list of INDRA Statements . | 128 | 12 |
17,759 | def filter_by_type ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmt_type_str = body . get ( 'type' ) stmt_type_str = stmt_type_str . capitalize ( ) stmt_type = getattr ( sys . modules [ __name__ ] , stmt_type_str ) stmts = stmts_from_json ( stmts_json ) stmts_out = ac . filter_by_type ( stmts , stmt_type ) return _return_stmts ( stmts_out ) | Filter to a given INDRA Statement type . | 175 | 9 |
17,760 | def filter_grounded_only ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) score_threshold = body . get ( 'score_threshold' ) if score_threshold is not None : score_threshold = float ( score_threshold ) stmts = stmts_from_json ( stmts_json ) stmts_out = ac . filter_grounded_only ( stmts , score_threshold = score_threshold ) return _return_stmts ( stmts_out ) | Filter to grounded Statements only . | 163 | 6 |
17,761 | def filter_belief ( ) : if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) belief_cutoff = body . get ( 'belief_cutoff' ) if belief_cutoff is not None : belief_cutoff = float ( belief_cutoff ) stmts = stmts_from_json ( stmts_json ) stmts_out = ac . filter_belief ( stmts , belief_cutoff ) return _return_stmts ( stmts_out ) | Filter to beliefs above a given threshold . | 155 | 8 |
17,762 | def get_git_info ( ) : start_dir = abspath ( curdir ) try : chdir ( dirname ( abspath ( __file__ ) ) ) re_patt_str = ( r'commit\s+(?P<commit_hash>\w+).*?Author:\s+' r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+' r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$' ) show_out = check_output ( [ 'git' , 'show' ] ) . decode ( 'ascii' ) revp_out = check_output ( [ 'git' , 'rev-parse' , '--abbrev-ref' , 'HEAD' ] ) revp_out = revp_out . decode ( 'ascii' ) . strip ( ) m = re . search ( re_patt_str , show_out , re . DOTALL ) assert m is not None , "Regex pattern:\n\n\"%s\"\n\n failed to match string:\n\n\"%s\"" % ( re_patt_str , show_out ) ret_dict = m . groupdict ( ) ret_dict [ 'branch_name' ] = revp_out finally : chdir ( start_dir ) return ret_dict | Get a dict with useful git info . | 330 | 8 |
17,763 | def get_version ( with_git_hash = True , refresh_hash = False ) : version = __version__ if with_git_hash : global INDRA_GITHASH if INDRA_GITHASH is None or refresh_hash : with open ( devnull , 'w' ) as nul : try : ret = check_output ( [ 'git' , 'rev-parse' , 'HEAD' ] , cwd = dirname ( __file__ ) , stderr = nul ) except CalledProcessError : ret = 'UNHASHED' INDRA_GITHASH = ret . strip ( ) . decode ( 'utf-8' ) version = '%s-%s' % ( version , INDRA_GITHASH ) return version | Get an indra version string including a git hash . | 165 | 11 |
17,764 | def _fix_evidence_text ( txt ) : txt = re . sub ( '[ ]?\( xref \)' , '' , txt ) # This is to make [ xref ] become [] to match the two readers txt = re . sub ( '\[ xref \]' , '[]' , txt ) txt = re . sub ( '[\(]?XREF_BIBR[\)]?[,]?' , '' , txt ) txt = re . sub ( '[\(]?XREF_FIG[\)]?[,]?' , '' , txt ) txt = re . sub ( '[\(]?XREF_SUPPLEMENT[\)]?[,]?' , '' , txt ) txt = txt . strip ( ) return txt | Eliminate some symbols to have cleaner supporting text . | 177 | 11 |
17,765 | def make_model ( self , add_indra_json = True ) : self . add_indra_json = add_indra_json for stmt in self . statements : if isinstance ( stmt , Modification ) : self . _add_modification ( stmt ) if isinstance ( stmt , SelfModification ) : self . _add_self_modification ( stmt ) elif isinstance ( stmt , RegulateActivity ) or isinstance ( stmt , RegulateAmount ) : self . _add_regulation ( stmt ) elif isinstance ( stmt , Complex ) : self . _add_complex ( stmt ) elif isinstance ( stmt , Gef ) : self . _add_gef ( stmt ) elif isinstance ( stmt , Gap ) : self . _add_gap ( stmt ) elif isinstance ( stmt , Influence ) : self . _add_influence ( stmt ) network_description = '' self . cx [ 'networkAttributes' ] . append ( { 'n' : 'name' , 'v' : self . network_name } ) self . cx [ 'networkAttributes' ] . append ( { 'n' : 'description' , 'v' : network_description } ) cx_str = self . print_cx ( ) return cx_str | Assemble the CX network from the collected INDRA Statements . | 291 | 13 |
17,766 | def print_cx ( self , pretty = True ) : def _get_aspect_metadata ( aspect ) : count = len ( self . cx . get ( aspect ) ) if self . cx . get ( aspect ) else 0 if not count : return None data = { 'name' : aspect , 'idCounter' : self . _id_counter , 'consistencyGroup' : 1 , 'elementCount' : count } return data full_cx = OrderedDict ( ) full_cx [ 'numberVerification' ] = [ { 'longNumber' : 281474976710655 } ] aspects = [ 'nodes' , 'edges' , 'supports' , 'citations' , 'edgeAttributes' , 'edgeCitations' , 'edgeSupports' , 'networkAttributes' , 'nodeAttributes' , 'cartesianLayout' ] full_cx [ 'metaData' ] = [ ] for aspect in aspects : metadata = _get_aspect_metadata ( aspect ) if metadata : full_cx [ 'metaData' ] . append ( metadata ) for k , v in self . cx . items ( ) : full_cx [ k ] = v full_cx [ 'status' ] = [ { 'error' : '' , 'success' : True } ] full_cx = [ { k : v } for k , v in full_cx . items ( ) ] if pretty : json_str = json . dumps ( full_cx , indent = 2 ) else : json_str = json . dumps ( full_cx ) return json_str | Return the assembled CX network as a json string . | 347 | 11 |
17,767 | def save_model ( self , file_name = 'model.cx' ) : with open ( file_name , 'wt' ) as fh : cx_str = self . print_cx ( ) fh . write ( cx_str ) | Save the assembled CX network in a file . | 55 | 10 |
17,768 | def set_context ( self , cell_type ) : node_names = [ node [ 'n' ] for node in self . cx [ 'nodes' ] ] res_expr = context_client . get_protein_expression ( node_names , [ cell_type ] ) res_mut = context_client . get_mutations ( node_names , [ cell_type ] ) res_expr = res_expr . get ( cell_type ) res_mut = res_mut . get ( cell_type ) if not res_expr : msg = 'Could not get protein expression for %s cell type.' % cell_type logger . warning ( msg ) if not res_mut : msg = 'Could not get mutational status for %s cell type.' % cell_type logger . warning ( msg ) if not res_expr and not res_mut : return self . cx [ 'networkAttributes' ] . append ( { 'n' : 'cellular_context' , 'v' : cell_type } ) counter = 0 for node in self . cx [ 'nodes' ] : amount = res_expr . get ( node [ 'n' ] ) mut = res_mut . get ( node [ 'n' ] ) if amount is not None : node_attribute = { 'po' : node [ '@id' ] , 'n' : 'expression_amount' , 'v' : int ( amount ) } self . cx [ 'nodeAttributes' ] . append ( node_attribute ) if mut is not None : is_mutated = 1 if mut else 0 node_attribute = { 'po' : node [ '@id' ] , 'n' : 'is_mutated' , 'v' : is_mutated } self . cx [ 'nodeAttributes' ] . append ( node_attribute ) if mut is not None or amount is not None : counter += 1 logger . info ( 'Set context for %d nodes.' % counter ) | Set protein expression data and mutational status as node attribute | 419 | 11 |
17,769 | def get_publications ( gene_names , save_json_name = None ) : if len ( gene_names ) != 2 : logger . warning ( 'Other than 2 gene names given.' ) return [ ] res_dict = _send_request ( gene_names ) if not res_dict : return [ ] if save_json_name is not None : # The json module produces strings, not bytes, so the file should be # opened in text mode with open ( save_json_name , 'wt' ) as fh : json . dump ( res_dict , fh , indent = 1 ) publications = _extract_publications ( res_dict , gene_names ) return publications | Return evidence publications for interaction between the given genes . | 148 | 10 |
17,770 | def _n ( name ) : n = name . encode ( 'ascii' , errors = 'ignore' ) . decode ( 'ascii' ) n = re . sub ( '[^A-Za-z0-9_]' , '_' , n ) n = re . sub ( r'(^[0-9].*)' , r'p\1' , n ) return n | Return valid PySB name . | 89 | 6 |
17,771 | def get_hash_statements_dict ( self ) : res = { stmt_hash : stmts_from_json ( [ stmt ] ) [ 0 ] for stmt_hash , stmt in self . __statement_jsons . items ( ) } return res | Return a dict of Statements keyed by hashes . | 60 | 10 |
17,772 | def merge_results ( self , other_processor ) : if not isinstance ( other_processor , self . __class__ ) : raise ValueError ( "Can only extend with another %s instance." % self . __class__ . __name__ ) self . statements . extend ( other_processor . statements ) if other_processor . statements_sample is not None : if self . statements_sample is None : self . statements_sample = other_processor . statements_sample else : self . statements_sample . extend ( other_processor . statements_sample ) self . _merge_json ( other_processor . __statement_jsons , other_processor . __evidence_counts ) return | Merge the results of this processor with those of another . | 146 | 12 |
17,773 | def wait_until_done ( self , timeout = None ) : start = datetime . now ( ) if not self . __th : raise IndraDBRestResponseError ( "There is no thread waiting to " "complete." ) self . __th . join ( timeout ) now = datetime . now ( ) dt = now - start if self . __th . is_alive ( ) : logger . warning ( "Timed out after %0.3f seconds waiting for " "statement load to complete." % dt . total_seconds ( ) ) ret = False else : logger . info ( "Waited %0.3f seconds for statements to finish loading." % dt . total_seconds ( ) ) ret = True return ret | Wait for the background load to complete . | 157 | 8 |
17,774 | def _merge_json ( self , stmt_json , ev_counts ) : # Where there is overlap, there _should_ be agreement. self . __evidence_counts . update ( ev_counts ) for k , sj in stmt_json . items ( ) : if k not in self . __statement_jsons : self . __statement_jsons [ k ] = sj # This should be most of them else : # This should only happen rarely. for evj in sj [ 'evidence' ] : self . __statement_jsons [ k ] [ 'evidence' ] . append ( evj ) if not self . __started : self . statements_sample = stmts_from_json ( self . __statement_jsons . values ( ) ) self . __started = True return | Merge these statement jsons with new jsons . | 177 | 11 |
17,775 | def _run_queries ( self , agent_strs , stmt_types , params , persist ) : self . _query_over_statement_types ( agent_strs , stmt_types , params ) assert len ( self . __done_dict ) == len ( stmt_types ) or None in self . __done_dict . keys ( ) , "Done dict was not initiated for all stmt_type's." # Check if we want to keep going. if not persist : self . _compile_statements ( ) return # Get the rest of the content. while not self . _all_done ( ) : self . _query_over_statement_types ( agent_strs , stmt_types , params ) # Create the actual statements. self . _compile_statements ( ) return | Use paging to get all statements requested . | 176 | 9 |
17,776 | def get_ids ( search_term , * * kwargs ) : use_text_word = kwargs . pop ( 'use_text_word' , True ) if use_text_word : search_term += '[tw]' params = { 'term' : search_term , 'retmax' : 100000 , 'retstart' : 0 , 'db' : 'pubmed' , 'sort' : 'pub+date' } params . update ( kwargs ) tree = send_request ( pubmed_search , params ) if tree is None : return [ ] if tree . find ( 'ERROR' ) is not None : logger . error ( tree . find ( 'ERROR' ) . text ) return [ ] if tree . find ( 'ErrorList' ) is not None : for err in tree . find ( 'ErrorList' ) . getchildren ( ) : logger . error ( 'Error - %s: %s' % ( err . tag , err . text ) ) return [ ] count = int ( tree . find ( 'Count' ) . text ) id_terms = tree . findall ( 'IdList/Id' ) if id_terms is None : return [ ] ids = [ idt . text for idt in id_terms ] if count != len ( ids ) : logger . warning ( 'Not all ids were retrieved for search %s;\n' 'limited at %d.' % ( search_term , params [ 'retmax' ] ) ) return ids | Search Pubmed for paper IDs given a search term . | 325 | 11 |
17,777 | def get_id_count ( search_term ) : params = { 'term' : search_term , 'rettype' : 'count' , 'db' : 'pubmed' } tree = send_request ( pubmed_search , params ) if tree is None : return None else : count = tree . getchildren ( ) [ 0 ] . text return int ( count ) | Get the number of citations in Pubmed for a search query . | 81 | 13 |
17,778 | def get_ids_for_gene ( hgnc_name , * * kwargs ) : # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client . get_hgnc_id ( hgnc_name ) if hgnc_id is None : raise ValueError ( 'Invalid HGNC name.' ) # Get the Entrez ID entrez_id = hgnc_client . get_entrez_id ( hgnc_id ) if entrez_id is None : raise ValueError ( 'Entrez ID not found in HGNC table.' ) # Query the Entrez Gene database params = { 'db' : 'gene' , 'retmode' : 'xml' , 'id' : entrez_id } params . update ( kwargs ) tree = send_request ( pubmed_fetch , params ) if tree is None : return [ ] if tree . find ( 'ERROR' ) is not None : logger . error ( tree . find ( 'ERROR' ) . text ) return [ ] # Get all PMIDs from the XML tree id_terms = tree . findall ( './/PubMedId' ) if id_terms is None : return [ ] # Use a set to remove duplicate IDs ids = list ( set ( [ idt . text for idt in id_terms ] ) ) return ids | Get the curated set of articles for a gene in the Entrez database . | 300 | 15 |
17,779 | def get_article_xml ( pubmed_id ) : if pubmed_id . upper ( ) . startswith ( 'PMID' ) : pubmed_id = pubmed_id [ 4 : ] params = { 'db' : 'pubmed' , 'retmode' : 'xml' , 'id' : pubmed_id } tree = send_request ( pubmed_fetch , params ) if tree is None : return None article = tree . find ( 'PubmedArticle/MedlineCitation/Article' ) return article | Get the XML metadata for a single article from the Pubmed database . | 118 | 14 |
17,780 | def get_abstract ( pubmed_id , prepend_title = True ) : article = get_article_xml ( pubmed_id ) if article is None : return None return _abstract_from_article_element ( article , prepend_title ) | Get the abstract of an article in the Pubmed database . | 57 | 12 |
17,781 | def get_metadata_from_xml_tree ( tree , get_issns_from_nlm = False , get_abstracts = False , prepend_title = False , mesh_annotations = False ) : # Iterate over the articles and build the results dict results = { } pm_articles = tree . findall ( './PubmedArticle' ) for art_ix , pm_article in enumerate ( pm_articles ) : medline_citation = pm_article . find ( './MedlineCitation' ) article_info = _get_article_info ( medline_citation , pm_article . find ( 'PubmedData' ) ) journal_info = _get_journal_info ( medline_citation , get_issns_from_nlm ) context_info = _get_annotations ( medline_citation ) # Build the result result = { } result . update ( article_info ) result . update ( journal_info ) result . update ( context_info ) # Get the abstracts if requested if get_abstracts : abstract = _abstract_from_article_element ( medline_citation . find ( 'Article' ) , prepend_title = prepend_title ) result [ 'abstract' ] = abstract # Add to dict results [ article_info [ 'pmid' ] ] = result return results | Get metadata for an XML tree containing PubmedArticle elements . | 299 | 12 |
17,782 | def get_metadata_for_ids ( pmid_list , get_issns_from_nlm = False , get_abstracts = False , prepend_title = False ) : if len ( pmid_list ) > 200 : raise ValueError ( "Metadata query is limited to 200 PMIDs at a time." ) params = { 'db' : 'pubmed' , 'retmode' : 'xml' , 'id' : pmid_list } tree = send_request ( pubmed_fetch , params ) if tree is None : return None return get_metadata_from_xml_tree ( tree , get_issns_from_nlm , get_abstracts , prepend_title ) | Get article metadata for up to 200 PMIDs from the Pubmed database . | 157 | 15 |
17,783 | def get_issns_for_journal ( nlm_id ) : params = { 'db' : 'nlmcatalog' , 'retmode' : 'xml' , 'id' : nlm_id } tree = send_request ( pubmed_fetch , params ) if tree is None : return None issn_list = tree . findall ( './/ISSN' ) issn_linking = tree . findall ( './/ISSNLinking' ) issns = issn_list + issn_linking # No ISSNs found! if not issns : return None else : return [ issn . text for issn in issns ] | Get a list of the ISSN numbers for a journal given its NLM ID . | 148 | 17 |
17,784 | def remove_im_params ( model , im ) : for param in model . parameters : # If the node doesn't exist e.g., it may have already been removed), # skip over the parameter without error try : im . remove_node ( param . name ) except : pass | Remove parameter nodes from the influence map . | 59 | 8 |
17,785 | def _get_signed_predecessors ( im , node , polarity ) : signed_pred_list = [ ] for pred in im . predecessors ( node ) : pred_edge = ( pred , node ) yield ( pred , _get_edge_sign ( im , pred_edge ) * polarity ) | Get upstream nodes in the influence map . | 66 | 8 |
17,786 | def _get_edge_sign ( im , edge ) : edge_data = im [ edge [ 0 ] ] [ edge [ 1 ] ] # Handle possible multiple edges between nodes signs = list ( set ( [ v [ 'sign' ] for v in edge_data . values ( ) if v . get ( 'sign' ) ] ) ) if len ( signs ) > 1 : logger . warning ( "Edge %s has conflicting polarities; choosing " "positive polarity by default" % str ( edge ) ) sign = 1 else : sign = signs [ 0 ] if sign is None : raise Exception ( 'No sign attribute for edge.' ) elif abs ( sign ) == 1 : return sign else : raise Exception ( 'Unexpected edge sign: %s' % edge . attr [ 'sign' ] ) | Get the polarity of the influence by examining the edge sign . | 171 | 13 |
17,787 | def _add_modification_to_agent ( agent , mod_type , residue , position ) : new_mod = ModCondition ( mod_type , residue , position ) # Check if this modification already exists for old_mod in agent . mods : if old_mod . equals ( new_mod ) : return agent new_agent = deepcopy ( agent ) new_agent . mods . append ( new_mod ) return new_agent | Add a modification condition to an Agent . | 92 | 8 |
17,788 | def _match_lhs ( cp , rules ) : rule_matches = [ ] for rule in rules : reactant_pattern = rule . rule_expression . reactant_pattern for rule_cp in reactant_pattern . complex_patterns : if _cp_embeds_into ( rule_cp , cp ) : rule_matches . append ( rule ) break return rule_matches | Get rules with a left - hand side matching the given ComplexPattern . | 85 | 14 |
17,789 | def _cp_embeds_into ( cp1 , cp2 ) : # Check that any state in cp2 is matched in cp1 # If the thing we're matching to is just a monomer pattern, that makes # things easier--we just need to find the corresponding monomer pattern # in cp1 if cp1 is None or cp2 is None : return False cp1 = as_complex_pattern ( cp1 ) cp2 = as_complex_pattern ( cp2 ) if len ( cp2 . monomer_patterns ) == 1 : mp2 = cp2 . monomer_patterns [ 0 ] # Iterate over the monomer patterns in cp1 and see if there is one # that has the same name for mp1 in cp1 . monomer_patterns : if _mp_embeds_into ( mp1 , mp2 ) : return True return False | Check that any state in ComplexPattern2 is matched in ComplexPattern1 . | 186 | 15 |
17,790 | def _mp_embeds_into ( mp1 , mp2 ) : sc_matches = [ ] if mp1 . monomer . name != mp2 . monomer . name : return False # Check that all conditions in mp2 are met in mp1 for site_name , site_state in mp2 . site_conditions . items ( ) : if site_name not in mp1 . site_conditions or site_state != mp1 . site_conditions [ site_name ] : return False return True | Check that conditions in MonomerPattern2 are met in MonomerPattern1 . | 111 | 16 |
17,791 | def _monomer_pattern_label ( mp ) : site_strs = [ ] for site , cond in mp . site_conditions . items ( ) : if isinstance ( cond , tuple ) or isinstance ( cond , list ) : assert len ( cond ) == 2 if cond [ 1 ] == WILD : site_str = '%s_%s' % ( site , cond [ 0 ] ) else : site_str = '%s_%s%s' % ( site , cond [ 0 ] , cond [ 1 ] ) elif isinstance ( cond , numbers . Real ) : continue else : site_str = '%s_%s' % ( site , cond ) site_strs . append ( site_str ) return '%s_%s' % ( mp . monomer . name , '_' . join ( site_strs ) ) | Return a string label for a MonomerPattern . | 189 | 10 |
17,792 | def _stmt_from_rule ( model , rule_name , stmts ) : stmt_uuid = None for ann in model . annotations : if ann . predicate == 'from_indra_statement' : if ann . subject == rule_name : stmt_uuid = ann . object break if stmt_uuid : for stmt in stmts : if stmt . uuid == stmt_uuid : return stmt | Return the INDRA Statement corresponding to a given rule by name . | 98 | 13 |
17,793 | def generate_im ( self , model ) : kappa = kappy . KappaStd ( ) model_str = export . export ( model , 'kappa' ) kappa . add_model_string ( model_str ) kappa . project_parse ( ) imap = kappa . analyses_influence_map ( accuracy = 'medium' ) graph = im_json_to_graph ( imap ) return graph | Return a graph representing the influence map generated by Kappa | 91 | 10 |
17,794 | def draw_im ( self , fname ) : im = self . get_im ( ) im_agraph = nx . nx_agraph . to_agraph ( im ) im_agraph . draw ( fname , prog = 'dot' ) | Draw and save the influence map in a file . | 53 | 10 |
17,795 | def check_model ( self , max_paths = 1 , max_path_length = 5 ) : results = [ ] for stmt in self . statements : result = self . check_statement ( stmt , max_paths , max_path_length ) results . append ( ( stmt , result ) ) return results | Check all the statements added to the ModelChecker . | 70 | 11 |
17,796 | def check_statement ( self , stmt , max_paths = 1 , max_path_length = 5 ) : # Make sure the influence map is initialized self . get_im ( ) # Check if this is one of the statement types that we can check if not isinstance ( stmt , ( Modification , RegulateAmount , RegulateActivity , Influence ) ) : return PathResult ( False , 'STATEMENT_TYPE_NOT_HANDLED' , max_paths , max_path_length ) # Get the polarity for the statement if isinstance ( stmt , Modification ) : target_polarity = - 1 if isinstance ( stmt , RemoveModification ) else 1 elif isinstance ( stmt , RegulateActivity ) : target_polarity = 1 if stmt . is_activation else - 1 elif isinstance ( stmt , RegulateAmount ) : target_polarity = - 1 if isinstance ( stmt , DecreaseAmount ) else 1 elif isinstance ( stmt , Influence ) : target_polarity = - 1 if stmt . overall_polarity ( ) == - 1 else 1 # Get the subject and object (works also for Modifications) subj , obj = stmt . agent_list ( ) # Get a list of monomer patterns matching the subject FIXME Currently # this will match rules with the corresponding monomer pattern on it. # In future, this statement should (possibly) also match rules in which # 1) the agent is in its active form, or 2) the agent is tagged as the # enzyme in a rule of the appropriate activity (e.g., a phosphorylation # rule) FIXME if subj is not None : subj_mps = list ( pa . grounded_monomer_patterns ( self . model , subj , ignore_activities = True ) ) if not subj_mps : logger . debug ( 'No monomers found corresponding to agent %s' % subj ) return PathResult ( False , 'SUBJECT_MONOMERS_NOT_FOUND' , max_paths , max_path_length ) else : subj_mps = [ None ] # Observables may not be found for an activation since there may be no # rule in the model activating the object, and the object may not have # an "active" site of the appropriate type obs_names = self . stmt_to_obs [ stmt ] if not obs_names : logger . debug ( "No observables for stmt %s, returning False" % stmt ) return PathResult ( False , 'OBSERVABLES_NOT_FOUND' , max_paths , max_path_length ) for subj_mp , obs_name in itertools . product ( subj_mps , obs_names ) : # NOTE: Returns on the path found for the first enz_mp/obs combo result = self . _find_im_paths ( subj_mp , obs_name , target_polarity , max_paths , max_path_length ) # If a path was found, then we return it; otherwise, that means # there was no path for this observable, so we have to try the next # one if result . path_found : return result # If we got here, then there was no path for any observable return PathResult ( False , 'NO_PATHS_FOUND' , max_paths , max_path_length ) | Check a single Statement against the model . | 751 | 8 |
17,797 | def score_paths ( self , paths , agents_values , loss_of_function = False , sigma = 0.15 , include_final_node = False ) : obs_model = lambda x : scipy . stats . norm ( x , sigma ) # Build up dict mapping observables to values obs_dict = { } for ag , val in agents_values . items ( ) : obs_list = self . agent_to_obs [ ag ] if obs_list is not None : for obs in obs_list : obs_dict [ obs ] = val # For every path... path_scores = [ ] for path in paths : logger . info ( '------' ) logger . info ( "Scoring path:" ) logger . info ( path ) # Look at every node in the path, excluding the final # observable... path_score = 0 last_path_node_index = - 1 if include_final_node else - 2 for node , sign in path [ : last_path_node_index ] : # ...and for each node check the sign to see if it matches the # data. So the first thing is to look at what's downstream # of the rule # affected_obs is a list of observable names alogn for affected_obs , rule_obs_sign in self . rule_obs_dict [ node ] : flip_polarity = - 1 if loss_of_function else 1 pred_sign = sign * rule_obs_sign * flip_polarity # Check to see if this observable is in the data logger . info ( '%s %s: effect %s %s' % ( node , sign , affected_obs , pred_sign ) ) measured_val = obs_dict . get ( affected_obs ) if measured_val : # For negative predictions use CDF (prob that given # measured value, true value lies below 0) if pred_sign <= 0 : prob_correct = obs_model ( measured_val ) . logcdf ( 0 ) # For positive predictions, use log survival function # (SF = 1 - CDF, i.e., prob that true value is # above 0) else : prob_correct = obs_model ( measured_val ) . logsf ( 0 ) logger . info ( 'Actual: %s, Log Probability: %s' % ( measured_val , prob_correct ) ) path_score += prob_correct if not self . rule_obs_dict [ node ] : logger . info ( '%s %s' % ( node , sign ) ) prob_correct = obs_model ( 0 ) . logcdf ( 0 ) logger . info ( 'Unmeasured node, Log Probability: %s' % ( prob_correct ) ) path_score += prob_correct # Normalized path #path_score = path_score / len(path) logger . info ( "Path score: %s" % path_score ) path_scores . append ( path_score ) path_tuples = list ( zip ( paths , path_scores ) ) # Sort first by path length sorted_by_length = sorted ( path_tuples , key = lambda x : len ( x [ 0 ] ) ) # Sort by probability; sort in reverse order to large values # (higher probabilities) are ranked higher scored_paths = sorted ( sorted_by_length , key = lambda x : x [ 1 ] , reverse = True ) return scored_paths | Return scores associated with a given set of paths . | 739 | 10 |
17,798 | def prune_influence_map ( self ) : im = self . get_im ( ) # First, remove all self-loops logger . info ( 'Removing self loops' ) edges_to_remove = [ ] for e in im . edges ( ) : if e [ 0 ] == e [ 1 ] : logger . info ( 'Removing self loop: %s' , e ) edges_to_remove . append ( ( e [ 0 ] , e [ 1 ] ) ) # Now remove all the edges to be removed with a single call im . remove_edges_from ( edges_to_remove ) # Remove parameter nodes from influence map remove_im_params ( self . model , im ) # Now compare nodes pairwise and look for overlap between child nodes logger . info ( 'Get successorts of each node' ) succ_dict = { } for node in im . nodes ( ) : succ_dict [ node ] = set ( im . successors ( node ) ) # Sort and then group nodes by number of successors logger . info ( 'Compare combinations of successors' ) group_key_fun = lambda x : len ( succ_dict [ x ] ) nodes_sorted = sorted ( im . nodes ( ) , key = group_key_fun ) groups = itertools . groupby ( nodes_sorted , key = group_key_fun ) # Now iterate over each group and then construct combinations # within the group to check for shared sucessors edges_to_remove = [ ] for gix , group in groups : combos = itertools . combinations ( group , 2 ) for ix , ( p1 , p2 ) in enumerate ( combos ) : # Children are identical except for mutual relationship if succ_dict [ p1 ] . difference ( succ_dict [ p2 ] ) == set ( [ p2 ] ) and succ_dict [ p2 ] . difference ( succ_dict [ p1 ] ) == set ( [ p1 ] ) : for u , v in ( ( p1 , p2 ) , ( p2 , p1 ) ) : edges_to_remove . append ( ( u , v ) ) logger . debug ( 'Will remove edge (%s, %s)' , u , v ) logger . info ( 'Removing %d edges from influence map' % len ( edges_to_remove ) ) # Now remove all the edges to be removed with a single call im . remove_edges_from ( edges_to_remove ) | Remove edges between rules causing problematic non - transitivity . | 530 | 11 |
17,799 | def prune_influence_map_subj_obj ( self ) : def get_rule_info ( r ) : result = { } for ann in self . model . annotations : if ann . subject == r : if ann . predicate == 'rule_has_subject' : result [ 'subject' ] = ann . object elif ann . predicate == 'rule_has_object' : result [ 'object' ] = ann . object return result im = self . get_im ( ) rules = im . nodes ( ) edges_to_prune = [ ] for r1 , r2 in itertools . permutations ( rules , 2 ) : if ( r1 , r2 ) not in im . edges ( ) : continue r1_info = get_rule_info ( r1 ) r2_info = get_rule_info ( r2 ) if 'object' not in r1_info or 'subject' not in r2_info : continue if r1_info [ 'object' ] != r2_info [ 'subject' ] : logger . info ( "Removing edge %s --> %s" % ( r1 , r2 ) ) edges_to_prune . append ( ( r1 , r2 ) ) im . remove_edges_from ( edges_to_prune ) | Prune influence map to include only edges where the object of the upstream rule matches the subject of the downstream rule . | 284 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.