idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
222,400 | def _get_gosrcs_upper ( self , goids , max_upper , go2parentids ) : gosrcs_upper = set ( ) get_nt = self . gosubdag . go2nt . get go2nt = { g : get_nt ( g ) for g in goids } # Sort by descending order of descendant counts to find potential new hdrgos go_nt = sorted ( go2nt . items ( ) , key = lambda t : - 1 * t [ 1 ] . dcnt ) goids_upper = set ( ) for goid , _ in go_nt : # Loop through GO ID, GO nt goids_upper . add ( goid ) if goid in go2parentids : goids_upper |= go2parentids [ goid ] #print "{} {:3} {}".format(goid, len(goids_upper), gont.GO_name) if len ( goids_upper ) < max_upper : gosrcs_upper . add ( goid ) else : break return gosrcs_upper | Get GO IDs for the upper portion of the GO DAG . | 241 | 13 |
222,401 | def _get_gosubdagplotnt ( self , ntplt , title , go2color , pltargs ) : kws_plt = pltargs . get_kws_plt ( ) kws_plt [ 'id' ] = '"{ID}"' . format ( ID = ntplt . hdrgo ) kws_plt [ 'title' ] = "{TITLE} of {M} user GOs" . format ( TITLE = title , M = ntplt . tot_usrgos ) kws_plt [ 'go2color' ] = go2color kws_plt [ 'go2bordercolor' ] = pltargs . go2bordercolor if ntplt . parentcnt : kws_plt [ "parentcnt" ] = True gosubdagplot = GoSubDagPlot ( ntplt . gosubdag , * * kws_plt ) return GoSubDagPlotNt ( self . grprobj , gosubdagplot , ntplt ) | Return GoSubDagPlotNt which contains both a GoSubDagPlot object and ntobj . | 249 | 23 |
222,402 | def _no_ntplt ( self , ntplt ) : sys . stdout . write ( " {GO_USR:>6,} usr {GO_ALL:>6,} GOs DID NOT WRITE: {B} {D}\n" . format ( B = self . grprobj . get_fout_base ( ntplt . hdrgo ) , D = ntplt . desc , GO_USR = len ( ntplt . gosubdag . go_sources ) , GO_ALL = len ( ntplt . gosubdag . go2obj ) ) ) | Print a message about the GO DAG Plot we are NOT plotting . | 143 | 14 |
222,403 | def _get_pltdag_ancesters ( self , hdrgo , usrgos , desc = "" ) : go_srcs = usrgos . union ( [ hdrgo ] ) gosubdag = GoSubDag ( go_srcs , self . gosubdag . get_go2obj ( go_srcs ) , relationships = self . gosubdag . relationships , rcntobj = self . gosubdag . rcntobj , go2nt = self . gosubdag . go2nt ) tot_usrgos = len ( set ( gosubdag . go2obj . keys ( ) ) . intersection ( self . usrgos ) ) return self . ntpltgo ( hdrgo = hdrgo , gosubdag = gosubdag , tot_usrgos = tot_usrgos , parentcnt = False , desc = desc ) | Get GoSubDag containing hdrgo and all usrgos and their ancesters . | 208 | 20 |
222,404 | def _get_pltdag_path_hdr ( self , hdrgo , usrgos , desc = "pruned" ) : go_sources = usrgos . union ( [ hdrgo ] ) gosubdag = GoSubDag ( go_sources , self . gosubdag . get_go2obj ( go_sources ) , relationships = self . gosubdag . relationships , rcntobj = self . gosubdag . rcntobj , go2nt = self . gosubdag . go2nt , dst_srcs_list = [ ( hdrgo , usrgos ) , ( None , set ( [ hdrgo ] ) ) ] ) tot_usrgos = len ( set ( gosubdag . go2obj . keys ( ) ) . intersection ( self . usrgos ) ) return self . ntpltgo ( hdrgo = hdrgo , gosubdag = gosubdag , tot_usrgos = tot_usrgos , parentcnt = True , desc = desc ) | Get GoSubDag with paths from usrgos through hdrgo . | 245 | 16 |
222,405 | def wrplt ( self , fout_dir , plt_ext = "png" ) : # Ex basename basename = self . grprobj . get_fout_base ( self . ntplt . hdrgo ) plt_pat = self . get_pltpat ( plt_ext ) fout_basename = plt_pat . format ( BASE = basename ) fout_plt = os . path . join ( fout_dir , fout_basename ) self . gosubdagplot . plt_dag ( fout_plt ) # Create Plot return fout_plt | Write png containing plot of GoSubDag . | 142 | 11 |
222,406 | def get_dotstr ( self ) : dotobj = self . gosubdagplot . get_pydot_graph ( ) # pydot.Dot dotstr = dotobj . create_dot ( ) return dotstr | Return a string containing DAG graph in Grpahviz s dot language . | 51 | 17 |
222,407 | def _get_wrhiercfg ( self ) : prtfmt = self . gosubdag . prt_attr [ 'fmt' ] prtfmt = prtfmt . replace ( '{GO} # ' , '' ) prtfmt = prtfmt . replace ( '{D1:5} ' , '' ) return { 'name2prtfmt' : { 'ITEM' : prtfmt , 'ID' : '{GO}{alt:1}' } , 'max_indent' : self . usrdct . get ( 'max_indent' ) , 'include_only' : self . usrdct . get ( 'include_only' ) , 'item_marks' : self . usrdct . get ( 'item_marks' , { } ) , 'concise_prt' : 'concise' in self . usrset , 'indent' : 'no_indent' not in self . usrset , 'dash_len' : self . usrdct . get ( 'dash_len' , 6 ) , 'sortby' : self . usrdct . get ( 'sortby' ) } | Initialize print format . | 257 | 5 |
222,408 | def _get_goroot ( self , goids_all , namespace ) : root_goid = self . consts . NAMESPACE2GO [ namespace ] if root_goid in goids_all : return root_goid root_goids = set ( ) for goid in goids_all : goterm = self . gosubdag . go2obj [ goid ] if goterm . depth == 0 : root_goids . add ( goterm . id ) if len ( root_goids ) == 1 : return next ( iter ( root_goids ) ) raise RuntimeError ( "UNEXPECTED NUMBER OF ROOTS: {R}" . format ( R = root_goids ) ) | Get the top GO for the set of goids_all . | 158 | 13 |
222,409 | def mknts ( self , add_dct ) : nts = [ ] assert len ( add_dct ) == len ( self . nts ) flds = list ( next ( iter ( self . nts ) ) . _fields ) + list ( next ( iter ( add_dct ) ) . keys ( ) ) ntobj = cx . namedtuple ( "ntgoea" , " " . join ( flds ) ) for dct_new , ntgoea in zip ( add_dct , self . nts ) : dct_curr = ntgoea . _asdict ( ) for key , val in dct_new . items ( ) : dct_curr [ key ] = val nts . append ( ntobj ( * * dct_curr ) ) return nts | Add information from add_dct to a new copy of namedtuples stored in nts . | 183 | 20 |
222,410 | def add_f2str ( self , dcts , srcfld , dstfld , dstfmt ) : # Example: f2str = objntmgr.add_f2str(dcts, "p_fdr_bh", "s_fdr_bh", "{:8.2e}") # ntobj = self.get_ntobj() # print(ntobj) assert len ( dcts ) == len ( self . nts ) for dct , ntgoea in zip ( dcts , self . nts ) : valorig = getattr ( ntgoea , srcfld ) valstr = dstfmt . format ( valorig ) dct [ dstfld ] = valstr | Add a namedtuple field of type string generated from an existing namedtuple field . | 163 | 18 |
222,411 | def get_ntobj ( self ) : if self . nts : return cx . namedtuple ( "ntgoea" , " " . join ( vars ( next ( iter ( self . nts ) ) ) . keys ( ) ) ) | Create namedtuple object with GOEA fields . | 53 | 10 |
222,412 | def get_info_content ( go_id , termcounts ) : # Get the observed frequency of the GO term freq = termcounts . get_term_freq ( go_id ) # Calculate the information content (i.e., -log("freq of GO term") return - 1.0 * math . log ( freq ) if freq else 0 | Calculates the information content of a GO term . | 81 | 11 |
222,413 | def resnik_sim ( go_id1 , go_id2 , godag , termcounts ) : goterm1 = godag [ go_id1 ] goterm2 = godag [ go_id2 ] if goterm1 . namespace == goterm2 . namespace : msca_goid = deepest_common_ancestor ( [ go_id1 , go_id2 ] , godag ) return get_info_content ( msca_goid , termcounts ) | Computes Resnik s similarity measure . | 109 | 8 |
222,414 | def lin_sim ( goid1 , goid2 , godag , termcnts ) : sim_r = resnik_sim ( goid1 , goid2 , godag , termcnts ) return lin_sim_calc ( goid1 , goid2 , sim_r , termcnts ) | Computes Lin s similarity measure . | 72 | 7 |
222,415 | def lin_sim_calc ( goid1 , goid2 , sim_r , termcnts ) : if sim_r is not None : info = get_info_content ( goid1 , termcnts ) + get_info_content ( goid2 , termcnts ) if info != 0 : return ( 2 * sim_r ) / info | Computes Lin s similarity measure using pre - calculated Resnik s similarities . | 82 | 15 |
222,416 | def common_parent_go_ids ( goids , godag ) : # Find candidates from first rec = godag [ goids [ 0 ] ] candidates = rec . get_all_parents ( ) candidates . update ( { goids [ 0 ] } ) # Find intersection with second to nth goid for goid in goids [ 1 : ] : rec = godag [ goid ] parents = rec . get_all_parents ( ) parents . update ( { goid } ) # Find the intersection with the candidates, and update. candidates . intersection_update ( parents ) return candidates | This function finds the common ancestors in the GO tree of the list of goids in the input . | 125 | 20 |
222,417 | def deepest_common_ancestor ( goterms , godag ) : # Take the element at maximum depth. return max ( common_parent_go_ids ( goterms , godag ) , key = lambda t : godag [ t ] . depth ) | This function gets the nearest common ancestor using the above function . Only returns single most specific - assumes unique exists . | 57 | 22 |
222,418 | def min_branch_length ( go_id1 , go_id2 , godag , branch_dist ) : # First get the deepest common ancestor goterm1 = godag [ go_id1 ] goterm2 = godag [ go_id2 ] if goterm1 . namespace == goterm2 . namespace : dca = deepest_common_ancestor ( [ go_id1 , go_id2 ] , godag ) # Then get the distance from the DCA to each term dca_depth = godag [ dca ] . depth depth1 = goterm1 . depth - dca_depth depth2 = goterm2 . depth - dca_depth # Return the total distance - i.e., to the deepest common ancestor and back. return depth1 + depth2 elif branch_dist is not None : return goterm1 . depth + goterm2 . depth + branch_dist | Finds the minimum branch length between two terms in the GO DAG . | 196 | 15 |
222,419 | def _init_count_terms ( self , annots ) : gonotindag = set ( ) gocnts = self . gocnts go2obj = self . go2obj # Fill gocnts with GO IDs in annotations and their corresponding counts for terms in annots . values ( ) : # key is 'gene' # Make a union of all the terms for a gene, if term parents are # propagated but they won't get double-counted for the gene allterms = set ( ) for go_id in terms : goobj = go2obj . get ( go_id , None ) if goobj is not None : allterms . add ( go_id ) allterms |= goobj . get_all_parents ( ) else : gonotindag . add ( go_id ) for parent in allterms : gocnts [ parent ] += 1 if gonotindag : print ( "{N} Assc. GO IDs not found in the GODag\n" . format ( N = len ( gonotindag ) ) ) | Fills in the counts and overall aspect counts . | 230 | 10 |
222,420 | def _init_add_goid_alt ( self ) : # Fill aspect_counts. Find alternate GO IDs that may not be on gocnts goid_alts = set ( ) go2cnt_add = { } aspect_counts = self . aspect_counts gocnts = self . gocnts go2obj = self . go2obj for go_id , cnt in gocnts . items ( ) : goobj = go2obj [ go_id ] assert cnt , "NO TERM COUNTS FOR {GO}" . format ( GO = goobj . item_id ) # Was the count set using an alternate GO? if go_id != goobj . item_id : go2cnt_add [ goobj . item_id ] = cnt goid_alts |= goobj . alt_ids # Group by namespace aspect_counts [ goobj . namespace ] += cnt # If alternate GO used to set count, add main GO ID for goid , cnt in go2cnt_add . items ( ) : gocnts [ goid ] = cnt # Add missing alt GO IDs to gocnts for alt_goid in goid_alts . difference ( gocnts ) : goobj = go2obj [ alt_goid ] cnt = gocnts [ goobj . item_id ] assert cnt , "NO TERM COUNTS FOR ALT_ID({GOa}) ID({GO}): {NAME}" . format ( GOa = alt_goid , GO = goobj . item_id , NAME = goobj . name ) gocnts [ alt_goid ] = cnt | Add alternate GO IDs to term counts . | 373 | 8 |
222,421 | def get_term_freq ( self , go_id ) : num_ns = float ( self . get_total_count ( self . go2obj [ go_id ] . namespace ) ) return float ( self . get_count ( go_id ) ) / num_ns if num_ns != 0 else 0 | Returns the frequency at which a particular GO term has been observed in the annotations . | 69 | 16 |
222,422 | def get_sections ( self , hdrgo , dflt_section = True ) : dflt_list = [ ] # If the hdrgo is not in a section, return the default name for a section if dflt_section : dflt_list = [ self . secdflt ] return self . hdrgo2sections . get ( hdrgo , dflt_list ) | Given a header GO return the sections that contain it . | 83 | 11 |
222,423 | def get_section_hdrgos ( self ) : return set ( [ h for _ , hs in self . sections for h in hs ] ) if self . sections else set ( ) | Get the GO group headers explicitly listed in sections . | 42 | 10 |
222,424 | def _chk_sections ( sections ) : if sections : assert len ( sections [ 0 ] ) == 2 , "SECTIONS DATA MUST BE A 2-D LIST. FOUND: {S}" . format ( S = sections ) for _ , hdrgos in sections : chk_goids ( hdrgos , "HdrgosSections::_chk_sections()" ) | Check format of user - provided sections variable | 88 | 8 |
222,425 | def _init_hdrgos ( self , hdrgos_dflt , hdrgos_usr = None , add_dflt = True ) : # Use default GO group header values if ( hdrgos_usr is None or hdrgos_usr is False ) and not self . sections : return set ( hdrgos_dflt ) # Get GO group headers provided by user hdrgos_init = set ( ) if hdrgos_usr : chk_goids ( hdrgos_usr , "User-provided GO group headers" ) hdrgos_init |= set ( hdrgos_usr ) if self . sections : self . _chk_sections ( self . sections ) hdrgos_sec = set ( [ hg for _ , hdrgos in self . sections for hg in hdrgos ] ) chk_goids ( hdrgos_sec , "User-provided GO group headers in sections" ) hdrgos_init |= hdrgos_sec # Add default depth-01 GOs to headers, if desired if add_dflt : return set ( hdrgos_init ) . union ( hdrgos_dflt ) # Return user-provided GO grouping headers return hdrgos_init | Initialize GO high | 288 | 4 |
222,426 | def get_all_parents ( go_objs ) : go_parents = set ( ) for go_obj in go_objs : go_parents |= go_obj . get_all_parents ( ) return go_parents | Return a set containing all GO Term parents of multiple GOTerm objects . | 50 | 14 |
222,427 | def prt_hdr ( self , prt = sys . stdout , name = "name " ) : hdr = "{NAME} | # {ITEMS:11} | range | 25th percentile | " " median | 75th percentile | mean | stddev\n" . format ( NAME = name , ITEMS = self . desc ) div = "{DASHES}|---------------|----------------------|" "-----------------|----------|-----------------|----------|-------\n" . format ( DASHES = '-' * ( len ( name ) ) ) prt . write ( hdr ) prt . write ( div ) | Print stats header in markdown style . | 134 | 8 |
222,428 | def prt_data ( self , name , vals , prt = sys . stdout ) : fld2val = self . get_fld2val ( name , vals ) prt . write ( self . fmt . format ( * * fld2val ) ) return fld2val | Print stats data in markdown style . | 65 | 8 |
222,429 | def getstr_data ( self , name , vals ) : fld2val = self . get_fld2val ( name , vals ) return self . fmt . format ( * * fld2val ) | Return stats data string in markdown style . | 47 | 9 |
222,430 | def get_fld2val ( self , name , vals ) : if vals : return self . _init_fld2val_stats ( name , vals ) return self . _init_fld2val_null ( name ) | Describe summary statistics for a list of numbers . | 53 | 10 |
222,431 | def _init_fld2val_stats ( self , name , vals ) : vals_stats = stats . describe ( vals ) stddev = math . sqrt ( vals_stats [ 3 ] ) # stats variance p25 = np . percentile ( vals , 25 ) p50 = np . percentile ( vals , 50 ) # median p75 = np . percentile ( vals , 75 ) fld2val = { 'name' : name , 'qty' . format ( ITEMS = self . desc ) : vals_stats [ 0 ] , # stats nobs 'range' : self . _get_str_range ( vals_stats ) , '25th percentile' : p25 , 'median' : p50 , '75th percentile' : p75 , 'mean' : vals_stats [ 2 ] , # stats mean 'stddev' : stddev } fmtflds = set ( [ '25th percentile' , 'median' , '75th percentile' , 'mean' , 'stddev' ] ) mkint = "," in self . fmtstr for key , val in fld2val . items ( ) : if key in fmtflds : if mkint : val = int ( round ( val ) ) fld2val [ key ] = self . fmtstr . format ( val ) return fld2val | Return statistics on values . | 301 | 5 |
222,432 | def _get_str_range ( self , vals_stats ) : minmax = vals_stats [ 1 ] # stats minmax minval = self . fmtstr . format ( minmax [ 0 ] ) maxval = self . fmtstr . format ( minmax [ 1 ] ) return '{A} to {B:6>}' . format ( A = minval , B = maxval ) | Return a string containing the range of values . | 88 | 9 |
222,433 | def summarize_sec2hdrgos ( self , sec2d_hdrgos ) : hdrgos_all = set ( [ ] ) hdrgos_grouped = set ( ) hdrgos_ungrouped = set ( ) sections_grouped = set ( ) for sectionname , hdrgos in sec2d_hdrgos : self . _chk_hdrgoids ( hdrgos ) hdrgos_all . update ( hdrgos ) if sectionname != HdrgosSections . secdflt : hdrgos_grouped . update ( hdrgos ) sections_grouped . add ( sectionname ) else : hdrgos_ungrouped . update ( hdrgos ) return { 'G' : hdrgos_grouped , 'S' : sections_grouped , 'U' : hdrgos_all . difference ( hdrgos_grouped ) } | Get counts of header GO IDs and sections . | 217 | 9 |
222,434 | def summarize_sec2hdrnts ( self , sec2d_hdrnts ) : sec2d_hdrgos = [ ( s , set ( nt . GO for nt in nts ) ) for s , nts in sec2d_hdrnts ] return self . summarize_sec2hdrgos ( sec2d_hdrgos ) | Given namedtuples in each sectin get counts of header GO IDs and sections . | 85 | 17 |
222,435 | def _chk_hdrgoids ( hdrgos ) : goid = next ( iter ( hdrgos ) ) if isinstance ( goid , str ) and goid [ : 3 ] == "GO:" : return assert False , "HDRGOS DO NOT CONTAIN GO IDs: {E}" . format ( E = goid ) | Check that hdrgo set is a set of GO IDs . | 77 | 13 |
222,436 | def get_matching_gos ( self , compiled_pattern , * * kws ) : # kws: prt gos matching_gos = [ ] obo_dag = self . obo_dag prt = kws [ 'prt' ] if 'prt' in kws else self . log prt . write ( '\nPATTERN SEARCH: "{P}"\n' . format ( P = compiled_pattern . pattern ) ) # Only look through GOs in annotation or user-specified GOs srchgos = kws [ 'gos' ] if 'gos' in kws else self . go2items . keys ( ) for go_id in srchgos : go_obj = obo_dag . get ( go_id , None ) if go_obj is not None : for hdr in self . goa_srch_hdrs : if hdr in go_obj . __dict__ : fld_val = getattr ( go_obj , hdr ) matches = self . _search_vals ( compiled_pattern , fld_val ) for mtch in matches : prt . write ( "MATCH {go_id}({NAME}) {FLD}: {M}\n" . format ( FLD = hdr , go_id = go_obj . id , NAME = go_obj . name , M = mtch ) ) if matches : matching_gos . append ( go_id ) else : prt . write ( "**WARNING: {GO} found in annotation is not found in obo\n" . format ( GO = go_id ) ) matching_gos = set ( matching_gos ) # Print summary message self . _summary_matching_gos ( prt , compiled_pattern . pattern , matching_gos , srchgos ) return matching_gos | Return all GOs which match the user regex pattern . | 410 | 11 |
222,437 | def _summary_matching_gos ( prt , pattern , matching_gos , all_gos ) : msg = 'Found {N} GO(s) out of {M} matching pattern("{P}")\n' num_gos = len ( matching_gos ) num_all = len ( all_gos ) prt . write ( msg . format ( N = num_gos , M = num_all , P = pattern ) ) | Print summary for get_matching_gos . | 102 | 11 |
222,438 | def _search_vals ( self , compiled_pattern , fld_val ) : matches = [ ] if isinstance ( fld_val , set ) : for val in fld_val : self . _search_val ( matches , compiled_pattern , val ) elif isinstance ( fld_val , str ) : self . _search_val ( matches , compiled_pattern , fld_val ) return matches | Search for user - regex in scalar or iterable data values . | 90 | 14 |
222,439 | def _search_val ( matches , compiled_pattern , fld_val ) : mtch = compiled_pattern . search ( fld_val ) if mtch : matches . append ( fld_val ) | Search for user - regex in scalar data values . | 45 | 11 |
222,440 | def add_children_gos ( self , gos ) : lst = [ ] obo_dag = self . obo_dag get_children = lambda go_obj : list ( go_obj . get_all_children ( ) ) + [ go_obj . id ] for go_id in gos : go_obj = obo_dag [ go_id ] lst . extend ( get_children ( go_obj ) ) return set ( lst ) | Return children of input gos plus input gos . | 105 | 11 |
222,441 | def get_items ( self , gos ) : items = [ ] for go_id in gos : items . extend ( self . go2items . get ( go_id , [ ] ) ) return set ( items ) | Given GO terms return genes or gene products for the GOs . | 48 | 13 |
222,442 | def prt_summary ( self , prt = sys . stdout ) : desc = "NtGoeaResults" if self . is_goterm else "namedtuple" prt . write ( "{N} GOEA results from {O}. P-values stored in {P}.\n" . format ( N = len ( self . go2res ) , O = desc , P = self . pval_name ) ) | Print summary of GOEA plotting object . | 94 | 8 |
222,443 | def set_goid2color_pval ( self , goid2color ) : alpha2col = self . alpha2col if self . pval_name is not None : pval_name = self . pval_name for goid , res in self . go2res . items ( ) : pval = getattr ( res , pval_name , None ) if pval is not None : for alpha , color in alpha2col . items ( ) : if pval <= alpha and res . study_count != 0 : if goid not in goid2color : goid2color [ goid ] = color | Fill missing colors based on p - value of an enriched GO term . | 135 | 14 |
222,444 | def get_goid2color_pval ( self ) : go2color = { } self . set_goid2color_pval ( go2color ) color_dflt = self . alpha2col [ 1.000 ] for goid in self . go2res : if goid not in go2color : go2color [ goid ] = color_dflt return go2color | Return a go2color dict containing GO colors determined by P - value . | 86 | 15 |
222,445 | def prttex_summary_cnts_all ( self , prt = sys . stdout ) : cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) self . _prttex_summary_cnts ( prt , cnts ) | Print LaTeX format summary of level and depth counts for all active GO Terms . | 76 | 16 |
222,446 | def write_summary_cnts_all ( self ) : cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) self . _write_summary_cnts ( cnts ) | Write summary of level and depth counts for all active GO Terms . | 61 | 13 |
222,447 | def write_summary_cnts ( self , go_ids ) : obo = self . obo cnts = self . get_cnts_levels_depths_recs ( [ obo . get ( GO ) for GO in go_ids ] ) self . _write_summary_cnts ( cnts ) | Write summary of level and depth counts for specific GO ids . | 74 | 13 |
222,448 | def get_cnts_levels_depths_recs ( recs ) : cnts = cx . defaultdict ( lambda : cx . defaultdict ( cx . Counter ) ) for rec in recs : if rec is not None and not rec . is_obsolete : cnts [ 'level' ] [ rec . level ] [ rec . namespace ] += 1 cnts [ 'depth' ] [ rec . depth ] [ rec . namespace ] += 1 return cnts | Collect counts of levels and depths in a Group of GO Terms . | 104 | 13 |
222,449 | def get_data ( self ) : # Count level(shortest path to root) and depth(longest path to root) # values for all unique GO Terms. data = [ ] ntobj = cx . namedtuple ( "NtGoCnt" , "Depth_Level BP_D MF_D CC_D BP_L MF_L CC_L" ) cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) max_val = max ( max ( dep for dep in cnts [ 'depth' ] ) , max ( lev for lev in cnts [ 'level' ] ) ) for i in range ( max_val + 1 ) : vals = [ i ] + [ cnts [ desc ] [ i ] [ ns ] for desc in cnts for ns in self . nss ] data . append ( ntobj . _make ( vals ) ) return data | Collect counts of GO terms at all levels and depths . | 214 | 11 |
222,450 | def main ( ) : # Load study, population, associations, and GoDag. Run GOEA. obj = GoeaCliFnc ( GoeaCliArgs ( ) . args ) # Reduce results to significant results (pval<value) results_specified = obj . get_results ( ) # Print results in a flat list obj . prt_results ( results_specified ) | Run gene enrichment analysis . | 82 | 5 |
222,451 | def get_objanno ( fin_anno , anno_type = None , * * kws ) : # kws get_objanno: taxids hdr_only prt allow_missing_symbol anno_type = get_anno_desc ( fin_anno , anno_type ) if anno_type is not None : if anno_type == 'gene2go' : # kws: taxid taxids return Gene2GoReader ( fin_anno , * * kws ) if anno_type == 'gaf' : return GafReader ( fin_anno , hdr_only = kws . get ( 'hdr_only' , False ) , prt = kws . get ( 'prt' , sys . stdout ) , allow_missing_symbol = kws . get ( 'allow_missing_symbol' , False ) ) if anno_type == 'gpad' : hdr_only = kws . get ( 'hdr_only' , False ) return GpadReader ( fin_anno , hdr_only ) if anno_type == 'id2gos' : return IdToGosReader ( fin_anno ) raise RuntimeError ( 'UNEXPECTED ANNOTATION FILE FORMAT: {F} {D}' . format ( F = fin_anno , D = anno_type ) ) | Read annotations in GAF GPAD Entrez gene2go or text format . | 311 | 16 |
222,452 | def get_relation_cnt ( self ) : ctr = cx . Counter ( ) for ntgpad in self . associations : if ntgpad . Extension is not None : ctr += ntgpad . Extension . get_relations_cnt ( ) return ctr | Return a Counter containing all relations contained in the Annotation Extensions . | 58 | 13 |
222,453 | def _get_id2gos ( self ) : kws = { } if self . args . ev_inc is not None : kws [ 'ev_include' ] = set ( self . args . ev_inc . split ( ',' ) ) if self . args . ev_exc is not None : kws [ 'ev_exclude' ] = set ( self . args . ev_exc . split ( ',' ) ) return self . objanno . get_id2gos ( * * kws ) | Return annotations as id2gos | 113 | 7 |
222,454 | def _get_objanno ( self , assoc_fn ) : # Determine annotation file format from filename, if possible anno_type = get_anno_desc ( assoc_fn , None ) # Default annotation file format is id2gos if anno_type is None : anno_type = self . args . annofmt if self . args . annofmt else 'id2gos' kws = { 'taxid' : self . args . taxid } if anno_type == 'gene2go' else { } return get_objanno ( assoc_fn , anno_type , * * kws ) | Get an annotation object | 144 | 4 |
222,455 | def _init_itemid2name ( self ) : if not hasattr ( self . args , 'id2sym' ) : return None fin_id2sym = self . args . id2sym if fin_id2sym is not None and os . path . exists ( fin_id2sym ) : id2sym = { } cmpl = re . compile ( r'^\s*(\S+)[\s,;]+(\S+)' ) with open ( fin_id2sym ) as ifstrm : for line in ifstrm : mtch = cmpl . search ( line ) if mtch : id2sym [ mtch . group ( 1 ) ] = mtch . group ( 2 ) return id2sym | Print gene symbols instead of gene IDs if provided . | 159 | 10 |
222,456 | def prt_results ( self , goea_results ) : # objaart = self.prepgrp.get_objaart(goea_results) if self.prepgrp is not None else None if self . args . outfile is None : self . _prt_results ( goea_results ) else : # Users can print to both tab-separated file and xlsx file in one run. outfiles = self . args . outfile . split ( "," ) grpwr = self . prepgrp . get_objgrpwr ( goea_results ) if self . prepgrp else None if grpwr is None : self . prt_outfiles_flat ( goea_results , outfiles ) else : grpwr . prt_outfiles_grouped ( outfiles ) | Print GOEA results to the screen or to a file . | 180 | 12 |
222,457 | def _prt_results ( self , goea_results ) : min_ratio = self . args . ratio if min_ratio is not None : assert 1 <= min_ratio <= 2 self . objgoea . print_date ( min_ratio = min_ratio , pval = self . args . pval ) results_adj = self . objgoea . get_adj_records ( goea_results , min_ratio , self . args . pval ) if results_adj : if not self . prepgrp : self . objgoea . print_results_adj ( results_adj , indent = self . args . indent ) else : grpwr = self . prepgrp . get_objgrpwr ( results_adj ) grpwr . prt_txt ( sys . stdout ) | Print GOEA results to the screen . | 181 | 8 |
222,458 | def chk_genes ( self , study , pop , assoc = None ) : if len ( pop ) < len ( study ) : exit ( "\nERROR: The study file contains more elements than the population file. " "Please check that the study file is a subset of the population file.\n" ) # check the fraction of genomic ids that overlap between study and population overlap = self . get_overlap ( study , pop ) if overlap < 0.95 : sys . stderr . write ( "\nWARNING: only {} fraction of genes/proteins in study are found in " "the population background.\n\n" . format ( overlap ) ) if overlap <= self . args . min_overlap : exit ( "\nERROR: only {} of genes/proteins in the study are found in the " "background population. Please check.\n" . format ( overlap ) ) # Population and associations if assoc is not None and pop . isdisjoint ( assoc . keys ( ) ) : if self . objanno . name == 'gene2go' : err = ( '**FATAL: NO POPULATION ITEMS SEEN IN THE NCBI gene2go ANNOTATIONS ' 'FOR taxid({T}). TRY: --taxid=<taxid number>' ) exit ( err . format ( T = next ( iter ( self . objanno . taxid2asscs . keys ( ) ) ) ) ) else : exit ( '**FATAL: NO POPULATION ITEMS SEEN IN THE ANNOTATIONS' ) | Check gene sets . | 342 | 4 |
222,459 | def get_results_sig ( self ) : # Only print results when uncorrected p-value < this value. print ( "{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\n" . format ( N = sum ( 1 for r in self . results_all if r . p_uncorrected < self . args . pval ) , M = len ( self . results_all ) , PVAL = self . args . pval ) ) pval_fld = self . get_pval_field ( ) results = [ r for r in self . results_all if getattr ( r , pval_fld ) <= self . args . pval ] return results | Get significant results . | 163 | 4 |
222,460 | def get_pval_field ( self ) : pval_fld = self . args . pval_field # If --pval_field [VAL] was specified if pval_fld is not None : if pval_fld [ : 2 ] != 'p_' : pval_fld = 'p_' + pval_fld # If only one method was used, use that instead of the uncorrected pvalue elif len ( self . methods ) == 1 : pval_fld = 'p_' + self . methods [ 0 ] # Use 'uncorrected pvalue' if there are many methods & none chosen using --pval_field else : pval_fld = 'p_uncorrected' if self . results_all : assert hasattr ( next ( iter ( self . results_all ) ) , pval_fld ) , 'NO PVAL({P}). EXPECTED ONE OF: {E}' . format ( P = self . args . pval_field , E = " " . join ( [ k for k in dir ( next ( iter ( self . results_all ) ) ) if k [ : 2 ] == 'p_' ] ) ) return pval_fld | Get p_uncorrected or the user - specified field for determining significant results . | 271 | 17 |
222,461 | def rd_files ( self , study_fn , pop_fn ) : study , pop = self . _read_geneset ( study_fn , pop_fn ) print ( "Study: {0} vs. Population {1}\n" . format ( len ( study ) , len ( pop ) ) ) return study , pop | Read files and return study and population . | 72 | 8 |
222,462 | def _read_geneset ( self , study_fn , pop_fn ) : pop = set ( _ . strip ( ) for _ in open ( pop_fn ) if _ . strip ( ) ) study = frozenset ( _ . strip ( ) for _ in open ( study_fn ) if _ . strip ( ) ) if next ( iter ( pop ) ) . isdigit ( ) : pop = set ( int ( g ) for g in pop ) study = frozenset ( int ( g ) for g in study ) # some times the pop is a second group to compare, rather than the # population in that case, we need to make sure the overlapping terms # are removed first if self . args . compare : common = pop & study pop |= study pop -= common study -= common sys . stderr . write ( "removed %d overlapping items\n" % ( len ( common ) ) ) sys . stderr . write ( "Set 1: {0}, Set 2: {1}\n" . format ( len ( study ) , len ( pop ) ) ) return study , pop | Open files containing genes . Return study genes and population genes . | 235 | 12 |
222,463 | def get_objgrpwr ( self , goea_results ) : sortobj = self . get_sortobj ( goea_results ) return GrpWr ( sortobj , self . pval_fld , ver_list = self . ver_list ) | Get a GrpWr object to write grouped GOEA results . | 57 | 13 |
222,464 | def get_sortobj ( self , goea_results , * * kws ) : nts_goea = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( * * kws ) goids = set ( nt . GO for nt in nts_goea ) go2nt = { nt . GO : nt for nt in nts_goea } grprobj = Grouper ( "GOEA" , goids , self . hdrobj , self . grprdflt . gosubdag , go2nt = go2nt ) grprobj . prt_summary ( sys . stdout ) # hdrgo_prt", "section_prt", "top_n", "use_sections" sortobj = Sorter ( grprobj , section_sortby = lambda nt : getattr ( nt , self . pval_fld ) ) return sortobj | Return a Grouper object given a list of GOEnrichmentRecord . | 214 | 16 |
222,465 | def _init_objaartall ( self ) : kws = { 'sortgo' : lambda nt : [ nt . NS , nt . dcnt ] , # fmtgo=('{p_fdr_bh:8.2e} {GO} ' # Formatting for GO terms in grouped GO list 'fmtgo' : ( '{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} ' '{dcnt:5} {childcnt:3} R{reldepth:02} ' '{D1:5} {GO_name} ({study_count} study genes)\n' ) , # Formatting for GO terms listed under each gene 'fmtgo2' : ( '{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} ' '{dcnt:5} R{reldepth:02} ' '{GO_name} ({study_count} study genes)\n' ) , # itemid2name=ensmusg2symbol} } return AArtGeneProductSetsAll ( self . grprdflt , self . hdrobj , * * kws ) | Get background database info for making ASCII art . | 273 | 9 |
222,466 | def wr_xlsx ( self , fout_xlsx ) : objwr = WrXlsxSortedGos ( "GOEA" , self . sortobj ) #### fld2fmt['ratio_in_study'] = '{:>8}' #### fld2fmt['ratio_in_pop'] = '{:>12}' #### ntfld2wbfmtdict = { # ntfld_wbfmt = { # 'ratio_in_study': {'align':'right'}, # 'ratio_in_pop':{'align':'right'}} kws_xlsx = { 'title' : self . ver_list , 'fld2fmt' : { f : '{:8.2e}' for f in self . flds_cur if f [ : 2 ] == 'p_' } , #'ntfld_wbfmt': ntfld_wbfmt, #### 'ntval2wbfmtdict': ntval2wbfmtdict, #'hdrs': [], 'prt_flds' : self . flds_cur } objwr . wr_xlsx_nts ( fout_xlsx , self . desc2nts , * * kws_xlsx ) | Print grouped GOEA results into an xlsx file . | 302 | 12 |
222,467 | def wr_tsv ( self , fout_tsv ) : with open ( fout_tsv , 'w' ) as prt : kws_tsv = { 'fld2fmt' : { f : '{:8.2e}' for f in self . flds_cur if f [ : 2 ] == 'p_' } , 'prt_flds' : self . flds_cur } prt_tsv_sections ( prt , self . desc2nts [ 'sections' ] , * * kws_tsv ) print ( " WROTE: {TSV}" . format ( TSV = fout_tsv ) ) | Print grouped GOEA results into a tab - separated file . | 153 | 12 |
222,468 | def wr_txt ( self , fout_txt ) : with open ( fout_txt , 'w' ) as prt : for line in self . ver_list : prt . write ( "{LINE}\n" . format ( LINE = line ) ) self . prt_txt ( prt ) print ( " WROTE: {TXT}" . format ( TXT = fout_txt ) ) | Write to a file GOEA results in an ASCII text format . | 88 | 13 |
222,469 | def prt_tsv ( self , prt = sys . stdout ) : prtfmt = self . objprt . get_prtfmt_str ( self . flds_cur ) prt . write ( "{FLDS}\n" . format ( FLDS = " " . join ( self . flds_cur ) ) ) WrSectionsTxt . prt_sections ( prt , self . desc2nts [ 'sections' ] , prtfmt , secspc = True ) | Print an ASCII text format . | 113 | 6 |
222,470 | def _init_flds_cur ( self ) : flds = [ ] # ('GO', 'NS', 'enrichment', 'name', 'ratio_in_study', 'ratio_in_pop', 'depth', # 'p_uncorrected', 'p_bonferroni', 'p_sidak', 'p_holm', 'p_fdr_bh', # 'pop_n', 'pop_count', 'pop_items' # 'study_n', 'study_count', 'study_items', # 'is_ratio_different', 'level', 'is_obsolete', # 'namespace', 'reldepth', 'alt_ids', 'format_txt', 'hdr_idx', # 'is_hdrgo', 'is_usrgo', 'num_usrgos', 'hdr1usr01', 'alt', 'GO_name', # 'dcnt', 'D1', 'tcnt', 'tfreq', 'tinfo', 'childcnt', 'REL', # 'REL_short', 'rel', 'id') flds0 = [ 'GO' , 'NS' , 'enrichment' , self . pval_fld , 'dcnt' , 'tinfo' , 'depth' , 'ratio_in_study' , 'ratio_in_pop' , 'name' ] flds_p = [ f for f in self . flds_all if f [ : 2 ] == 'p_' and f != self . pval_fld ] flds . extend ( flds0 ) if flds_p : flds . extend ( flds_p ) flds . append ( 'study_count' ) flds . append ( 'study_items' ) return flds | Choose fields to print from a multitude of available fields . | 406 | 11 |
222,471 | def do_hdr ( self , line , hdrs_usr ) : # If there is no header hint, consider the first line the header. if self . hdr_ex is None : self . _init_hdr ( line , hdrs_usr ) return True # If there is a header hint, examine each beginning line until header hint is found. elif self . hdr_ex in line : self . _init_hdr ( line , hdrs_usr ) return True return False | Initialize self . h2i . | 109 | 8 |
222,472 | def hdr_xform ( self , hdrs ) : xform = [ ] hdrs = self . replace_nulls ( hdrs ) for hdr in hdrs : hdr = hdr . replace ( '.' , '_' ) hdr = hdr . replace ( ' ' , '_' ) hdr = hdr . replace ( '#' , 'N' ) hdr = hdr . replace ( '-' , '_' ) hdr = hdr . replace ( '"' , '' ) xform . append ( hdr ) return xform | Transform NCBI Gene header fields into valid namedtuple fields . | 127 | 13 |
222,473 | def _init_nt_hdr ( self , line ) : line = line . replace ( '.' , '_' ) line = line . replace ( ' ' , '_' ) line = line . replace ( '#' , 'N' ) line = line . replace ( '-' , '_' ) line = line . replace ( '"' , '' ) #line = re.sub(r"_$", r"", line) hdrs = re . split ( self . sep , line ) if '' in hdrs : hdrs = NCBIgeneFileReader . replace_nulls ( hdrs ) # Init indexes which will be converted to int or float self . idxs_int = [ idx for idx , hdr in enumerate ( hdrs ) if hdr in self . int_hdrs ] self . idxs_float = [ idx for idx , hdr in enumerate ( hdrs ) if hdr in self . float_hdrs ] assert hdrs [ 6 ] == 'Aliases' return namedtuple ( 'ntncbi' , ' ' . join ( hdrs ) ) | Convert headers into valid namedtuple fields . | 250 | 10 |
222,474 | def replace_nulls ( hdrs ) : ret = [ ] idx = 0 for hdr in hdrs : if hdr == '' : ret . append ( "no_hdr{}" . format ( idx ) ) else : ret . append ( hdr ) return ret | Replace in hdrs . | 62 | 7 |
222,475 | def _init_data_line ( self , fnc , lnum , line ) : fld = re . split ( self . sep , line ) # Lines may contain different numbers of items. # The line should have all columns requested by the user. if self . usr_max_idx < len ( fld ) : self . convert_ints_floats ( fld ) fnc ( fld ) else : for fld in enumerate ( zip ( self . hdr2idx . keys ( ) , fld ) ) : print ( fld ) for hdr in self . hdrs_usr : print ( hdr ) print ( '# ITEMS ON A LINE:' , len ( fld ) ) print ( 'MAX USR IDX:' , self . usr_max_idx ) raise Exception ( "ERROR ON LINE {} IN {}" . format ( lnum + 1 , self . fin ) ) | Process Data line . | 199 | 4 |
222,476 | def convert_ints_floats ( self , flds ) : for idx in self . idxs_float : flds [ idx ] = float ( flds [ idx ] ) for idx in self . idxs_int : dig = flds [ idx ] #print 'idx={} ({}) {}'.format(idx, flds[idx], flds) # DVK flds [ idx ] = int ( flds [ idx ] ) if dig . isdigit ( ) else dig for idx in self . idxs_strpat : hdr = self . hdr2idx . items ( ) [ idx ] [ 0 ] pat = self . strpat_hdrs [ hdr ] flds [ idx ] = pat . format ( flds [ idx ] ) | Convert strings to ints and floats if so specified . | 187 | 12 |
222,477 | def _init_hdr ( self , line , hdrs_usr ) : self . hdr2idx = OrderedDict ( [ ( v . strip ( ) , i ) for i , v in enumerate ( re . split ( self . sep , line ) ) ] ) self . len = len ( self . hdr2idx ) # If user is requesting specific data fields... if hdrs_usr is not None : # Loop through the user headers for usr_hdr in hdrs_usr : # If the user header is contained in the file.... if usr_hdr in self . hdr2idx : # Add the user header and the field index to a list self . hdrs_usr . append ( [ usr_hdr , self . hdr2idx [ usr_hdr ] ] ) else : raise Exception ( "NO COLUMN({}) FOUND:\n HDR={}\n" . format ( hdrs_usr , '\n HDR=' . join ( self . hdr2idx . keys ( ) ) ) ) usr_hdrs = [ E [ 0 ] for E in self . hdrs_usr ] if self . hdrs_usr else self . hdr2idx self . _init_idxs_float ( usr_hdrs ) self . _init_idxs_int ( usr_hdrs ) self . _init_idxs_strpat ( usr_hdrs ) self . usr_max_idx = max ( E [ 1 ] for E in self . hdrs_usr ) if self . hdrs_usr else len ( self . hdr2idx ) - 1 | Initialize self . hdr2idx self . len self . idxs_float and self . idxs_int | 372 | 25 |
222,478 | def _init_idxs_float ( self , usr_hdrs ) : self . idxs_float = [ Idx for Hdr , Idx in self . hdr2idx . items ( ) if Hdr in usr_hdrs and Hdr in self . float_hdrs ] | List of indexes whose values will be floats . | 66 | 9 |
222,479 | def _init_idxs_int ( self , usr_hdrs ) : self . idxs_int = [ Idx for Hdr , Idx in self . hdr2idx . items ( ) if Hdr in usr_hdrs and Hdr in self . int_hdrs ] | List of indexes whose values will be ints . | 66 | 10 |
222,480 | def _init_idxs_strpat ( self , usr_hdrs ) : strpat = self . strpat_hdrs . keys ( ) self . idxs_strpat = [ Idx for Hdr , Idx in self . hdr2idx . items ( ) if Hdr in usr_hdrs and Hdr in strpat ] | List of indexes whose values will be strings . | 78 | 9 |
222,481 | def _get_geneid2nt ( nts ) : geneid2nt = { } for ntd in nts : geneid = ntd . GeneID if geneid not in geneid2nt : geneid2nt [ geneid ] = ntd else : print ( "DUPLICATE GeneID FOUND {N:9} {SYM}" . format ( N = geneid , SYM = ntd . Symbol ) ) return geneid2nt | Get geneid2nt given a list of namedtuples . | 101 | 13 |
222,482 | def _wrpy_ncbi_gene_nts ( fout_py , geneid2nt , log ) : num_genes = len ( geneid2nt ) with open ( fout_py , 'w' ) as ofstrm : docstr = "Data downloaded from NCBI Gene converted into Python namedtuples." ofstrm . write ( '"""{PYDOC}"""\n\n' . format ( PYDOC = docstr ) ) ofstrm . write ( "from collections import namedtuple\n\n" ) ofstrm . write ( 'WRITTEN = "{DATE}"' . format ( DATE = re . sub ( '-' , '_' , str ( datetime . date . today ( ) ) ) ) ) ofstrm . write ( ' # {N} items\n\n' . format ( N = num_genes ) ) ntd = next ( iter ( geneid2nt . values ( ) ) ) # Access one dictionary value in Python 2 ofstrm . write ( "#pylint: disable=line-too-long,too-many-lines,invalid-name\n" ) ofstrm . write ( "{NtName} = namedtuple('{NtName}', '{FLDS}')\n\n" . format ( NtName = type ( ntd ) . __name__ , FLDS = ' ' . join ( ntd . _fields ) ) ) ofstrm . write ( "GENEID2NT = {{ # {N:,} items\n" . format ( N = num_genes ) ) for geneid , ntd in sorted ( geneid2nt . items ( ) , key = lambda t : t [ 0 ] ) : ofstrm . write ( " {GeneID} : {NT},\n" . format ( GeneID = geneid , NT = ntd ) ) ofstrm . write ( "}\n" ) log . write ( " {N:9} geneids WROTE: {PY}\n" . format ( N = num_genes , PY = fout_py ) ) | Write namedtuples to a dict in a Python module . | 468 | 12 |
222,483 | def get_goobjs_altgo2goobj ( go2obj ) : goobjs = set ( ) altgo2goobj = { } for goid , goobj in go2obj . items ( ) : goobjs . add ( goobj ) if goid != goobj . id : altgo2goobj [ goid ] = goobj return goobjs , altgo2goobj | Separate alt GO IDs and key GO IDs . | 88 | 10 |
222,484 | def add_alt_goids ( go2values , altgo2goobj ) : for goobj_key in altgo2goobj . values ( ) : values_curr = go2values [ goobj_key . id ] for goid_alt in goobj_key . alt_ids : go2values [ goid_alt ] = values_curr return go2values | Add alternate source GO IDs . | 84 | 6 |
222,485 | def fill_main_goids ( go2obj , goids ) : # User GO IDs (goids) may be either main GO IDs or alternate GO IDs. for goid in goids : goobj = go2obj [ goid ] # If a user specified an ALT GO ID and main GO ID not in go2obj: if goid != goobj . id and goobj . id not in go2obj : # Add main GO ID to go2obj go2obj [ goobj . id ] = goobj | Ensure main GO IDs are included in go2obj . | 112 | 12 |
222,486 | def fill_altgoids ( go2obj ) : alt2obj = { altgo : goobj for goobj in go2obj . values ( ) for altgo in goobj . alt_ids } for goid , goobj in alt2obj . items ( ) : go2obj [ goid ] = goobj | Given a go2obj containing key GO IDs fill with all alternate GO IDs . | 69 | 16 |
222,487 | def fill_relationshipobjs ( go2obj , relationships ) : # Get all GO Term record objects that have relationships obj = RelationshipFill ( go2obj , relationships ) for goobj in go2obj . values ( ) : if goobj . relationship : obj . fill_relationshipgo2obj ( goobj ) if goobj . relationship_rev : obj . fill_relationshiprevgo2obj ( goobj ) | Add GO IDs to go2obj that are involved in relationships . | 89 | 13 |
222,488 | def fill_childgoid2obj ( childgoid2obj , parent_obj ) : for child_obj in parent_obj . children : if child_obj . id not in childgoid2obj : childgoid2obj [ child_obj . id ] = child_obj fill_childgoid2obj ( childgoid2obj , child_obj ) | Fill childgoid2obj with all child key GO IDs and their objects . | 79 | 16 |
222,489 | def get_leaf_children ( gos_user , go2obj_arg ) : childgoid2obj = { } for goid_usr in gos_user : goobj_usr = go2obj_arg [ goid_usr ] fill_childgoid2obj ( childgoid2obj , goobj_usr ) return set ( go for go , o in childgoid2obj . items ( ) if not o . children ) | Find all the GO descendants under all user GO IDs . Return leaf - level GO IDs . | 97 | 18 |
222,490 | def chk_goids ( goids , msg = None , raise_except = True ) : for goid in goids : if not goid_is_valid ( goid ) : if raise_except : raise RuntimeError ( "BAD GO({GO}): {MSG}" . format ( GO = goid , MSG = msg ) ) else : return goid | check that all GO IDs have the proper format . | 80 | 10 |
222,491 | def _get_sorted_relationships ( self , goterm ) : if goterm . id in self . goids_seen : return self . goids_seen . add ( goterm . id ) for goterm_upper in goterm . get_goterms_upper ( ) : self . _get_sorted_relationships ( goterm_upper ) self . goterms_sorted . append ( goterm ) | Traverse GO Terms above the current GO Term . Then add current GO Term to sorted . | 93 | 18 |
222,492 | def read_sections ( sections_file , exclude_ungrouped = False , prt = sys . stdout ) : if sections_file is None : return None assert isinstance ( sections_file , str ) , "BAD SECTIONS FILENAME({S})" . format ( S = sections_file ) if os . path . exists ( sections_file ) : return ReadGoids ( ) . read_sections ( sections_file , False , exclude_ungrouped ) # Is 'sections_file' a module string? if '/' not in sections_file and r'\\' not in sections_file and pkgutil . find_loader ( sections_file ) is not None : mod = importlib . import_module ( sections_file ) var = getattr ( mod , 'SECTIONS' , None ) if var is not None : dat = SummarySec2dHdrGos ( ) . summarize_sec2hdrgos ( var ) print ( Grouper . fmtsum . format ( GO_DESC = 'hdr' , SECs = len ( dat [ 'S' ] ) , GOs = len ( dat [ 'G' ] ) , UNGRP = "N/A" , undesc = "unused" , ACTION = "IMPORTED: " , FILE = sections_file ) ) return var raise RuntimeError ( "NO 'SECTIONS' VARIABLE FOUND IN MODULE({M})" . format ( M = sections_file ) ) if prt : prt . write ( "CANNOT READ: {SEC}\n" . format ( SEC = sections_file ) ) | Get sections and GO grouping hdrgos from file if sections exist . | 354 | 15 |
222,493 | def read_py ( self , fin_txt , get_goids_only , exclude_ungrouped , prt = sys . stdout ) : goids_fin = self . _read_py ( fin_txt , get_goids_only , exclude_ungrouped ) sections = self . _read_finish ( goids_fin , prt ) # Print summary of GO IDs read if prt is not None : self . _prt_read_msg ( prt , fin_txt , exclude_ungrouped ) return sections | Read GO IDs or sections data from a Python file . | 119 | 11 |
222,494 | def read_sections ( self , sections_file , get_goids_only , exclude_ungrouped ) : ext = os . path . splitext ( sections_file ) [ 1 ] file_contents = None if ext == '.py' : file_contents = self . read_py ( sections_file , get_goids_only , exclude_ungrouped ) else : file_contents = self . read_txt ( sections_file , get_goids_only , exclude_ungrouped ) if file_contents : return file_contents . get ( 'sections' , None ) | Read sections variable from a text file of from a Python file . | 133 | 13 |
222,495 | def _rpt_unused_sections ( self , prt ) : sections_unused = set ( self . sections_seen ) . difference ( self . section2goids . keys ( ) ) for sec in sections_unused : prt . write ( " UNUSED SECTION: {SEC}\n" . format ( SEC = sec ) ) | Report unused sections . | 75 | 4 |
222,496 | def _prt_read_msg ( self , prt , fin_txt , exclude_ungrouped ) : if self . sections_seen or exclude_ungrouped : # dat = Grouper.get_summary_data(self.section2goids.items(), HdrgosSections.secdflt) dat = SummarySec2dHdrGos ( ) . summarize_sec2hdrgos ( self . section2goids . items ( ) ) sys . stdout . write ( Grouper . fmtsum . format ( GO_DESC = 'hdr' , SECs = len ( dat [ 'S' ] ) , GOs = len ( dat [ 'G' ] ) , UNGRP = "N/A" , undesc = "unused" , ACTION = "READ: " , FILE = fin_txt ) ) elif self . goids_fin : prt . write ( " {G} GO IDs READ: {FIN}\n" . format ( G = len ( self . goids_fin ) , FIN = fin_txt ) ) | Print which file was read and the number of GO IDs found . | 240 | 13 |
222,497 | def rm_gos ( self , rm_goids ) : self . edges = self . _rm_gos_edges ( rm_goids , self . edges ) self . edges_rel = self . _rm_gos_edges_rel ( rm_goids , self . edges_rel ) | Remove any edges that contain user - specified edges . | 68 | 10 |
222,498 | def _rm_gos_edges_rel ( self , rm_goids , edges_rel ) : edges_ret = { } for rname , edges_cur in edges_rel . items ( ) : edges_new = self . _rm_gos_edges ( rm_goids , edges_cur ) if edges_new : edges_ret [ rname ] = edges_new return edges_ret | Remove any relationship that contain user - specified edges . | 90 | 10 |
222,499 | def _rm_gos_edges ( rm_goids , edges_all ) : edges_reduced = [ ] for goid_child , goid_parent in sorted ( edges_all , key = lambda t : t [ 1 ] ) : if goid_child not in rm_goids and goid_parent not in rm_goids : edges_reduced . append ( ( goid_child , goid_parent ) ) return edges_reduced | Remove any is_a edges that contain user - specified edges . | 102 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.